Search Results

Search found 3773 results on 151 pages for 'args'.

Page 31/151 | < Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >

  • In Python, are there builtin functions for elementwise boolean operators over boolean lists?

    - by bshanks
    For example, if you have n lists of bools of the same length, then elementwise boolean AND should return another list of that length that has True in those positions where all the input lists have True, and False everywhere else. It's pretty easy to write, i just would prefer to use a builtin if one exists (for the sake of standardization/readability). Here's an implementation of elementwise AND: def eAnd(*args): return [all(tuple) for tuple in zip(*args)] example usage: >>> eAnd([True, False, True, False, True], [True, True, False, False, True], [True, True, False, False, True]) [True, False, False, False, True] thx

    Read the article

  • ActiveRecord :through to set default values on through table.

    - by Dmitriy Likhten
    I would like to set a default value in a has_many through association. Lets say I have three models: People Friends Dogs A person can request that a dog becomes their friend. So a person would create an association where friends has an active column = false. User has_many :friends has_many :dogs, :through => :friends Now when I assign a dog to a user User.find(1).dogs << dog The friends table has null in the active column. My friends model is defined as Friend def initialize(args = {}) super(args) active = false end yet this does not work because the friend object is never created. Do I have to manually create one?

    Read the article

  • .Net - interop assemblies taking 15 seconds to load when being referenced in a function

    - by Jon
    This is a C# console application. I have a function that does something like this: static void foo() { Application powerpointApp; Presentation presentation = null; powerpointApp = new Microsoft.Office.Interop.PowerPoint.ApplicationClass(); } That's all it does. When it is called there is a fifteen second delay before the function gets hit. I added something like this: static void MyAssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args) { Console.WriteLine(DateTime.Now.ToString() + " ASSEMBLY LOADED: " + args.LoadedAssembly.FullName); Console.WriteLine(); } This gets fired telling me that my interop assemblies have been loaded about 10 milliseconds before my foo function gets hit. What can I do about this? The program needs to call this function (and eventually do something else) once and then exit so I need for these assemblies to be cached or something. Ideas?

    Read the article

  • Is it possible to write a Java printf statement that prints the statement itself?

    - by polygenelubricants
    Is it possible to have a Java printf statement, whose output is the statement itself? Some snippet to illustrate: // attempt #1 public class Main { public static void main(String[] args) { System.out.printf("something"); } } This prints something. So the output of attempt #1 is not quite exactly the printf statement in attempt #1. We can try something like this: // attempt #2 public class Main { public static void main(String[] args) { System.out.printf("System.out.printf(\"something\");"); } } And now the output is System.out.printf("something"); So now the output of attempt #2 matches the statement in output #1, but we're back to the problem we had before, since we need the output of attempt #2 to match the statement in attempt #2. So is it possible to write a one-line printf statement that prints itself?

    Read the article

  • What is the explanation of this results in Java ?

    - by M.H
    I have the following code : public class Main { private int i = j; //1 private int j = 10; public static void main(String[] args) { System.out.println((new Main()).i); } } and there is a compiler error in line 1 because an illegal forward reference. But when I am trying the following code : public class Main { int i = getJ(); //1 int getJ(){ return j; } int j=10; public static void main(String[] args) { System.out.println(new Main().i); } } it works fine and the result is 0.Why there is no illegal forward reference in line 1 here?.The two codes look similar to me.

    Read the article

  • Add up values from a text file

    - by Stanley
    Hi Guys I have a text file that contains Amounts at Substring (34, 47) of each line. I need to sum Up all the Values to the End of the File. I have this code that I had started to build but I do not know how to proceed from here: public class Addup { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here FileInputStream fs = new FileInputStream("C:/Analysis/RL004.TXT"); BufferedReader br = new BufferedReader(new InputStreamReader(fs)); String line; while((line = br.readLine()) != null){ String num = line.substring(34, 47); double i = Double.parseDouble(num); System.out.println(i); } } } The output is like this: 1.44576457E4 2.33434354E6 4.56875685E3 The Amount is in two decimal Places and I need the result also in the Two decimal Places. What Is the Best way to achieve this?

    Read the article

  • Constructing a function call in C

    - by 0x6adb015
    Given that I have a pointer to a function (provided by dlsym() for example) and a linked list of typed arguments, how can I construct a C function call with those arguments? Example: struct param { enum type { INT32, INT64, STRING, BOOL } type; union { int i32; long long i64; char *str; bool b; } value; struct param *next; }; int call_this(int (*function)(), struct param *args) { int result; /* magic here that calls function(), which has a prototype of f(int, long long, char *, bool); , when args consist of a linked list of INT32, INT64, STRING, BOOL types. */ return result; } The OS is Linux. I would like the solution to be portable across MIPS, PPC and x86 (all 32 bits) architecture, using GCC as the compiler. Thanks!

    Read the article

  • Cleanest Way to Invoke Cross-Thread Events

    - by Nick
    I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is. Based on the community suggestions, I've used this: // earlier in the code mCoolObject.CoolEvent+= new CoolObjectEventHandler(mCoolObject_CoolEvent); // then private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { if (InvokeRequired) { CoolObjectEventHandler cb = new CoolObjectEventHandler( mCoolObject_CoolEvent); Invoke(cb, new object[] { sender, args }); return; } // do the dirty work of my method here }

    Read the article

  • Saving data in a inherited django model

    - by aldeano
    I'm building an app to save data and some calculations made with those datas, the idea is keep the data in one model and the calculations in other. So, the models are like this: class FreshData(models.Model): name = models.CharField(max_length=20) one = models.IntegerField() two = models.IntegerField() def save(self, *args, **kwargs): Calculations() Calculations.three = self.one + self.two super(FreshData, self).save(*args, **kwargs) Calculations.save() class Calculations(FreshData): three = models.IntegerField() I've got a valueerror pointing out "self.one" and "self.two" as without value. I keep the idea in witch my design is wrong and django has a simpler way to store related data.

    Read the article

  • 2 dimensional arraylists in java

    - by Chris Maness
    So here's the deal I'm working on a project that requires me to have a 2 dimensional arraylist of 1 dimensional arrays. But every time I try to load in my data I get an error: Can't do this opperation because of bad input java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 On some of the inputs. I've got no idea where I'm going wrong on this one. A little help please? Source Code: import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JOptionPane; import java.io.InputStream; public class Facebull { public static void main (String[] args) { if(args.length != 0){ load(args[0]); } else{ load("testFile"); } } public static void load(String fname) { int costOfMach = 0; ArrayList <Integer> finalMach = new ArrayList<Integer>(); ArrayList <ArrayList<int[]>>machines = new ArrayList<ArrayList<int[]>>(); Scanner inputFile = null; File f = new File(fname); if (f.exists ()) { try { inputFile = new Scanner (f); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null,"Can't find the file\n" + e); } int i = 0; while (inputFile.hasNext ( )) { String str = inputFile.nextLine ( ); String [ ] fields = str.split ("[\t ]"); System.out.println(str); if (!(fields[0].isEmpty() || fields[0].equals (""))){ fields[0] = fields[0].substring(1); fields[1] = fields[1].substring(1); fields[2] = fields[2].substring(1); try { //data to be inputed is 0 and 3 location of data is 1 and 2 int[] item = new int[2]; item[1] = Integer.parseInt(fields[0]); item[0] = Integer.parseInt(fields[3]); if(machines.size() < Integer.parseInt(fields[1])){ ArrayList<int[]> column = new ArrayList<int[]>(); machines.add (Integer.parseInt(fields[1])-1, column); System.out.println("we're in the if"); } machines.get(Integer.parseInt(fields[1])-1).add(Integer.parseInt(fields[2])-1, item); } //catches any exception catch (Exception e) { System.out.println("Can't do this opperation because of bad input \n" + e); } } } inputFile.close ( ); } System.out.print(machines); }//end load }

    Read the article

  • Why do I have to explicitly cast sometimes for varargs?

    - by Daniel Lew
    I've got a Class that uses reflection a lot, so I wrote a method to help out: private <T> T callMethod(String methodName, Class[] parameterTypes, Object[] args) { try { Class c = mVar.getClass(); Method m = c.getMethod(methodName, (Class[]) parameterTypes); return (T) m.invoke(mVar, args); } // Insert exception catching here [...] } This worked well for any method that had parameters, however I had to explicitly cast parameterTypes to Class[] in order for this to work for methods with no parameters (e.g., callMethod('funName', null, null);). I've been trying to figure out why this is the case. It seems to me that if parameterTypes, when null, had no concept of what type it is (Class[]), then I'd need to cast it for getMethod(). But if that's the case, why is getMethod() able to tell the difference between null, and (Class[]) null when the method is invoked?

    Read the article

  • Using generics in dotnet for functions with any number of arguments?

    - by Zarigani
    I would like to have a function that can "wrap" any other function call. In this particular case, it would allow me to write some more generic transaction handling around some specific operations. I can write this for any particular number of arguments, e.g. for one argument: Public Shared Sub WrapFunc(Of T)(ByVal f As Action(Of T), ByVal arg As T) ' Test some stuff, start transaction f(arg) ' Test some stuff, end transaction End Sub ... but I was hoping to have this handle any number of arguments without having to have duplicate code for 0 args, 1 arg, 2 args, etc. Is there a way of doing this?

    Read the article

  • How to inherit from the main class in java

    - by user225269
    I have two java classes. One is NewFrame.java where the forms(buttons, textfields) are located. And the other one is Main.java where I have put the connection string for mysql: Main.java looks like this: public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_record", "root", "password"); PreparedStatement statement = con.prepareStatement("select * from employee"); ResultSet result = statement.executeQuery(); } } How do I inherit from the main.java so that the declarations in it would be universally accessible to the forms in NewFrame.java? Please help. Thanks

    Read the article

  • Django: Staff Decorator

    - by Mark
    I'm trying to write a "staff only" decorator for Django, but I can't seem to get it to work: def staff_only(error='Only staff may view this page.'): def _dec(view_func): def _view(request, *args, **kwargs): u = request.user if u.is_authenticated() and u.is_staff: return view_func(request, *args, **kwargs) messages.error(request, error) return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('home'))) _view.__name__ = view_func.__name__ _view.__dict__ = view_func.__dict__ _view.__doc__ = view_func.__doc__ return _view return _dec Trying to follow lead from here. I'm getting: 'WSGIRequest' object has no attribute '__name__' But if I take those 3 lines out, I just get a useless "Internal Server Error". What am I doing wrong here?

    Read the article

  • variadic constructors

    - by FredOverflow
    Are variadic constructors supposed to hide the implicitly generated ones, i.e. the default constructor and the copy constructor? struct Foo { template<typename... Args> Foo(Args&&... x) { std::cout << "inside the variadic constructor\n"; } }; int main() { Foo a; Foo b(a); } Somehow I was expecting this to print nothing after reading this answer, but it prints inside the variadic constructor twice on g++ 4.5.0 :( Is this behavior correct?

    Read the article

  • How do i change Object to String in a class which extends AsyncTask?

    - by Filip V.
    I'm learning from Google's Android developing tutorial and i came across a problem. On this link https://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask it says to create a class that extends AsyncTask. So when i write the class it automatically implements the method as follows: private Object doInBackground(Object... args) {..} //it's fine but when i try writing just as it says in the tutorial: private String doInBackground(String... args) {..} //it gives an error and the error says: The method doInBackground(String...) of type MainActivity.DownloadWebpageText must override a superclass method. So how do i change Object to String without getting an error there?

    Read the article

  • C++ return type overload hack

    - by aaa
    I was bored and came up with such hack (pseudocode): 1 struct proxy { 2 operator int(); // int function 3 operator double(); // double function 4 proxy(arguments); 5 arguments &arguments_; 6 }; 7 8 proxy function(arguments &args) { 9 return proxy(args); 10 } 11 int v = function(...); 12 double u = function(...); is it evil to use in real code?

    Read the article

  • Why is Rake not able to invoke multiple tasks consecutively?

    - by PandaWood
    I have a Rake task which I have simplified below. I'm using Ruby 1.9 on Windows. Perhaps you would like to guess the outcome of calling the Rake task "list_all_levels" below? It should be: "Hello level 1" "Hello level 2" "Hello level 3" But for reasons unknown to me, it prints only "Hello level 1" and then stops. That is, it always invokes only the first task. If I change the first line to pass the arg "42", it would print "Hello level 42" and then stop. I'm wondering why does it not invoke the task 3 times and print all 3 lines? And is there any way to get it to work how I would expect? task :list_all_levels => [] do Rake::Task[:list].invoke 1 Rake::Task[:list].invoke 2 Rake::Task[:list].invoke 3 end task :list, [:level] => [] do |t, args| puts "Hello level #{args.level}" end

    Read the article

  • python mock side_effect or return_value dependent on call_count

    - by user18380
    To test a polling function I want to mock the calling of a sub function so that the first time it is called it will fail, and the second time it is called it will succeed. Here's a very simplified version of it: poll_function(var1): value = sub_function(var1) # First call will return None while not value: time.sleep(POLLING_INTERVAL) value = sub_function(var1) # A subsequent call will return a string, e.g "data" return value Is this possible to do with a Mock object from the mock framework? I know Mock objects have a call_count attribute I should be able to use somehow. Right now I've solved it by creating a custom mock object that I use to monkey patch sub_function(), but I feel there should be a better less verbose way of doing it: def test_poll(): class MyMock(object): def __init__(self, *args): self.call_count = 0 def sub_function(self, *args, **kwargs): if self.call_count > 1: return "data" else: self.call_count += 1 return None my_mock = MyMock() with patch('sub_function', my_mock.sub_function): ok_(poll_function())

    Read the article

  • Adding a method to a function object at runtime

    - by Carson Myers
    I read a question earlier asking if there was a times method in Python, that would allow a function to be called n times in a row. Everyone suggested for _ in range(n): foo() but I wanted to try and code a different solution using a function decorator. Here's what I have: def times(self, n, *args, **kwargs): for _ in range(n): self.__call__(*args, **kwargs) import new def repeatable(func): func.times = new.instancemethod(times, func, func.__class__) @repeatable def threeArgs(one, two, three): print one, two, three threeArgs.times(7, "one", two="rawr", three="foo") When I run the program, I get the following exception: Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\py\repeatable.py", line 24, in threeArgs.times(7, "one", two="rawr", three="foo") AttributeError: 'NoneType' object has no attribute 'times' So I suppose the decorator didn't work? How can I fix this?

    Read the article

  • Iterating over a database column in Django

    - by curious
    I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column: import MySQLdb import sys try: conn = MySQLdb.connect (host = "localhost", user = "user", passwd="passwd", db="db") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) cursor = conn.cursor() for table in ['foo', 'bar']: for column in ['foobar1', 'foobar2']: cursor.execute('select %s from %s' % (column, table)) exec "%s_%s = cursor.fetchall()" % (table, column) cursor.close() conn.commit() conn.close() Is there any functionality built into Django to more conveniently iterate through the values of a column in a database table? I'm dealing with millions of rows so speed of execution is important.

    Read the article

  • Actual SQL statement after bind variables specified

    - by bioffe
    I am trying to log every SQL statement executed from my scripts. However I contemplate one problem I can not overcome. Is there a way to compute actual SQL statement after bind variables were specified. In SQLite I had to compute the statement to be executed manually, using code below: def __sql_to_str__(self, value,args): for p in args: if type(p) is IntType or p is None: value = value.replace("?", str(p) ,1) else: value = value.replace("?",'\'' + p + '\'',1) return value It seems CX_Oracle has cursor.parse() facilities. But I can't figure out how to trick CX_Oracle to compute my query before its execution.

    Read the article

  • How do I replace "this" in Java with something that works.

    - by Luke Alderton
    I'm looking to get the showGUI() method work, the compiler says "this" is not a static variable and cannot be referenced from a static context, what would I use to replace "this"? I've tried test.main (test being the package it's in). The reason I'm using the static method showGUI() is because I need the method to be called from another static method, as well as the startup() method. Below are my two main classes. public class Main extends SingleFrameApplication { @Override protected void startup() { showGUI(); } @Override protected void configureWindow(java.awt.Window root) { } public static Main getApplication() { return Application.getInstance(Main.class); } public static void main(String[] args) { launch(Main.class, args); } public static void showGUI() { show(new GUI(this)); } } public class GUI extends FrameView { public GUI(SingleFrameApplication app) { super(app); initComponents(); } private void initComponents() { //all the GUI stuff is somehow defined here } }

    Read the article

  • Print the next X number of lines in Scala

    - by soulesschild
    Trying to learn Scala using the Programming in Scala book and they have a very basic example for reading lines from a file. I'm trying to expand on it and read a file line by line, look for a certain phrase, then print the next 6 lines following that line if it finds the line. I can write the script easily enough in something like java or Perl but I have no idea how to do it in Scala (probably because I'm not very familiar with the language yet...) Here's the semi adapted sample code from the Programming in Scala book, import scala.io.Source if(args.length>0) { val lines = Source.fromFile(args(0)).getLines().toList for(line<-lines) { if(line.contains("secretPhrase")) { println(line) //How to get the next lines here? } } } else Console.err.println("Pleaseenterfilename")

    Read the article

  • how to return value from groovy to java

    - by Sid
    Hi I am very new to groovy and having trouble with some parts. I have a jsp page tied to a servlet that runs groovy scripts. I am able to get to the groovy script from the servlet. But after the script runs how do I return the response from the groovy script back to the servlet to be displayed in the jsp page? My java servlet code is as follows: File file = new File("TestScript.groovy"); ClassLoader parent = getClass().getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); Class groovyClass = loader.parseClass(file); Object[] args = {}; GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); groovyObject.invokeMethod("runTest", args);

    Read the article

< Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >