text
stringlengths
64
81.1k
meta
dict
Q: sleep() and time() not functioning as expected inside for loop I'm trying to create an array of tm struct pointers, with each struct having a tm_sec value 2 seconds larger than the previous one. #include <stdio.h> #include <time.h> #include <unistd.h> /* sleep() */ int main(signed int argc, char **argv) { struct tm *collection[5]; for(struct tm **p = collection; p < collection + 5; p += 1) { sleep(2); const time_t timeNow = time(NULL); *p = gmtime(&timeNow); } for(struct tm **p = collection; p < collection + 5; p += 1) { if(p != collection + 4) { puts((**p).tm_sec == (**(p + 1)).tm_sec ? "equal" : "not equal"); } puts(asctime(*p)); } } Execution lasts around 10 seconds, which seems fine, but the resulting output is: equal Sat Jul 28 01:42:15 2018 equal Sat Jul 28 01:42:15 2018 equal Sat Jul 28 01:42:15 2018 equal Sat Jul 28 01:42:15 2018 Sat Jul 28 01:42:15 2018 Compiled with GCC 7.3.0 on linux64. Don't know what I'm doing wrong. note: Initially I didn't have the first for loop sleep on the insertion of the first element, but I removed it here for simplicity's sake. It doesn't make a difference. A: From the man page: POSIX.1-2001 says: "The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken-down time structure and an array of type char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions." This can occur in the glibc implementation. For single-threaded programs, simply dereference the pointers: #include <stdio.h> #include <time.h> #include <unistd.h> /* sleep() */ int main(signed int argc, char **argv) { struct tm collection[5]; for (struct tm *p = collection; p < collection + 5; p++) { sleep(2); const time_t timeNow = time(NULL); *p = *gmtime(&timeNow); } for(struct tm *p = collection; p < collection + 5; p++) { if(p != collection + 4) { puts((*p).tm_sec == (*(p + 1)).tm_sec ? "equal" : "not equal"); } puts(asctime(p)); } } For multi-threaded programs, you'll need to use gmtime_r and asctime_r
{ "pile_set_name": "StackExchange" }
Q: Laravel blade hardcode variable on compile I'm moving some of my view strings to config because I want to use the same code for similar sites, and I'm wondering if there's a way to avoid a call to Config:: or Lang:: on every runtime. <h1>{{ Config::get('siteName') }}</h1> blade makes in into <h1><?php echo Config::get('siteName'); ?></h1> But I want it to be just plain HTML like <h1>MySite</h1> My approach is trying to make this when Blade compiles the views into plain PHP / HTML , is there any built-in way to do this? I've tried with some Blade methods like @string with no results Thanks A: OK solved it by extending Blade I created a blade tag such as @hardcodeConfig('siteName') And in my blade_extensions I did this: Blade::extend(function($view, $compiler) { $pattern = $compiler->createMatcher('hardcodeConfig'); $matches = []; preg_match_all($pattern, $view, $matches); foreach($matches[2] as $index => $key){ $key = str_replace([ "('", "')" ], '', $key); $configValue = \Config::get( $key ); $view = str_ireplace($matches[0][$index], $configValue, $view); } return $view; }); This does exactly was I was looking for, I created one for Config and another for Lang
{ "pile_set_name": "StackExchange" }
Q: How to improve the quality of JPEG images that are generated from PDFs using Ghostscript? I use this code to generate JPEG images from a PDF file: String cmd = @"./lib/gswin32c"; String args = "-dNOPAUSE -sDEVICE=jpeg -dJPEGQ=100 -dBATCH -dSAFER -sOutputFile=" + fileName + "-%03d.jpg " + fileName + ".pdf"; Process proc = new Process(); proc.StartInfo.FileName = cmd; proc.StartInfo.Arguments = args; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.Start(); I works really fine, but the quality is really bad. It seems to be blurred. Any hints how to improve the quality? EDIT Now I'm using the following arguments and it is working as expected: String args = "-dNOPAUSE -sDEVICE=pngalpha -r300 -dBATCH -dSAFER -sOutputFile=" + fileName + "-%03d" + FILEEXTENSION + " " + fileName + ".pdf"; A: JPEG? For documents? Generate gifs or pngs, if you can. JPEGs are unsuitable for anything else than photos, even at a "maximum" quality setting. http://lbrandy.com/blog/2008/10/my-first-and-last-webcomic/
{ "pile_set_name": "StackExchange" }
Q: How to take screenshot of entire screen on a Jailbroken iOS Device? I need to take screenshot of the whole screen including the status bar, I use CARenderServerRenderDisplay to achieve this, it works right on iPad, but wrong at iPhone 6 Plus. As the * marked part in the code, if I set width=screenSize.width*scale and height=screenSize.height*scale, it will cause crash, if I just change them as:width=screenSize.height*scale and height=screenSize.width*scale, it will works, but produce a image like that: , I've tried much but no reason found, does anyone know that? I hope I've described it clear enough. - (void)snapshot { CGFloat scale = [UIScreen mainScreen].scale; CGSize screenSize = [UIScreen mainScreen].bounds.size; //*********** the place where problem appears size_t width = screenSize.height * scale; size_t height = screenSize.width * scale; //*********** size_t bytesPerElement = 4; OSType pixelFormat = 'ARGB'; size_t bytesPerRow = bytesPerElement * width; size_t surfaceAllocSize = bytesPerRow * height; NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], kIOSurfaceIsGlobal, [NSNumber numberWithUnsignedLong:bytesPerElement], kIOSurfaceBytesPerElement, [NSNumber numberWithUnsignedLong:bytesPerRow], kIOSurfaceBytesPerRow, [NSNumber numberWithUnsignedLong:width], kIOSurfaceWidth, [NSNumber numberWithUnsignedLong:height], kIOSurfaceHeight, [NSNumber numberWithUnsignedInt:pixelFormat], kIOSurfacePixelFormat, [NSNumber numberWithUnsignedLong:surfaceAllocSize], kIOSurfaceAllocSize, nil]; IOSurfaceRef destSurf = IOSurfaceCreate((__bridge CFDictionaryRef)(properties)); IOSurfaceLock(destSurf, 0, NULL); CARenderServerRenderDisplay(0, CFSTR("LCD"), destSurf, 0, 0); IOSurfaceUnlock(destSurf, 0, NULL); CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, IOSurfaceGetBaseAddress(destSurf), (width * height * 4), NULL); CGImageRef cgImage = CGImageCreate(width, height, 8, 8*4, IOSurfaceGetBytesPerRow(destSurf), CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst |kCGBitmapByteOrder32Little, provider, NULL, YES, kCGRenderingIntentDefault); UIImage *image = [UIImage imageWithCGImage:cgImage]; UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); } A: If you are on a Jailbroken environment, you can use the private UIImage method _UICreateScreenUIImage: OBJC_EXTERN UIImage *_UICreateScreenUIImage(void); // ... - (void)takeScreenshot { UIImage *screenImage = _UICreateScreenUIImage(); // do something with your screenshot } This method uses CARenderServerRenderDisplay for faster rendering of the entire device screen. It replaces the UICreateScreenImage and UIGetScreenImage methods that were removed in the arm64 version of the iOS 7 SDK.
{ "pile_set_name": "StackExchange" }
Q: Setup table column width I am trying to setup a table column width to only 200px or 10%. However, when I populate the data from the database, the column seems to ignore the column width and expand it as much as it can. Here is my table html. <table> <thead> <tr> <th><a href='#'>City</a></th> <th width='200' class='table_width'><a href='#'>name</a></th> <th><a href='#'>Agent</a></th> <th>... //I have tried class and width attribute. both don't work. </tr> </thead> <tbody> <tr> //these column data were popluated from database <td><?= $row->city; ?></td> <td width='200' class='table_width'><?= $row->_name; ?></td> //ignore the width and expand the table cell. <td><?= $row->agent; ?></td> <td>... </tr> A: You want to use word-wrap:break-word;. http://jsfiddle.net/RF4F6/1/ HTML <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> <th>Col 3</th> <th>Col 4</th> <th>Col 5</th> </tr> </thead> <tbody> <tr> <td>Normal Width</td> <td>Normal Width</td> <td class="forcedWidth">hiThisIsAreallyLongStringThatWillHaveToWrapAt200PixelsOrI'llBeUnhappyAndYouWon'tLikeMeWhenI'mUnhappy.</td> <td>Normal Width</td> <td>NormalWidth</td> </tr> </tbody> </table> CSS table td{ padding:.5em; /* Not essential for this answer, just a little buffer for the jsfiddle */ } .forcedWidth{ width:200px; word-wrap:break-word; display:inline-block; }
{ "pile_set_name": "StackExchange" }
Q: Can't place ImageView at top corner at runtime I want to place a ImageView at top left corner when runtime, but it does not work. This is my layout and code: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:id="@+id/layout_main" android:layout_height="fill_parent" tools:context=".Main"> </RelativeLayout> This is code: RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout_main); ImageView imageView =new ImageView(getApplicationContext()); imageView.setImageResource(R.drawable.green_apple); imageView.setScaleX(0.3f); imageView.setScaleY(0.3f); imageView.setLeft(0); imageView.setTop(0); layout.addView(imageView); I also tried: RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout_main); ImageView imageView =new ImageView(getApplicationContext()); imageView.setImageResource(R.drawable.green_apple); imageView.setScaleX(0.3f); imageView.setScaleY(0.3f); imageView.setX(0); imageView.setY(0); layout.addView(imageView); And: RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout_main); ImageView imageView =new ImageView(getApplicationContext()); imageView.setImageResource(R.drawable.green_apple); imageView.setScaleX(0.3f); imageView.setScaleY(0.3f); layout.addView(imageView); set = new AnimatorSet(); ObjectAnimator aniX = ObjectAnimator.ofFloat(imageView, "x", 0); aniX.setDuration(100); ObjectAnimator aniY = ObjectAnimator.ofFloat(imageView, "y", 0); aniY.setDuration(100); set.playTogether(aniX, aniY); set.start() But same result, this is my result: Always have large space to Top and Left screen, Although I set 0,0. I also try set height and width of screen, it fly out of screen. I don't know why. Thank you very much for anyone can explain and how to help me fix it A: That is because you use setScaleX and setScaleY, so try the code below: final ImageView iv = new ImageView(context); iv.setImageResource(R.drawable.green_apple); rl.addView(iv); iv.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() { @Override public boolean onPreDraw() { iv.getViewTreeObserver().removeOnPreDrawListener(this); int w = (int) (iv.getWidth() * 0.3); int h = (int) (iv.getHeight() * 0.3); RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(w, h); iv.setLayoutParams(rlp); return true; } });
{ "pile_set_name": "StackExchange" }
Q: Change size/alpha of markers in the legend box of matplotlib What is the most convenient way to enlarge and set the alpha value of the markers (back to 1.0) in the legend box? I'm also happy with big coloured boxes. import matplotlib.pyplot as plt import numpy as np n = 100000 s1 = np.random.normal(0, 0.05, n) s2 = np.random.normal(0, 0.08, n) ys = np.linspace(0, 1, n) plt.plot(s1, ys, ',', label='data1', alpha=0.1) plt.plot(s2, ys, ',', label='data2', alpha=0.1) plt.legend(bbox_to_anchor=(1.005, 1), loc=2, borderaxespad=0.) A: For the size you can include the keyword markerscale=## in the call to legend and that will make the markers bigger (or smaller). import matplotlib.pyplot as plt import numpy as np fig = plt.figure(1) fig.clf() x1,y1 = 4.*randn(10000), randn(10000) x2,y2 = randn(10000), 4.*randn(10000) ax = [fig.add_subplot(121+c) for c in range(2)] ax[0].plot(x1, y1, 'bx',ms=.1,label='blue x') ax[0].plot(x2, y2, 'r^',ms=.1,label='red ^') ax[0].legend(loc='best') ax[1].plot(x1, y1, 'bx',ms=.1,label='blue x') ax[1].plot(x2, y2, 'r^',ms=.1,label='red ^') ax[1].legend(loc='best', markerscale=40) A: If you name your legend, you can then iterate over the lines contained within it. For example: leg=plt.legend(bbox_to_anchor=(1.005, 1), loc=2, borderaxespad=0.) for l in leg.get_lines(): l.set_alpha(1) l.set_marker('.') note, you also have to set the marker again. I suggest setting it to . rather than , here, to make it a little more visible
{ "pile_set_name": "StackExchange" }
Q: Link Node.js C++ add-on with static library I have a C++ project that is intended to perform some calculations. The C++ code will sit on a server that as back end to a browser based GUI. Node.js seems to be suitable for this job. I've gone through the tutorials and learnt to build C++ code to be used as a nodejs module. For the sake of simplicity, I'd like to compile the C++ code as a static library. I could then write a C++ class which references this library which can then be used in the nodejs environment. The point of this is so I don't have to use node-gyp build to build my entire C++ project. This way I can further develop the C++ code without worrying too much about the front end. To achieve this, I have done the following: Built a simple C++ library as follows. Building this in Visual Studio 2013 to get the .lib file. //MyClass.h #pragma once class MyClass { public: double Multiply(double a, double b) { return a*b; } MyClass(); ~MyClass(); }; Created the C++ object to be used as a nodejs module like so: // myobject.h #ifndef MYOBJECT_H #define MYOBJECT_H #include <node.h> #include <node_object_wrap.h> #include "MyLib\MyClass.h" namespace demo { class MyObject : public node::ObjectWrap { public: static void Init(v8::Local<v8::Object> exports); static MyClass* mycalcobj; private: explicit MyObject(double value = 0); ~MyObject(); static void New(const v8::FunctionCallbackInfo<v8::Value>& args); static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args); static v8::Persistent<v8::Function> constructor; double value_; }; } // namespace demo #endif and the cpp file // myobject.cpp #include "myobject.h" //#include "worker.h" namespace demo { using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; Persistent<Function> MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init(Local<Object> exports) { Isolate* isolate = exports->GetIsolate(); // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); constructor.Reset(isolate, tpl->GetFunction()); exports->Set(String::NewFromUtf8(isolate, "MyObject"), tpl->GetFunction()); } void MyObject::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); args.GetReturnValue().Set(cons->NewInstance(argc, argv)); } } //define functions here void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder()); double x = obj->value_; mycalcobj = new MyClass(); x=mycalcobj->Multiply(2, x); obj->value_= x; args.GetReturnValue().Set(Number::New(isolate, obj->value_)); } } // namespace demo Create the main cpp file to initialise #include <node.h> #include "myobject.h" namespace demo { using v8::Local; using v8::Object; void InitAll(Local<Object> exports) { MyObject::Init(exports); } NODE_MODULE(addon, InitAll) } // namespace demo The binding.gyp file is defined as: { "targets": [ { "target_name": "cpphello", "sources": [ "cpphello.cpp", "myobject.cpp"], "libraries": [ "D:/East101/Adri/javascript/socketio/cpplib/build/x64/Debug/MyLib"] } ] } Build the project using node-gyp configure build I get the following messages: MyLib.lib(MyClass.obj) : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:ICF' specification [D:\East101\Adri\javascript\socketio\cpplib\build\cpphello.vcxproj] LINK : warning LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs;use /NODEFAULTLIB:library [D:\East101\Adri\javascript\socketio\cpplib\build\cpphello.vcxproj] myobject.obj : error LNK2001: unresolved external symbol "public: static class MyClass * demo::MyObject::mycalcobj" (?mycalcobj@MyObject@demo@@2PEAVMyClass@@EA) [D:\East101\Adri\javascript\socketio\cpplib\build\cpphello.vcxproj] D:\East101\Adri\javascript\socketio\cpplib\build\Release\cpphello.node : fatal error LNK1120: 1 unresolved externals [D:East101\Adri\javascript\socketio\cpplib\build\cpphello.vcxproj] I need some assistance to either fix this error and make it work as I envision it or let me know if there's a better way. I'm quite new to C++ and coding in general so I may just be approaching this wrong. A: C++ is a Little bit different than Java etc... If you declare a static member, you Need to define it in the CPP file. Think like this: a normal member variable is allocated when you instantiate an object. But a static member variable exists from the beginning. So you Need to define it somewhere to actually allocate Memory for it. You can resolve it if you put the following in your cpp file: namespace demo { MyClass* MyObject::mycalcobj; //... (e.g. have a look here or here)
{ "pile_set_name": "StackExchange" }
Q: Deactivating pass from Apple wallet I'm trying to implement functionality which will send push notification for pass deactivation/cancellation. But I can't find any word about it in apple/android documentation. Can any one suggest a solution how to deactivate pass? A: You cannot directly deactivate or delete a pass. But you can render it 'useless'. When we invalidate a pass, we remove locations, beacons and the barcode from pass.json. We also remove webServiceURL and authenticationToken to remove the ability for the pass to update in the future. However - you have to bear in mind that there may be stale versions of the pkpass bundle floating around in cyberspace. You should ideally have your server set up to respond to web service calls if a legacy version of the pass is installed on a device and replace with the invalidated version.
{ "pile_set_name": "StackExchange" }
Q: Count PWM Pulses fed into Stepper Motor FET Driver I am trying to (accurately) count the number of pulses fed to a stepper motor driver TI DRV8711. This driver "converts" one rising edge, depending on the settings, to a full step or microstep. The MCU I am using to generate those PWM pulses is a Freescale MPC5602D. The pulse frequency is going to be less than 30kHz per stepper motor. The application I am using this device for is position control with a stepper motor. This requires accurate knowledge of the steps taken (given the stepper motor does not stall). How are those kind of drivers normally driven? Using a regular GPIO pin that is asserted in a timer interrupt routine or via PWM? I want to avoid cramming the main loop with asserting and deasserting a GPIO pin. (I have to control 5+ stepper motors simultaneously) Counting the PWM pulses sent to the driver is trivial with a regular GPIO pin. On the other hand, how is one going to approach the problem of accurately counting the number of PWM pulses? Is this done by feeding the PWM output back to the MCU and using a counter to count the rising edges? I guess I have to decrease the PWM frequency before I reach the desired number of pulses in order to disable the PWM before the last pulse and thus guaranteeing not to "overshoot" the setpoint. A: I know of three ways to accomplish what you need (and I have used all three). You have mentioned the first two in your comment. Having an ISR count the step-pulses is the simplest. The ISR need only increment or decrement a position counter. In the 8-bit micros that I use, such an ISR would take less than a microsecond (although I code in assembly language, not C, on that MCU). It shouldn't be much overhead on any MCU. The second way is to bring the step pulse into a counter. That could be difficult to manage if your motor runs in both directions, as you need to increment sometimes and decrement others (or just know which direction the count is in relation to). I used this method back in the 80's when counter/timer chips were typically used for motion control. The most efficient way to control a stepper is with a separate rate-generator circuit, controlled by the MCU. A simple way to build one is to use the 7497 rate-multiplier chip. Each 7497 is six-bits, and you cascade them to get your desired resolution. However, their output pulse stream is not very even, which can cause instability in some applications (it can be filtered, however). A better technique is the adder/accumulator method, which gives a very clean output pulse stream, and is easily multiplexed to drive multiple motors (if you need that). I've had some 32-axis systems that used this approach. The Adder/accumulator (and the mux) fits very nicely in an FPGA. The big advantage of a rate-generator is the simplicity of the software. The rate-generator gives you an interrupt at a fixed rate, which is your update period. In that ISR you simply load the number of steps you want executed in the next period. The update interrupts can be relatively infrequent, so overhead is low. The position is easy to maintain - you just add the value you load into the rate generator to your position counter. The velocity is easily controlled because it is in direct proportion to the number of steps you load into the rate-generator. Acceleration is easy to control as well - just add/subtract a fixed value on each update. If you have multiple motors, you would update them all in the same ISR. (whew) I'm sorry if that was too long-winded.
{ "pile_set_name": "StackExchange" }
Q: Duda sobre el uso de Threads, AsyncTask y Handler En este código hacen uso de threads, handlers y AsyncTask, lo que no entiendo es porque se hace uso de los 3 y no solo de threads o handlers, ¿Cual es la diferencia?, En el código tengo comentado las razones y el porque se usaban desde mi perspectiva, pero todavía estoy muy confundido import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Wifi_Information extends AppCompatActivity implements View.OnClickListener { private TextView infoview; EditText e1; EditText e2; TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wifi__information); Button getinfo = (Button) findViewById(R.id.bwifiinfo); getinfo.setOnClickListener(this); e1 = (EditText) findViewById(R.id.editText2); e2 = (EditText) findViewById(R.id.bmensaje); tv = (TextView) findViewById(R.id.textView); Thread mythread = new Thread(new MyServer()); mythread.start(); infoview = findViewById(R.id.infoView); } //Esta clase lo que hace es simplemente crear el servidor //Y ponerlo disponible //Runnable solo es una interfaz que necesita para instanciar un hilo para contenerlo class MyServer implements Runnable { ServerSocket ss; Socket mysocket; DataInputStream dis; String message; Handler handler = new Handler(); @Override public void run() { try { ss = new ServerSocket(8080); //Nos sirve para ejecutar una accion especifica desde un hilo que estemos ejecutando sobre un view //Aqui no entiendo porque uso ese handler handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Esperando al cliente", Toast.LENGTH_LONG).show(); } }); while (true) { //El codigo se queda en la siguiente linea hasta que una conexion a nuestro servidor se estableca mysocket = ss.accept(); dis = new DataInputStream(mysocket.getInputStream()); message = dis.readUTF(); handler.post(new Runnable() { @Override public void run() { tv.append("ANDROID:" + message); tv.append("\n"); } }); } } catch (IOException e) { e.printStackTrace(); } } } //La clase async task nos permite crear acciones en el hilo principal, pero no acceder a sus componentes //ente los caracteres <> ponemos los tipos de variables que maneja y devuelve //datos que pasaremos al comenzar la tarea, parametros que necesitareos al actualizar la Interfaz+ //Dato que devolveremos una vez terminada la tarea //Usamos async task para poder actualizar la interfaz //Porque la interfaz no acepta llamadas desde otros hilos que no sea el suyo //Solo para tareas mas pequeñas //Y no entiendo porque para esta operacion uso async task class BackgroundTask extends AsyncTask<String, Void, String> { Socket s; DataOutputStream dos; String ip, message; @Override //Esto es un hilo en segundo plano //Se encarga de realizar la tarea en segundo plano protected String doInBackground(String... params) { ip = params[0]; message = params[1]; //El ip es la direccion ip del servidor y el puerto al cual esta siendo excuchado try { //Aqui el socket recibe de parametros el ip de destino y el puerto del servidor s = new Socket(ip, 8080); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF(message); dos.close(); } catch (IOException E) { E.printStackTrace(); } return null; } } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void GetWifiInformation() { infoview.setText(" "); WifiManager wifimng = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifimng.getConnectionInfo(); if (isWifiConected()) { infoview.append("SSID: " + wifiInfo.getSSID() + "\n"); infoview.append("BSSID(ACCESS POINT): " + wifiInfo.getBSSID() + "\n"); infoview.append("LINK SPEED: " + String.valueOf(wifiInfo.getLinkSpeed()) + "\n"); //No funciona en android M o superior infoview.append("YOUR MAC ADDRESS: " + this.getMacAddress() + "\n"); infoview.append("IP ADDRESS: " + getIpAddress() + "\n"); infoview.append("DNS 1: " + getDns(1) + "\n"); infoview.append("DNS 2: " + getDns(2) + "\n"); infoview.append("CHANNEL: " + getChannel(wifiInfo.getFrequency())); } else { Toast.makeText(this, "NO WIFI CONECTION", Toast.LENGTH_LONG).show(); } } @Override public void onClick(View view) { switch (view.getId()) { case (R.id.bwifiinfo): { BackgroundTask b = new BackgroundTask(); //Verificar que el ip sea el mismo b.execute(e1.getText().toString(), e2.getText().toString()); break; } default: { break; } } } } A: En la clase MyServer: class MyServer implements Runnable { ... @Override public void run() { ... handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Esperando al cliente", Toast.LENGTH_LONG).show(); } }); } } Si no se utilizara el handler para mostrar el Toast se arrojaria una excepcion del tipo: java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare() Al ser ejecutado a traves de un handler el codigo se ejecuta en el Looper asociado al thread y el error no ocurre. Mas abajo no era necesario utilizar AsyncTask para la comunicacion con sockets, se pudo haber utilizado tambien un thread, no hay interaccion alguna con la interfaz de usuario.
{ "pile_set_name": "StackExchange" }
Q: does a runonce command exist to limit command execution Does this command exist for Linux? runonce --dampen 300 echo "hello" The command would take a command to run and optional criteria to limit of frequently it is executed. The option dampen says wait 300 milliseconds and then run the command. Any other executions of this command get coalesced into a single run. This allows you to collapse events in a generic way and combine their execution. if you ran runonce --dampen 300 echo "hello" runonce --dampen 300 echo "hello" runonce --dampen 300 echo "hello" From three different sub-shells at roughly the same time, the first one would live for 300 milliseconds and print hello. The other two would return immediately and do nothing. If this exists, what is the name of the tool or a link to it's project page? A: A possible solution, somehow taken from flock man page, would be: #!/bin/sh # name me 'runonce' timeout="$1"; shift command="$1"; shift hash=$(echo "$command" "$@" | md5sum) ( flock -xw0 3 || exit sleep "$timeout" "$command" "$@" ) 3>"/tmp/$hash" Example usage: runonce 10 echo "hello" where 10 is a number of seconds (not milliseconds). EDIT: introduced hashing on commad+parameters
{ "pile_set_name": "StackExchange" }
Q: Sync LINQ-to-SQL DBML schema with SQL Server database After creating a SQL Server 2008 database, I made a Linq-to-SQL schema in Visual Studio. Next, in the .dbml visual editor (in Visual Studio 2010), I added PK-to-FK and PK-to-PK associations to the schema. How do I copy those associations that I created in Visual Studio over to the database? In other words, how do I sync with the DB? A: Linq-to-SQL is a great tool, but never ever rely on it to update the schema. Always apply schema changes through upgrade SQL scripts that use DDL CREATE/ALTER/DROP statements to change the deployed schema from the on-disk version to the current version. This way you keep all you schema changes under version control as source text files, you can upgrade from any past version to the current application version and you can easily test all your upgrade paths, including upgrading deployments with very large tables. The far worse alternative is to use SQL compare tools that can diff your desired schema from your deployed schema, like vsdbcmd. This may work on trivial deployments, but copying and renaming tables of millions of records will quickly show it's ugly downside. What you absolutely cannot do is rely on the .dbml file as the 'master' copy of your schema. This is a little detail usually omitted by the Linq-to-SQL advocates, one that you discover usually when you attempt to deliver v2 of your application and realize you have no upgrade tool set.
{ "pile_set_name": "StackExchange" }
Q: NHibernate AliasToBean transformer associations I'm trying to use the following statement to get an entity with the fields I'm after: retVal = session.CreateCriteria(typeof(MyEntity)) .CreateAlias("MyEntityProperty", "MyEntityProperty") .Add(Restrictions.Eq("MyEntityProperty.Year", year)) .SetProjection( Projections.Distinct( Projections.ProjectionList() .Add(Projections.Property("Property1"), "Property1") .Add(Projections.Property("Property2"), "Property2") .Add(Projections.Property("MyEntityProperty.RegisteredUser"), "MyEntityProperty.RegisteredUser") .Add(Projections.Property("MyEntityProperty.CompanyInfo"), "MyEntityProperty.CompanyInfo") ) ) .SetResultTransformer(Transformers.AliasToBean(typeof(MyEntity))) .List<MyEntity>() .Cast<BaseMyEntity>(); MyEntity is the entity I want to return, and MyEntityProperty is a property of MyEntity that is another entity (of type MyEntityProperty). The error I get is Could not find a setter for property 'MyEntityProperty.RegisteredUser' in class 'MyEntity' Is the AliasToBean transformer not able to handle sub entities? Or is there something more I need to do to make it work? A: There is my master piece... which I'm using to transform any level of projections depth. Take it and use it like this: .SetResultTransformer(new DeepTransformer<MyEntity>()) It could be used for any ValueType properties, many-to-one references and also for dynamic objects... public class DeepTransformer<TEntity> : IResultTransformer where TEntity : class { // rows iterator public object TransformTuple(object[] tuple, string[] aliases) { var list = new List<string>(aliases); var propertyAliases = new List<string>(list); var complexAliases = new List<string>(); for(var i = 0; i < list.Count; i++) { var aliase = list[i]; // Aliase with the '.' represents complex IPersistentEntity chain if (aliase.Contains('.')) { complexAliases.Add(aliase); propertyAliases[i] = null; } } // be smart use what is already available // the standard properties string, valueTypes var result = Transformers .AliasToBean<TEntity>() .TransformTuple(tuple, propertyAliases.ToArray()); TransformPersistentChain(tuple, complexAliases, result, list); return result; } /// <summary>Iterates the Path Client.Address.City.Code </summary> protected virtual void TransformPersistentChain(object[] tuple , List<string> complexAliases, object result, List<string> list) { var entity = result as TEntity; foreach (var aliase in complexAliases) { // the value in a tuple by index of current Aliase var index = list.IndexOf(aliase); var value = tuple[index]; if (value.IsNull()) { continue; } // split the Path into separated parts var parts = aliase.Split('.'); var name = parts[0]; var propertyInfo = entity.GetType() .GetProperty(name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); object currentObject = entity; var current = 1; while (current < parts.Length) { name = parts[current]; object instance = propertyInfo.GetValue(currentObject); if (instance.IsNull()) { instance = Activator.CreateInstance(propertyInfo.PropertyType); propertyInfo.SetValue(currentObject, instance); } propertyInfo = propertyInfo.PropertyType.GetProperty(name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); currentObject = instance; current++; } // even dynamic objects could be injected this way var dictionary = currentObject as IDictionary; if (dictionary.Is()) { dictionary[name] = value; } else { propertyInfo.SetValue(currentObject, value); } } } // convert to DISTINCT list with populated Fields public System.Collections.IList TransformList(System.Collections.IList collection) { var results = Transformers.AliasToBean<TEntity>().TransformList(collection); return results; } }
{ "pile_set_name": "StackExchange" }
Q: Enthusiastic about learning to play chess Is there a quick way to learn to play chess? How did you get started playing chess? A: If you really have nobody that can teach you chess, you can get the rules and some basic advice from the Wikibook, and for playing you can choose from a lot of free chess programs (e.g. Arena) or websites (e.g. chess tempo). Once you have some basic skills, you can try to play against humans as well (e.g. on chess cube). But it's definitely more fun if you find someone in real life to learn from and to play with... A: Find a good player who can teach you the rules and the basics, and then play with him. Playing is surely the easiest (and the most enjoyable) way to learn a game like chess: you'll improve quickly, even if at first you probably will get beaten very often. Then teach chess yourself to some friend of yours, or play with some beginner: this way you may play games with no difference of level (it can be frustrating losing every single game to a more experienced player!). After that you may try starting playing online, in beginner's rooms of many sites. I'll suggest you to find a chess club near you, if there's any: you'll meet people with same passion as yours, and chess will become even more fun. As a final advice, after having mastered the rules and played some games (20 to 100 more or less, it depends on you) go and read a beginner strategy-tactics book, there's plenty of them. Find some forum, and resources on the Net. Just like this site. :)
{ "pile_set_name": "StackExchange" }
Q: Data reader already open Have already looked questions similar to mine but none of them works for me this is my code dbconn = New SqlConnection dbconn.ConnectionString = ("Data Source=JENELIE\SQLEXPRESS;Initial Catalog=feeding_monitoring_system;User ID=sa;Password=Jenelie19; MultipleActiveResultSets = true") Dim reader As SqlDataReader Dim sda As New SqlDataAdapter Dim ds As New DataSet() Try dbconn.Open() Dim sql As String sql = "select Count (Gender) as NumberofStudent, Gender from Student_Info Group by Gender" dbcomm = New SqlCommand(sql, dbconn) reader = dbcomm.ExecuteReader sda.SelectCommand = dbcomm sda.Fill(ds, "Student_Info") Catch ex As SqlException MessageBox.Show(ex.Message) Finally dbconn.Dispose() End Try Then at sda.Fill(ds, "Student_Info") an error happens A: You dont use that reader at all, so i don't understand your code. You want to fill the DataSet with the DataAdapter, then this is needed (always use Using): Dim ds As New DataSet() Using dbconn As New SqlConnection("Data Source=JENELIE\SQLEXPRESS;Initial Catalog=feeding_monitoring_system;User ID=sa;Password=Jenelie19;MultipleActiveResultSets = true") Dim sda = New SqlDataAdapter("select Count (Gender) as NumberofStudent, Gender from Student_Info Group by Gender", dbconn) Try sda.Fill(ds, "Student_Info") ' you dont need to open/close the connection Catch ex As SqlException MessageBox.Show(ex.Message) End Try End Using
{ "pile_set_name": "StackExchange" }
Q: How was debt handled in the change over from the Julian calendar to the Gregorian? I was reading about New Style and Old Style dates, and I thought about the deletion of dates during the transition. From Wikipedia's article on the Gregorian calendar: When the new calendar was put in use, the error accumulated in the 13 centuries since the Council of Nicaea was corrected by a deletion of 10 days. The Julian calendar day Thursday, 4 October 1582 was followed by the first day of the Gregorian calendar, Friday, 15 October 1582 (the cycle of weekdays was not affected). And later, such as in the British colonies in 1752, the prior year was a short 282 days (a deletion of over 80 days). So, how were debts, such as accrued interest loans, fixed/balloon payments, etc handled? If this kind of change were to occur today and suddenly 10 days were deleted and it suddenly went from May 21st to June 1st, I'd have a check of a time making the mortgage payment. Were loan terms adjusted for the new calendar? Or did the government reduce its tax rates temporarily? How did the economies at the time adjust to this? A: Different societies use different days to start the calendar year. Changing the start date of the year is possibly the most simple change to make to a calendar. Thus in medieval Europe it was possible to travel from one year to another by traveling between places that started their calendar years at different dates. In England the calendar years started on March 25th from about 1200 AD. Thus March 24, 1250, would be followed in England by March 25, 1251, and 12 months later there would be March 1 to March 24, 1251, followed by March 25, 1252. England changed the start of the calendar year to January 1 at the same time as adopting the Gregorian calendar, thus making one year a few months shorter. Added 05-15-2017. There were, however, legitimate concerns about tax and other payments under the new calendar. Provision 6 (Times of Payment of Rents, Annuities) of the Act stipulated that monthly or yearly payments would not become due until the dates that they originally would have in the Julian calendar, or in the words of the Act "[Times of Payment of Rents, Annuities] at and upon the same respective natural days and times as the same should and ought to have been payable or made or would have happened in case this Act had not been made". 1https://en.wikipedia.org/wiki/Calendar_(New_Style)_Act_17501 http://www.legislation.gov.uk/apgb/Geo2/24/23/contents2 A: While I doubt there was much debt involving monthly payments as compared to today, it is known that (any) calender reform caused a lot of confusion that even today confounds historians. All legal documents were impacted and there even were protests where people reclaimed the days lost as they were believed to shorten their lives. Theoretically if your debt was due between September 3 and 14 in the Britain of 1752 you'd be off for free as these days never existed. In practice I think that did not happen at all as failure to repay your debts made you a felon and punishment was harsh, the law being very much on the side of the creditor. In the end I expect people just muddled through with the courts having a field day. References: http://www.legislation.gov.uk/apgb/Geo2/24/23/contents https://en.wikipedia.org/wiki/Dual_dating https://en.wikipedia.org/wiki/Promissory_note https://en.wikipedia.org/wiki/History_of_bankruptcy_law http://mentalfloss.com/article/51370/why-our-calendars-skipped-11-days-1752
{ "pile_set_name": "StackExchange" }
Q: Find flow of function over polygon The problem: Evaluate $\displaystyle\int_{C} (x^{4}+5y^{2})\,dx + (xy-y^{5})\,dy$, where C is the polygonal path joining the vertices $\left[\begin{array}{c}-1\\0\\\end{array}\right], \left[\begin{array}{c}4\\0\\\end{array}\right], \left[\begin{array}{c}6\\4\\\end{array}\right], \left[\begin{array}{c}4\\8\\\end{array}\right], \left[\begin{array}{c}-1\\8\\\end{array}\right], and \left[\begin{array}{c}-1\\0\\\end{array}\right]$, oriented counterclockwise. I know I can use Green's theorem and change the integral to $\int \int_D (y - (10y))dA$, and I think the center of mass is $(2.4 , 4)$ but where do I go from here? A: Reinterpret your double integral, remembering that the $y$-coordinate of the center of mass is given by $$\bar y = \frac{\iint_D y\,dA}{\text{area}(D)}.$$
{ "pile_set_name": "StackExchange" }
Q: How to identify genes? You and me are different at DNA level. My eye color gene is different from yours. So, my DNA is different from yours. How can a scientist identify a certain gene in a chromosome (and its function) if chromosomes are different? How can we talk about "the" human DNA when nobody share the same (except twins)? Please, this is a practical question about how scientists identify genes, not a philosophic one (a question that bother me every time I read about discoveries in genetic) A: First of all: We are not very different on the genetic level - the identity is somewhere around 99.6 to 99.9%. See here for details. If this wouldn't be like this, things like blood transfusions or organ transplants wouldn't work. To identify genes there are different routes. "In the old days" (meaning before the possibility of massive high throughput sequencing or DNA microarrays), genes were usually discovered when they were connected to a disease which had a noticable phenotype. Researchers then tried to find out which protein or pathway was affected and from there went backwards to identify the genetic region. This way of discovery was relatively slow. An example for this kind of identification is the identification of the Mitf gene which is important for the development of pigmentation. If you sequence DNA (doesn't matter here if these are complete genomes or only parts of it) you can identify genes based on homology with already known genes. You can also predict the presence of genes in a certain sequence based on regulatory sequences in the region before the gene (the promoter). These sequences are known and also highly conserved, so this gives a good estimate. Predicted genes usually need to be verified experimentally. What is done today are the so called "genome wide association studies". Here you take a big cohort of people which all share one phenotype (for example blue eye color). Then you take a second group of people which do not show this phenotype and analyse their genomes (usually by sequencing or SNP genotyping). Then you compare the two groups to find the differences. Ideally you can then more or less directly identify a causative mutation which is responsible for the phenotypic difference between the two study groups. This usually needs also to be verified further.
{ "pile_set_name": "StackExchange" }
Q: Not exported function cannot be used or it is Ok? In R package there may be some not exported functions which can only access by package name:::function name. These functions were not exported by the author of the package. Is that mean we cannot access them in anyway because the copyright? What about if I really need to based my work on these functions? Any help please? A: The functions that are not exported are usually internal helper functions for the package. These are not normally meant for general usage. It should be fine to use them, but there may be little or no documentation about them.
{ "pile_set_name": "StackExchange" }
Q: After switching mouse buttons is with xinput, each computer restart resets the settings How does one go about "saving" settings in Ubuntu? I change my buttons on my trackpad using xinput set-button-map 11 3 2 1 (im a lefty) and it works during that session. However, when I reboot my computer, I lose my setting change, and the mouse goes back to being right-handed. How can I get the setting to "stick" indefinately? Thank you! My Machine is: Toshiba Satellite S50-B 64-bit Ubuntu version 16.04 LTS A: This should work to make it stick after log in: Add the following command to startup Applications: /bin/bash -c "sleep 15 && xinput set-button-map 11 3 2 1" Open Dash > Startup Applications > Add, then add the command above. Explanation Adding a command to Startup Applications makes the command run on log in, so this will work from the moment you are logged in. The sleep 15 is to make sure the desktop is fully loaded before the command runs. If you leave it out, the command either breaks, misses target or is overruled by possible local procedures, setting other values. This goes specifically for mouse, keyboard and screen (xrandr) related commands.
{ "pile_set_name": "StackExchange" }
Q: Issue with Java - odd even letters I am working on getting the output from user input to just show odd numbers or even numbers if the first CharAt(0) == 'w', as an example. Does it work by "System.out.println(CharAt(0) + CharAt(2) + CharAt(4))"? I am working on using the Scanner project to get user input and already have the following input part: Scanner input = new Scanner(System.in); System.out.print("Please enter a uncoded string: "); String first = input.nextLine(); input.close(); if (first.charAt(0) == 'u') { first = first.toUpperCase(); } else if (first.charAt(0) == 'l') { first = first.toLowerCase(); } else if (first.charAt(0) == 'o') { first = first.charAt(0) + charAt(2) + charAt (4); } System.out.println("The decoded string is: " + first); Is there a way of just having a formula like (0 + odd)? A: I guess you're trying to "decode" an "encoded" string by examining its prefix char: Scanner input = new Scanner(System.in); System.out.print("Please enter a uncoded string: "); String first = input.nextLine(); input.close(); if (first.charAt(0) == 'u') { first = first.toUpperCase(); } else if (first.charAt(0) == 'l') { first = first.toLowerCase(); } else if (first.charAt(0) == 'o') { StringBuilder sb = new StringBuilder(); for (int i = 0; i < first.length(); i = i + 2) { sb.append(first.charAt(i)); } first = sb.toString(); } else if (first.charAt(0) == 'e') { StringBuilder sb = new StringBuilder(); for (int i = 1; i < first.length(); i = i + 2) { sb.append(first.charAt(i)); } first = sb.toString(); } System.out.println("The decoded string is: " + first); I'm not sure if in the case of the prefix "o" you want this prefix to be included in the result. Edit If you don't like StringBuilder: } else if (first.charAt(0) == 'o') { String str = ""; for (int i = 0; i < first.length(); i = i + 2) { str += first.charAt(i); } first = str; } else if (first.charAt(0) == 'e') { String str = ""; for (int i = 1; i < first.length(); i = i + 2) { str += first.charAt(i); } first = str; }
{ "pile_set_name": "StackExchange" }
Q: Preloaded Core Data Database Not Working I have created a core data database in one application which involved sucking out info from an API and populating a database. I would now like to use it in another app. I have copied the .xcdatamodeld file and NSManagedObject classes across. I have added and imported Core Data framework. I have copied the .sqlite file into my new application's resources as the default database. I am using the following code which is supposed to copy out the default database to the Documents directory and open it so that I may perform queries on it. It is causing the app to crash with no error message, any thoughts on where I'm going wrong? If I was to create a database here using saveToURL, I know the filename would be persistentStore not Trailer.sqlite as per below, is that relevant? Thanks - (void)viewDidLoad { [super viewDidLoad]; // Get URL -> "<Documents Directory>/<TrailerDB>" NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; url = [url URLByAppendingPathComponent:@"TrailerDB"]; UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url]; // Copy out default db to documents directory if it doesn't already exist NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:[url path]]) { NSString *defaultDB = [[NSBundle mainBundle] pathForResource:@"trailerdatabase" ofType:@"sqlite"]; if (defaultDB) { [fileManager copyItemAtPath:defaultDB toPath:[url path] error:NULL]; } } if (doc.documentState == UIDocumentStateClosed) { // exists on disk, but we need to open it [doc openWithCompletionHandler:^(BOOL success) { if (success) [self useDatabase:doc]; if (!success) NSLog(@"couldn’t open document at %@", url); }]; } else if (doc.documentState == UIDocumentStateNormal) { [self useDatabase:doc]; } } A: Ive had another look and I'm not sure what you're doing but this code below is what i do that would answer your question. I check to see if the working database exists and if it doesn't i move it in place from the application bundle and then proceed to load it. I have left the stock comments from the Apple template in as i think they may end up being helpful. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (__persistentStoreCoordinator != nil) { return __persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"workingDataBase.sqlite"]; NSError *error = nil; if (![[NSFileManager defaultManager] fileExistsAtPath:[[self applicationDocumentsDirectoryString] stringByAppendingPathComponent: @"workingDataBase.sqlite"]]){ //database not detected NSLog(@"database not detected"); NSURL * defaultDatabase = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"DefaultData" ofType:@"sqlite"]]; NSError * error; if (![[NSFileManager defaultManager] copyItemAtURL:defaultDatabase toURL:storeURL error:&error]){ // Handle Error somehow! NSLog(@"copy file error, %@", [error description]); } } __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] * Performing automatic lightweight migration by passing the following dictionary as the options parameter: [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return __persistentStoreCoordinator; }
{ "pile_set_name": "StackExchange" }
Q: Building array from string values I have a table that has a column with data stored as comma-separated strings. I need to output the table contents and build an array from these values (don't need any keys). I need to remove duplicates and sort it in alphabetical order. $arr = array(); foreach ($myTable AS $t) { $str = $t->myStr; array_push($arr, $str); } array_unique($arr); asort($arr); I did print_r($arr); Now I see values but they are still an array of strings. Something like this: Array ( [1] => Chinese, Asian Fusion, Food Trucks [0] => Chinese, Asian Fusion, Gluten-Free [2] => Chinese, Barbeque [3] => Dim Sum, Seafood, Soup ) What I would like to see is: Array ('Asian Fusion', 'Barbeque', 'Chinese', 'Food Trucks', 'Gluten-Free'...); A: You have to change this line: array_push( $arr, $str ); in: $arr = array_merge( $arr, explode( ',', $str) ); and this: array_unique( $arr ); in: $arr = array_unique( $arr ); array_push() add the comma-separated string to the array. Using explode() you obtain an array with single values, then you have to merge this array with main array. You can't use array_push() with exploded array, because using it you will obtain a multidimensional array ( [ [Chinese,Asian,...] , [Chinese,Asian,...] ] ). array_unique() doesn't change the original array, but it return the modified array, so you have to catch the result in a variable. Edit: The delimiter must be the complete separation string. So, if your string is like this: Chinese, Asian Fusion, Food Trucks ^ ^ you have to use: $arr = array_merge( $arr, explode( ', ', $str) ); // ^
{ "pile_set_name": "StackExchange" }
Q: tool that shows javascript errors in code While debugging in Console in IE or any other browser, it shows the javascript errors. I was wondering if there are any tools like plunkr or jsfiddle that shows the javascript issues (and i can show the code issues to other users on websites like SO) even when the functionality works fine. For ex. I have created this piece of code in plunkr and it shows the code works as expected, but while debugging in console in browser, it gives errors. Does even plunkr or jsfiddle have this functionality? A: Use Closure Tools from google: https://developers.google.com/closure/ Especially you want Closure Linter, shows also fixes errors: https://developers.google.com/closure/utilities/ Best of luck. (Mark this as answer if this serves your need)
{ "pile_set_name": "StackExchange" }
Q: Thread of SDWebImage's sd_setImage What is the thread of the completion block of SDWebImage's sd_setImage? If I modify the UI from the completion block, should I always wrap that code inside a DispatchQueue.main.async() {}? A: You don't need to use DispatchQueue.main.async() {}, the completion block is always called on the main thread. The parts source code of sd_setImage method:
{ "pile_set_name": "StackExchange" }
Q: Creating a ruler bar in MFC What's the best way to go about creating a vertical and horizontal ruler bars in an SDI app? Would you make it part of the frame or the view? Derive it from CControlBar, or is there a better method? The vertical ruler must also be docked to a pane and not the frame. To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only). It gets repositioned whenever the tree view is resized. A: I would not use control bars. I have no good reason other then (IMOHO) are difficult to get to do what you want - if what you want if something other than a docking toolbar. I would just draw them directly on the View window using GDI calls. I guess I might think about making each ruler its own window, and draw the rulers on their own window. I would then create these two CWnd derived classes in the view and position as child windows. This is good if you want to interact with the mouse on these rulers (easier to sort out what messages are for the rulers).
{ "pile_set_name": "StackExchange" }
Q: Spring xd issue with http-client I have spring xd module with rabbitmq as a transport. My module has http source http client processor which calls a rest url http://x.y.z/test stream create --name cycletest4 --definition "http | http-client --url='''https://x.y.z/test''' --httpMethod=GET | log" http post --data '{ "messageAttribute": { "channelType" : "EML", "contentKey" : "20020", "messageFormat" : "1", "contentSubscriber" : "dmttts", "languageCode" : "en-ca" }, "substitutionKeyValueData" : { "SvcgLOBCd": "CA", "User": "user", "phone": "yyyy, "accountLast": "tttt", "userName": "LP", "Company": "bbbb", "firstName": "Ryan" } }' Now when my rest client throws any exception like 404 or connection time out exception and the message is going back the rabbit queue between http|http-client My understanding was only connection time out exception will be put back queue and any other exception or 200 will move the message to next component it is http-client| log.But when i tried it all exception were put back the queue between http|http-client. Now my usecase was i want to retry all socket time /connection time out exception .any other system exception 50x errors I want to write to log or file sink?How can I achieve this.Basically depending on exception I want to route retry and non retry exception. A: Only 2xx results will go to the log. 4xx and 5xx are considered errors. You will need a custom http-client module to trap the exceptions you consider 'ok' and forward them to the output channel. Something like... <int:service-activator input-channel="input" ref="gw" /> <int:gateway request-channel="toHttp" error-channel="errors" /> <int:chain input-channel="errors" output-channel="output"> <!-- examine payload.cause (http status code etc) and decide whether to throw an exception or return the status code for sending to output --> </int:chain>
{ "pile_set_name": "StackExchange" }
Q: Using method missing in Rails I have a model with several date attributes. I'd like to be able to set and get the values as strings. I over-rode one of the methods (bill_date) like so: def bill_date_human date = self.bill_date || Date.today date.strftime('%b %d, %Y') end def bill_date_human=(date_string) self.bill_date = Date.strptime(date_string, '%b %d, %Y') end This performs great for my needs, but I want to do the same thing for several other date attributes... how would I take advantage of method missing so that any date attribute can be set/get like so? A: As you already know signature of desired methods it might be better to define them instead of using method_missing. You can do it like that (inside you class definition): [:bill_date, :registration_date, :some_other_date].each do |attr| define_method("#{attr}_human") do (send(attr) || Date.today).strftime('%b %d, %Y') end define_method("#{attr}_human=") do |date_string| self.send "#{attr}=", Date.strptime(date_string, '%b %d, %Y') end end If listing all date attributes is not a problem this approach is better as you are dealing with regular methods instead of some magic inside method_missing. If you want to apply that to all attributes that have names ending with _date you can retrieve them like that (inside your class definition): column_names.grep(/_date$/) And here's method_missing solution (not tested, though the previous one is not tested either): def method_missing(method_name, *args, &block) # delegate to superclass if you're not handling that method_name return super unless /^(.*)_date(=?)/ =~ method_name # after match we have attribute name in $1 captured group and '' or '=' in $2 if $2.blank? (send($1) || Date.today).strftime('%b %d, %Y') else self.send "#{$1}=", Date.strptime(args[0], '%b %d, %Y') end end In addition it's nice to override respond_to? method and return true for method names, that you handle inside method_missing (in 1.9 you should override respond_to_missing? instead). A: You might be interested in ActiveModel's AttributeMethods module (which active record already uses for a bunch of stuff), which is almost (but not quite) what you need. In a nutshell you should be able to do class MyModel < ActiveRecord::Base attribute_method_suffix '_human' def attribute_human(attr_name) date = self.send(attr_name) || Date.today date.strftime('%b %d, %Y') end end Having done this, my_instance.bill_date_human would call attribute_human with attr_name set to 'bill_date'. ActiveModel will handle things like method_missing, respond_to for you. The only downside is that these _human methods would exist for all columns.
{ "pile_set_name": "StackExchange" }
Q: Specifying criteria as named range in Excel I have this formula which is working properly: =SUM(COUNTIFS( dataExport.csv!$A:$A, {"itm1","itm2"}, dataExport.csv!$C:$C, [@[TheName]] )) Is there a way to use the array part of the criteria in this line as a named range?: dataExport.csv!$A:$A, {"itm1","itm2"}, If I had a named range – "itms" – which consisted of two cells with values "itm1" and "itm2", would there be a way to refer to it? I realize the array is a constant, and cannot take references, but is there another way to do it? dataExport.csv!$A:$A, ** matches any value from "itms" **, A: When I enter =SUM(COUNTIFS($A:$A,itms,$C:$C,[@TheName])) as an array formula CTRL-SHIFT-ENTER the named range works.
{ "pile_set_name": "StackExchange" }
Q: Wrap elements with new element depending on parent and/or class I have three different div classes: design-box-triple, double, and single. There are multiple divs with the varying classes and they are all float left to be responsive. <div class="collageWidgets"> <div class="design-box-double"></div> <!--width 50%--> <div class="design-box-triple"></div> <!--width 33%--> <div class="design-box-triple"></div> <!--width 33%--> <div class="design-box-triple"></div> <!--width 33%--> <div class="design-box-double"></div> <!--width 50%--> <div class="design-box-double"></div> <!--width 50%--> <div class="design-box-single"></div> <!--width 100%--> <div class="design-box-single"></div> <!--width 100%--> </div> What I want is to use jQuery to check if the div has class with certain conditions then wrap with div row so that it is 100% width and the float:left divs stay visually nice and don't break the flow of the float. Example end result: <div class="collageWidgets"> <div class="row"> <!--width 100%--> <div class="design-box-double"></div> <!--width 50%--> </div> <div class="row"> <!--width 100%--> <div class="design-box-triple"></div> <!--width 33%--> <div class="design-box-triple"></div> <!--width 33%--> <div class="design-box-triple"></div> <!--width 33%--> </div> <div class="row"> <!--width 100%--> <div class="design-box-double"></div> <!--width 50%--> <div class="design-box-double"></div> <!--width 50%--> </div> <div class="row"><!--width 100%--> <div class="design-box-single"></div> <!--width 100%--> </div> <div class="row"><!--width 100%--> <div class="design-box-single"></div> <!--width 100%--> </div> <div class="row"> <!--width 100%--> <div class="design-box-triple"></div> <!--width 33%--> <div class="design-box-triple"></div> <!--width 33%--> <!-- Example missing triple, but won't look messed up because it is wrapped with a row 100% width, display block, and clearfix--> </div> </div><!--End of Collage Widget Div--> Here is the jQuery that I have with double and single working. I am struggling on the triple code. The divs with design-box-triple. Here is my logic thinking: I need to check if the previous object parent has a class="row" && if div has class design-box-triple. If it does, then push that first widget that has design-box-triple into an array. Then check if the next object has design-box-triple class, if not then wrap the triple widget in div class = row. Then I need to check if the first class has design-box-triple, and the next has design-box-triple, then next next has design-box-triple wrap all in a div class = row. But if there are only two divs with class design-box-triple next to each other then wrap that in a row. Here is the code that I have: (function() { var widgetArray = $(".careerCollageWidgets").find(".career-widget"); var prevClass = ''; var prevObject = ''; var prevPrevObject = ''; var tripleArray = []; console.log(widgetArray.length); $(widgetArray).each(function(index, value){ console.log($(this)); var widget = $(this); if (widget.hasClass('design-box-single')){ widget.wrapAll('<div class="row"></div>'); prevClass = 'design-box-single'; } else if (widget.hasClass('design-box-double')){ if(prevClass == 'design-box-double' && !prevObject.parent().hasClass('row')) { //var previousArray = [prevObject, widget]; prevObject.add(widget).wrapAll('<div class="row"></div>'); } else if (!widget.next().hasClass('design-box-double')){ widget.wrapAll('<div class="row"></div>'); } prevClass = 'design-box-double'; } else if (widget.hasClass('design-box-triple')){ tripleArray.push(widget); if (!prevObject.parent().hasClass('row')){ tripleArray.push(widget); console.log(tripleArray); console.log("tripleArray"); //tripleArray.wrap('<div class="row"></div>'); } //else if(prevClass == 'design-box-triple' && !prevObject.parent().hasClass('row')) { // if (!widget.next().hasClass('design-box-triple')){ // prevObject.add(widget).wrapAll('<div class="row"></div>'); // } //} //else if (!widget.next().hasClass('design-box-triple')){ // widget.wrapAll('<div class="row"></div>'); //} prevClass = 'design-box-triple'; } prevObject = widget; }); })(); $('.row').css({'width':'100%', 'display':'block'}); $('.row').addClass('clearfix'); A: http://jsfiddle.net/isherwood/7jpy4/ $('.single').wrap('<div class="row"></div>'); var doubles = $('.double'); for (var i=0; i<doubles.length;) { i += doubles.eq(i).nextUntil(':not(.double)').andSelf() .wrapAll('<div class="row"></div>').length; } var triples = $('.triple'); for (var i=0; i<triples.length;) { i += triples.eq(i).nextUntil(':not(.triple)').andSelf() .wrapAll('<div class="row"></div>').length; } Notice that I broke up your class names to simplify things for this demo. Also, you'd have to put a counter in to prevent stacks of doubles and triples if you ever have more than two or three consecutive, respectively. Inspiration from this question.
{ "pile_set_name": "StackExchange" }
Q: Binding multiple definitions to one "variable" in scheme? I think I read somewhere that you could bind multiple definitions to a single name in scheme. I know I might be using the terminology incorrectly. By this I mean it is possible to do the following (which would be really handy to defining an operator)? I believe I read something like this (I know this is not real syntax) (let () define operator "+" define operator "-" define operator "*" define operator "/")) I want to test another variable against every operator. A: I'm not really sure what you're asking. Do you want a single procedure that can handle different types of arguments? (define (super-add arg1 arg2) (cond ((and (string? arg1) (string? arg2)) (string-append arg1 arg2)) ((and (number? arg1) (number? arg2)) (+ arg1 arg2)) (else (error "UNKNOWN TYPE -- SUPER-ADD")))) (super-add "a" "b") => "ab" (super-add 2 2) => 4 Are you interested in message passing? (define (math-ops msg) ;<---- returns a procedure depending on the msg (cond ((eq? msg 'add) +) ((eq? msg 'sub) -) ((eq? msg 'div) /) ((eq? msg 'multi) *) (else (error "UNKNOWN MSG -- math-ops")))) ((math-ops 'add) 2 2) => 4 ((math-ops 'sub) 2 2) => 0 Also the proper syntax for a let binding: (let (([symbol] [value]) ([symbol] [value])) ([body])) (let ((a 2) (b (* 3 3))) (+ a b)) => 11 It will be very hard to help more than this without you clarifying what it is you are trying to do. EDIT: After your comment, I have a little bit better of an idea for what you're looking for. There is not way to bind multiple values to the same name in the way that you mean. You are looking for a predicate that will tell you whether the thing you are looking at is one of your operators. From your comment it looked like you will be taking in a string, so that's what this is based on: (define (operator? x) (or (string=? "+" x) (string=? "-" x) (string=? "*" x) (string=? "/" x))) If you are taking in a single string then you will need to split it into smaller parts. Racket has a built in procedure regexp-split that will do this for you. (define str-lst (regexp-split #rx" +" [input str]))
{ "pile_set_name": "StackExchange" }
Q: How to inject specific interface implementation using DI in ASP NET Core Hello i have the following problem.I have an interface that is implemented by 2 classes.One of these classes does the real work while the other use the first one mentioned. How can i tell the framework to use a specific implementation of an interface when instantiating a type of object ? I want the controller to get the facaded implementation and not the real one: public interface IDependency{ void Method(); } public class Real:IDependency { public void Method() { } } public class Facade:IDependency { private IDependency dependency; Facade(IDependency dependency) //i want a Real here { this.dependency=dependency; } public void Method()=>dependency.Method(); } public MyController:Controller { private IDependency dependency; MyController(IDependency dependency) //i want the `Facade` here not the `Real` { this.dependency=dependency; } [HttpGet] [Route("[some route]")] public async Task CallMethod() { await this.dependency.Method(); } } As you can see in the above example , i need a Real type of IDependency injected inside my Facade one , while i need a Facade type of IDependency injected in my MyController. How could that be done ? A: Microsoft.Extensions.DependencyInjection doesn't have any means to do this. All you can do is inject all implementations, i.e. via List<IDependency>. Then, you can implement whatever manual logic you'd like to pick and choose from the available options there. If you have any control over these classes, it would be better to simply implement a different interface, to distinguish the two. For example, you could create an IFacadeDependency interface that inherits from IDependency, and then have your Facade class implement that instead. Then, you can inject IFacadeDependency and get exactly what you want.
{ "pile_set_name": "StackExchange" }
Q: error - NullpointException in an android app with DrawerLayout I was trying to create a simple material design interface in android studio. I am getting error at particular line where I am opening drawer. As soon as I click home icon in actionbar (toolbar), the app crashes. Here is the code I tried. public class MainActivity extends AppCompatActivity { public DrawerLayout mDrawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); actionBar.setHomeAsUpIndicator(R.drawable.ic_menu); actionBar.setDisplayHomeAsUpEnabled(true); DrawerLayout mDrawerLayout; mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Snackbar.make(findViewById(R.id.drawer_layout), "I'm a Snackbar", Snackbar.LENGTH_LONG).setAction("Action", new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Snackbar Action", Toast.LENGTH_LONG).show(); } }).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; case R.id.action_settings: return true; } return super.onOptionsItemSelected(item); } } I have tried to change the action of FAB and Home Icon, that is working !! But in normal drawer open with home icon, I get following error. java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference at jani.jigar.designdemo.MainActivity.onOptionsItemSelected(MainActivity.java:67) I have seen same cases, but they didn't initialized object. I did in the beginning. I can't find the error. Any help will be appreciated. A: This is happening because you're aliasing your activity's instance variable mDrawerLayout in the onCreate method with a local variable. And since scoping in Java goes from the inside out, you're never setting the reference of mDrawerLayout outside of the method. So all you need to in order to fix your issue is to remove DrawerLayout mDrawerLayout; from onCreate.
{ "pile_set_name": "StackExchange" }
Q: How to read a structure with a size that isn't a multiple of 4 I'm reading structure in file *stl, but the structure is: typedef struct { float x; float y; float z; } point; typedef struct { point normal_vector; //12 bytes point p1; //12 bytes point p2; //12 bytes point p3; //12 bytes short int notuse; //2 bytes } triangle; sizeof(triangle) is 52—12+12+12+12+2+...2 (I don't know where the last 2 comes from?) The size of each unit in file *stl is 50 (not multiple of 4). How can I reduce the size of structure to read file (from 52 to 50)? Thank you. A: A way to be preferred over reading the struct - whose memory layout can vary, as you see - as it is and reducing its size could be the way to go. That said, you can read the file in large blocks and cut the data in the parts you need. Then you read out field for field and put the data into your target array. Something like float read_float(void ** data) { float ** fp = data; float ret = **fp; (*fp)++; return ret; } point read_point(void ** data) { point ret; ret.x = read_float(data); ret.y = read_float(data); ret.z = read_float(data); return ret; } int16_t read16(void ** data) { int16_t ** i16p = data; int16_t ret = **i16p; (*i16p)++; return ret; } point read_triangle(void ** data) { triangle ret; ret.normal_vector = read_point(data); ret.p1 = read_point(data); ret.p2 = read_point(data); ret.p3 = read_point(data); ret.notuse = read_int16(data); // using short int is not portable as well as its size could vary... return ret; } void * scursor = source_array; // which would be a char array while (scursor < source_array + sizeof(source_array)) { // make sure that there are enough data present... target[tcursor++] = read_triangle(&scursor); // the scursor will be advanced by the called function. } This way could as well - with certain enhancements - be used to keep e. g. the endianness of your numbers the same - which would be preferrably big endian on files intended to be interchanged between platforms. The changes to read16 would be small, the changes to read_float a bit bigger, but still doable.
{ "pile_set_name": "StackExchange" }
Q: Multipe rewrite urls : domain.tld/posts.php?blog=&id= to domain.tld/posts/blog/id How i can rewrite my urls from this domain.tld/posts.php?blog=&id= to this one: domain.tld/posts/blog/id A: Build your url in script to form: /posts/blog/id and rewrite this with mod_rewrite. content of .htaccess file: <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([0-9a-zA-Z\-]+?)/([0-9a-zA-Z\-]+?)?/([0-9a-zA-Z\-]+?)?$ $1.php?blog=$2&id=$3 </IfModule> for example: for http://so.localhost/posts/YourBlog/YourID and posts.php with code: <?php var_dump($_GET); Result: array (size=2) 'blog' => string 'YourBlog' (length=8) 'id' => string 'YourID' (length=6) I hope I helped.
{ "pile_set_name": "StackExchange" }
Q: PHP + SSH: Interactive Shell I am using phpseclib to run commands via SSH on another server. I am currently using the Interactive Shell example (See Here) If I want to send a command, I use $ssh->write("ls -la\n"); and then I run $ansi->appendString($ssh->read()); echo $ansi->getScreen(); to see the screen output. Is there a way for me to run commands from a form where can I use it like a web-based console? A: Yes why not! Then you have to implement a form and send the command to your server. But there is a much easier way. Perhaps with ajax and fetch the return from your command line. http://www.web-console.org/ There are a lot of projects doing exact that. When you build that on your own you have to look at security and much more.
{ "pile_set_name": "StackExchange" }
Q: Why is the Principle of Superposition true in EM? Does it hold more generally? In the theory of electromagnetism (EM), why is the principle of superposition true? Can we read it off from Maxwell's equations directly? Does it have any limit of applicability or is it a fundamental property of nature? A: The principle of superposition comes from the fact that equations you solve most of the time are made of Linear operators (just like the derivative). So as long as you are using these operators you can write something like $$ \mathcal L\cdot \psi = 0$$ where $\mathcal L$ is a linear operator and, let say, $\psi$ is a function that depends on coordinates that $\mathcal L$ is acting on. The superposition principle is the same that saying this $$\mathcal L \cdot \left(\sum_i \psi_i \right) = \mathcal L\cdot\psi_1 + \mathcal L\cdot\psi_2 + ... = 0$$ holds. An example when it doesn't would be, for example... $$\mathcal L^2 \cdot\left(\sum_i \psi_i\right) \neq \mathcal L^2\cdot\psi_1 + \mathcal L^2\cdot\psi_2 + ...$$ in general (for the Laplacian in Euclidean space it is equal to). So then, the question is if Maxwell equations are linear. And they are because they are made up with this kind of operators. For instance, Gauss law for two different electric fields can be written as one $$ \nabla \cdot \vec{E}_1 = \rho_1/\varepsilon \quad; \quad \nabla \cdot \vec{E}_2 = \rho_2/\varepsilon $$ $$ \nabla \cdot \overbrace{\left(\vec{E}_1 + \vec{E}_2\right)}^{\vec{E}} = \frac{\overbrace{\rho_1 + \rho_2}^{\rho_T}}{\varepsilon} \Rightarrow \boxed{\nabla \cdot\vec E = \frac{\rho_T}{\varepsilon}} $$ just because $\nabla$ is a linear operator. A: It is true up to very high filed strengths. For too high strengths the field itself is not stable, it can create real pairs. It is like a limit on a field strength in a capacitor. The capacitor dielectric can break. EDIT: Classical Maxwell equations are linear indeed so the principle of superposition is implemented into them. But break of a dielectric can be introduced too as a resistance depending on the field strength. Thus one can make the Maxwell equation non-linear starting from some threshold strength. In fact, the dielectric break or capacitor discharge due to cold electron emission (classical non linearity) occurs "well before" creating electron-positron pair in vacuum. A: Within the realm of Maxwell's equations, the principle of superposition is exactly true because Maxwell's equations are linear in both the sources and the fields. So if you have two solutions to Maxwell's equations for two different sets of sources then the sum of those two solutions will be a solution to the case where you add together the two sets of sources. This will only break down when Maxwell's equations break down, for example, when the field strengths are so high that pair production becomes significant. In that case the quantum field theory of Quantum Electrodynamics (QED) would be required. Now, quantum theories are also linear, at least as far as the quantum wave function is concerned, however the probabilities that quantum theories predict depend on the magnitude of the wave function, so in that sense they are nonlinear, and therefore superposition will not apply to the results.
{ "pile_set_name": "StackExchange" }
Q: What I said the nuance of the phrase きっと青春が聞こえる? In one of my favorite μ's songs, the title is きっと青春が聞こえる. My problem is with the 青春. I think the title means something like "I can surely hear the youth" but that sounds kind of strange. Is there something I'm missing? A: Yep, I agree, as a native Japanese it does sound a little off, but then, this is a song, so the bar is a little lower. I can only imagine that the song is set in the context in which this sounds OK, for example, you were a member of a brass band and every time you hear a trombone, that reminds you of the youth, that kind of thing.
{ "pile_set_name": "StackExchange" }
Q: Building MySQL from source changes Makefile due to cmake I am working on MySQL optimization with another researcher and we are using git for version control. The problem is that each of us has to compile those sources on separate machines and running cmake . generates different versions of makefile on our machine. If we think about the following cases 1. A changes source 2. A runs cmake, builds the source, and test performance 3. B pulls the code change 4. B changes source, runs cmake and builds the source After the step 4, B will have a different version of Makefile and files such as cmake_install.cmake that depend on users and user paths. For example, some of the files have the following diffs. # The program to use to edit the cache. -CMAKE_EDIT_COMMAND = /usr/local/bin/ccmake +CMAKE_EDIT_COMMAND = /usr/bin/ccmake # The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/dcslab/userA/mysql/mysql-5.6.21-original +CMAKE_SOURCE_DIR = /home/dcslab/userB/mysql-5.6.21-original # The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/dcslab/userA/mysql/mysql-5.6.21-original +CMAKE_BINARY_DIR = /home/dcslab/userB/mysql-5.6.21-original These are all user-dependent paths generated by cmake commands. The direct way to resolve this conflict is to untrack Makefiles or any file generated by cmake after initially committing them. I am wondering if there is any better and legit way of managing projects using cmake for more than one user. Thanks for your help in advance! A: Files generated by CMake are machine-dependent, so they will not work on any machine except one where they has been generated. Because of that, they are useless on for others and there is no needs to track them in git. There are two ways for achive this: Tune gitignore for ignore files, generated by CMake, on commit. Patterns for such files are relatively simple and can be found by googling. Disadvantage of this approach is that files, generated by project's CMake scripts (configure_file, add_custom_command) will not be automatically ignored and will require explicit notion in gitignore Perform out-of-source builds, that is not run cmake from source directory. CMake generates additional files only in build directory, correct project's CMake scripts also should follow this rule. So git repo will be clean without any gitignore patterns. It is common practice to perform out-of-source build in ./build subdirectory of source directory. In this case you can add /build/** to gitignore, and everything will work.
{ "pile_set_name": "StackExchange" }
Q: WPF TextBox Caret Disappearing I'm developing a WPF application that has TextBox components. I'm having a problem with the caret of the text boxes. It seems that, depending on the location of the TextBox itself, the caret disappears on certain specific locations Caret showing: Caret disappears: Caret returns: The TextBox style is very simple: <Style TargetType="{x:Type TextBox}" x:Key="FormTextBox"> <Setter Property="Width" Value="464"/> <Setter Property="Height" Value="74"/> <Setter Property="HorizontalAlignment" Value="Left"/> <Setter Property="FontFamily" Value="Microsoft Sans Serif"/> <Setter Property="FontSize" Value="43.2"/> <Setter Property="MaxLength" Value="50"/> </Style> I tried even setting the font to Courier New which is monospace font, same thing. A: The problem seems to be common (1, 2) with the scale transformation, which is being applied by the behavior you mentioned in comments. mainElement.LayoutTransform = scaleTransform; And from MSDN, there's no effective solution for this issue. So, if you want to support multi-resolution, I would recommend ViewBox; simple, and do the job.
{ "pile_set_name": "StackExchange" }
Q: How to get bundle for a struct? In Swift, you can call let bundle = NSBundle(forClass: self.dynamicType) in any class and get the current bundle. If you NSBundle.mainBundle() this will fail getting correct bundle when for example running unit tests. So how can you get the current bundle for a Swift struct? A: The best solution here depends on what you need a bundle for. Is it to look up resources that exist only in a specific app, framework, or extension bundle that's known to be loaded when the code you're writing runs? In that case you might want to use init(identifier:) instead of dynamically looking up the bundle that defines a certain type. Beware of "follows the type" bundle lookups. For example, if a framework class Foo uses NSBundle(forClass: self.dynamicType) to load a resource, a subclass of Foo defined by the app loading that framework will end up looking in the app bundle instead of the framework bundle. If you do need a "follows the type" bundle lookup for a struct (or enum), one workaround that might prove helpful is to define a class as a subtype: struct Foo { class Bar {} static var fooBundle: NSBundle { return NSBundle(forClass: Foo.Bar.self) } } Note there's nothing dynamic here, because nothing needs to be — every Foo comes from the same type definition (because structs can't inherit), so its static type matches its dynamic type. (Admittedly, an NSBundle(forType:) that could handle structs, enums, and protocols might make a nice feature request. Though I imagine it could be tricky to make it handle extensions and everything...) A: Updated for Swift 3.0+: struct Foo { class Bar {} static var fooBundle: Bundle { return Bundle(for: Foo.Bar.self) } } A: extension Bundle { static var current: Bundle { class __ { } return Bundle(for: __.self) } }
{ "pile_set_name": "StackExchange" }
Q: php try catch wsod I have an issue. When I run: try { $as ->setForename($_POST['fname']) ->setSurname($_POST['sname']) ->setEmail($_POST['email']) ->setUser($_POST['user']) ->setPass($_POST['pw']) ->setPhone($_POST['tel']) ->setMobile($_POST['mob']) ->setJob($_POST['job']) ->setAuth($_POST['auth']) ->addProcess(); } catch (Exception $e) { echo $e; } I get "white screen of death" however when I use: $as ->setForename($_POST['fname']) ->setSurname($_POST['sname']) ->setEmail($_POST['email']) ->setUser($_POST['user']) ->setPass($_POST['pw']) ->setPhone($_POST['tel']) ->setMobile($_POST['mob']) ->setJob($_POST['job']) ->setAuth($_POST['auth']) ->addProcess(); It all works fine. I am really confused please help, thanks in advance. A: The try-catch block seems to be fine, try putting these lines on top of your script to see the possible error: ini_set('display_errors', true); error_reporting(E_ALL);
{ "pile_set_name": "StackExchange" }
Q: How to track Window close of SmartGwt I am developing a SDI web app using SmartGwt. In the main window, I want to popup a Window, when a button is clicked. However when the popup Window is closed, the main window is not able to trap the event. Is there any good way to do that? IButton showPopupButton = new IButton(); showPopupButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { Window popup = new Window(); popup.show(); SC.say("The popup was closed"); // UNEXPECT: It shows up just after the popup is shown. } }); Currently, I can declare an argument BooleanCallback into the constructor, so that when the popup window is going to be closed, it should call the callback function. I have a solution: IButton showPopupButton = new IButton(); showPopupButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { Window popup = new MyWindow(new BooleanCallback() { public void execute(Boolean value) { SC.say("The popup was closed"); } }); popup.show(); } }); But if someone else writes a plugin for me and does not using such "callback function" into its constructor, how to track Window close event? I tried to register a VisiblityChangedHandler to the popup window, but it does not work. A: Window closing handler event catch closing event, Try with Window.addWindowClosingHandler(new ClosingHandler() { @Override public void onWindowClosing(ClosingEvent event) { } });
{ "pile_set_name": "StackExchange" }
Q: Working Rpi Hotspot but can't get ethernet/internet to work I've set up my pi as a wireless hotspot and am trying to share my Mac's internet via ethernet. The hotspot side of things works ok and if I have my mac's wifi (or even internet sharing) turned off I can ping and ssh with the Pi via ethernet. As soon as I enable internet sharing on the mac, I lose the ethernet connection. Anyone any ideas? A: If you have internet sharing turned off, and things work, that implies that either you have set up static IPs, or you are running a DHCP server on the pi side of the ethernet. I'm guessing the latter. If you share your mac's wifi connection over ethernet, the mac will be expecting to act as a DHCP server, not a client. Either way, your pi is now sitting there as either a static IP or a DHCP server, but definitely not a DHCP client, which is why it's not working. You need to reconfigure your eth0 to be a DHCP client. You need iface eth0 inet dhcp in /etc/network/interfaces You likely have iface eth0 inet static which won't work in this case.
{ "pile_set_name": "StackExchange" }
Q: Unexpected Indent error in Python I have a simple piece of code that I'm not understanding where my error is coming from. The parser is barking at me with an Unexpected Indent on line 5 (the if statement). Does anyone see the problem here? I don't. def gen_fibs(): a, b = 0, 1 while True: a, b = b, a + b if len(str(a)) == 1000: return a A: If you just copy+pasted your code, then you used a tab on the line with the if statement. Python interprets a tab as 8 spaces and not 4. Don't ever use tabs with python1 :) 1 Or at least don't ever use tabs and spaces mixed. It's highly advisable to use 4 spaces for consistency with the rest of the python universe. A: You're mixing tabs and spaces. Tabs are always considered the same as 8 spaces for the purposes of indenting. Run the script with python -tt to verify.
{ "pile_set_name": "StackExchange" }
Q: variations on public static main (String args[]) What is the difference between these 4 method signatures, and why does the 4th not work? public void main(String args[]) {... } public void main(String[] args) {... } public void main(String... args) {... } public void main(String[] args[]) {... } A: The first three are equivalent.* The last one is equivalent to String[][] args (i.e. an array of arrays), which doesn't match what Java requires for main. However, the idiomatic version is the second one. * The third one is only valid from Java 5 onwards.
{ "pile_set_name": "StackExchange" }
Q: Display On when plugged in Is there a way to keep the display "ON" whilst the device is plugged in? I am running Android 2.2 Froyo on Samsung Galaxy S. A: Settings > Applications > Development > Stay awake
{ "pile_set_name": "StackExchange" }
Q: Как уничтожить элемента массива которые равны null Как уничтожить элементы массива которые равны null? Вот например: Я создаю массив String: String[] aTempVisibleServers = new String[max]; Дальше происходит проверка элементов, тд... И вот я имею массив aTempVisibleServers в котором некоторые из элементов не записывались и они имеют значение null. Пример: aTempVisibleServers[0]="45" aTempVisibleServers[1]=null aTempVisibleServers[2]=null Как мне уничтожить эти null? Просто у меня AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setSingleChoiceItems(Массив, индекс и тд) Видит эти null и начинает просто вылетать, заполнить эти null не вариант, так как будут видны лишне пункты в меню. A: Сначала преобразуем массив String[] в List<String>, это можно сделать методом Arrays.asList(T...). Однако надо иметь ввиду что данный метод возвращает не изменяемую коллекцию, т.е. удалить оттуда элементы не получится. Поэтому создаем новый ArrayList в конструктор которого передаем List который получили на предыдущем этапе. После чего из только что созданного ArrayList можно удалить все интересующие нас элементы методом removAll(Collection<?> c). В качестве параметров к этому методу передается коллекция элементов, которые необходимо удалить.
{ "pile_set_name": "StackExchange" }
Q: How to add cells within column in html table? I have trouble finding the right way to add cells into columns: Here is what I want to do: A fiddle you get from : http://jsfiddle.net/AKrB3/ <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <table style="margin-top: 40px" width="600" height="358" cellspacing="0" cellpadding="2" align="center" border="1"> <tr> <td align="center">fasfg1 </td> <td width="42"></td> <td align="center">fasfg2 </td> </tr> </table> </body> </html> A: Try this, with rowspan. <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <table style="margin-top: 40px" width="600" height="358" cellspacing="0" cellpadding="2" align="center" border="1"> <tr> <td align="center">fasfg1 </td> <td width="42" rowspan="3"></td> <td align="center" rowspan="3">fasfg2 </td> </tr> <tr> <td>zroizj</td> </tr> <tr> <td>zroizj</td> </tr> </table> </body> </html> Note that it may be really hard to maintain this code if you want to add more rows in the left column in the future. It may be preferable to use 2 different tables.
{ "pile_set_name": "StackExchange" }
Q: How to simplify my model code? I am new to Rails and I wonder if there's any way to simplify this code from my model: class Item < ActiveRecord::Base def subtotal if price and quantity price * quantity end end def vat_rate if price and quantity 0.19 end end def total_vat if price and quantity subtotal * vat_rate end end end As far as I know *before_filter* does not work within models? A: I'd do: class Item < ActiveRecord::Base VAT_RATE = 0.19 def subtotal (price || 0) * (quantity || 0) end def total_vat subtotal * VAT_RATE end end A: Personally I would override the getter methods for price and quantity so that they return zero when not set, which allows your other methods to return valid results when no values are set rather than checking that they are and returning nil. Additionally, creating a method to provide the VAT rate seems a little overkill for what should be a constant. If it isn't a constant then it should probably be stored in the DB so that it can be modified. Here's a modification of your model based on my thoughts: class Item < ActiveRecord::Base VAT_RATE = 0.19 def price self.price || 0 end def quantity self.quantity || 0 end def subtotal price * quantity end def total_vat subtotal * VAT_RATE end end
{ "pile_set_name": "StackExchange" }
Q: Python XML SOAP parsing I have trying to get list of all ROW elements from SOAP xml by ET.findall('*/ROW') method (xml.etree.ElementTree as ET), but without result. The xml look like: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><SOAP-CHK:Success xmlns:SOAP-CHK = "http://soaptest1/soaptest/" xmlns="urn:candle-soap:attributes"><TABLE name="O4SRV.TSITSTSH"> <OBJECT>Status_History</OBJECT> <DATA> <ROW> <Global_Timestamp>tttt01</Global_Timestamp> <Situation_Name>nnn01</Situation_Name> <Status>Raised</Status> <Atomize></Atomize> </ROW> <ROW> <Global_Timestamp>tttt02</Global_Timestamp> <Situation_Name>nnn02</Situation_Name> <Status>Reset</Status> <Atomize></Atomize> </ROW> <ROW> <Global_Timestamp>tttt03</Global_Timestamp> <Situation_Name>nnn03</Situation_Name> <Status>Raised</Status> <Atomize></Atomize> </ROW> </DATA> </TABLE> </SOAP-CHK:Success></SOAP-ENV:Body></SOAP-ENV:Envelope> When I remove all SOAP tags from this xml, everything its ok, getting list of ROWs. How I must modify string in findall method to get list of ROW elements without remove SOAP tags? Trying also '*/SOAP-ENV:Envelope[@SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"]/SOAP-ENV:Body/SOAP-CHK:Success[@xmlns="urn:candle-soap:attributes"]/TABLE[@name="O4SRV.TSITSTSH"]/DATA//ROW' and other combinations, but without results, getting error: SyntaxError: prefix 'SOAP-ENV' not found in prefix map or SyntaxError: prefix 'SOAP-ENV' not found in prefix map A: I basically extracted the text value of all tags under all <ROW> tags. Is that what you're looking for? Code: from bs4 import BeautifulSoup xml = ''' <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><SOAP-CHK:Success xmlns:SOAP-CHK = "http://soaptest1/soaptest/" xmlns="urn:candle-soap:attributes"><TABLE name="O4SRV.TSITSTSH"> <OBJECT>Status_History</OBJECT> <DATA> <ROW> <Global_Timestamp>tttt01</Global_Timestamp> <Situation_Name>nnn01</Situation_Name> <Status>Raised</Status> <Atomize></Atomize> </ROW> <ROW> <Global_Timestamp>tttt02</Global_Timestamp> <Situation_Name>nnn02</Situation_Name> <Status>Reset</Status> <Atomize></Atomize> </ROW> <ROW> <Global_Timestamp>tttt03</Global_Timestamp> <Situation_Name>nnn03</Situation_Name> <Status>Raised</Status> <Atomize></Atomize> </ROW> </DATA> </TABLE> </SOAP-CHK:Success></SOAP-ENV:Body></SOAP-ENV:Envelope> ''' soup = BeautifulSoup(xml, 'xml') for i in soup.find_all('ROW'): print(i.text) Output: tttt01 nnn01 Raised tttt02 nnn02 Reset tttt03 nnn03 Raised
{ "pile_set_name": "StackExchange" }
Q: How to switch from embedded etcd to external etcd cluster Is that possible to switch existing cluster with "embedded" etcd to external etcd? Thanks A: The devil's in the details, but for the most part, yes: join your new external etcd members to the internal etcd cluster update the kubeadm-config ConfigMap to indicate to future control plane members where etcd lives patch the existing control plane yaml remove the stacked etcd members pray etcd Be Sure you have an understanding of this document, and have practiced it on a sample cluster, because if things go bad, unsticking an angry etcd cluster is painful. Make etcd snapshots early and often kubeadm-config kubectl -n kube-system edit configmap kubeadm-config and replace the ClusterConfiguration etcd: key with something akin to etcd: external: caFile: /etc/kubernetes/pki/etcd/ca.crt certFile: /etc/kubernetes/pki/etcd/apiserver-etcd-client.crt endpoints: - https://your-new-etcd-url:2379 keyFile: /etc/kubernetes/pki/etcd/apiserver-etcd-client.key existing control plane pods This is just the materialization of the yaml described above, but after provisioning, control plane Nodes don't watch that kubeadm-config for changes. You may actually be happier to just rotate all the control plane nodes if you have an autoscaling system in place, but if you have "pet" control plane nodes then: containers: - command: - kube-apiserver # ... - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt - --etcd-certfile=/etc/kubernetes/pki/etcd/apiserver-etcd-client.crt - --etcd-keyfile=/etc/kubernetes/pki/etcd/apiserver-etcd-client.key - --etcd-servers=https://your-new-etcd-url:2379 and ensure the new apiserver pod comes up a-ok etcd member teardown This step depends a great deal on how your current stacked members are running, whether through systemd, static pods, an operator, ... whatever, but you'll for sure need to remove their membership if the existing process doesn't do that as part of stopping them export ETCDCTL_API=3 etcdctl member list # find the memberid of the one to remove bye_bye_member_id=cafebabedeadbeef etcdctl member remove $bye_bye_member_id and repeat that for every embedded etcd member as you shut them down
{ "pile_set_name": "StackExchange" }
Q: integration tests - embedded jetty - how to setup data I wonder how do you usually setup data for integration tests. When my tests begin I start embedded jetty: @Before public void startServer() throws Exception { server = new Server(8080); server.setStopAtShutdown(true); WebAppContext webAppContext = new WebAppContext(); webAppContext.setDescriptor("WEB-INF/embedded-web.xml"); webAppContext.setContextPath("/core-test"); webAppContext.setResourceBase("src/main/webapp"); webAppContext.setClassLoader(getClass().getClassLoader()); server.addHandler(webAppContext); server.start(); } In embedded-web.xml there is a reference to spring application context: <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/applicationContext-test.xml</param-value> </context-param> In applicationContext-test.xml there is a configuration for in memory h2 database: <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.h2.Driver" /> <property name="url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1" /> </bean> The best solution would be to autowire Spring service classes into tests and then setup database, but I guess it's impossible to access application context started by jetty. A: I found out that there are 3 solutions to provide data to integration tests: Use spring application listener that is being run when application context starts public class CustomTestInitializer implements ApplicationListener<ContextRefreshedEvent> { @Autowired CustomService customService; @Override public void onApplicationEvent(ContextRefreshedEvent event) { // TODO: implement you loginc } } You can provide sql import files while configuring entity manager (it-test-init.sql is located in src/test/resouces): <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaProperties"> <props> <prop key="hibernate.hbm2ddl.auto">create</prop> <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop> <prop key="hibernate.hbm2ddl.import_files">it-test-init.sql</prop> </props> </property> </bean> You can use Arquillian and execute test on the remote server (e.g. JBoss). It is highly recommended when you use Java EE/container technologies that are difficult to run on the embedded server (CDI, EJB, etc.).
{ "pile_set_name": "StackExchange" }
Q: Matlab use fminsearch to optimize multi variables I am using Matlab fminsearch to minimize a equation with two variables sum((interval-5).^2, 2)*factor The interval is a vector contains 5 values. They can be only picked sequentially from value 1 to 30 with step size is 1. The factor is a value from 0.1 to 0.9. The code is below. I think the interval values are correct but factor value is wrong. Interval value: [3 4 5 6 7] factor value: 0.6 Final Output: 6 I think the factor value should be 0.1 and final output should be 1 as global minimum. %% initialization of problem parameters minval = 1; maxval = 30; step = 1; count = 5; minFactor = 0.1; maxFactor = 0.9; %% the objective function fun = @(interval, factor) sum((interval-5).^2, 2)*factor; %% a function that generates an interval from its initial value getinterval = @(start) floor(start) + (0:(count-1)) * step; getfactor =@(start2) floor(start2 * 10)/10; %% a modified objective function that handles constraints objective = @(start, start2) f(start, fun, getinterval, minval, maxval, getfactor, minFactor, maxFactor); %% finding the interval that minimizes the objective function start = [(minval+maxval)/2 (minFactor+maxFactor)/2]; y = fminsearch(objective, start); bestvals = getinterval(y(1)); bestfactor = getfactor(y(2)); eval = fun(bestvals,bestfactor); disp(bestvals) disp(bestfactor) disp(eval) The code uses the following function f. function y = f(start, fun, getinterval, minval, maxval, getfactor, minFactor, maxFactor) interval = getinterval(start(1)); factor = getfactor(start(2)); if (min(interval) < minval) || (max(interval) > maxval) || (factor<minFactor) || (factor>maxFactor) y = Inf; else y = fun(interval, factor); end end I tried the GA function as Adam suggested. I changed it to two different sets given the fact that my variables are from different ranges and steps. Here are my changes. step1 = 1; set1 = 1:step1:30; step2 = 0.1; set2 = 0.1:step2:0.9; % upper bound depends on how many integer used for mapping ub = zeros(1, nvar); ub(1) = length(set1); ub(2) = length(set2); Then, I changed the objective function % objective function function y = f(x,set1, set2) % mapping xmap1 = set1(x(1)); xmap2 = set2(x(2)); y = (40 - xmap1)^xmap2; end After I run the code, I think I get the answer I want. A: Illustration of ga() optimizing over a set objective function f = xmap(1) -2*xmap(2)^2 + 3*xmap(3)^3 - 4*xmap(4)^4 + 5*xmap(5)^5; Set set = {1, 5, 10, 15, 20, 25, 30} The set contains 7 elements: index 1 is equivalent to 1 Set(1) index 2 to 5... index 7 to 30 set(7) The input to ga will be in the range 1 to 7. The lower bound is 1, and the upper bound is 7. ga optimization is done by calculation the fitness function, that's s by evaluating f over the input variable. The tips here will be using integer as input and later while evaluating f use the mapping just discussed above. The code is as follows % settting option for ga opts = optimoptions(@ga, ... 'PopulationSize', 150, ... 'MaxGenerations', 200, ... 'EliteCount', 10, ... 'FunctionTolerance', 1e-8, ... 'PlotFcn', @gaplotbestf); % number of variable nvar = 5; % uppper bound is 1 lb = ones(1, nvar); step = 2.3; set = 1:step:30; limit = length(set); % upper bound depends on how many integer used for mapping ub = limit.*lb; % maximization, used the opposite of f as ga only do minimization % asking ga to minimize -f is equivalent to maximize f fitness = @(x)-1*f(x, step, set); [xbest, fbest, exitflag] = ga(fitness,nvar, [], [], [], [], lb, ub, [], 1:nvar, opts); % get the discrete integer value and find their correspond value in the set mapx = set(xbest) % objective function function y = f(x, step, set) l = length(x); % mapping xmap = zeros(1, l); for i = 1:l xmap(i) = set(x(i)); end y = xmap(1) -2*xmap(2)^2 + 3*xmap(3)^3 - 4*xmap(4)^4 + 5*xmap(5)^5; end
{ "pile_set_name": "StackExchange" }
Q: Creating Buttons Dynamically inside a for loop for use in a scrollview I have an issue with creating buttons dynamically. I used the help provided by How can I dynamically create a button in Android? Although is does help tremendously it isn't exactly working with my specific situation. I am trying to create an array of buttons inside of a scroll view. These buttons will basically be created on the fly based off the answer to the query from a sqlite database. I havent implemented the database as of yet but im just using a for loop with a set variable to create the buttons. I am recieving a Null Pointer Exception when the code ran at this point.... myButton[index].setText("Button # "); Here is the code I have been working with for this project. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_aquarium); //test creating of dynamic buttons Button[] myButton = new Button[4]; LinearLayout scrViewButLay = (LinearLayout) findViewById(R.id.scrollViewLinLay); for(int index = 0; index < 4; index++){ Log.i("ForTag", "Inside for loop"); Log.i("ForTag", "button length is "+myButton.length); myButton[index].setText("Button # ");//null ptr exception error Log.i("ForTag", "After set text"); scrViewButLay.addView(myButton[index]); Log.i("ForTag", "After adding to view"); } } And here is the Null Pointer Exception Error 10-02 12:07:11.373: D/ActivityThread(16944): setTargetHeapUtilization:0.25 10-02 12:07:11.373: D/ActivityThread(16944): setTargetHeapIdealFree:8388608 10-02 12:07:11.373: D/ActivityThread(16944): setTargetHeapConcurrentStart:2097152 10-02 12:07:11.443: I/ForTag(16944): Inside for loop 10-02 12:07:11.443: I/ForTag(16944): button length is 4 10-02 12:07:11.443: W/dalvikvm(16944): threadid=1: thread exiting with uncaught exception (group=0x41c5a438) 10-02 12:07:11.443: E/AndroidRuntime(16944): FATAL EXCEPTION: main 10-02 12:07:11.443: E/AndroidRuntime(16944): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aquariumdatabase.seanrsolution/com.aquariumdatabase.seanrsolution.MainAquariumActiv ity}: java.lang.NullPointerException 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2073) 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2098) 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.app.ActivityThread.access$600(ActivityThread.java:138) 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1204) 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.os.Handler.dispatchMessage(Handler.java:99) 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.os.Looper.loop(Looper.java:137) 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.app.ActivityThread.main(ActivityThread.java:4905) 10-02 12:07:11.443: E/AndroidRuntime(16944): at java.lang.reflect.Method.invokeNative(Native Method) 10-02 12:07:11.443: E/AndroidRuntime(16944): at java.lang.reflect.Method.invoke(Method.java:511) 10-02 12:07:11.443: E/AndroidRuntime(16944): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) 10-02 12:07:11.443: E/AndroidRuntime(16944): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) 10-02 12:07:11.443: E/AndroidRuntime(16944): at dalvik.system.NativeStart.main(Native Method) 10-02 12:07:11.443: E/AndroidRuntime(16944): Caused by: java.lang.NullPointerException 10-02 12:07:11.443: E/AndroidRuntime(16944): at com.aquariumdatabase.seanrsolution.MainAquariumActivity.onCreate(MainAquariumActivity.java:23) 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.app.Activity.performCreate(Activity.java:5240) 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082) 10-02 12:07:11.443: E/AndroidRuntime(16944): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2037) 10-02 12:07:11.443: E/AndroidRuntime(16944): ... 11 more A: You are initializing an array to store your buttons in. You still need to initialize each individual button within that array. for(int index = 0; index < 4; index++) { myButton[index] = new Button(this); //initialize the button here myButton[index].setText("Button # "); }
{ "pile_set_name": "StackExchange" }
Q: Picasa 3.5: how to share the tagged faces from one PC to another At home, we share our photos from a server. I've been tagging the faces in Picasa 3.5 in one PC, but in the other PC the same photos needs to be retagged. Where is this info stored so it can be shared between computers? A: The face tag information is stored in .picasa.ini files. Although the tags are actually references to contacts that are stored in user's directory. On my PC (Windows Vista) the contacts are stored in %LocalAppData%\Google\Picasa2\contacts\contacts.xml file. The contacts can be local (sync_enabled="0" in the XML file), so there is no need to sync with the web server. So, if you synchronize your contacts.xml between your PCs the face tag information should be synchronized as well. The question is how to do it. This howto describes how to share picasa data between multiple accounts on same PC. Ideally picasa local data should be put on the same server where you store your pictures and then %LocalAppData%\Google\Picasa2* directories are to be linked to the remote directories. Unfortunately I don't know a way of creating links to remote shares. NTFS junctions obviously don't work in this case. I'm not a Windows expert though. If you can't link to a remote share, you will have to synchronize your picasa folders in some other way. Update: just found a "WinXP - Map network location to local folder" (can't post a link because I don't have enough reputation points) thread on serverfault.com. Conclusion there is that you can't map a shared folder to a local folder (not a drive letter). A: For information, I created a little application that gives a solution to this problem. To be found here: http://sites.google.com/site/picasastartersite/home A: Picasa stores face tag information in a database file and a .picasa.ini file. Both can be found in the directory where the images reside. To find where your images are, right click one and select "locate on disk".
{ "pile_set_name": "StackExchange" }
Q: Trying to run Timer1 in ATmega2560 with assembly I have a slight problem with Timer1 in arduino (ATmega2560) while coding it in assembly. I try to run the Timer1 in CTC mode - I configure everything well in my opinion, but the TCNT1 just doesn't increment each clock cycle, as it should. I checked the registers in Atmel Studio and everything seems okay, but maybe I forgot about something? Here is the code .ORG 0 jmp start .ORG 0x22 call isr_toggle_PA0 .ORG 0x400 start: LDI R16, HIGH(RAMEND) OUT SPH, R16 LDI R16, LOW(RAMEND) OUT SPL, R16 ; initialize stack pointer clr r16 ldi r16, 0xff out DDRA, r16 ; port A output ldi r16, 0x00 out DDRD, r16 ; port D input clr r16 ldi r20, 1<<OCIE1A sts TIMSK1, r20 ; enable Timer1 A comapre match interrupt sei ldi r20, HIGH(25000) sts OCR1AH, r20 ldi r20, LOW(25000) sts OCR1AL, r20 ldi r20, 0b00000010 ; CTC mode, int clk; sts TCCR1A, r20 ldi r20, 0b000000101 ; prescaler /1024 sts TCCR1B, r20 ldi r20, 0 sts TCCR1C, r20 ; --- start main main: inc r16 rjmp main ; --- end main isr_toggle_PA0: // toggle bit on PA0 ldi r16,0x00000001 in r17, PORTA eor r17,r16 out PORTA, r17 reti Thank you and have a good day :) A: Here: ldi r20, 0b00000010 ; CTC mode, int clk; sts TCCR1A, r20 ldi r20, 0b000000101 ; prescaler /1024 sts TCCR1B, r20 you are setting the bit WGM11 on TCCR1A. The timer then runs in mode 2 (PWM, Phase Correct, 9-bit) rather than mode 4 (CTC).
{ "pile_set_name": "StackExchange" }
Q: Reverse Proxy Server and Webserver architecture I'm very confused. If I setup a Reverse Proxy Server, does this mean that I need a second computer? Or can both Server (e.g. nginx as reverse proxy server and apache as webserver) run on the same computer and different port!? For example this pic! it seems to me that there are 4 computers (one for each server) ? A: "A server is a process" said to me a teacher years ago :-) Both servers can run on the same computer and different ports/IP. For example you can set apache to Listen 127.0.0.1:8080 and then nginx point to it server { listen 80; location / { proxy_pass http://127.0.0.1:8080/; } } Note that the above is pseudo-code.
{ "pile_set_name": "StackExchange" }
Q: How to pass parameters to custom action for a managed code dll written in C#? I have a requirement where I have to pass 3 parameters to the c# code for managed code custom action in installshield. Cant give the code. Please someone help me out even with basic way of doing so. Thanks in advance. A: Since you mention a custom action, refer to Specifying the Signature for a Managed Method in an Assembly Custom Action. Specify values, or properties that store the values, that you need to pass to the parameters in the function. Note that if this is a deferred custom action, you will need to pass them through CustomActionData as mentioned in the third paragraph "Using a Custom Method Signature for a Deferred, Commit, or Rollback Custom Action."
{ "pile_set_name": "StackExchange" }
Q: AJAX request causes change function unbind I want to implement simple functionality to allow users to save their message text as template to be used in the future. php: echo '<div id="container">'; $sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates WHERE member_id = {$member_id}"); $result = mysql_query($sql) or die(mysql_error()); $num_rows = mysql_num_rows($result); $confName = get_conference_name($confID); $confName = formatText_safe($confName); echo "<label>" . $lang['my_template'] . "</label><select id='tempchoose' name='templates'>"; if ($num_rows == 0) { echo '<option value=""> ' . $lang['no_saved'] . '</option>'; } else { for ($i = 0; $i < $num_rows; $i++) { //$template_id = mysql_result($result, $i, 0); $temp_text = mysql_result($result, $i, 1); $temp_name = mysql_result($result, $i, 2); echo '<option value="' . $temp_text . '">' . $temp_name . '</option>'; } } echo "</select></div>"; echo '<input id="send" name="Message" value="send" disabled="disabled" type="submit" /> <input id="temp" name="temp" type="button" value="save as template" />" <textarea style="width: 99%;" id="textarea" name="TextBox" rows="8" disabled="disabled" type="text" value=""/></textarea>'; javascript: $("#temp").bind("click", function(){ name=prompt("template name?"); temp_text = $("#textarea").val(); if (name!=null && name!="" && name!="null") { $.ajax ({ data: {temp_text:temp_text, name:name}, type: 'POST', url: 'save_template.php', success: function(response) { if(response == "1") { alert("template saved successfully"); } else { alert(response); } } }); } else { alert("invalid template name"); } $.ajax ({ url: 'update_templates.php', success: function(response) { $("#container").html(response); } }); }); $("select").change(function () { $("select option:selected").each(function () { $("#textarea").removeAttr("disabled"); $("#send").removeAttr("disabled"); }); $("#textarea").val($(this).val()); }) .trigger('change'); update_temp.php $sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates WHERE member_id = {$member_id}"); $result = mysql_query($sql) or die(mysql_error()); $num_rows = mysql_num_rows($result); $confName = get_conference_name($confID); $confName = formatText_safe($confName); echo "<label>".$lang['my_template']."</label><select id='tempchoose' name='templates'>"; if ($num_rows == 0) { echo '<option value=""> '.$lang['no_saved'].'</option>'; } else { for ($i = 0; $i < $num_rows; $i++) { //$template_id = mysql_result($result, $i, 0); $temp_text = mysql_result($result, $i, 1); $temp_name = mysql_result($result, $i, 2); echo '<option value="' . $temp_text . '">' . $temp_name . '</option>'; } } echo "</select>"; the last ajax request in #temp click function is used to updated the droplist with the newly created template, the problem is that when i click save template; ajax request is performed successfully and droplist is updated, however something wired happen which is that the change function of select is not working anymore! anyone knows where's the problem? A: Because ajax will inject new elements to your DOM and those elements don't know about the binding you already defined. Solution : use jQuery on Change $("select").change(function () { to $(document).on("change","select", function(){ jQuery on is available from 1.7+ version onwards, if you are using a previous version of jQuery, consider using delegate.
{ "pile_set_name": "StackExchange" }
Q: Command-line snake game? I remember a long time ago having an old mobile phone which had a game on it which I believe was called something like "Snake" or "Snakes" and it was basically you get to change the direction of the snake with the arrow keys, the snake cannot touch itself (or game over), but if it touches the edges of the map it will simply appear at the other side. The aim of the game was to get the snake to eat food, but with each bit of food (every time it ate some some more would appear somewhere else, but normally one at a time) the snake would get a little bit longer making it harder to play the game. I'm sure that you will all be familiar with this game, so I was wondering (as I miss this game and can only find odd 3D versions) if there is a version of this game in Terminal? I was hoping it would stick to the original and would go something along the lines of ASCII perhaps? I am running Ubuntu GNOME 16.04.1 with GNOME 3.20, is there such a free application in the official repositories (which is where I would prefer it to come from)? A: ", is there such a free application in the official repositories (which is where I would prefer it to come from)?" First there is nsnake that should meet your need exactly sudo apt-get install nsnake Two more I found are snake4 this opens in a new window though, so not a terminal game and gnibbles but I could not get it to run. A: The game is called centipede and it full story can be found here: http://wp.subnetzero.org/?p=269. This is a bash game requiring no downloads and an interesting study for those interested in bash scripts. You can change the size of the screen to make it smaller and more challenging by changing these variables: LASTCOL=40 # Last col of game area LASTROW=20 # Last row of game area Here's the code: #!/bin/bash # # Centipede game # # v2.0 # # Author: [email protected] # # Functions drawborder() { # Draw top tput setf 6 tput cup $FIRSTROW $FIRSTCOL x=$FIRSTCOL while [ "$x" -le "$LASTCOL" ]; do printf %b "$WALLCHAR" x=$(( $x + 1 )); done # Draw sides x=$FIRSTROW while [ "$x" -le "$LASTROW" ]; do tput cup $x $FIRSTCOL; printf %b "$WALLCHAR" tput cup $x $LASTCOL; printf %b "$WALLCHAR" x=$(( $x + 1 )); done # Draw bottom tput cup $LASTROW $FIRSTCOL x=$FIRSTCOL while [ "$x" -le "$LASTCOL" ]; do printf %b "$WALLCHAR" x=$(( $x + 1 )); done tput setf 9 } apple() { # Pick coordinates within the game area APPLEX=$[( $RANDOM % ( $[ $AREAMAXX - $AREAMINX ] + 1 ) ) + $AREAMINX ] APPLEY=$[( $RANDOM % ( $[ $AREAMAXY - $AREAMINY ] + 1 ) ) + $AREAMINY ] } drawapple() { # Check we haven't picked an occupied space LASTEL=$(( ${#LASTPOSX[@]} - 1 )) x=0 apple while [ "$x" -le "$LASTEL" ]; do if [ "$APPLEX" = "${LASTPOSX[$x]}" ] && [ "$APPLEY" = "${LASTPOSY[$x]}" ]; then # Invalid coords... in use x=0 apple else x=$(( $x + 1 )) fi done tput setf 4 tput cup $APPLEY $APPLEX printf %b "$APPLECHAR" tput setf 9 } growsnake() { # Pad out the arrays with oldest position 3 times to make snake bigger LASTPOSX=( ${LASTPOSX[0]} ${LASTPOSX[0]} ${LASTPOSX[0]} ${LASTPOSX[@]} ) LASTPOSY=( ${LASTPOSY[0]} ${LASTPOSY[0]} ${LASTPOSY[0]} ${LASTPOSY[@]} ) RET=1 while [ "$RET" -eq "1" ]; do apple RET=$? done drawapple } move() { case "$DIRECTION" in u) POSY=$(( $POSY - 1 ));; d) POSY=$(( $POSY + 1 ));; l) POSX=$(( $POSX - 1 ));; r) POSX=$(( $POSX + 1 ));; esac # Collision detection ( sleep $DELAY && kill -ALRM $$ ) & if [ "$POSX" -le "$FIRSTCOL" ] || [ "$POSX" -ge "$LASTCOL" ] ; then tput cup $(( $LASTROW + 1 )) 0 stty echo echo " GAME OVER! You hit a wall!" gameover elif [ "$POSY" -le "$FIRSTROW" ] || [ "$POSY" -ge "$LASTROW" ] ; then tput cup $(( $LASTROW + 1 )) 0 stty echo echo " GAME OVER! You hit a wall!" gameover fi # Get Last Element of Array ref LASTEL=$(( ${#LASTPOSX[@]} - 1 )) #tput cup $ROWS 0 #printf "LASTEL: $LASTEL" x=1 # set starting element to 1 as pos 0 should be undrawn further down (end of tail) while [ "$x" -le "$LASTEL" ]; do if [ "$POSX" = "${LASTPOSX[$x]}" ] && [ "$POSY" = "${LASTPOSY[$x]}" ]; then tput cup $(( $LASTROW + 1 )) 0 echo " GAME OVER! YOU ATE YOURSELF!" gameover fi x=$(( $x + 1 )) done # clear the oldest position on screen tput cup ${LASTPOSY[0]} ${LASTPOSX[0]} printf " " # truncate position history by 1 (get rid of oldest) LASTPOSX=( `echo "${LASTPOSX[@]}" | cut -d " " -f 2-` $POSX ) LASTPOSY=( `echo "${LASTPOSY[@]}" | cut -d " " -f 2-` $POSY ) tput cup 1 10 #echo "LASTPOSX array ${LASTPOSX[@]} LASTPOSY array ${LASTPOSY[@]}" tput cup 2 10 echo "SIZE=${#LASTPOSX[@]}" # update position history (add last to highest val) LASTPOSX[$LASTEL]=$POSX LASTPOSY[$LASTEL]=$POSY # plot new position tput setf 2 tput cup $POSY $POSX printf %b "$SNAKECHAR" tput setf 9 # Check if we hit an apple if [ "$POSX" -eq "$APPLEX" ] && [ "$POSY" -eq "$APPLEY" ]; then growsnake updatescore 10 fi } updatescore() { SCORE=$(( $SCORE + $1 )) tput cup 2 30 printf "SCORE: $SCORE" } randomchar() { [ $# -eq 0 ] && return 1 n=$(( ($RANDOM % $#) + 1 )) eval DIRECTION=\${$n} } gameover() { tput cvvis stty echo sleep $DELAY trap exit ALRM tput cup $ROWS 0 exit } ###########################END OF FUNCS########################## # Prettier characters but not supported # by all termtypes/locales #SNAKECHAR="\0256" # Character to use for snake #WALLCHAR="\0244" # Character to use for wall #APPLECHAR="\0362" # Character to use for apples # # Normal boring ASCII Chars SNAKECHAR="@" # Character to use for snake WALLCHAR="X" # Character to use for wall APPLECHAR="o" # Character to use for apples # SNAKESIZE=3 # Initial Size of array aka snake DELAY=0.2 # Timer delay for move function FIRSTROW=3 # First row of game area FIRSTCOL=1 # First col of game area LASTCOL=40 # Last col of game area LASTROW=20 # Last row of game area AREAMAXX=$(( $LASTCOL - 1 )) # Furthest right play area X AREAMINX=$(( $FIRSTCOL + 1 )) # Furthest left play area X AREAMAXY=$(( $LASTROW - 1 )) # Lowest play area Y AREAMINY=$(( $FIRSTROW + 1)) # Highest play area Y ROWS=`tput lines` # Rows in terminal ORIGINX=$(( $LASTCOL / 2 )) # Start point X - use bc as it will round ORIGINY=$(( $LASTROW / 2 )) # Start point Y - use bc as it will round POSX=$ORIGINX # Set POSX to start pos POSY=$ORIGINY # Set POSY to start pos # Pad out arrays ZEROES=`echo |awk '{printf("%0"'"$SNAKESIZE"'"d\n",$1)}' | sed 's/0/0 /g'` LASTPOSX=( $ZEROES ) # Pad with zeroes to start with LASTPOSY=( $ZEROES ) # Pad with zeroes to start with SCORE=0 # Starting score clear echo " Keys: W - UP S - DOWN A - LEFT D - RIGHT X - QUIT If characters do not display properly, consider changing SNAKECHAR, APPLECHAR and WALLCHAR variables in script. Characters supported depend upon your terminal setup. Press Return to continue " stty -echo tput civis read RTN tput setb 0 tput bold clear drawborder updatescore 0 # Draw the first apple on the screen # (has collision detection to ensure we don't draw # over snake) drawapple sleep 1 trap move ALRM # Pick a random direction to start moving in DIRECTIONS=( u d l r ) randomchar "${DIRECTIONS[@]}" sleep 1 move while : do read -s -n 1 key case "$key" in w) DIRECTION="u";; s) DIRECTION="d";; a) DIRECTION="l";; d) DIRECTION="r";; x) tput cup $COLS 0 echo "Quitting..." tput cvvis stty echo tput reset printf "Bye Bye!\n" trap exit ALRM sleep $DELAY exit 0 ;; esac done
{ "pile_set_name": "StackExchange" }
Q: Oracle - returning aggregate sum as well as pivoted aggregate sums? I want to return a result set in the following format: YEARMONTH Total ModelA ModelB ModelC 200101 0 0 0 0 200102 10 5 5 0 200103 8 2 2 4 where the total is the sum of the hours for all model types grouped by yearmonth, and the individual model columns are the sum of hours per model type grouped by yearmonth. I can get the correct results using the following query with nested selects: select distinct yearmonth, sum(a.hours) as Total, (select sum(b.hours) from model_hours b where model = 'ModelA' and a.yearmonth = b.yearmonth) as ModelA, (select sum(b.hours) from model_hours b where model = 'ModelB' and a.yearmonth = b.yearmonth) as ModelB, (select sum(b.hours) from model_hours b where model = 'ModelC' and a.yearmonth = b.yearmonth) as ModelC from model_hours a group by yearmonth order by yearmonth I was curious to try using the pivot function in Oracle 11 to achieve the same results, and am able to get all the results EXCEPT the total hours using the following query: select * from ( select yearmonth, hours, model from model_hours a ) pivot ( sum(hours) for model in ('ModelA', 'ModelB', 'ModelC') ) order by yearmonth which returns this result: YEARMONTH ModelA ModelB ModelC 200101 0 0 0 200102 5 5 0 200103 2 2 4 I have not been able to figure out how to also get the sum of the hours for all models, grouped by yearmonth, into this resultset. Is it possible? And if so, would it be likely to be more efficient than the nested selects? This particular table has some 200K rows right now. A: From forums.oracle.com, there are several similar ways to do it... the most straightforward syntax seems to be: select yearmonth,ModelA + ModelB + ModelC Total,ModelA,ModelB,ModelC from ( select yearmonth, hours, model from model_hours a ) pivot ( sum(hours) for model in ('ModelA' as ModelA, 'ModelB' as ModelB, 'ModelC' as ModelC) ) order by yearmonth As an aside, the pivoted queries are approximately 100 times faster than the original query with scalar sub-queries!
{ "pile_set_name": "StackExchange" }
Q: find "/p" with preg_match in first place of string Small problem: $content='/p test some text'; when "/p" is in front of the line the string should be exploded to an array if(preg_match('^(/p)',$content)==true) { $private=explode(" ",$content,3); } i think their is an error, but i've no idea for the correct search parameter A: This should work for you: (No need to compare it with true, because if it doesn't find anything it returns an empty array, which then is false. Also you need delimiters for your regex and escape the slash with a backslash) $content='/p test some text'; if(preg_match('/^\/p/',$content)) { //^ ^ See delimiters $private=explode(" ",$content,3); }
{ "pile_set_name": "StackExchange" }
Q: Quickly application with ListStore as preference I'm starting to write a program with 'quickly'. A list of desired languages will be one prefereces. Example: languages = ["en", "de"] The (automaticly created) quickly code that handles the preference part looks like this: # Define your preferences dictionary in the __init__.main() function. # The widget names in the PreferencesTestProjectDialog.ui # file need to correspond to the keys in the preferences dictionary. # # Each preference also need to be defined in the 'widget_methods' map below # to show up in the dialog itself. Provide three bits of information: # 1) The first entry is the method on the widget that grabs a value from the # widget. # 2) The second entry is the method on the widget that sets the widgets value # from a stored preference. # 3) The third entry is a signal the widget will send when the contents have # been changed by the user. The preferences dictionary is always up to # date and will signal the rest of the application about these changes. # The values will be saved to desktopcouch when the application closes. # # TODO: replace widget_methods with your own values widget_methods = { 'languages': ['getter', 'setter', 'changed'], } In the GUI, it seems as if the widget of choice in gtk for a list is a ListStore (which isn't a widget, but a model, but it's defined in the Glade file...). Can someone tell me what would work for a ListStore for the'getter', 'setter' and 'changed' in the code above? The approach looks easy for simple entry widgets and such, but I don't know how to use it with lists. Alternatively, I would of course accept any other way to deal with lists as preferences, provided that the length of the list is not fixed. A: Disclaimer: I didn't know anything about quickly until I read your post, or about gui programming in general for that matter. Therefore I honestly have no business attempting to answer this question :) That said, quickly is a neat project. I scanned the boilerplate source briefly and identified the following potential approaches for adding a ListStore backed list-style preference: 'Monkey-patch' get and set widget_methods onto a stock TreeView widget (w/ ListStore model) as defined in data/ui/Preferences$PROJECTNAME$Dialog.ui with glade. Implement set_widget_from_preference and set_preference in the project's subclass of PreferencesDialog (the subclass is Preferences$PROJECTNAME$Dialog), and do something different when key or widget is your ListStore backed TreeView widget. Write a custom subclass of gtk.TreeView with a matching custom widget for glade. To test them out, I implemented all three of these ideas -- each worked as intended, and AFAICT, identically. In the end, the third (in particular) seemed the cleanest to me, and closer to conventions used throughout the boilerplate, despite initially expecting the opposite. Here are the steps I followed for number three ... Using glade via quickly design (quickly 11.10, btw), and loosely following this tutorial (part 2), add a ScrolledWindow widget to the Preferences$PROJECTNAME$Dialog.ui, drop a TreeView onto it, name the TreeView language_treeview. Create a new ListStore model for the TreeView when prompted, and name it language_liststore, etc ... eventually I ended up with something like this: Next, add a glade catalog (data/ui/preferences_$PROJECTNAME$_treeview.xml) with the following contents: <glade-catalog name="preferences_$PROJECTNAME$_treeview" domain="glade-3" depends="gtk+" version="1.0"> <glade-widget-classes> <glade-widget-class title="$PROJECTNAME$ Preferences TreeView" name="Preferences$PROJECTNAME$TreeView" generic-name="Preference$PROJECTNAME$TreeView" parent="GtkTreeView" icon-name="widget-gtk-treeview"/> </glade-widget-classes> </glade-catalog> Then, edit Preferences$PROJECTNAME$Dialog.ui, adding ... <!-- interface-requires preferences_$PROJECTNAME$_treeview 1.0 --> ... to the top, under the requires tag. And change the class attribute of language_treeview to Preferences$PROJECTNAME$TreeView, in preparation for a later step. Finally, add the following element to widget_methods list in Preferences$PROJECTNAME$Dialog.py 'language_treeview': ['get_languages', 'set_languages', 'button-release-event'] And at the end of the same file (Preferences$PROJECTNAME$Dialog.py), add import gtk ALL_LANGUAGES = [ 'en', 'uk', 'de', 'fr', # ... much longer list ] class Preferences$PROJECTNAME$TreeView(gtk.TreeView): __gtype_name__ = "Preferences$PROJECTNAME$TreeView" def __init__(self, *args): super(Preferences$PROJECTNAME$TreeView, self).__init__(*args) self.get_selection().set_mode(gtk.SELECTION_MULTIPLE) # loads the liststore with all languages, # selecting/highlighting in the treeview those # already retrieved from previously saved preferences def set_languages(self, preferred_languages): model = self.get_model() for row, lang in enumerate(ALL_LANGUAGES): model.append([lang]) if lang in preferred_languages: self.get_selection().select_iter(model.get_iter(row)) # collects only the selected languages in the treeview # to save in the preferences database def get_languages(self): model, rows = self.get_selection().get_selected_rows() result = [model.get_value(model.get_iter(row), 0) for row in rows] return result If you're interested in seeing my attempts for one and two, I'm happy to oblige. Edit: For the casual reader, replace any occurrence of $PROJECTNAME$ with the actual name of your quickly project (as specified in quickly create). HTH!
{ "pile_set_name": "StackExchange" }
Q: How to load dll in C++ I would like to load Dll in my c++ project, but the problem is I do not have the source code of the Dll that I was using. So I can't modify anything in the dll e.g. add export def file, or export c method for the dll. Any solution for this situation ? Have tried load library function, and it was successful load the Dll. How to call the function within the dll without def file, or export c method ? A: You need to know what the DLL provides to you. You should get a header files with the definitions of structures (if any) and the function prototype(s) including the calling conventions. You can get the list of exported functions with dumpbin /exports TheDll.dll. You should further check the CPU it is made for with the dumpbin command. This avoids a 32/64 bit trouble. You can load any compatible DLL (32/64) with the LoadLibrary API function. Include the appropriate header to get the prototype. You get a pointer to an exported function with the GetProcAddress function. If you have the function signature, you can use this pointer to call the function.
{ "pile_set_name": "StackExchange" }
Q: Why can't Al3+ be reduced to solid, pure aluminum? There are efforts underway to develop ionic liquids for the purpose of reducing bauxite using exotic intermediates such as aluminum fluoride. However, the aqueous $\ce{Al^3+}$ ion is tantalizingly close to pure aluminum. What prevents it from being reduced? A: It is aluminium’s standard electrode potential that prevents it from easily being reduced. For the half-cell $\ce{Al^3+ + 3e- <=> Al(s)}$, the standard potential is $E^0 = -1.66~\mathrm{V}$. For comparison a few other values: $\ce{Fe2O3 + 3 H2O + 2e- <=> 2 Fe(OH)2(s) + 2 OH-}$ and $\ce{Fe(OH)2 + 2 e- <=> Fe(s) + 2 OH-}$ have potentials of $E^0 = -0.86~\mathrm{V}$ and $-0,89~\mathrm{V}$, respectively; $\ce{Zn^2+ + 2 e- <=> Zn(s)}$ has a potential of $E^0 = -0.76~\mathrm{V}$; $\ce{Cr^3+ + 3 e- <=> Cr(s)}$ has a potential of $E^0 = -0.74~\mathrm{V}$; $\ce{Co^2+ + 2 e- <=> Co(s)}$ has a potential of $E^0 = -0.28~\mathrm{V}$; $\ce{Cu^2+ + 2 e- <=> Cu(s)}$ has a potential of $E^0 = +0.34~\mathrm{V}$. (All values taken from Wikipedia) The higher the standard potentials are, the easier the ion can be reduced. Hydrogen, of course, has a potential of $E^0 = 0~\mathrm{V}$ at pH 0 by definition. So in acidic media, hydrogen is reduced first. So let’s lower the pH to impede the formation of hydrogen. According to the Nernst equation: $$E = E^0 + \frac{0.059~\mathrm{V}}{z} \lg \frac{a_\mathrm{Ox}}{a_\mathrm{red}}$$ Where $z$ is the number of electrons transferred in the half-cell, and $a$ is the activity of the reduced/oxidised species. $a_\mathrm{red}$ is $1$ by definition and $z = 2$ for the hydrogen half-cell. So we need to solve the following simplified equation to determine the acid concentration that will allow reduction of aluminium: $$-1.66~\mathrm{V} = 0~\mathrm{V} + \frac{0.059~\mathrm{V}}{2} \lg \frac{[\ce{H+}]}{1}\\ \frac{0.059}{2} \mathrm{pH} = 1.66 \\ 0.059 \times \mathrm{pH} = 3.32 \\ \mathrm{pH} = 3.32 / 0.059 = 56$$ Whoops, so we would need a pH of $56$ to allow the reduction of aluminium in the presence of water. This calculation was highly theoretical, because: A pH of 56 is impossible in anything that once could have been water. Wikipedia gives the $\mathrm{p}K_\mathrm{b}(\ce{O^2-}) \approx -38$; because $\mathrm{p}K_\mathrm{a}(\ce{HA}) + \mathrm{p}K_\mathrm{b}(\ce{A-}) = 14$ in water that must mean that $\mathrm{p}K_\mathrm{a}(\ce{OH-}) \approx 52$ — thus we would be dealing with an ‘oxide solution’ rather than water. Although it is nice that both equations (pH and Nernst) use acitivities, we cannot really say anything about the activities at this large a concentration range. The redox system of both species would be totally different in these environments. Note that you can reduce most air-stable metals in thermite reactions from their oxides thereby creating aluminium oxide. An example reaction would be: $$\ce{Fe2O3 + 2Al -> 2Fe + Al2O3}$$ That alone should show the unwillingness of aluminium to be reduced in aquaeous solutions; think about the heat that the thermite reactions generate.
{ "pile_set_name": "StackExchange" }
Q: how to use "war.context" in Configuration file of Play Framework ? how to use "war.context" in Configuration file of Play Framework ? A: Take a look at this thread on the Google Groups for a description of what you are asking. http://groups.google.com/group/play-framework/browse_thread/thread/b4783c821fd29898?pli=1 In essence, what it is saying, is. In your application.conf file, you set a property such as war.context=/MyAppName Then, in your routes file, you set it up to include your WAR context in the following way # Set context name %{ ctx = play.configuration.getProperty('war.context', '') }% # Routes # This file defines all application routes (Higher priority routes first) # ~~~~ # Home page GET ${ctx}/ Application.index # Map static resources from the /app/public folder to the /public path GET ${ctx}/public/ staticDir:public # Catch all * ${ctx}/{controller}/{action} {controller}.{action} You can see therefore, whatever you place in your war.context, you can then put into your routes to pick up the correct path.
{ "pile_set_name": "StackExchange" }
Q: Trigger Locking Table calculating Running Total I have the following trigger on a table in SQL Server 2012: CREATE TRIGGER [dbo].[UpdateTotals] ON [dbo].[DEC10assessmentData] AFTER UPDATE AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; --update list pract test 1 total if update (list_practTest1_s1) or update (list_practTest1_s2) begin update DEC10assessmentData set list_practTest1_total = CAST(list_practTest1_s1 AS decimal(3 , 1)) + CAST(list_practTest1_s2 AS decimal(3 , 1)) where TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest1_s1) IS NOT NULL and TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest1_s2) IS NOT NULL update DEC10assessmentData set list_practTest1_total = NULL where TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest1_s1) IS NULL or TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest1_s2) IS NULL end --update list test 1 total if UPDATE (list_test1_s1) or update (list_test1_s2) begin update DEC10assessmentData set list_test1_total = CAST(list_test1_s1 AS decimal(3 , 1)) + CAST(list_test1_s2 AS decimal(3 , 1)) where TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test1_s1) IS NOT NULL and TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test1_s2) IS NOT NULL update DEC10assessmentData set list_test1_total = NULL where TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test1_s1) IS NULL or TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test1_s2) IS NULL end --update list pract test 2 total if update (list_practTest2_s1) or update (list_practTest2_s2) begin update DEC10assessmentData set list_practTest2_total = CAST(list_practTest2_s1 AS decimal(3 , 1)) + CAST(list_practTest2_s2 AS decimal(3 , 1)) where TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest2_s1) IS NOT NULL and TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest2_s2) IS NOT NULL update DEC10assessmentData set list_practTest2_total = NULL where TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest2_s1) IS NULL or TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest2_s2) IS NULL end --update list test 2 total if UPDATE (list_test2_s1) or update (list_test2_s2) begin update DEC10assessmentData set list_test2_total = CAST(list_test2_s1 AS decimal(3 , 1)) + CAST(list_test2_s2 AS decimal(3 , 1)) where TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test2_s1) IS NOT NULL and TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test2_s2) IS NOT NULL update DEC10assessmentData set list_test2_total = NULL where TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test2_s1) IS NULL or TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test2_s2) IS NULL end --update read total update DEC10assessmentData set read_total = ((read_test1_Scaled / 100 * 8) + (read_test2_scaled / 100 * 12)) / 20 * 100 where read_test1_Scaled is not null and read_test2_scaled is not null --update read total to null where scores don't exist update DEC10assessmentData set read_total = NULL where read_test1_Scaled is null or read_test2_scaled is null --update write total update DEC10assessmentData set writ_total = (CAST(writ_literatureReview as decimal(3,1)) / 100 * 4 + CAST(writ_exposition as decimal(3,1)) / 100 * 8 + CAST(writ_groupReport as decimal(3,1)) / 100 * 8 + cast(writ_synthSummary as decimal(3,1)) / 100 * 8 + cast(writ_critEvaluation as decimal(3,1)) / 100 * 12) / 40 * 100 where TRY_CONVERT(decimal(3 , 1) , writ_literatureReview) is not null and TRY_CONVERT(decimal(3 , 1) , writ_exposition) is not null and TRY_CONVERT(decimal(3 , 1) , writ_groupReport) is not null and TRY_CONVERT(decimal(3 , 1) , writ_synthSummary) is not null and TRY_CONVERT(decimal(3 , 1) , writ_critEvaluation) is not null --update write total where scores don't exist update DEC10assessmentData set writ_total = NULL where TRY_CONVERT(decimal(3 , 1) , writ_literatureReview) is null or TRY_CONVERT(decimal(3 , 1) , writ_exposition) is null or TRY_CONVERT(decimal(3 , 1) , writ_groupReport) is null or TRY_CONVERT(decimal(3 , 1) , writ_synthSummary) is null or TRY_CONVERT(decimal(3 , 1) , writ_critEvaluation) is null --update list total update DEC10assessmentData set list_total = ((list_test1_scaled / 100 * 8) + (list_test2_scaled / 100 * 12)) / 20 * 100 where list_test1_scaled is not null and list_test2_scaled is not null --update list total to null where scores don't exist update DEC10assessmentData set list_total = NULL where list_test1_scaled is null or list_test2_scaled is null --update speak total update DEC10assessmentData set speak_total = (cast(speak_groupPres as decimal(3,1)) / 100 * 4 + CAST(speak_indivPres as decimal(3,1)) / 100 * 8 + cast(speak_tutorialDiscus as decimal(3,1)) / 100 * 8) / 20 * 100 where TRY_CONVERT(decimal(3 , 1) , speak_groupPres) is not null and TRY_CONVERT(decimal(3 , 1) , speak_indivPres) is not null and TRY_CONVERT(decimal(3 , 1) , speak_tutorialDiscus) is not null --update speak total where scores don't exist to null update DEC10assessmentData set speak_total = NULL where TRY_CONVERT(decimal(3 , 1) , speak_groupPres) is null or TRY_CONVERT(decimal(3 , 1) , speak_indivPres) is null or TRY_CONVERT(decimal(3 , 1) , speak_tutorialDiscus) is null --update overall score update DEC10assessmentData set overall_total = (read_total + writ_total * 2 + list_total + speak_total) / 5 --update rec/not rec's for skills and overall update DEC10assessmentData set read_rec = t.rec_read, writ_rec = t.rec_writ, list_rec = t.rec_list, speak_rec = t.rec_speak, overall_rec = t.rec_overall from dbo.udf_getDEC10RecSkillAndOverall() as t inner join DEC10assessmentData on t.studentID = DEC10assessmentData.studentID and t.assessmentLookup = DEC10assessmentData.assessmentLookup --update rec/not rec's for final rec update DEC10assessmentData set final_rec = t.rec_final from dbo.udf_getDEC10RecFinal() as t inner join DEC10assessmentData on t.studentID = DEC10assessmentData.studentID and t.assessmentLookup = DEC10assessmentData.assessmentLookup END GO I am getting a trigger to calculate running totals in a table after updates to other columns in the table. As you can see, there is unfortunately a lot of casting of varchar values, however it does the job except for one issue - locking. I intermittently get users complaining they can't perform updates and this seems to be because the trigger is locking the table. Is there any way to avoid this and how do I confirm this is what is happening? They are not updating the columns the trigger updates. I get the following output from two updates that deadlock using Erland Sommarskog's beta_lockinfo: rsctype locktype lstatus ownertype waittime spid waittype KEY U WAIT TRANSACTION 2.192 LCK_M_U 69 DATABASE S grant STW 69 KEY X grant TRANSACTION 69 OBJECT IX grant TRANSACTION 69 PAGE IU grant TRANSACTION 69 PAGE IX grant TRANSACTION 69 KEY U WAIT TRANSACTION 2.188 LCK_M_U 89 DATABASE S grant STW 89 KEY X grant TRANSACTION 89 OBJECT IX grant TRANSACTION 89 PAGE IU grant TRANSACTION 89 PAGE IX grant TRANSACTION 89 A: The first advice should probably be not to do use triggers and move the business logic to some other layer. Your updates affects the whole table, that will probably produce a table lock: update DEC10assessmentData set overall_total = (read_total + writ_total * 2 + list_total + speak_total) / 5 etc Why update other rows than the changed one? How to work only on the updated row For your calculations, use calculated columns instead. Do you really need to do all the converting? Can't you fix your data types in your table definition instead? But if this is something you absolutely have to do with triggers then maybe you could refactor your table so that you don't store the data in the same table but in two. That way the users would be able to update their data and you can update yours.
{ "pile_set_name": "StackExchange" }
Q: Specify float when initializing double. gcc and clang differs I tried running this simple code on ideone.com #include<stdio.h> int main() { double a = 0.7f; // Notice: f for float double b = 0.7; if (a == b) printf("Identical\n"); else printf("Differ\n"); return 0; } With gcc-5.1 the output is Identical With clang 3.7 the output is Differ So it seems gcc ignores the f in 0.7f and treats it as a double while clang treats it as a float. Is this a bug in one of the compilers or is this implementation dependent per standard? Note: This is not about floating point numbers being inaccurate. The point is that gcc and clang treats this code differently. A: The C standard allows floating point operations use higher precision than what is implied by the code during compilation and execution. I'm not sure if this is the exact clause in the standard but the closest I can find is §6.5 in C11: A floating expression may be contracted, that is, evaluated as though it were a single operation, thereby omitting rounding errors implied by the source code and the expression evaluation method Not sure if this is it, or there's a better part of the standard that specifies this. There was a huge debate about this a decade ago or two (the problem used to be much worse on i386 because of the internally 40/80 bit floating point numbers in the 8087).
{ "pile_set_name": "StackExchange" }
Q: Solve for variable in integral limit when using NIntegrate I am trying to solve for a variable which appears in the limits of an integral, rather like in the following; Clear[f, a, x] f[a_] := Integrate[x^2 + a x, {x, 0, a }] f[Power[6, (3)^-1]] NSolve[5 == f[a], a, Reals] This works absolutely fine. But the integral I really care about is a mess, and so has, of course, no nice closed form. So I try the following; Clear[f, a, x] f[a_] := NIntegrate[x^2 + a x, {x, 0, a }] f[Power[6, (3)^-1]] NSolve[5 == f[a], a, Reals] and this does not work. Instead I get NIntegrate::nlim: x = a is not a valid limit of integration. In both of these examples, the third line evaluates the function f[a] fine. I also tried f[a_?NumericQ] := NIntegrate[x^2 + a x, {x, 0, a }] which fails with NSolve::nsmet: This system cannot be solved with the methods available to NSolve. I rather hoped the link below would answer my problem, but of course it refers to Integrate, not NIntegrate. https://math.stackexchange.com/questions/38012/compute-unknown-limit-from-known-integral-in-mathematica I'd be very grateful for any suggestions. A: When a is a symbol in f[a_] := NIntegrate[x^2 + a x, {x, 0, a }] you won't get the result. Defining f[a_?NumericQ] :=NIntegrate[...] it can't work in NSolve[5 == f[a], a, Reals] since a is assumed to be a Symbol therein. You can use FindRoot[f[a] - 5, {a, 1}] {{a -> 1.81712}} or you should define f this way: f[a_] := Integrate[x^2 + a x, {x, 0, a}] A: Use FindRoot[] Clear[f, a, x] x0 = Power[6, (3)^-1]; f[a_?NumericQ] := NIntegrate[x^2 + a x, {x, 0, a}] (a /. FindRoot[f[a] == 5, {a, 1}]) == N@x0 (* True *)
{ "pile_set_name": "StackExchange" }
Q: Array intersection issue (Matlab) I am trying to carry out the intersection of two arrays in Matlab but I cannot find the way. The arrays that I want to intersect are: and I have tried:[dur, itimes, inewtimes ] = intersect(array2,char(array1)); but no luck. However, if I try to intersect array1 with array3 (see array3 below), [dur, itimes, inewtimes ] = intersect(array3,char(array1));the intersection is performed without any error. Why I cannot intersect array1 with array2?, how could I do it?. Thank you. A: Just for ease of reading, your formats for Arrays are different, and you want to make them the same. There are many options for you, like @Visser suggested, you could convert the date/time into a long int which allows faster computation, or you can keep them as strings, or even convert them into characters (like what you have done with char(Array2)). This is my example: A = {'00:00:00';'00:01:01'} %//Type is Cell String Z = ['00:00:00';'00:01:01'] %//Type is Cell Char Q = {{'00:00:00'};{'00:01:01'}} %//Type is a Cell of Cells A = cellstr(A) %//Convert CellStr to CellStr is essentially doing nothing Z = cellstr(Z) %//Convert CellChar to CellStr Q = vertcat(Q{:,:}) %// Convert Cell of Cells to Cell of Strings I = intersect (A,Z) >>'00:00:00' '00:01:01' II = intersect (A,Q) >>'00:00:00' '00:01:01' This keeps your dates in the format of Strings in case you want to export them back into a txt/csv file.
{ "pile_set_name": "StackExchange" }
Q: Python unittest call and unexpected program run Let's say i have a simple python program and a simple test file iseven.py: import math def is_even(n): return n%2==0 print is_even(2) print is_even(3) and test_iseven.py: import unittest from iseven import is_even class IsevenTests(unittest.TestCase): def test1(self): self.assertTrue(is_even(2)) self.assertFalse(is_even(3)) if __name__ == '__main__': unittest.main() Is there a difference in running the tests between python test_iseven.py and python -m unittest test_iseven.py ? Because I've seen both in guides and tutorials, and output is identical. Also: The test is just for that one function, yet the whole program is executed when running the tests, so I get the program's output in the console. That is not supposed to happen, right? A: Is there a difference between ...? There is no big difference when it comes to executing the tests. The main difference is that in the latter case, you can omit the if __name__ == '__main__': unittest.main() but you have to type more on the command line every time you want to run the tests. So I prefer the first solution. Python executes the whole program. The behavior is correct. To be able to import is_even from the module iseven, Python has to parse the whole module. It can't really just look at the function. Since Python is a scripting language, parsing the module means that it has to execute all the commands in it. From Python's point of view, def is a command like print which creates a new function instance and adds it to the current scope. Or to put it differently: If it wouldn't run the print, it also couldn't run the def. This behavior is often used to do magic. For example, in my i18n module for Python, I use: @i18n def name(): pass At runtime, I collect all functions decorated with @i18n and turn them into code which checks the current language, loads the correct text from the translation file and returns it. That means I can do later: print name() and it will do the right thing. EDIT Now you may have code in your module that you want to execute only when the module is run as a "program" (i.e. not when it's imported from somewhere else). Here is how you can do that: def is_even(n): return n%2==0 def main(): print is_even(2) print is_even(3) if __name__ == '__main__': main() General recipe: Always move all code into functions; avoid keeping anything at the "root" level of the module.
{ "pile_set_name": "StackExchange" }
Q: Determine max/min speeds of trochoid Find the minimum and maximum speeds of the point of a trochoid and the locations where each occurs. I know a trochoid has equations $ (x)t = at - b \sin{t} $ ; $ y(t) = a- b \cos{t} $ for trochoid of radius a and b distance from center of circle (According to Wolfram) The only speed equation I'm familiar with thus far in my study of parametric equations is the arc-length equation. Would I set that equal to zero and then try and solve for a & b (cause I did and that gets really messy- not sure I know how to do that)? Any/all suggestions appreciated A: For a parametric curve, the speed is just the modulus of the tangent vector, hence if $$\gamma(t)=(at-b\sin t,a-b\cos t)$$ we have $$ \dot{\gamma}(t) = (a-b\cos t,b\sin t) $$ so $$ v^2(t) = a^2+b^2-2ab\cos t $$ and the stationary points for $v(t)$ are the ones for which $\cos t=\pm 1$: $$ \max_{t} v(t) = |a+b|,$$ $$ \min_{t} v(t) = |a-b|.$$
{ "pile_set_name": "StackExchange" }
Q: How to store an auth token in an Angular app I have an Angular application (SPA) that communicates with a REST API server and I'm interested in finding out the best method to store an access token that is returned from an API server so that the Angular client can use it to authenticate future requests to the API. For security reasons, I would like to store it as a browser session variable so that the token is not persisted after the browser is closed. I'm implementing a slightly customized version of OAuth 2.0 using the Resource Owner Password grant. The Angular application provides a form for the user to enter their username and password. These credentials are then sent to the API in exchange for an access token which must then be sent as a header (Authorization: Bearer %Token%) for all outbound requests to the API so that it can authorize requests to other routes. I'm fairly new to the realm of Angular, but the workflow I would like to implement as far as handling these tokens is summarized as follows. 1) The client makes a request to the API providing it with user credentials. 2) If this request is successful, the token is stored somewhere (where is the question) 3) Intercept HTTP requests. If token is set, pass it along as a header to API 4) Token is destroyed when the browser/tab is closed. I know Angular offers $window.sessionStorage, which appears to be what I am looking for, but I am concerned by the potential for it not to work on all browsers according to various resources I've read. This is an enterprise grade application and must be compatible across a broad range of browsers (IE, Chrome, Firefox). Can I safely use this with the confidence that it will be stable? The alternatives, from what I understand, are either $window.localStorage or cookies ($cookies, $cookieStore). This would not be an ideal solution for me since I don't want this data to persist, but if this is more reliable I'll have to sacrifice efficiency for compatibility. I was also thinking it might be possible to simply set it as a value on the $rootScope and reference it this way, but I'm not sure if this is feasible. I hope that all made sense. Any help / suggestions would be greatly appreciated. Thanks! A: If you are looking for something that will definitely not persist then I would simply keep the token in memory and not rely on the browser for storage. However storing inside rootScope would not be best practice. I would recommend that you wrap your server access code in an Angular Service if you have not done so already. You can then encapsulate your token within that Service at runtime (e.g. as a property) without worrying about having to access it when calling from other parts of your application. Angular Services are singleton so your "server service" will be a global instance that can be accessed using normal dependency injection. A: $window.sessionStorage is the way to go unless you're targeting very old browsers. According to www.w3schools.com sessionStorage is supported from IE 8.0, Chrome 4.0, Firefox 3.5, and Safari 4.0.
{ "pile_set_name": "StackExchange" }
Q: Running vs. walking in slippery condition We are experiencing warmer weather than normal, which is causing the snow to melt and re-freeze daily. This has led to very slippery conditions. A few years ago, I was running in similar conditions, and I got to an area where the ice started to feel more slippery. So my reaction was to stop running and start walking. To my surprise, it was harder to walk in the icy conditions than it was to run: it felt as I was slipping with every single step. Today, in light of the conditions, I tried the experiment again, and my sensations seemed to confirm what I felt the previous time. Is there any physical basis to what I felt? Is it possible that running on ice produces a more stable footing than walking does? If it makes any difference, the ice is of course not smooth, and one is usually slipping on the "slopes" of small creases. A: https://www.sciencedaily.com/releases/2011/03/110324103610.htm "Biomechanics researchers Timothy Higham of Clemson University and Andrew Clark of the College of Charleston conclude that moving quickly in a forward, firm-footed stance across a slippery surface is less likely to lead to a fall than if you move slowly. Approaching a slippery surface slowly hinders the necessary task of shifting the center of mass forward once foot contact is made." "The key to avoiding slips seems to be speed and keeping the body mass forward, slightly ahead of the ankles after the foot contacts the ground." "Once the knee passes the ankle during contact with slippery ground, slipping stops."
{ "pile_set_name": "StackExchange" }
Q: LNK 2019 Error when trying to overload the "<<" opeartor I have a template class MGraph<T>with a member function print_relation and a friend function which is ostream& operator<<(ostream& os, const MGraph<T>& other) I follwed the instructions here and wrote this code: template<class T> ostream& MGraph<T>::print_relation(ostream& os) const { for (VertexId i = 0; i < max_size; i++) { for (VertexId j = 0; j < max_size; j++) { os << relation[i][j] << ' '; } os << endl; } return os; } ... template<class T> ostream& operator<<(ostream& os, const MGraph<T>& other) { os << other.print_relation(os); return os; } I get the following error when compiling: 1>main.obj : error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class MGraph<bool> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$MGraph@_N@@@Z) referenced in function "void __cdecl exec<bool>(class MGraph<bool> *)" (??$exec@_N@@YAXPAV?$MGraph@_N@@@Z) It appears 4 times, once for every data type (int, char, double, bool). What did I do wrong? A: In your overload of operator<<, you are doing this os << other.print_relation(os); And since MGraph<T>::print_relation returns std::ostream&, that is not valid. operator<< is not overloaded in such way, that it takes std::ostream& on RHS. So, just remove the os <<. template<class T> ostream& operator<<(ostream& os, const MGraph<T>& other) { other.print_relation(os); return os; }
{ "pile_set_name": "StackExchange" }
Q: brew installed Vim in Terminal with RVM (Ruby 1.9.3), MacVim and Command-T I'm using RVM (1.17.7) and Ruby 1.9.3p362. In the long run I want to move over to Vim in the Terminal with Tmux. I'm trying to learn how to install and run with my choices for plugins instead of defaulting to Janus, just trying to learn it all and not be a cargo cult programmer. I did a brew install of Vim git clone of Command-T (I'm using Pathogen) while the Ruby was set to 1.9.3... and everything is good in Terminal using Vim and Command-T. When I run :ruby puts RUBY_VERSION in Terminal Vim, it gives 1.9.3 back. The Command-T works fine too. When I try and use the same Command-T in MacVim it crashes and the Terminal says: Vim: Caught deadly signal SEGV Vim: Finished. I did a brew install macvim while in 1.9.3, but when I launch mvim from Terminal and run :ruby puts RUBY_VERSION I get back 1.8.7. I know Wincent recommends the system version of Ruby for installing Command-T and I've read you have to match up the Ruby version either way. I've managed to get it working for both when I had the system ruby, but can't get it for both on the RVM version with 1.9.3... Is it possible? Should I just forget about MacVim and stick with Vim in the Terminal? Other things I thought I could do would be to have a disabled folder and just move the different Command-T installations in and out of it. Or maybe do an if for 'gui_running' and target the different installs. Any advice to set me straight would be great. I've installed Tim Pope's rvm.vim and can set the Ruby version, but that doesn't seem to stop the crash in the MacVim when I call :CommandT. A: I'm guessing that you installed the macvim package before you installed installed all the rest of that, and then installed the vim package afterwards. That'd explain why it works in terminal mode. These are two different packages, and they have their own build options. Run: vim --version And compare the output to: mvim --version In particular, check out the last line (starts with Linking:). You'll probably see ruby-1.8 linked in for mvim, and ruby-1.9.1 linked in for vim (note that 1.9.3 reports 1.9.1; it's the C API version, not the Ruby version). If all this is true, fix it by doing: brew uninstall macvim brew install macvim It should build against your 1.9.3 config. Make sure rvm current reports 1.9.3 before you do that.
{ "pile_set_name": "StackExchange" }
Q: Design consideration to have User Exit in a software product We develop product and these products have business logic implemented as EJB. Idea is to provide a User Exit (an extension point which user can override the default behavior). It should be a common problem in product development, but I don't see any design pattern or abstraction mechanism to support override of business logic written in Java. User exit can either be a overridden Bean class or a groovy script. Are there any design patterns or design considerations to develop products in which EJB's can be overridden using some Java class or a script? Can anything be done using AspectJ to dynamically decide whether the default implementation should be used or a method in user specific implementation (overridden user exit code) should be used? A: Aspect Oriented Programming is the way to go. AOP using Spring 3 or Plain AspectJ enables user to override the existing feature. Refer AspectJ in Action book for more information. Hope it will be useful for someone.
{ "pile_set_name": "StackExchange" }
Q: How to implement mysql compress() function in php I want to compress TEXT for storing in MySQL. So I would just do gzcompress() in php and then send to mysql, but I am also setting up Sphinx full text search, and it would be nice if it can populate its index with a simple query i.e. select uncompress(thing) from table However I would still like to do compression and decompression for the application in php rather than mysql, and only use the mysql uncompress() function for sphinx indexing. The mysql documentation says the following about its compress function: Nonempty strings are stored as a four-byte length of the uncompressed string (low byte first), followed by the compressed string. So my question is... how do I construct this four-byte length of the uncompressed string? After that, the compressed BLOB looks just like the results of the php gzcompress() function. A: haven't ever done this, but here are some thoughts: 1) find the length of the uncompressed string... strlen() function ought to work 2) compress the string... you've already done this part 3) pack both together for storage in mysql, formatting the number as mysql wants it: php's pack function: sounds like you need to use format value "V" for the length (unsigned long... 32 bit, little endian byte order)
{ "pile_set_name": "StackExchange" }
Q: "FATAL: Module vboxdrv not found in directory /lib/modules/4.10.0-20-generic" Running the sudo sh vboxsign.sh and getting "FATAL: Module vboxdrv not found in directory /lib/modules/4.10.0-20-generic" What am I missing? This ran fine last time, but I've since upgraded, and must have forgotten something. I set working directory correctly. A: Try do reinstall "virtualbox-dkms" sudo apt install --reinstall virtualbox-dkms A: For me, reinstalling virtualbox-dkms always gave an error. It was my first time upgrading the kernel, and hadn't upgraded the headers. I needed to also do sudo aptitude install linux-headers-`uname -r` and not accept it's first solution (which was to actually do nothing), but accept the second solution which was to upgrade some further library. After that, then sudo apt install --reinstall virtualbox-dkms worked for me.
{ "pile_set_name": "StackExchange" }
Q: Woocomerce - Update max quantity for product variation I'm trying to update max quantity for all variations of my variable product to ie 345. $available_variations = $product->get_available_variations(); foreach ($available_variations as $variation) { $variation_ID = $variation->ID; update_post_meta( $variation_ID , 'max_qty', 345 ); } It doesn't happen. A: You are not using the correct way to get the variation ID and the product meta key max_qty doesn't exist in WooCommerce database on wp_postmeta table for product_variation post type. Instead you can use the following filter hook to set a specific maximum quantity to product variations: add_filter( 'woocommerce_available_variation', 'wc_available_variation_max_qty', 10, 3 ); function wc_available_variation_max_qty( $data, $product, $variation ) { $data['max_qty'] = 345; return $data; } Code goes in functions.php file of your active child theme (or active theme). Tested and work.
{ "pile_set_name": "StackExchange" }
Q: drupal undefined function static html with post to php I have placed my own php file in /sites/all/modules/<myfolder> and call it via $.post(<myphppage>) from a static html page (javascript function) also in /sites/all/modules/<myfolder>. However, the php does not appear to be executing as expected, but is getting called (access logs in Apache HTTPD show it is post'ed to). If I try to manually request the same php page, I receive this error: Fatal error: Call to undefined function db_insert() in /full/path/to/sites/modules/<myfolder>/<myphppage> on line x. The echo statement I have in the php page is outputted properly above this error, and simply uses $_GET['paramname']. (And _POST, changed for testing direct request) to print a few query string parameters for debugging). Also, when I added a call to watchdog, I receive: Fatal error: Call to undefined function watchdog() in /full/path/to/sites/modules/<myfolder>/<myphppage> on line x. Is it not possible to access the PHP page directly? Or is there a Drupal library I need to import? Or am I just plain missing something else with how Drupal works? A: You are getting those errors about undefined functions because your PHP file is independent from Drupal and it is not bootstrapping it. The Drupal way of doing what you are trying to do is to create a module (see Creating Drupal 7.x modules, and Creating Drupal 6.x modules) that defines a URL it handles with hook_menu(); that URL is then used with $.post(). As example of the way of bootstrapping Drupal, see the content of the index.php file that comes with every Drupal installation. (The following code is the one used from Drupal 7.) /** * Root directory of Drupal installation. */ define('DRUPAL_ROOT', getcwd()); require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); The code changes from Drupal 6 to Drupal 7, but drupal_bootstrap() is defined in both Drupal versions. The correct way is to create a module, anyway. For a list of reasons why a module should use a PHP file that bootstraps Drupal, see Are there cases where a third-party module would need to use its own file similar to xmlrp.php, cron.php, or authenticate.php?
{ "pile_set_name": "StackExchange" }
Q: Problems replacing head of a linked list Writing a function to do a head insert on a linked-list. It's half working as in it's inserting the object into head and reattaching the list but I'm losing my original head node in the list somehow. If list is [green, red, blue] and I try to insert yellow, it will work but the new list will be [yellow, red, blue]. Node class is: template<class T> class Node { public: Node(T theData, Node<T>* theLink) : data(theData), link(theLink){} Node<T>* getLink( ) const { return link; } const T& getData( ) const { return data; } void setData(const T& theData) { data = theData; } void setLink(Node<T>* pointer) { link = pointer; } private: T data; Node<T> *link; }; List is stored into a queue, so the head insert is a method of that class. Queue has private variables front and back that point to the corresponding positions of the list. template<class T> void Queue<T>::headInsert(T& theData) { Node<T> *temp; temp = front->getLink(); front->setLink(new Node<T>(theData, temp->getLink() )); front = front->getLink(); } A: Your problem is in your setLink call: template<class T> void Queue<T>::headInsert(T& theData) { Node<T> *temp; temp = front->getLink(); front->setLink(new Node<T>(theData, temp->getLink() )); // Right here front = front->getLink(); } You actually have a number of problems. First off, let's suppose we have the following test list: front = Red -> Green -> Blue -> NULL The call temp = front->getLink() yields the following output: temp = Green -> Blue -> NULL. The new Node<T>(theData, temp->getLink()) call, where theData = Yellow, then yields: new Node<T>(theData, temp->getLink()) = Yellow -> Blue -> NULL. Calling front->setLink(new(...) then gives you: front = Red -> Yellow -> Blue -> NULL Lastly, front = front->getLink(): front = Yellow -> Blue -> NULL. This is not what you want. You simply want to take yellow and pop it on the front of the list: template<class T> void Queue<T>::headInsert(T& theData) { front = new Node<T>(theData, front); } No need to modify internal pointers. Just point front to be the new node containing your data, with it's next pointer pointing to the old data.
{ "pile_set_name": "StackExchange" }
Q: iOS Share Extension issue when sharing images from Photo library Below is a code that I use to share images within my "ShareViewController.m". NSExtensionItem *item = [self.extensionContext.inputItems objectAtIndex:i]; NSItemProvider *itemProvider = item.attachments.firstObject; if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeURL]) { [itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypeURL options:nil completionHandler:^(NSData *data, NSError *error) { NSLog(@"%@", data); // the rest of uploading script goes here }]; } It all works fine if I share an image from WhatsApp. But it doesn't work if I want to share an image from Photo Library or from Facebook Messenger. Does anyone know what the problem might be? Thanks A: Here is how I solved it. I got rid of (NSString *)kUTTypeURL] and added itemProvider.registeredTypeIdentifiers to get array with all the available type identifiers. Then I'm just using the first one available as registeredTypeIdentifiers.firstObject. Also, very important, NSData *data got changed to id<NSSecureCoding> item which makes it a bit different to get the NSData from it. That's important especially when sharing images from Messenger - they have type identifier "public.image" rather than "public.jpeg" or "public.url" like in Photos library or WhatsApp. NSExtensionItem *item = [self.extensionContext.inputItems objectAtIndex:i]; NSItemProvider *itemProvider = item.attachments.firstObject; // get type of file extention (jpeg, file, url, png ...) NSArray *registeredTypeIdentifiers = itemProvider.registeredTypeIdentifiers; if ([itemProvider hasItemConformingToTypeIdentifier:registeredTypeIdentifiers.firstObject) { [itemProvider loadItemForTypeIdentifier:registeredTypeIdentifiers.firstObject options:nil completionHandler:^(id<NSSecureCoding> item, NSError *error) { NSData *imgData; if([(NSObject*)item isKindOfClass:[NSURL class]]) { imgData = [NSData dataWithContentsOfURL:(NSURL*)item]; } if([(NSObject*)item isKindOfClass:[UIImage class]]) { imgData = UIImagePNGRepresentation((UIImage*)item); } // the rest of uploading script goes here }]; }
{ "pile_set_name": "StackExchange" }
Q: Hyphenation command doesn't print I am having problems during the writing of my thesis. Everytime I use \hyphenation to split a ward so that it goes on a new line rather than going out of the margins, that words disappear instead. An example is: In addition, mechanistically more challenging transformations have \hyphenation{be-en} extensively studied in recent years, including NHC-catalyzed transformation As you can see, the "been" is missing. I have nothing specified in the preamble. Thanks a lot in advance A: \hyphenation is a declaration to be used in the preamble that declares how automatic hyphenation should work on a particular word so \hyphenation{trans-for-ma-tions} for example would specify the places TeX could break transformations (this is actually the default in this case). For one-off discretionary hyphen within the body of the document you can use \- but it would be very wrong to hyphenate been. You hadn't provided a real example but I assume that your case is like this with an overfull box: Overfull \hbox (2.73953pt too wide) in paragraph at lines 8--11 []\OT1/cmr/m/n/10 In ad-di-tion, mech-a-nis-ti-cally more chal-leng-ing trans-f or-ma-tions have been From the input \documentclass[a4paper]{article} \addtolength\textwidth{-23.1pt} \begin{document} Zzzzzz\dotfill zzzz In addition, mechanistically more challenging transformations have been extensively studied in recent years, including NHC-catalyzed transformation Zzzzzz\dotfill zzzz \end{document} Changing been to be\-en would remove the warning at the cost of making the text much harder to read. There are much better alternatives, for example if you add \usepackage{microtype} then not only does the overfull box go, so does the slightly ugly short final line of the paragraph with just the tion from the end of transformation \documentclass[a4paper]{article} \addtolength\textwidth{-23.1pt} \usepackage{microtype} \begin{document} Zzzzzz\dotfill zzzz In addition, mechanistically more challenging transformations have been extensively studied in recent years, including NHC-catalyzed transformation Zzzzzz\dotfill zzzz \end{document}
{ "pile_set_name": "StackExchange" }
Q: SQL ignores 2nd criterion in WHERE clause Why would the second criterion in this WHERE clause be ignored? $old = time() - 2592000; $sql_deleteold = ("DELETE FROM todolist WHERE status='done' AND stamp < $old"); mysql_query($sql_deleteold); I want to delete data from the database older than 30 days with the status "done". Instead it will go deleting all rows with the status "done". A: I think that your question is referring to the "second statement" in the SQL query? With this assumption, the problem with all rows being deleted with the status "done" is because the WHERE filters are similar to conditional statements like the ones used in "If" statements. If the first statement, or WHERE filter is true, then execute. Try doing the following: $old = time() - 2592000; $sql_deleteold = ("DELETE FROM todolist WHERE (status='done' AND stamp < $old)"); mysql_query($sql_deleteold); You also might want to verify the value of $old and compare it to the values in the 'stamp' field of your table, to be sure that there are some rows that have a value in the 'stamp' field that are greater than the value of $old.
{ "pile_set_name": "StackExchange" }
Q: Choice between REST API or Java API I have been reading about neo4j last few days. I got very confused about whether I need to use REST API or if can I go with Java APIs. My need is to create millions of nodes which will have some connection among them. I want to add indexes on few of node attributes for searching. Initially I started with embedded mode of GraphDB with Java API but soon reached OutOfMemory with indexing on few nodes so I thought it would be better if my neo4j is running as service and I connect to it through REST API then it will do all memory management by itself by swapping in/out data to underlying files. Is my assumption right? Further, I have plans to scale my solution to billion of nodes which I believe wont be possible with single machine's neo4j installation. I also believe Neo4j has the capability of running in distributed mode. For this reason also I thought continuing with REST API implementation is best idea. Though I couldn't find out any good documentation about how to run Neo4j in distributed environment. Can I do stuff like batch insertion, etc. using REST APIs as well, which I do with Java APIs with Graph DB running in embedded mode? A: Do you know why you are getting your OutOfMemory Exception? This sounds like you are creating all these nodes in the same transaction, which causes it to live in memory. Try committing small chunks at a time, so that Neo4j can write it to Disk. You don't have to manage the memory of Neo4j aside from things like cache. Distributed mode is in a Master/Slave architecture, so you'll still have a copy of the entire DB on each system. Neo4j is very efficient for disk storage, a Node taking 9 Bytes, Relationship taking 33 Bytes, properties are variable. There is a Batch REST API, which will group many calls into the same HTTP call, however making REST calls is still a slower then if this were embedded. There are some disadvantages to using the REST API that you did not mentions, and that's stuff like transactions. If you are going to do atomic operations, where you need to create several nodes, relationships, change properties, and if any step fails not commit any of it, you cannot do this in the REST API.
{ "pile_set_name": "StackExchange" }
Q: Problems installing LYNC on non-domain controler I have two servers in this set up. AD and EX, the domain is called mydomain.net The AD is a Windows 2008 Server (32 bit) with Active Directory installed AD only has it's own ip in the DNS-servers list AD.mydomain.net does resolve correctly in the dns EX is a Windows 2008 R2 that is connected to the mydomain.net-domain EX only DNS server is the ip of the ad.mydomain.net There are no firewalls running between the two servers When trying to install Lync 2010 on the EX server I get the following error "Not available :Failure occurred attempting to check the schema state.Please ensure Active Directory is reachable." I can control the AD from EX, also login to it and do successful checks like netdom query /domain:mydomain.net fsmo ...that resolves correctly I suspect there is something fundamentally wrong with my setup, maybe Lync need a 2k8 R2 ad? A: I had to obtain and run the extadsch.exe from the Microsoft System Center 2012 Configuration Manager on my Domain Controller.
{ "pile_set_name": "StackExchange" }
Q: How to start threads in turn in python in a for loop? I would like to start threads in turns in a for loop, but the next thread should not start until the current one is completed. Please help me with this issue. I want to achieve this, because I have a GUI, and for each loop a progress bar will appear and run, and the GUI will not be locked (it won't give that ugly "Not Responding" error) for op in ["op1", "op2"]: start_thread() def start_thread(): display_and_run_progress_bar() do_the_operation() when_op_is_completed_destroy_progress_bar() A: To run each op in its own thread, but only one at a time, you'd have to join after starting each thread. A join tells the main process to wait until the thread is complete before continuing. Going with your pseudocode style: for op in ["op1", "op2"]: thread = start_thread(op) thread.join() Depending on what threading library you use it'll be a little different, but see for example https://docs.python.org/2/library/threading.html#threading.Thread.join. If you run the code above on the main thread though, that'll still lock up the GUI. What I suggest is not creating a new thread for each op, but rather creating a single thread that does each op one by one, like so: thread = threading.Thread(target=do_ops, args=[["op1", "op2"]]) thread.start() def do_ops(ops): for op in ops: display_and_run_progress_bar() do_the_operation() when_op_is_completed_destroy_progress_bar() Now all of the ops are run in a single thread that's off the main process so that it doesn't lock the GUI.
{ "pile_set_name": "StackExchange" }
Q: StreamBuilder throws Dirty State saying Invalid Arguments I am trying the bloc pattern for my flutter app. I want to change colour of text field when the stream value changes. Following is my bloc code class Bloc { final StreamController<bool> _changeColor = PublishSubject<bool>(); Function(bool) get changeColour => _changeColor.sink.add; Stream<bool> get colour => _changeColor.stream; void dispose(){ _changeColor.close(); } } Following is my Inherited Widget class Provider extends InheritedWidget { final bloc = Bloc(); Provider({Key key,Widget child}): super(key: key,child: child); @override bool updateShouldNotify(InheritedWidget oldWidget) { return true; } static Bloc of(BuildContext context){ return (context.inheritFromWidgetOfExactType(Provider) as Provider).bloc; } } Following is my main class class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { final bloc = Provider.of(context); return Column( children: <Widget>[ RaisedButton( onPressed: () { bloc.changeColour(true); }, child: Text("Change colour"), ), StreamBuilder( builder: (context, snapshot) { print("pritish" + snapshot.data); return Text( "First text", style: TextStyle(color: snapshot.hasData ? Colors.red : Colors.green), ); }, stream: bloc?.colour, ), ], ); } } Following is the exception thrown flutter: The following ArgumentError was thrown building StreamBuilder<bool>(dirty, state: flutter: _StreamBuilderBaseState<bool, AsyncSnapshot<bool>>#24b36): flutter: Invalid argument(s) flutter: flutter: When the exception was thrown, this was the stack: flutter: #0 _StringBase.+ (dart:core/runtime/libstring_patch.dart:251:57) flutter: #1 _HomePageState.build.<anonymous closure> (package:bloc_pattern_for_booleans/main.dart:42:29) A: The error is because you are trying to sum String + null in this line: print("pritish" + snapshot.data); So, to fix your issue use String interpolation: print("pritish : ${snapshot.data}"); Don't forget to wrap your HomePage widget inside the provider. MaterialApp( home: Provider( child: HomePage() ), ),
{ "pile_set_name": "StackExchange" }
Q: Array.map doesn't seem to work on uninitialized arrays I'm trying to set default values on an uninitialized array using the map function but it doesn't seem to work, any ideas on how to set default values? Consider this code snippet I tried in Chrome console. > var N = 10; > var x = new Array(N); > x [undefined x 10] > x.map(function(i) { return 0;}); [undefined x 10] I was expecting the array to be initialized to 0's. A: If you'd like to fill an array, you can use Array(5).fill() and the methods will then work as expected--see the alternate related answer from aasha7. Older pre-fill approaches include: Array.apply(null, new Array(5)).map(function() { return 0; }); // [ 0, 0, 0, 0, 0 ] After some reading one of the posts linked in the comments, I found this can also be written as Array.apply(null, {length: 5}).map(function() { return 0; }); However, trying to use .map on undefined values will not work. x = new Array(10); x.map(function() { console.log("hello"); }); // so sad, no "hello" // [ , , , , , , , , , ] .map will skip over undefined values :( A: I'd just like to point out that you can now do: Array(2).fill().map(_ => 4); This will return [4, 4]. A: That's how it's described by the ECMAScript Language specification Here's the relevant part of Array.prototype.map, as described by (§15.4.4.19) ... 8. Repeat, while k < len a) Let Pk be ToString(k). b) Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument Pk. c) If kPresent is true, then do the magic ... Since there is no initilized member in your array, calling e.g new Array (1337).hasOwnProperty (42)evaluates to false, hence the condition in step 8.c is not met. You can however use a little "hack" to do what you want. Array.apply(null, { length: 5 }).map(Number.call, Number) //[0, 1, 2, 3, 4] How this works has been thouroughly explained by @Zirak
{ "pile_set_name": "StackExchange" }
Q: ¿Quisiera saber si mi consulta tiene registros en MySQL PHP? Tengo este código, pero lo que busco es como hacer para saber si el num_rows es mayor a 0, necesito ese proceso para poder mandar una notificación push en WS. $stmt= $conn->prepare("select Token from usuariosempleados;"); $stmt->execute(); if($stmt->bind_result($Token)->num_rows > 0) { echo enviarNotificacion($stmt->fetch(), $msj); } else { echo "-1"; } A: Puedes realizar lo siguiente /* Esta es la consulta SQL */ $consulta = $mysqli->prepare("SELECT empr.nombre_empresa FROM empresa empr WHERE empr.id_empresa = ? AND empr.token_empresa = ?"); /* Comprobamos si la consulta se preparó correctamente */ if ($consulta === false) { die('Error SQL: ' . $mysqli->error); } /*Asignamos al primer "?"*/ $consulta->bind_param('is', $idEmpresa, $tokenMovimiento); /* Comprobamos si la consulta se ejecutó correctamente */ if ($consulta->execute() === false) { die('Error SQL: ' . $consulta->error); } //Asignamos una variable al valor seleccionado desde nuestra consulta, esto si requieres usarla posteriormente, sino puedes obviar esta linea $consulta->bind_result($nombreEmpresa); /* Aquí obtenemos el registro (si lo hay) */ if ($consulta->fetch() !== true) { $resultado['mensaje'] = "No se han encontrado coincidencias"; } else { $resultado['mensaje'] = "Si ingresa aquí, es porque ha retornado un valor mayor que 0"; } //Imprimimos el valor que ha retornado como $mensaje echo json_encode($resultado);
{ "pile_set_name": "StackExchange" }
Q: UNIX password scheme and encryption function Recent versions of Unix store encrypted passwords in a file that is not publicly accessible. Such files are called shadow password files. In the UNIX password scheme, if only the operating system and system administrators have access to the password file. What are the security requirements for the underlying encryption function Ek? A: Most people would not call what we do to store passwords encryption as it is not reversible. It's a cryptographic hash. Also the diagram has some specific numbers which correspond to the orignal unix DES based system which nobody should be using any more for many reasons but mainly only 8 chars ASCII passwords. The principals however remain the same. We want to protext the system also in the event of data from the shadow file is leaked ans to a limited extent from the system adminstrator. It should be impossible to recover the plain text password from what we store, anyone trying to brute force the passwords should need to this one password at a time and not all together. Brute forcing passwords should be a slow process. It should not be practical to precompute rainbow tables for even a faily modest collection of passwords. We should still be able to verify a given plain text matches the stored record and it should be extremely unlikely another password will accidentally match. We do this with a special kind of cryptographic hash function and with the help a random salt. The salt (originally 12 bits nowadays more) makes attaxking passwords together and building rainbow tables very difficult. And the hash function should be slow so a single password brute force is impractical. Since the original implementation we also add that speed should be paramaterized so we can increase compute difficulty as computers become faster. This was missing in the original unix implementation. Also we want to support long passwords and we want the hash function to preserve as much of the entropy in the password as possible (unlike the infamous LanMan). The hash function should be preimage and collision resistant (unlike the LanMan). Some may want to add diverse charset support which many now use to increase password entropy.
{ "pile_set_name": "StackExchange" }
Q: Cut the background to expose the layer below Is there a way to cut a div background to expose the layer below?, like going from this: to this: Any bleeding edge css rule is welcome! UPDATE Ok, I've made a sample code: http://jsfiddle.net/coma/9ae7g/1/ <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Menu</title> <style type="text/css"> @charset 'UTF-8'; body { padding: 0; margin: 0; font-family: "Lucida Grande", "Lucida Sans Unicode", Tahoma, Verdana, Arial, sans-serif; font-size: 12px; background: #fff url("http://colourlovers.com.s3.amazonaws.com/images/patterns/1762/1762793.png?1314797062"); } a { text-decoration: none; } #menu { position: fixed; top: 0; left: 0; bottom: 0; width: 250px; } body.wide>#menu { width: 0; } #menu * { line-height: 1em; } #menu:after { content: ''; position: absolute; top: 0; right: 0; width: 5px; height: 100%; border-right: 1px solid #666; pointer-events: none; background: -moz-linear-gradient(left, rgba(0,0,0,0) 0%, rgba(0,0,0,0.25) 100%); background: -webkit-linear-gradient(left, rgba(0,0,0,0) 0%,rgba(0,0,0,0.25) 100%); background: -o-linear-gradient(left, rgba(0,0,0,0) 0%,rgba(0,0,0,0.25) 100%); background: -ms-linear-gradient(left, rgba(0,0,0,0) 0%,rgba(0,0,0,0.25) 100%); background: linear-gradient(to right, rgba(0,0,0,0) 0%,rgba(0,0,0,0.25) 100%); } #menu ul, #menu li { padding: 0; margin: 0; list-style: none; background-color: #fafafb; } #menu li { position: relative; } #menu>a { position: absolute; left: 100%; top: 50%; z-index: 1; display: block; width: 10px; height: 20px; margin: -10px 0 0 0; text-indent: -100em; overflow: hidden; border-radius: 0 2px 2px 0; background-color: #666; transition: background-color .3s ease-out; -moz-transition: background-color .3s ease-out; -webkit-transition: background-color .3s ease-out; -o-transition: background-color .3s ease-out; -ms-transition: background-color .3s ease-out; } #menu>a:before { position: absolute; top: 5px; right: 4px; display: block; content: ''; border-width: 5px 6px 5px 0; border-style: solid; border-color: transparent #fff transparent transparent; } body.wide>#menu>a:before { right: 2px; border-width: 5px 0 5px 6px; border-color: transparent transparent transparent #fff; } #menu>ul { height: 100%; background-color: #888; overflow: hidden; } #menu>ul span, #menu>ul a { display: block; padding: .4em; color: #666; font-weight: bold; border-bottom: 1px solid #999; } #menu>ul a { border-top: 1px solid #fff; border-bottom: 1px solid #e9ecee; } #menu>ul>li>span { font-size: 1.25em; font-weight: bold; color: #666; text-shadow: 0 1px 1px #fff; background-color: #eee; background-image: -moz-linear-gradient(top, rgba(0,0,0,0) 0%, rgba(0,0,0,0.2) 100%); background-image: -webkit-linear-gradient(top, rgba(0,0,0,0) 0%, rgba(0,0,0,0.2) 100%); background-image: -o-linear-gradient(top, rgba(0,0,0,0) 0%, rgba(0,0,0,0.2) 100%); background-image: -ms-linear-gradient(top, rgba(0,0,0,0) 0%, rgba(0,0,0,0.2) 100%); background-image: linear-gradient(top, rgba(0,0,0,0) 0%, rgba(0,0,0,0.2) 100%); cursor: pointer; transition: background-color .4s; -moz-transition: background-color .4s; -webkit-transition: background-color .4s; -o-transition: background-color .4s; -ms-transition: background-color .4s; } #menu>ul>li>span:hover { background-color: #fff; } #menu>ul>li>ul { display: none; } #menu>ul>li.opened>ul, #menu>ul>li.current_ancestor>ul { display: block; } #menu>ul>li>ul>li>a { font-size: 1.2em; color: #4183c4; transition: background-color .4s; -moz-transition: background-color .4s; -webkit-transition: background-color .4s; -o-transition: background-color .4s; -ms-transition: background-color .4s; } #menu>ul>li>ul>li.current>a, #menu>ul>li>ul>li.current>a:hover { color: #fff; background-color: #39f; border-color: #39f; } #menu>ul>li>ul>li.current:after { content: ''; position: absolute; right: -1px; top: 50%; margin: -9px 0 0 0; display: block; border-width: 10px 10px 10px 0; border-style: solid; border-color: transparent #fff transparent transparent; z-index: 1; } #menu>ul>li>ul>li>a:hover { background: #fff; } #menu>ul>li>ul>li:last-child { border-bottom: 1px solid #aaa; } #menu>ul>li>ul>li[data-count]:after { position: absolute; top: 50%; right: 14px; display: block; content: attr(data-count); padding: .26em .5em; background-color: #fff; border-radius: 8px; font-size: 12px; margin: -9px 0 0 0; color: #777; border-top: 1px solid #ccc; } #section { height: 2000px; } </style> </head> <body> <div id="menu"> <a title="cerrar o abrir el menú" href="#">toggle</a> <ul> <li class="first opened"> <span>Usuario</span> <ul class="menu_level_1"> <li class="first"> <a href="/logout">Logout</a> </li> <li class="current"> <a href="/">Home</a> </li> <li> <a href="/user/">Usuarios</a> </li> <li class="last"> <a href="/discount/">Descuentos</a> </li> </ul> </li> <li> <span>Artistas</span> <ul class="menu_level_1"> <li class="first"> <a href="/artist/">Artistas</a> </li> <li class="last"> <a href="/artists/top10">Top 10 (3)</a> </li> </ul> </li> <li> <span>Obras</span> <ul class="menu_level_1"> <li class="first"> <a href="/artwork/">Obras</a> </li> <li> <a href="/artworks/destacadas">Destacadas (4)</a> </li> <li class="last"> <a href="/artworks/ofertas">Ofertas (3)</a> </li> </ul> </li> <li> <span>Pedidos</span> <ul class="menu_level_1"> <li class="first last"> <a href="/order/">Pedidos</a> </li> </ul> </li> <li> <span>Blog</span> <ul class="menu_level_1"> <li class="first"> <a href="/article/">Artículos</a> </li> <li class="last"> <a href="/category/">Categorías</a> </li> </ul> </li> <li class="last"> <span>Newsletter</span> <ul class="menu_level_1"> <li class="first last"> <a href="/newsletter/">Emails</a> </li> </ul> </li> </ul> </div> <div id="section"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var style = { opened: 'opened', wide: 'wide', currentAncestor: 'current_ancestor' }; var menu = $('#menu'); var items = $('#menu>ul>li'); var body = $('body'); items.filter('.' + style.currentAncestor) .removeClass(style.currentAncestor) .first() .addClass(style.opened); items.children('span').click(function(event) { event.preventDefault(); var group = $(this).parent(); if(!group.hasClass(style.opened)) { items.filter('.' + style.opened).removeClass(style.opened); group.addClass(style.opened); } }); menu.children('a').click(function(event) { event.preventDefault(); body.toggleClass(style.wide); }); }); </script> </body> </html> The birdy background and the #section with a height of 2000px is just for testing by moving the content. Thanks to everyone! A: An element will be transparent if it and all of it's children are transparent (no background-color, no background-image). To accomplish what you're asking for, here's what I'd do: Avoid background styling on the container of that group of elements. Do all background styling on those individual navigation elements via a single image, even if you have to clip it to get it to be flexible. For the active navigation element, swap the background image to one which has the transparent indent that you want. See this JSFiddle, forked from your code: http://jsfiddle.net/2XSd5/. This demonstrates the approach I described: make all backgrounds transparent, and use a background image for the cut out. Here's the code that I modified: #menu:after { background: none; } #menu > ul > li > ul > li.current:after { content: none; } #menu ul, #menu li { background-color: transparent; } #menu > ul { background-color: transparent; } #menu > ul > li > ul > li > a, #menu > ul > li > ul > li > a { background-color: white; } #menu > ul > li > ul > li.current > a, #menu > ul > li > ul > li.current > a:hover { background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAAyCAYAAADm1uYqAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAV5JREFUeNrs21FKw0AUQNEZcQluR91EVXSFQnUN1f3oEjROSwQrcYyl4HvhHHjQhHzl4yZtZ+rQFIAETtwCQLAABAsQLADBAhAsQLAABAtAsADBAhAsAMECFh+sYRyAFMEqogVEd9qmjp+r2wEE9DIVLICIsbr6GiyAyLF6+jzhX0IgRawEC0gTK8ECIsbqeipWggVE8tqLlWABkWJ10+a5d5FgARFidTvGqrvzRrCA/3bXZtPm/bcLrcNavu3Tqv5wfMh2LAuNOba3MnOLoDes3CGaM6VzLExEcN/mfM4DVLDyxukvb0K17O8ZnTOlcx6O6azNeoyWYC1APWDKRGQEh8jRemxzIVjAIqIlWECaaAkWEDVal4IFZInWw/do1aFxb4CgtpuhV4IFZIrWjpXuQIavhzt+wwLSECxAsAAECxAsAMECECxAsAAEC0CwAMECECwAwQIECyCEDwEGAGnvSNs6OT13AAAAAElFTkSuQmCC) right center no-repeat; color: grey; }
{ "pile_set_name": "StackExchange" }
Q: Heroku: Combining node.js and java dynos in the same app I am building a web api service that has two components: node.js and java. Every request reaches the node service which in turn makes an API call to the java service. I implemented this architecture using two different heroku apps, with both services implemented as "web" dynos. It works, but it will be easier to manage as a single app. I don't fully understand what are the options and the process for combining the two components in the same application. I guess I can make two entries in the Procfile, but I don't understand how the request routing could work. How can the node "web" dyno make requests to the java dyno? Is there some mechanism for inter-dyno requests? A: Heroku only allows the "web" dyno to accept network connections (well, HTTP at least...). The docs say specifically "The web process type is special as it’s the only process type that will receive HTTP traffic from Heroku’s routers. Other process types can be named arbitrarily." Looking at a similar question, my $.02 would be that an MQ-based solution (or something MQ-ish, like Redis pub/sub) would be the way to go. The rub is that it works best if the API call is asynchronous. For example, you could have the Node app publish to a Redis channel, and have your Java processes (defined via a 'worker' dyno in your Procfile). If the Node app actually needs the results as part of it's response... hm... I suppose you'd have to build something going the opposite direction, and include enough data in the message or channel structure to match up responses with the originating request. In that case, you might just be better off sticking with the multi-app configuration. Though I have not tested the FIFO solution mentioned there, I'm not clear how it would work since the dynos are isolated from each other.
{ "pile_set_name": "StackExchange" }
Q: Special characters must be escaped: [>] Ok, I'm lost. I created this unordered list with 6 items (no bullets intentional). the problem is the last two items of the list are coming up with "Special characters must be escaped: [>]" in Dreamweaver CC 2017. Call me blind, but I am just not seeing any special characters in those lines. Am I missing something obvious? <ul style="list-style-type:none"> <li>The Oscar is only worth $1</li> <li>It takes 10 days to make one Oscar</li> <li>The statuettes are 24K gold plated, bronze underneath</li> <li>For 3 years during WWII, the statues were made of plaster</li> <li>>Over 3000 Oscars have been awarded</li> <li>>The statues are 8.5 pounds and 13.5 inches tall</li> </ul> A: They're in your last two items: <li>>Over 3000 Oscars have been awarded</li> <li>>The statues are 8.5 pounds and 13.5 inches tall</li> Strictly speaking though, you don't need to encode them in this context; doing so is always good advice, but what you have here isn't invalid. But in any case, judging by the content they probably weren't supposed to be there in the first place and so your first instinct is probably to remove them; go ahead and do so.
{ "pile_set_name": "StackExchange" }
Q: Access values within a JSON object using Javascript I have a JSON object (of objects) that firefox tells me looks like this: Object(8) ​0: Object { name: "Appleby", value: 8670, line_count: 4, … } ​1: Object { name: "Armthorpe", value: 1470, line_count: 3, … } ​2: Object { name: "Blackbrook", value: 300, line_count: 2, … } ​3: Object { name: "Blackpool", value: 600, line_count: 1, … } I would like to extract two arrays from this, a list of the names and values, such as: myArray['names'] = ["Appleby", "Armthorpe", ...] myArray['values'] = [8670, 1470, ...] Can you please advise how I can do this? I tried using a for in loop but it only returned intergers not the objects. A: Pass in your object of objects as inputObject and use this function: /** * This function converts a JSON object of objects into two separate arrays: * 1. names * 2. values */ function myFunction(inputObject) { const myArray = { // should be myObject, really. names: [], values: [] }; for(const item of inputObject) { myArray.names.push(item.name); myArray.values.push(item.value); } return myArray; }
{ "pile_set_name": "StackExchange" }
Q: Creating a custom pcore for Xilinx ISE 14.7? A bit of a general question, but what is the most popular/common/easiest way of creating a custom pcore? I have seen some examples and they were mostly done on Matlab and since I do not have Matlab anywhere, I am a bit lost here. There has got to be a proper way of doing without it! Thank you in advance!!! A: You can create it with VHDL or Verilog languages, but after that you need to make few files like .mdp and .pao, create directory move all the files there and then put the directory to a library. Detailed information you can find in Xilinx Manual
{ "pile_set_name": "StackExchange" }
Q: Howto easily monitor usage of Eden and Survivor Spaces What is the best way howto monitor usage of Eden and Survivor heap spaces? I have all the GC logging options on but I can see only YoungGen occupation: -XX:+PrintTenuringDistribution -XX:+UnlockDiagnosticVMOptions -XX:+LogVMOutput -XX:LogFile=jvm.log -server -XX:+HeapDumpOnOutOfMemoryError -XX:+DisableExplicitGC -Xloggc:gc.log -XX:+PrintGCTimeStamps -XX:+PrintGCDetails -showversion -XX:+PrintClassHistogramBeforeFullGC -XX:+PrintClassHistogramAfterFullGC -XX:+UseParallelOldGC -XX:ParallelGCThreads=4 -XX:MaxTenuringThreshold=15 I would use VisualGC but cannot find its distribution anywhere. The default distribution of VisualVM that comes with JDK does not come with VisualGC. The VisualGC plugin links to the VisualGC site are broken. UPDATE: jstat is what I was looking for, specifically : jstat -gcutil -t <pid> <interval> <number_of_samples> A: If I understand you correctly, I think you can use JVisualVM to monitor your Java applications. A: Depending on what you mean by "monitor", you might just need jstat. Check out the -gc* options. A: According to this page, you can download the relevant plugin center "updates.xml" file, an install it per the instructions. Then you can install the VisualGC plugin. But the page also says that you should simply be able to install plugins using "Tools | Plugins | Available Plugins". The links to projects on java.net are often broken in my experience. You typically have to look harder to find stuff that is hosted there.
{ "pile_set_name": "StackExchange" }