instruction
stringlengths
22
34.6k
input
stringclasses
1 value
output
stringlengths
70
4.33k
python - RGB matrix of an image <sep> Taking an image as input, how can I get the rgb matrix corresponding to it? I checked out the numpy.asarray function. Does that give me the rgb matrix or some other matrix?
Note that this answer is outdated as of 2018; `scipy` has deprecated `imread`, and you should switch to `imageio.imread`. See this transition doc about differences between the two. The code below should work with no changes if you just import the new library in place of the old, but I haven't tested it. The simplest answer is to use the NumPy and SciPy wrappers around PIL. There's a great tutorial, but the basic idea is: ```python from scipy import misc arr = misc.imread('lena.png') # 640x480x3 array arr[20, 30] # 3-vector for a pixel arr[20, 30, 1] # green value for a pixel ``` For a 640x480 RGB image, this will give you a 640x480x3 array of `uint8`. Or you can just open the file with PIL (or, rather, Pillow; if you're still using PIL, this may not work, or may be very slow) and pass it straight to NumPy: ```python import numpy as np from PIL import Image img = Image.open('lena.png') arr = np.array(img) # 640x480x4 array arr[20, 30] # 4-vector, just like above ``` This will give you a 640x480x4 array of type `uint8` (the 4th is alpha; PIL always loads PNG files as RGBA, even if they have no transparency; see `img.getbands()` if you're ever unsure). If you don't want to use NumPy at all, PIL's own `PixelArray` type is a more limited array: ```python arr = img.load() arr[20, 30] # tuple of 4 ints ``` This gives you a 640x480 `PixelAccess` array of RGBA 4-tuples. Or you can just call `getpixel` on the image: ```python img.getpixel(20, 30) # tuple of 4 ints ```
How do I swap the order of two parents of a Git commit? <sep> A merge commit is a commit with at least two parents. These parents are in specific order. If I'm currently on the branch <code>master</code>, and I merge in the branch <code>feature</code>, I create a new commit with its first parent being the commit from <code>master</code>, and the second commit being the commit from <code>feature</code>. This order is especially evident by running <code>git log --first-parent</code>. <code>* The merge commit |\ | * The commit from `feature` * | The commit from `master` </code> Say I now realise that the order is the wrong way round: I intended to merge the branch <code>master</code> into <code>feature</code> by running <code>git checkout feature; git merge master</code>. I want to swap the order of the parents of a merge commit, but I do not want to go through the hassle of resolving all the merge conflicts again. How can I do this? <code>* The merge commit |\ * | The commit from `feature` | * The commit from `master` </code>
Actually, there's a really cool command I learned recently that will do exactly what you want: ``` git commit-tree -p HEAD^2 -p HEAD^1 -m "Commit message" "HEAD^{tree}" ``` This will create a new commit based on what is currently HEAD, but pretend that its parents were HEAD^2, HEAD^1 (note this is the reversed order). `git commit-tree` prints the new revision as output, so you might combine it with a `git reset --hard`: ``` git reset --hard $(git commit-tree -p HEAD^2 -p HEAD^1 -m "New commit message" "HEAD^{tree}") ```
jQuery create and append multiple elements <sep> I have created 2 divs, Div1(freeze) Div2(parent) and again 3 divs(loading, header, msg) appended it to Div2(parent). Entire divs in to body tag. Below are my code, I think there is some other best way to achieve this. <code> var freeze = $('<div/>',{ "class" : "freeze" }); var parent = $('<div/>',{ "class":"parent" }); var loading = $('<div/>',{ "class":"loadimg" }).appendTo(parent); var header = $('<div/>',{ "class":"header" }).appendTo(parent); var msg = $('<div/>',{ "class":"msg" }).appendTo(parent); $('body').append(freeze,parent); </code>
```javascript $('body').append([ $('<div/>', { "class": "freeze" }), $('<div/>', { "class": "parent" }).append([ $('<div/>', { "class": "loadimg" }), $('<div/>', { "class": "header" }), $('<div/>', { "class": "msg" }) ]) ]); ``` In some cases, operating with structural data is more reliable and convenient than raw markup.
Accessing Objective-c base class's instance variables from a Swift class <sep> Having an Objective c base class: <code>@interface ObjcClass : NSObject { NSString *aVariable_; } </code> And a swift sub-class: <code>class SwiftClass : ObjcClass { func init() { // aVariable_ can't be accessed here. An Objective-c derived // class has direct access to it's super's instance variables! } } </code> How do I access <code>ObjcClass</code> <code>aVariable_</code> from within <code>SwiftClass</code>?
Great query. We have tried hard to get this done. The only working solution I found is to get the value by using `self.valueForKey("aVariable_")` and set the value using `self.setValue("New Value", forKey: "aVariable_")`. Hope that helps. A possible solution without altering the superclass.
How to get the 3D view of UI in Xcode 6? <sep> I am a newbie in this field of development. I started using Xcode 6 after using Xcode 5.1.1 for a week. After getting fascinated with newly added features, I installed Xcode 6. Now, I am not able to find this 3D view of UI in ios. I am using OSX 10.9.4.
Run the app. View Debugging works in the simulator and on devices, but it's important to note that it needs to be an iOS 8 simulator or device. That said, you may allow earlier deployment targets in your project, just make sure you run on iOS 8 when you try View Debugging. Navigate to the screen/view that you want to inspect within the running app. In the Navigators Panel (left column), select the Debug Navigator (sixth tab). Next to your process, you'll see two buttons—press the rightmost button and select "View UI Hierarchy." Alternatively, use the menu: Xcode will stop your app and let you inspect your views. There's no need for you to set a breakpoint; Xcode will do that for you. However, if you want to set a breakpoint manually to inspect local variables, etc., alongside your views, you can set a normal breakpoint and once the app pauses, press the View Debugging button in the Debug Area (bottom panel).
Move a view when scrolling in UITableView <sep> I have a <code>UIView</code> with a <code>UITableView</code> below it: What I would like to do is to have the view above the <code>UITableView</code> move up (out of the way) when the user starts scrolling in the table in order to have more space for the <code>UITableView</code> (and come down when you scroll down again). I know that this is normally done with a table header view, but my problem is that my table view is inside a tab (actually it is a side-scrolling page view implemented using <code>TTSliddingPageviewcontroller</code>). So while I only have one top <code>UIView</code> there are three <code>UITableView</code>s. Is it possible to accomplish this manually? My first thought is to put everything in a <code>UIScrollView</code>, but according to Apple's documentation one should never place a <code>UITableView</code> inside a <code>UIScrollView</code> as this leads to unpredictable behavior.
```swift var oldContentOffset = CGPoint.zero let topConstraintRange = (CGFloat(120)...CGFloat(300)) func scrollViewDidScroll(scrollView: UIScrollView) { let delta = scrollView.contentOffset.y - oldContentOffset.y if delta > 0 && topConstraint.constant > topConstraintRange.lowerBound && scrollView.contentOffset.y > 0 { topConstraint.constant -= delta scrollView.contentOffset.y -= delta } else if delta < 0 && topConstraint.constant < topConstraintRange.upperBound && scrollView.contentOffset.y < 0 { topConstraint.constant -= delta scrollView.contentOffset.y -= delta } oldContentOffset = scrollView.contentOffset } ```
Sort NSArray with sortedArrayUsingComparator <sep> In <code>Objective-C</code> I can sort an <code>NSArray</code> using this statement: <code>NSArray *sortedArray = [persons sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2) { return [p1.name compare:p2.name]; }]; </code> I'm unable to reproduce the same statement with Swift. All I found was using <code>Array</code>.
You can use Swift's built-in `sort` functions or, since a Swift array is bridged to `NSArray`, you can call `sortedArrayUsingComparator` from Swift directly. Using Swift's `sorted` function: ```swift var sortedArray = persons.sorted { (obj1, obj2) in let p1 = obj1 as Person let p2 = obj2 as Person return p1.name < p2.name } ``` Or, using `NSArray`'s `sortedArrayUsingComparator`: ```swift var sortedArray = persons.sortedArrayUsingComparator { (obj1, obj2) -> NSComparisonResult in let p1 = obj1 as Person let p2 = obj2 as Person let result = p1.name.compare(p2.name) return result } ```
C++ round a double up to 2 decimal places <sep> I am having trouble rounding a GPA double to 2 decimal places. (ex of a GPA needed to be rounded: 3.67924) I am currently using ceil to round up, but it currently outputs it as a whole number (368) here is what I have right now <code>if (cin >> gpa) { if (gpa >= 0 && gpa <= 5) { // valid number gpa = ceil(gpa * 100); break; } else { cout << "Please enter a valid GPA (0.00 - 5.00)" << endl; cout << "GPA: "; } } </code> using the above code with 3.67924 would output 368 (which is what I want, but just without the period between the whole number and the decimals). How can I fix this?
To round a double up to 2 decimal places, you can use: ```cpp #include <iostream> #include <cmath> int main() { double value = 0.123; value = std::ceil(value * 100.0) / 100.0; std::cout << value << std::endl; // prints 0.13 return 0; } ``` To round up to *n* decimal places, you can use: ```cpp double round_up(double value, int decimal_places) { const double multiplier = std::pow(10.0, decimal_places); return std::ceil(value * multiplier) / multiplier; } ``` This method won't be particularly fast; if performance becomes an issue, you may need another solution.
How to change(Hide) the Nginx Server Signature? <sep> I can hide Nginx version by using server_tokens option set to off. But not able to change the Nginx Server signature. Steps I did, 1.) Change the Nginx server name in source file(src/http/ngx_http_header_filter_module.c) to " My-Server". After that, compiled the nginx. But its not working when I load the url. Strange here is I can see my updated Signature when I use curl command. But this same is not updated in browser. 2.) So I tried 3rd party module(headers-more-nginx-module). This too not working. Getting updated name via Curl. But not in Browser.
If you are working in Ubuntu, then first install `nginx-extras` with `sudo apt-get install nginx-extras`. Go to `/etc/nginx/nginx.conf` and under `http`, add: `http { more_set_headers "Server: Your_New_Server_Name"; server_tokens off; }`. Restart nginx with `sudo service nginx restart`.
Chrome debugger - how to turn off console.log message grouping? <sep> Say, in my Google Chrome extension I do this: <code>console.log(msg); </code> and the Chrome debugger groups similar messages like so: Is there any any to turn it off and have messages post just as they are?
It only collapses consecutive identical rows. I don't see it as much of a problem, but with the settings button in the top right corner of the console, you can enable 'Show timestamps,' which will put them on different lines. You can see they only collapse consecutive duplicates with this: ```javascript msgs = ['hello', 'world', 'there']; for (i = 0; i < 20; i++) console.log(msgs[Math.floor((i/3)%3)]); ``` The console API has a lot of other functions that might help you follow your code. For instance, `console.count(label)` logs label with a count of how many times it's been logged, `console.group()` lets you group other logging calls together, and `console.timeline(label)` lets you group logs into a timeline.
O(N+M) time complexity <sep> I'm working through some practice problems where I'm given a target time complexity and space complexity. One of them gives a target time complexity of O(N+M). I'm having some trouble with the intuition of what an O(N+M) algorithm would look like. Does anyone have an example of an algorithm like this or can explain it clearly? Every example I try to think of seems like O(N*M) to me.
Quick and simple example of an O(n + m) algorithm: ``` for (i = 0; i < n; i++) { // do something but don't loop or invoke recursive functions // only constant O(c) complexity is allowed: a simple series of commands } for (i = 0; i < m; i++) { // idem } ``` Complexity is commutative when added (O(n + m) == O(m + n)), this means you may invert the two `for()` loops without affecting complexity. Obviously, on an algorithmic level the inverted one MAY not be equivalent to the straight one. As an additional help, here is an example of an O(n * m) algorithm: ``` for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { // do something but don't loop or invoke recursive functions // only constant O(c) complexity is allowed: a simple series of commands } } ``` Again, you may invert the inside with outside loops without affecting complexity (O(n * m) == O(m * n)). The same obvious considerations apply. The limitation on what you may put into the `for()` bodies is because the big-O notation constraints the upper bound. If it were a lower bound (little-o notation) you may have put more complex stuff in, but it could never get less than that.
How to check that a file has more than 1 line in a BASH conditional? <sep> I need to check if a file has more than 1 line. I tried this: <code>if [ `wc -l file.txt` -ge "2" ] then echo "This has more than 1 line." fi if [ `wc -l file.txt` >= 2 ] then echo "This has more than 1 line." fi </code> These just report errors. How can I check if a file has more than 1 line in a BASH conditional?
The command: ``` wc -l file.txt ``` will generate output like: ``` 42 file.txt ``` with `wc` helpfully telling you the file name as well. It does this in case you're checking out a lot of files at once and want individual as well as total stats: ``` pax> wc -l *.txt 973 list_of_people_i_must_kill_if_i_find_out_i_have_cancer.txt 2 major_acheivements_of_my_life.txt 975 total ``` You can stop `wc` from doing this by providing its data on standard input, so it doesn't know the file name: ``` if [[ $(wc -l <file.txt) -ge 2 ]] ``` The following transcript shows this in action: ``` pax> wc -l qq.c 26 qq.c pax> wc -l <qq.c 26 ``` As an aside, you'll notice I've also switched to using `[[ ]]` and `$()`. I prefer the former because it has less issues due to backward compatibility (mostly to do with string splitting) and the latter because it's far easier to nest executables.
Running node-inspector alongside nodemon? <sep> I'm currently using node along with nodemon. Then I got to thinking it might be sometimes nice to use an inspector with node so have started using node-inspector However, is it possible to run both at the same time? Normally to run nodemon I would use: <code>nodemon server.js //and similarly node-debug server.js </code> I have also tried: <code>nodemon --debug http.js </code> But sadly this didn't work either. But both together!?
If you want to run them as one command, this works for me: `node-inspector & nodemon --debug app.js` (replacing app.js with the name of your script). If things get messed up, you will occasionally have to kill node-inspector manually, but running the command this way gives you the option of running `rs` to restart nodemon manually if needed. HTH
Import Cordova project in Android Studio <sep> I am trying to create a Cordova project. After creating the project <code>cordova create myProject</code> I would like to open it in Android Studio. The problem is ... it doesn't work. The CordovaLib will not build with various errors <code>package android.* does not exist</code>. Does anyone know how to import a cordova project in Android Studio?
Unfortunately, the accepted answer is a bit out of date. Using Cordova v5.3.3 (it probably works on all versions > 5), the process is much the same as building and then entering Xcode for an iOS application now—the build system has moved to Gradle. Before opening in Android Studio, run `cordova build android`. Then, just open the project using File > Open and pointing to the (yourProjectDir)/Platforms/Android directory. If you are using an older version of the Cordova Android platform, you might need to run `cordova platform android update` to get moved to the Gradle build system, which is compatible with the current version of Android Studio.
How to remove all packages from specific repo without dependencies <sep> I know following code will remove all package from specific repo. <code>yum remove $(yum list installed | grep rpmforge | awk '{ print $1 }') </code> And following code will remove a package without dependencies. <code>rpm -e --nodeps "php-sqlite2-5.1.6-200705230937" </code> But i don't know how to use together.
Print a list of all repositories to get the repo ID (first column): ``` $ dnf repolist ``` Now remove all packages from the selected repository: ``` # dnf repository-packages <repo-id> remove ``` See the "repository-packages" section of the `dnf` manual page for details regarding manipulation of all packages in a specific repository.
Android Studio, change the editor background color (not the whole theme) <sep> The same question was marked as "duplicate" even though it obviously was not a duplicate. At least it should be obvious to anyone who is familiar with configuring an editor. When you want to change the background color, you aren't talking about changing the whole theme, you are talking about changing the background color. Is there a way to change only the background color in Android Studio editor?
Sorry, but I believe you all have this one wrong. To change the editor's background, go to File, Settings, Editor, Colors & Fonts, and select General. You'll see an item called "Default text." On the right side of the window, you'll see a checkbox for background. Click in the color window and choose your preferred color. Now the entire editor window will show that color as the background.
Clone project with eclipse? <sep> I'm learning JAVA with Eclipse (ADT , Latest version - For Android development). Each lesson we enhance the same project. (I don't like this approach) So - I want to create different project for each lesson so : Each lesson I'm cloning the main folder - and then I import it as an existing project. ( I thought that cloning + renaming the folder - would be fine) But : Eclipse says that the project already exists. (make sense) Question If I have a folder that contains a project ( <code>LeadoMat</code>) : , And I'm creating folder <code>LeadoMat_Ver2</code> ( cloned files) How/What should I do in order for eclipse to accept it as a new project named : <code>LeadoMat_Ver2</code> ?
The simplest approach would probably be to do the copying right in `eclipse`: `Right Click your Project -> Copy`, `Right Click in the Project Explorer -> Paste` or `CTRL + C & CTRL + V`. Eclipse will then automatically prompt you to enter a new name for the clone. Then you'll have a full copy of your project with the new name. The reason why `eclipse` thinks that it is the same project is because you also clone the `.project` files, which contain the name of the project used in `eclipse`.
Is it possible to create a data type of length one bit in C <sep> Esentially I want to create a data type <code>uint1_t</code>. Is that even possible? I know the size of the bool data type is one byte. But boolean values only need one bit. So does C essentially only use one bit for bool? If yes, then what does it do with the other seven. Using eight bits where one is sufficient seems such a waste of space.
It is not really possible to create a type that occupies one bit. The smallest addressable unit in C is the `char` (which is by definition one byte and usually, but not necessarily, 8 bits long; it might be longer but isn't allowed to be shorter than 8 bits in Standard C). You can approach it with: `typedef _Bool uint1_t;` or: `#include <stdbool.h> typedef bool uint1_t;` but it will occupy (at least) one byte, even though a Boolean variable only stores the values 0 or 1, `false` or `true`. You could, in principle, use a bit-field: `typedef struct { unsigned int x : 1; } uint1_t;` but that will also occupy at least one byte (and possibly as many bytes as an `unsigned int`; that's usually 4 bytes) and you'll need to use `.x` to access the value. The use of bit-fields is problematic (most aspects of them are implementation defined, such as how much space the storage unit that holds it will occupy) — don't use a bit-field. (Including amendments suggested by Drew McGowen, Drax and Fiddling Bits.)
Array.from vs Array.prototype.map <sep> So what is the difference between this two functions? They both create <code>new Array</code> object. Only difference I found so far is that <code>Array.from</code> supports <code>ArrayLike</code> parameters. I don't see any reason why they just haven't added <code>ArrayLike</code> support for <code>Array.prototype.map</code> function. Am I missing something?
The purpose of `Array.from()` is to take a non-array (but array-like) object and make a copy of it into an actual array. This then allows you to use all array methods on the copy, including things beyond just iterating it, such as `splice()`, `sort()`, `push()`, `pop()`, etc. This is obviously much more capable than just making `map()` work with array-like things.
What is the definition of cardinality in SQL <sep> My school book Database Systems defines cardinality as follows: <blockquote> The cardinality of a relation is the number of tuples it contains. By contrast, the number of tuples is called the cardinality of the relation and this changes as tuples are added or deleted. High-cardinality - many tuples, low-cardinality - few tuples. </blockquote> While the Wikipedia article on Cardinality (SQL statements), defines it as follows: <blockquote> Cardinality refers to the uniqueness of data values contained in a particular column (attribute) of a database table. The lower the cardinality, the more duplicated elements in a column. There are 3 types of cardinality: high-cardinality, normal-cardinality, and low-cardinality. </blockquote> They might both be right, but i can't connect the two definitions as related definitions. A rephrase would be appriciated!
They are speaking the same thing and it has to do with tuples (relational algebra) or rows (layman's term). When it says high-cardinality, it refers to possible values of a particular attribute (or field) that are unique, and therefore the number of rows or tuples is higher. **Example:** ``` StudentID Lastname Firstname Gender 101 Smith John M 102 Jones James M 103 Mayo Ann F 104 Jones George M 105 Smith Suse F ``` As far as StudentID is concerned, the cardinality is high because it is unique. In this case, there are five (5) tuples/rows. On the other hand, Lastname has normal cardinality, with only three (3) unique tuples/rows. Thus, it has normal cardinality. And finally, Gender has only two possible unique values, resulting in low cardinality. You probably confuse cardinality with the degree of a relation, which has to do with the number of attributes/fields in a relation (or table). On the other hand, when speaking of cardinality in the context of databases, it usually refers to the relationship between entities. That is, the number of possible relationship occurrences for an entity participating in a given relationship type. Thus, for example, for a binary relationship, cardinality could be either one-to-one, one-to-many, or many-to-many.
Caused by: android.database.sqlite.SQLiteException: no such table: (code 1) Android <sep> We have a sqlite database in our Application. Its working fine for all the users but few of them experiencing the <code>Caused by: android.database.sqlite.SQLiteException: no such table: generalSettings (code 1): , while compiling: select * from generalSettings</code> error. Below is my sqlite helper class to create the db and the error log. In <code>assert/Master.db</code> we have the table <code>generalSettings</code>. But after copying it to the device the table is missing. This is happening only for few users. I searched for the solution but I cant find the exact one. Team please help me to fix this. Code: <code>import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.util.Log; public class InstallDB extends SQLiteOpenHelper { Context ctx; String DBNAME; String DBPATH; Modules modObj = new Modules(); public InstallDB(Context context, String name) { super(context, name, null, 1); this.ctx = context; this.DBNAME = name; this.DBPATH = this.ctx.getDatabasePath(DBNAME).getAbsolutePath(); Log.e("Path 1", DBPATH); } public void createDataBase() { boolean dbExist = checkDataBase(); SQLiteDatabase db_Read = null; if (!dbExist) { synchronized (this) { db_Read = this.getReadableDatabase(); Log.e("Path 2", this.getReadableDatabase().getPath()); db_Read.close(); copyDataBase(); Log.v("copyDataBase---", "Successfully"); } // try { // } catch (IOException e) { // throw new Error("Error copying database"); // } } } private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DBPATH; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } catch (Exception e) { Log.i("SQLite Error", "database does't exist yet."); } if (checkDB != null) { checkDB.close(); } return checkDB != null ? true : false; } private void copyDataBase() { try { InputStream myInput = ctx.getAssets().open(DBNAME); String outFileName = DBPATH; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024 * 3]; int length = 0; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); myInput.close(); } catch (Exception e) { Modules.stacTaceElement = e.getStackTrace(); StringWriter stackTrace1 = new StringWriter(); e.printStackTrace(new PrintWriter(stackTrace1)); System.err.println(stackTrace1); Intent send = new Intent(Intent.ACTION_SENDTO); String uriText; uriText = "mailto:test@test.com" + "&subject=Error Report" + "&body=" + stackTrace1.toString(); uriText = uriText.replace(" ", "%20"); Uri uri = Uri.parse(uriText); send.setData(uri); ctx.startActivity(Intent.createChooser(send, "Send mail...")); // TODO: handle exception } } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } </code> Error Log: <code>java.lang.RuntimeException: Unable to start activity ComponentInfo{palmagent.FidelityAgent.Two/palmagent.FidelityAgent.Two.PassNew}: android.database.sqlite.SQLiteException: no such table: generalSettings (code 1): , while compiling: select * from generalSettings at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5102) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method) Caused by: android.database.sqlite.SQLiteException: no such table: generalSettings (code 1): , while compiling: select * from generalSettings at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58) at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44) at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314) at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253) at palmagent.FidelityAgent.Two.masterDatabase.selectquery(masterDatabase.java:59) at palmagent.FidelityAgent.Two.Modules.checkDatabase(Modules.java:28825) at palmagent.FidelityAgent.Two.PassNew$LoaduserDetails.onPreExecute(PassNew.java:140) at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587) at android.os.AsyncTask.execute(AsyncTask.java:535) at palmagent.FidelityAgent.Two.PassNew.onCreate(PassNew.java:120) at android.app.Activity.performCreate(Activity.java:5248) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173) ... 11 more </code>
After spending a couple of hours, I got this solution: 1) Settings > Application Manager 2) Select App 3) Clear Data 4) Uninstall App. Now run the app from Android Studio. Hope this works properly.
Why does a boxplot in ggplot requires axis x and y? <sep> I have a variable ceroonce which is number of schools per county (integers) in 2011. When I plot it with <code>boxplot()</code> it only requires the ceroonce variable. A boxplot is then retrieved in which the y axis is the number of schools and the x axis is... the "factor" ceroonce. But in <code>ggplot</code>, when using <code>geom_boxplot</code>, it requires me to input both x and y axis, but I just want a boxplot of ceroonce. I have tried inputing ceroonce as both the x and y axis. But then a weird boxplot is retrieved in which the y axis is the number of schools but the x axis (which should be the factor variable) is also the number of schools? I am assuming this is very basic statistics, but I am just confused. I am attaching the images hoping this will clarify my question. This is the code I am using: <code>ggplot(escuelas, aes(x=ceroonce, y=ceroonce))+geom_boxplot() boxplot(escuelas$ceroonce) </code>
``` ggplot(escuelas, aes(x = "ceroonce", y = "ceroonce")) + geom_boxplot() ggplot will interpret the character string "ceroonce" as a vector with the same length as the ceroonce column and it will give the result you're looking for. ```
Black Border on My IOS Icon <sep> I plugged in my application, the icons for the application itself .. Unfortunately I have a problem. In the Home Screen icon has a black border. What am I doing wrong? Why in the simulator I see correctly while the icon on the device I can not see properly. I am attaching the screen thanks, Vincenzo icon iphone simulator icon real device
You probably can't see it on the simulator because it has a black background. I'm going to guess that you have some transparency in your icon. Make sure your icon fills the entire image; you don't need to add the corner radius yourself, as the OS will do it for you.
How to divide list in a single ul into 3 columns <sep> I have a ul has list inside it. Is it possible to divide the list into 3 columns. The structure of my html is like this: <code> <ul> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul> </code> Problem: I cannot directly edit the page and divide the list in to 3 ul. I must edit it via CSS. Output: The final output should have 3 columns. And edited via CSS Please help me.
CSS3 `flexbox` can also do this: ```css ul { flex-direction: column; flex-wrap: wrap; display: flex; height: 100vh; } ul li { flex: 1 0 25%; } ``` Above CSS will create the following layout: ``` +--------------------+ | 01 | 05 | 09 | +--------------------+ +--------------------+ | 02 | 06 | 10 | +--------------------+ +--------------------+ | 03 | 07 | 11 | +--------------------+ +--------------------+ | 04 | 08 | 12 | +--------------------+ ``` ```css * { box-sizing: border-box; } body { margin: 0; } .list { flex-direction: column; list-style: none; flex-wrap: wrap; height: 100vh; display: flex; padding: 0; margin: 0; } .list li { border-bottom: 1px solid #fff; border-right: 1px solid #fff; flex: 1 0 25%; padding: 10px; color: #fff; } .col1 { background: blue; } .col2 { background: orange; } .col3 { background: green; } ``` ```html <ul class="list"> <li class="col1">Test 1</li> <li class="col1">Test 2</li> <li class="col1">Test 3</li> <li class="col1">Test 4</li> <li class="col2">Test 5</li> <li class="col2">Test 6</li> <li class="col2">Test 7</li> <li class="col2">Test 8</li> <li class="col3">Test 9</li> <li class="col3">Test 10</li> <li class="col3">Test 11</li> <li class="col3">Test 12</li> </ul> ``` In case you want the following layout: ``` +-----------------------+ | 1 | 2 | 3 | 4 | +-----------------------+ +-----------------------+ | 5 | 6 | 7 | 8 | +-----------------------+ +-----------------------+ | 9 | 10 | 11 | 12 | +-----------------------+ ``` you can use the following CSS: ```css ul { flex-wrap: wrap; display: flex; } ul li { flex: 1 0 25%; } ``` ```css * { box-sizing: border-box; } body { margin: 0; } .list { list-style: none; flex-wrap: wrap; display: flex; padding: 0; margin: 0; } .list li { border-bottom: 1px solid #fff; flex: 1 0 25%; padding: 10px; color: #fff; } .list li:nth-child(4n + 1) { background: blue; } .list li:nth-child(4n + 2) { background: orange; } .list li:nth-child(4n + 3) { background: green; } .list li:nth-child(4n + 4) { background: purple; } ``` ```html <ul class="list"> <li>Test 1</li> <li>Test 2</li> <li>Test 3</li> <li>Test 4</li> <li>Test 5</li> <li>Test 6</li> <li>Test 7</li> <li>Test 8</li> <li>Test 9</li> <li>Test 10</li> <li>Test 11</li> <li>Test 12</li> </ul> ```
Watch variable and change it <sep> In AngularJS I have a directive that watches a scope variable. When the variable contains certain data then I need to alter that variable a bit. The problem is that when I change the variable that my <code>$watch</code> is triggered again. So I end up in a continuous loop. <code>scope.$watch('someVar', function(newValue, oldValue) { console.log(newValue); scope.someVar = [Do something with someVar]; }); </code> This keeps triggering <code>$watch</code> again, which makes sense. But I do need a way to change the watched variable. Is there a way to do this?
When a variable is watched for changes using `$scope.$watch`, Angular checks if the reference has changed. If it has, the `$watch` handler is executed to update the view. If you plan on changing the scope variable within the `$watch` handler, it will trigger an infinite digest loop because the scope variable reference changes every time it is called. The trick to getting around the infinite digest issue is to preserve the reference inside your `$watch` handler using `angular.copy` (docs): ```javascript scope.$watch('someVar', function(newValue, oldValue) { console.log(newValue); var someVar = [Do something with someVar]; // angular.copy will preserve the reference of $scope.someVar // so it will not trigger another digest angular.copy(someVar, $scope.someVar); }); ``` Note: This trick only works for object references. It will not work with primitives. In general, it's not a good idea to update a `$watched` variable within its own `$watch` listener. However, sometimes it may be unavoidable.
Using withTrashed with relationships in Eloquent <sep> Is there a way to use <code>withTrashed</code> with relationships in Eloquent. What I need is this. I have table and model <code>Mark</code> and another table <code>User</code>. <code>User</code> has many <code>Mark</code> and <code>Mark</code> belongs to <code>User</code>. So I defined this in Eloquent models. Now I need to get an instance of <code>Mark</code> that is soft deleted. This is not a problem if <code>User</code> isn't soft deleted, but if both <code>Mark</code> and <code>User</code> are soft deleted, I get an error <code>Trying to get property of non-object</code>, because <code>$mark->user </code> won't return actual user, cause it is soft deleted. Is there a way that I can do something like <code>$mark->withTrashed()->user </code> to get this related user even if it is deleted?
Depending on your needs, you can define the relationship: ```php public function marks() { return $this->hasMany('Mark')->withTrashed(); } // then just $user->marks; ``` or use it on the fly: ```php $user->marks()->withTrashed()->get(); // or when lazy/eager loading $user = User::with(['marks' => function ($q) { $q->withTrashed(); }])->find($userId); ``` Then your case would turn into: ```php $mark->user() ->withTrashed() ->first(); // fetch the user // alternatively you use getResults relation method $mark->user() ->withTrashed() ->getResults(); // returns single model for belongsTo $user->marks()->withTrashed() ->getResults(); // returns collection for hasMany ```
Apache PoolingHttpClientConnectionManager throwing illegal state exception <sep> Here is how I use it - <code>private static final PoolingHttpClientConnectionManager connPool; static { connPool = new PoolingHttpClientConnectionManager(); // Increase max total connection to 200 connPool.setMaxTotal(200);//configurable through app.properties // Increase default max connection per route to 50 connPool.setDefaultMaxPerRoute(20);//configurable through app.properties } CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connPool) .build(); </code> ALso I have put a finally block around http GET - <code>finally { try { httpClient.close(); } catch (IOException e) { LOGGER.error(e.getMessage()); } } </code> Here is my stacktrace - <code>java.lang.IllegalStateException: Connection pool shut down at org.apache.http.util.Asserts.check(Asserts.java:34) at org.apache.http.pool.AbstractConnPool.lease(AbstractConnPool.java:169) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.requestConnection(PoolingHttpClientConnectionManager.java:217) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:157) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:194) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:85) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106) at com.A.B.C.CustomHttpClient.doGETAndValidate(CustomHttpClient.java:44) at com.A.B.C.SiteMonitorTask.monitorAndUpdateEndPoints(SiteMonitorTask.java:48) at com.A.B.C.SiteMonitorTask.run(SiteMonitorTask.java:37) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) </code> I am using Quartz to schedule a job of monitoring Http end points.. Here is my connection pool configuration <code>totalMaxHttpConn=200 maxHttpConnPerRoute=20 </code> Maven dependency.. artifact version <code>httpclient 4.3.1 httpcore 4.3.1 </code> EDIT - Well the problem got away by not closing CloseableHttpClient in the finally block.. Can anyone tell why is it behaving like that? Why is connection pool shut down if i close a client? Is the closeablehttpclient above is a handle to the pool rather than a single conn
In version 4.4, the method `setConnectionManagerShared(boolean)` was added to `HttpClientBuilder`. If you set it to `true`, the client won't close the connection manager. ```java HttpClients.custom() .setConnectionManager(Util.getConnectionManager()) // shared connection manager .setConnectionManagerShared(true) ```
How to do multiple "match" or "match_phrase" values in ElasticSearch <sep> So ElasticSearch has the terms query, which lets me supply multiple values and return a ist of documents where field X matches any of those values. But I want to do the same thing with match_phrase - i.e. return documents where field X contains a case insensitive match for a term with spaces. I currently do it my using an or filter (see below). But that seems like a very verbose way of doing what I want, considering that terms does something similar already. Current method It seems ridiculous that a query searching a single field for one of three values should be 33 lines long. <code>{ "query": { "filtered": { "filter": { "or": { "filters": [ { "query": { "match_phrase": { "myField1": "My first search phrase" } } }, { "query": { "match_phrase": { "myField1": "My second search phrase" } } }, { "query": { "match_phrase": { "myField1": "My third search phrase" } } } ] } } } } } </code>
```json "query": { "bool": { "should": [ { "match_phrase": { "myField1": "My first search phrase" } }, { "match_phrase": { "myField1": "My second search phrase" } } ] } } ```
itunes store operation failed in xcode 6 <sep> <code>iTunes store operation failed</code> <code>No eligible software found. Make sure this software is owned by your developer organization.</code> I get above error while validating app from xcode 6. I don't understand this error why it is coming. Can anyone help me to solve this error? Thank you
I was able to upload using Application Loader as suggested in iTunes Connect. Archive your app with the distribution provisioning profile, and export the archive for distribution to a location you can find it again. Download Application Loader 3.0 from iTunes Connect if it isn't already installed. Open Application Loader. In App Loader, log into the iTunes Connect account you want to release the app from. In App Loader, upload the archive. Not exactly painless, but it does allow you to build with an iTunes developer account and release from a different iTunes Connect ID.
How to deserialize a Map into POJO? <sep> I have a Map<String, Object> which contains a deserialized form of JSON. I would like to deserialize this into the fields of a POJO. I can perform this using Gson by serializing the Map into a JSON string and then deserializing the JSON string into the POJO, but this is inefficient (see example below). How can I perform this without the middle step? The solution should preferably use either Gson or Jackson, as they're already in use by the project. Example code: <code>import java.util.HashMap; import java.util.Map; import com.google.gson.Gson; public class Test { public static void main(String[] args) { Map<String, Object> innermap = new HashMap<String, Object>(); innermap.put("number", 234); innermap.put("string", "bar"); Map<String, Object> map = new HashMap<String, Object>(); map.put("number", 123); map.put("string", "foo"); map.put("pojo2", innermap); Gson gson = new Gson(); // How to perform this without JSON serialization? String json = gson.toJson(map); MyPojo pojo = gson.fromJson(json, MyPojo.class); System.out.println(pojo); } } class MyPojo { private int number; private String string; private MyPojo pojo2; @Override public String toString() { return "MyPojo[number=" + number + ", string=" + string + ", pojo2=" + pojo2 + "]"; } } </code>
Using Gson, you can turn your Map into a `JsonElement`, which you can then parse in exactly the same way using `fromJson`: `JsonElement jsonElement = gson.toJsonTree(map); MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);`. This is similar to the `toJson` method that you are already using, except that it avoids writing the JSON String representation and then parsing that JSON String back into a `JsonElement` before converting it to your class.
Enable horizontal scrolling Phpstorm <sep> Is it possible to enable horizontal scrolling in <code>Phpstorm</code>? I have found nothing whilst searching through the settings.
Have you tried holding SHIFT + mouse scrolling? I tested it from version 8.0.3 up to 9.0.2, and it works just fine. Bonus hint: This feature is actually pretty standard on many programs. Even on your browser, if you zoom in right now so that the horizontal scroll bar appears, and try to scroll while holding SHIFT, it will side scroll.
How to speed up / parallelize downloads of git submodules using git clone --recursive? <sep> Cloning git repositories that have a lot submodules takes a really long time. In the following example are ~100 submodules <code>git clone --recursive https://github.com/Whonix/Whonix </code> Git clones them one by one. Takes much longer than required. Let's make the (probable) assumption that both the client and the server has sufficient resources to answer multiple (parallel) requests at the same time. How to speed up / parallelize downloads of git submodules using <code>git clone --recursive</code>?
With Git 2.8 (Q1 2016), you will be able to initiate the fetch of submodules in parallel! See commit fbf7164 (16 Dec 2015) by Jonathan Nieder (<code>artagnon</code>). See also commits 62104ba, fe85ee6, c553c72, bfb6b53, b4e04fb, and 1079c4b (16 Dec 2015) by Stefan Beller (<code>stefanbeller</code>). (Merged by Junio C Hamano -- <code>gitster</code> -- in commit 187c0d3, 12 Jan 2016) > Add a framework to spawn a group of processes in parallel, and use it to run "<code>git fetch --recurse-submodules</code>" in parallel. For that, `git fetch` has the new option: `-j, --jobs=<n>` > Number of parallel children to be used for fetching submodules. Each will fetch from different submodules, such that fetching many submodules will be faster. By default submodules will be fetched one at a time. Example: `git fetch --recurse-submodules -j2` The bulk of this new feature is in commit c553c72 (16 Dec 2015) by Stefan Beller (<code>stefanbeller</code>). > `run-command`: add an asynchronous parallel child processor > > This allows to run external commands in parallel with ordered output on stderr. > If we run external commands in parallel we cannot pipe the output directly to our stdout/err as it would mix up. > So each process's output will flow through a pipe, which we buffer. > One subprocess can be directly piped to our stdout/err for a low latency feedback to the user. Note that, before Git 2.24 (Q4 2019), "<code>git fetch --jobs=<n></code>" allowed `<n>` parallel jobs when fetching submodules, but this did not apply to "<code>git fetch --multiple</code>" that fetches from multiple remote repositories. It now does. See commit d54dea7 (05 Oct 2019) by Johannes Schindelin (<code>dscho</code>). (Merged by Junio C Hamano -- <code>gitster</code> -- in commit d96e31e, 15 Oct 2019) > `fetch`: let `--jobs=<n>` parallelize `--multiple`, too > Signed-off-by: Johannes Schindelin > > So far, `--jobs=<n>` only parallelizes submodule fetches/clones, not `--multiple` fetches, which is unintuitive, given that the option's name does not say anything about submodules in particular. Let's change that. > With this patch, also fetches from multiple remotes are parallelized. > For backwards-compatibility (and to prepare for a use case where submodule and multiple-remote fetches may need different parallelization limits): the config setting `submodule.fetchJobs` still only controls the submodule part of `git fetch`, while the newly-introduced setting `fetch.parallel` controls both (but can be overridden for submodules with `submodule.fetchJobs`).
difference between origin/branch_name and branch_name? <sep> for pushing to bitbucket. If I do: <code>git push origin origin/branch_name</code> my commits are not pushed. <code>Total 0 (delta 0), reused 0 (delta 0) </code> If I do <code>git push origin branch_name</code> my commits are pushed: <code>Counting objects: 160, done. Delta compression using up to 8 threads. Compressing objects: 100% (13/13), done. Writing objects: 100% (20/20), 2.10 KiB | 0 bytes/s, done. Total 20 (delta 6), reused 0 (delta 0) </code> so what is the origin/ mean in front of the branch_name? And why does it matter?
You have to keep in mind that there are different types of branches: (Purely) local branches, i.e., branches you commit to, and branches that live in a remote repository, for lack of a better term. You may know the remote repository in question under a remote name, such as `origin`. From that repository's point of view, though, such a branch is local. Welcome to Distributed Version Control! `:)` Remote-tracking branches. Also simply called remote branches, as in the Pro Git book, but I find this phrase confusing; remote-tracking branch is more accurate. They're special local branches whose sole purpose is to reflect the state of branches that live in a remote repository at the time of your last communication with the server. In particular, you can't commit to branches of this type. Here, `branch_name` is a local branch, whereas `origin/branch_name` is a remote-tracking branch; it reflects the state of the corresponding branch that lives in `origin`. Right after running `git fetch`, the remote-tracking branch `origin/master` and the corresponding branch that lives in `origin` should be perfectly in sync (modulo concurrent pushes to the remote server, of course). It shouldn't be a surprise, then, that `git push origin origin/branch_name` doesn't push anything: you're essentially attempting to push stuff that is already present in the ancestry of the corresponding branch that lives in `origin`. However, if your local branch, `branch_name`, is ahead by one or more commits, then running `git push origin branch_name` will push the commits contained in `branch_name` but not in the branch that lives in `origin`.
r random forest error - type of predictors in new data do not match <sep> I am trying to use quantile regression forest function in R (quantregForest) which is built on Random Forest package. I am getting a type mismatch error that I can't quite figure why. I train the model by using <code>qrf <- quantregForest(x = xtrain, y = ytrain) </code> which works without a problem, but when I try to test with new data like <code>quant.newdata <- predict(qrf, newdata= xtest) </code> it gives the following error: <code>Error in predict.quantregForest(qrf, newdata = xtest) : Type of predictors in new data do not match types of the training data. </code> My training and testing data are coming from separate files (hence separate data frames) but having the same format. I have checked the classes of the predictors with <code>sapply(xtrain, class) sapply(xtest, class) </code> Here is the output: <code>> sapply(xtrain, class) pred1 pred2 pred3 pred4 pred5 pred6 pred7 pred8 "factor" "integer" "integer" "integer" "factor" "factor" "integer" "factor" pred9 pred10 pred11 pred12 "factor" "factor" "factor" "factor" > sapply(xtest, class) pred1 pred2 pred3 pred4 pred5 pred6 pred7 pred8 "factor" "integer" "integer" "integer" "factor" "factor" "integer" "factor" pred9 pred10 pred11 pred12 "factor" "factor" "factor" "factor" </code> They are exactly the same. I also checked for the "NA" values. Neither xtrain nor xtest has a NA value in it. Am I missing something trivial here? Update I: running the prediction on the training data still gives the same error <code>> quant.newdata <- predict(qrf, newdata = xtrain) Error in predict.quantregForest(qrf, newdata = xtrain) : names of predictor variables do not match </code> Update II: I combined my training and test sets so that rows from 1 to 101 are the training data and the rest is the testing. I modified the example provided in (quantregForest) as: <code>data <- read.table("toy.txt", header = T) n <- nrow(data) indextrain <- 1:101 xtrain <- data[indextrain, 3:14] xtest <- data[-indextrain, 3:14] ytrain <- data[indextrain, 15] ytest <- data[-indextrain, 15] qrf <- quantregForest(x=xtrain, y=ytrain) quant.newdata <- predict(qrf, newdata= xtest) </code> And it works! I'd appreciate if any one could explain why it works this way and not with the other way?
I had the same problem. You can try using a small trick to equalize the classes of the training and test sets. Bind the first row of the training set to the test set and then delete it. For your example, it should look like this: ``` xtest <- rbind(xtrain[1, ], xtest) xtest <- xtest[-1,] ```
How do I remove emoji from string <sep> My problem is to remove emoji from a string, but not CJK (Chinese, Japanese, Korean) characters from a string using regex. I tried to use this regex: <code>REGEX = /[^\u1F600-\u1F6FF\s]/i </code> This regex works fine except it also detects the Chinese, Japanese and Korean character where I need those characters. Any idea how to solve this issue?
Karol S already provided a solution, but the reason might not be clear: `"\u1F600"` is actually `"\u1F60"` followed by `"0"`: `"\u1F60" # => "" "\u1F600" # => "0"`. You have to use curly braces for code points above FFFF: `"\u{1F600}" #=> ""`. Therefore, the character class `[\u1F600-\u1F6FF]` is interpreted as `[\u1F60 0-\u1F6F F]`, i.e. it matches `"\u1F60"`, the range `"0"`..`"\u1F6F"` and `"F"`. Using curly braces solves the issue: ` /[\u{1F600}-\u{1F6FF}]/`. This matches (emoji) characters in these Unicode blocks: U+1F600..U+1F64F Emoticons, U+1F650..U+1F67F Ornamental Dingbats, U+1F680..U+1F6FF Transport and Map Symbols. You can also use `unpack`, `pack`, and `between?` to achieve a similar result. This also works for Ruby 1.8.7 which doesn't support Unicode in regular expressions. `s = 'Hi!\360\237\230\200"` `s.unpack('U*').reject{ |e| e.between?(0x1F600, 0x1F6FF) }.pack('U*') #=> "Hi!"`. Regarding your Rubular example, Emoji are single characters: `"".length #=> 1 "".chars #=> [""]`. Whereas kaomoji are a combination of multiple characters: ` "^_^".length #=> 3 "^_^".chars #=> ["^", "_", "^"]`. Matching these is a very different task (and you should ask that in a separate question).
jQuery autocomplete selection event <sep> I have created jQuery UI autocomplete which is working very good. But my requirement is that what I display as list should also select same in text box. But it is not selecting For example list like XXX (XYZ) but when I select it only select XXX not XXX (XYZ) what I am missing !! <code>function getDeptStations() { $("#txDestination").autocomplete({ source: function (request, response) { var term = request.term; var Query = ""; if (lang === "en") Query = "City_Name_EN"; else if (lang === "fr") Query = "City_Name_FR"; if (lang === "de") Query = "City_Name_DE"; if (lang === "ar") Query = "City_Name_AR"; var requestUri = "/_api/lists/getbytitle('Stations')/items?$select=City_Code," + Query + "&$filter=startswith(" + Query + ",'" + term + "')"; $.ajax({ url: requestUri, type: "GET", async: false, headers: { "ACCEPT": "application/json;odata=verbose" } }).done(function (data) { if (data.d.results) { response($.map(eval(data.d.results), function (item) { return { label: item[Query] + " (" + item.City_Code + ")", value: item[Query], id: item[Query] } })); } else { } }); }, response: function (event, ui) { if (!ui.content.length) { var noResult = { value: "", label: "No cities matching your request" }; ui.content.push(noResult); } }, select: function (event, ui) { $("#txDestination").val(ui.item.label); cityID = ui.item.id; }, minLength: 1 }); } </code>
Almost there, just return `false` from the `select` event. ```javascript select: function (event, ui) { $("#txDestination").val(ui.item.label); cityID = ui.item.id; return false; }, ``` or simply: ```javascript select: function (event, ui) { alert(ui.item.id); return false; }, ``` This will guide jQuery autocomplete to know that `select` has set a value. Update: This is not in the documentation. I figured it out by digging into the source code, it took me some time. But indeed it deserves to be in the doc or in the options.
Display UIAlertController from UIView/NSObject class <sep> I have <code>working iOS application</code> In order to <code>support iOS8</code>, I am replacing <code>UIAlertView/UIActionSheet with UIAlertController</code>. Problem : For display UIAlertController I need presentViewController method of UIViewController class. But UIAlertView is display from classes which are <code>inherited</code> from <code>UIView or NSObject</code>, I can not get <code>[self presentViewController...]</code> method for obvious reason. My Work : I tried getting rootViewController form current window and display UIAlertController. <code>[[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController ...] </code> but have some rotation problems like if my current view controller do not have rotation support it will rotate if UIAlertController is open. Question : Did any one faced same problem and have safe solution ? if yes please provide me some example or give some guide
I solved an essentially similar problem today. Like Jageen, I ran into a situation where I wanted to present a UIAlertController but from a non-UIViewController class. In my case, I wanted an alert to pop up when the failure block of an HTTP request is run. This is what I used, and unlike our friend here, it worked quite perfectly for me: `UIApplication.shared.keyWindow?.rootViewController?.present(errorAlert, animated: true, completion: nil)`
How to catch ERR_CONNECTION_REFUSED thrown by browser if server goes down? <sep> I think this question is pretty straightforward, but I haven't found an answer yet in the official Socket.io docs. I have my Socket.io server and client communicating successfully, and when I shut down the server, the client will attempt to reconnect with the server unsuccessfully. This is shown in the Chrome developer's console here: Is there any way to detect this event in the client-side Javscript and react to it some way? I'm thinking I would display a dialog on the page, such as "Sorry, server is under heavy load", etc.
The correct way to handle this, as of Socket.IO 1.x, is to use the Manager object for a given socket. It throws a `connect_error` event that can be handled as shown: ```javascript socket.io.on('connect_error', function(err) { // handle server error here console.log('Error connecting to server'); }); ```
how to add token auth to swagger + django rest framework? <sep> I am using both great tools DRF and Django-REST-Swagger, however a few of my API views are under token authentication. So now I'd like to add to my swagger doc page of my API the possibility to test those token auth api urls, including the Token header. How could I do this?. A snapshot of my class API view is like this: <code>class BookList(APIView): """ List all books, or create a new book. """ authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated,) ... </code> Since Swagger auto detects a lot of stuff, I was expecting to notice about token auth, and ask me about token or user id in its web interface, but it doesn't. Hence I am testing it manually through CURL commands...
If you're using token authentication, you might want to look at this question. Basically, you just need to add this to your `settings.py`: ``` SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'api_key': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' } }, } ``` In your Swagger UI page, you should see an Authorize button. Click that and enter your Authorization value in the input text field.
Difference between running lint via Android Studio menu and gradlew command-line <sep> When I run the following on a command line: <code>./gradlew -lint </code> I get different results than if I choose the following menu option within Android Studio. <code>Analyze->Inspect Code... </code> Can anyone explain this? Is this normal? Should a prudent developer run both in order to find all potential problems with his/her project?
You are running two different tools. The command: `$ ./gradlew lint` runs the lint tool that comes with the Android SDK, and the menu option `Analyze -> Inspect Code...` in Android Studio is a feature inherited from JetBrains IntelliJ IDEA which runs: `<android studio path>/bin/inspect.sh`
Firebase, variable as key name <sep> what I basically want to do is this: <code>variable = 'whatever'; fb.set({ variable : "More Stuff" }); </code> So this will result in an entry that looks like: <code>whatever: "More Stuff" </code> Currently it just ends up as <code>variable: "More Stuff" </code> Can this be done?
For the latest version of Firebase, use brackets around the variable name: `firebase.database().ref("pathName").set({[variable]: 'MoreStuff'});`. Using the other method of setting the index of the variable to the value will create an additional layer in the database structure.
redraw a custom uiview when changing a device orientation <sep> If I draw my chart inside <code>- (void)drawRect:(CGRect)rect</code> is just enough to set [<code>_chartView setContentMode:UIViewContentModeRedraw]</code> and this method will be called when device changes it's orienatation and it's possible to calculate f.e. new center point for my chart. If I create a view like a subview using <code>- (id)initWithFrame:(CGRect)frame</code> and then add it in view controller like <code>[self.view addSubview:chartView];</code>. How in this case I can handle rotation to redraw my chart?
While a preferred solution requires zero lines of code, if you must trigger a redraw, do so in `setNeedsDisplay`, which in turn invokes `drawRect`. No need to listen to notifications nor refactor the code. Swift: ``` override func layoutSubviews() { super.layoutSubviews() self.setNeedsDisplay() } ``` Objective-C: ``` - (void)layoutSubviews { [super layoutSubviews]; [self setNeedsDisplay]; } ``` Note: `layoutSubviews` is a `UIView` method, not a `UIViewController` method.
Passing dynamic object to C# method changes return type <sep> I created a class that inherits <code>DynamicObject</code> and want to create a static method that can create new instances with pre-determined properties (stored in the <code>Dictionary</code>). <code>public class CustomDynamic : DynamicObject { protected Dictionary<string, object> InnerDictionary; public static T Create<T>(Dictionary<string, object> dictionary) where T : CustomDynamic , new() { return new T { InnerDictionary = dictionary }; } } </code> Usage: <code>dynamic d = new Dictionary<string, object>(); var realPlayer = CustomDynamic.Create<Player>(d as Dictionary<string, object>); var dynaPlayer = CustomDynamic.Create<Player>(d); realPlayer // Player type according to VS2013 dynaPlayer // dynamic type according to VS2013 </code> Since there is only one method signature, why does passing in a dynamic return a dynamic object? Or is actually just Visual Studio 2013 getting confused?
This is because almost any operation involving a dynamic value is resolved dynamically at execution time. There are no exceptions made for cases where there is only one method present at compile time; the language is simpler that way. (For certain calls, the compiler does perform enough resolution at compile time to ensure that there is at least one method with a suitable number of parameters—this is specified in the C# 5 spec in section 7.5.4, but that doesn't affect the effective return type.) From the C# 5 spec, section 7.6.5: > An invocation-expression is dynamically bound if at least one of the following holds: > * The primary-expression has compile-time type `dynamic`. > * At least one argument of the optional argument-list has compile-time type `dynamic` and the primary-expression does not have a delegate type. > In this case the compiler classifies the invocation-expression as a value of type `dynamic`. [...] There are a few operations involving dynamic values which still have a non-dynamic overall type. For example: * `d is Foo` is always `bool` * `d as Foo` is always `Foo` * `new Foo(d)` is always `Foo` even though the exact constructor to use is determined at execution time. But any method call is treated as having a return type of `dynamic`.
Django REST framework foreign keys and filtering <sep> I have following models in django app: models.py: <code>class Make(BaseModel): slug = models.CharField(max_length=32) #alfa-romeo name = models.CharField(max_length=32) #Alfa Romeo def __unicode__(self): return self.name class Model(BaseModel): make = models.ForeignKey(Make) #Alfa Romeo name = models.CharField(max_length=64) # line[2] engine_capacity = models.IntegerField() trim = models.CharField(max_length=128) # line[4] </code> And serializers.py: <code>from .models import Make,Model from rest_framework import serializers class MakeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Make fields = ('url', 'slug', 'name') class ModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Model fields = ('url', 'make', 'name', 'trim', 'engine_capacity') </code> and also views.py: <code>from rest_framework import viewsets from rest_framework import filters from rest_framework import generics from .models import Make, Model from .serializers import MakeSerializer, ModelSerializer class MakeViewSet(viewsets.ModelViewSet): queryset = Make.objects.all() serializer_class = MakeSerializer filter_backends = (filters.DjangoFilterBackend,) class ModelViewSet(viewsets.ModelViewSet): make = MakeSerializer queryset = Model.objects.all() serializer_class = ModelSerializer filter_backends = (filters.DjangoFilterBackend,) </code> What I need to to, I want to fetch all Models manufactured by specific make. How can I get all models with particular make foreign key using query params? And my 2nd question - can I filter results using queryparams to get models with specific engine_capacity? One comment: It would be perfect, if I can to query results using something like this in url: <code>/api/models/?make=ford</code> where make is <code>slug</code> field in <code>Make</code> model
You can specify `filter_fields = ('make__slug',)` in your view set. Don't forget to include `filter_backends = (DjangoFilterBackend, )` as well. Also, you will need to add the `django-filter` dependency. ```python class ModelViewSet(viewsets.ModelViewSet): queryset = Model.objects.all() serializer_class = ModelSerializer filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('make__slug',) ``` Then you query like `/api/models/?make__slug=ford`. Note the double underscore symbol. Docs. If you don't like the `make__slug` keyword argument in the URL, then you can create a filter class: ```python import django_filters from myapp.models import Make class ModelFilter(django_filters.FilterSet): make = django_filters.ModelChoiceFilter(field_name="make__slug", queryset=Make.objects.all()) class Meta: model = Model fields = ('make',) ``` And then: ```python class ModelViewSet(viewsets.ModelViewSet): make = MakeSerializer queryset = Model.objects.all() serializer_class = ModelSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = ModelFilter ``` `/api/models/?make=ford` should work.
Why relative path doesn't work in Ruby require <sep> I'm starting learning Ruby, one thing that I don't understand, why relative path for require directive doesn't work in ruby. It's something that works almost in every scripting language that I now (JSP, PHP...). I explain with a real example. I have a folder named shapes which contains 3 classes shape, rectangle and square. I have also another file test_shapes.rb from where I call and test my classes. When I import my classes to the main file like this: <code>require "./shape" require "./rectangle" require "./square" </code> I got error for files not found. When I include the name of my subfolder like this: <code>require "./shapes/shape" require "./shapes/rectangle" require "./shapes/square" </code> The code is perfectly working. Because I specified the whole path to the root directory of the project (the lib folder I think). When I include I include the absolute path to the hard disk, like this: <code>require "#{File.dirname(__FILE__)}/shape" require "#{File.dirname(__FILE__)}/rectangle" require "#{File.dirname(__FILE__)}/square" </code> It's also working perfectly. So, I just want some explanation if know why the first import method (the relative path to the current folder) in not working.
Relative path is based on the working directory. I assume that there is a main file in the same directory. If you run `ruby ./shapes/main.rb` on the project root, Ruby will try to find `{project_root}/shape.rb`, not `{project_root}/shapes/shape.rb`. It doesn't work. You need to use `require_relative` like below. ```ruby # {project_root}/shapes/main.rb require_relative './shape' require_relative './rectangle' require_relative './square' ```
How to create an empty IReadOnlyCollection <sep> I'm creating an extension method for MultiValueDictionary to encapsulate frequent <code>ContainsKey</code> checks and I was wondering what was the best way to create an empty <code>IReadOnlyCollection</code>?. What I've used so far is <code>new List<TValue>(0).AsReadOnly()</code> but there must be a better way, an equivilant to <code>IEnumerable</code>'s <code>Enumerable.Empty</code> <code>public static IReadOnlyCollection<TValue> GetValuesOrEmpty<TKey, TValue>(this MultiValueDictionary<TKey, TValue> multiValueDictionary, TKey key) { IReadOnlyCollection<TValue> values; return !multiValueDictionary.TryGetValue(key, out values) ? new List<TValue>(0).AsReadOnly() : values; } </code>
```csharp The new .NET 4.6 adds an API to get an empty array: `Array.Empty<T>` and arrays implement `IReadOnlyCollection<T>`. This also reduces allocations as it only creates an instance once: `IReadOnlyCollection<int> emptyReadOnlyCollection = Array.Empty<int>();`. What I ended up doing is mimicking the implementation of `Enumerable.Empty` using `new TElement[0]`: ```csharp public static class ReadOnlyCollection { public static IReadOnlyCollection<TResult> Empty<TResult>() { return EmptyReadOnlyCollection<TResult>.Instance; } private static class EmptyReadOnlyCollection<TElement> { static volatile TElement[] _instance; public static IReadOnlyCollection<TElement> Instance { get { return _instance ?? (_instance = new TElement[0]); } } } } ``` Usage: `IReadOnlyCollection<int> emptyReadOnlyCollection = ReadOnlyCollection.Empty<int>();` ```
Is it safe to put increment/decrement operators inside ternary/conditional operators? <sep> Here's an example <code>#include <iostream> using namespace std; int main() { int x = 0; cout << (x == 0 ? x++ : x) << endl; //operator in branch cout << "x=" << x << endl; cout << (x == 1 || --x == 0 ? 1 : 2) << endl; //operator in condition cout << "x=" << x << endl; return 0; } </code> output: <code>0 x=1 1 x=1 </code> I understand the output, but is this undefined behaviour or not? Is the order of evaluation guaranteed in either case? Even if guaranteed, I'm quite aware using increment/decrement can quickly become an issue for readability. I only ask as I saw similar code and was immediately unsure, given there are lots of examples of ambiguous/undefined use of increment/decrement operators, such as... <blockquote> C++ does not define the order in which function parameters are evaluated. </blockquote> <code>int nValue = Add(x, ++x); </code> <blockquote> The C++ language says you cannot modify a variable more than once between sequence points. </blockquote> <code> x = ++y + y++ </code> <blockquote> Because increment and decrement operators have side effects, using expressions with increment or decrement operators in a preprocessor macro can have undesirable results. </blockquote> <code> #define max(a,b) ((a)<(b))?(b):(a) k = max( ++i, j ); </code>
For the conditional operator (5.16 [expr.cond]/p1): > Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression. For the logical OR operator (5.15 [expr.log.or]/p1-2): > The second operand is not evaluated if the first operand evaluates to `true`. [...] If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression. The behavior of your code is well-defined.
Is there a way to set a UITableView's contentInset through Storyboard? <sep> <code>self.tableView.contentInset = UIEdgeInsetsMake(232, 0, 232, 0) </code> is there a way of setting this in Storyboard?
The content inset option seems to be gone from the Attribute Inspector since Xcode 6. But if you don't want to define `contentInset` in code (as it is user interface related), there's still an option left: Select your `UITableView` and open the Identity Inspector (Alt+Cmd+3), and click the plus button to add a user-defined runtime attribute. Select `Rect` as its type and `contentInset` as its key path. See this example that changes the top inset. `50` appears to be stored as the `x` value but strangely it changes the top inset. Reference: `{{top, left}, {bottom, right}}`
Why is numpy.power 60x slower than in-lining? <sep> Maybe I'm doing something odd, but maybe found a surprising performance loss when using numpy, seems consistent regardless of the power used. For instance when x is a random 100x100 array <code>x = numpy.power(x,3) </code> is about 60x slower than <code>x = x*x*x </code> A plot of the speed up for various array sizes reveals a sweet spot with arrays around size 10k and a consistent 5-10x speed up for other sizes. Code to test below on your own machine (a little messy): <code>import numpy as np from matplotlib import pyplot as plt from time import time ratios = [] sizes = [] for n in np.logspace(1,3,20).astype(int): a = np.random.randn(n,n) inline_times = [] for i in range(100): t = time() b = a*a*a inline_times.append(time()-t) inline_time = np.mean(inline_times) pow_times = [] for i in range(100): t = time() b = np.power(a,3) pow_times.append(time()-t) pow_time = np.mean(pow_times) sizes.append(a.size) ratios.append(pow_time/inline_time) plt.plot(sizes,ratios) plt.title('Performance of inline vs numpy.power') plt.ylabel('Nx speed-up using inline') plt.xlabel('Array size') plt.xscale('log') plt.show() </code> Anyone have an explanation?
It's well known that multiplication of doubles, which your processor can do in a very fancy way, is very, very fast. `pow` is decidedly slower. Some performance guides out there even advise people to plan for this, perhaps even in a way that might be a bit overzealous at times. NumPy special-cases squaring to make sure it's not too, too slow, but it sends cubing right off to your libc's `pow`, which isn't nearly as fast as a couple of multiplications.
How to filter a dataframe of dates by a particular month/day? <sep> So my code is as follows: <code>df['Dates'][df['Dates'].index.month == 11] </code> I was doing a test to see if I could filter the months so it only shows November dates, but this did not work. It gives me the following error: AttributeError: 'Int64Index' object has no attribute 'month'. If I do <code>print type(df['Dates'][0]) </code> then I get class 'pandas.tslib.Timestamp', which leads me to believe that the types of objects stored in the dataframe are Timestamp objects. (I'm not sure where the 'Int64Index' is coming from... for the error before) What I want to do is this: The dataframe column contains dates from the early 2000's to present in the following format: dd/mm/yyyy. I want to filter for dates only between November 15 and March 15, independent of the YEAR. What is the easiest way to do this? Thanks. Here is df['Dates'] (with indices): <code>0 2006-01-01 1 2006-01-02 2 2006-01-03 3 2006-01-04 4 2006-01-05 5 2006-01-06 6 2006-01-07 7 2006-01-08 8 2006-01-09 9 2006-01-10 10 2006-01-11 11 2006-01-12 12 2006-01-13 13 2006-01-14 14 2006-01-15 ... </code>
Using `pd.to_datetime` & `dt` accessor The accepted answer is not the "pandas" way to approach this problem. To select only rows with `month 11`, use the `dt` accessor: `# df['Date'] = pd.to_datetime(df['Date']) -- if column is not datetime yet df = df[df['Date'].dt.month == 11]` Same works for days or years, where you can substitute `dt.month` with `dt.day` or `dt.year`. Besides that, there are many more, here are a few: `dt.quarter` `dt.week` `dt.weekday` `dt.day_name` `dt.is_month_end` `dt.is_month_start` `dt.is_year_end` `dt.is_year_start` For a complete list see the documentation.
C++ Detect when user presses arrow key <sep> I have been having a problem with detecting arrow key presses in my C++ console application. I have tried everything I have found, both here and on other tutorial sites, but all of them give me the same thing whenever I press the arrow: <code>Process returned 0 <0x0> execution time : 2.249 s Press any key to continue. </code> Here are all the methods of detecting the key press that I have tried, all ending up the same way. These are the only two left in my code, the others I attempted I deleted instead of commenting out. Method one: <code>c1 = getch(); if(c1 == 0) { c2 = getch(); if(c2 == 72) {cout << endl << "Up Arrow" << endl;} else if(c2 == 80) {cout << endl << "Down Arrow" << endl;} else{cout << endl << "Incorrect Input" << endl;} } </code> Method two: <code>switch(getch()) { case 65: cout << endl << "Up" << endl;//key up break; case 66: cout << endl << "Down" << endl; // key down break; case 67: cout << endl << "Right" << endl; // key right break; case 68: cout << endl << "Left" << endl; // key left break; } </code> Is there some error in my code which made me go back to my main method, or did it skip over some code? Is there a faster way to do this? I'm almost 100% sure that my other code doesn't have anything to do with this problem, because I isolated the code from be dependent on any other aspect of the program, and I kept having the same problem. Again, I tried every method of getting the arrow key press that I could find, and I keep getting the same problem. If it matters, I'm on a Windows 8 Samsung ATIV Smart PC and using the keyboard dock. Thanks in advance for any help.
```cpp #include <conio.h> #include <iostream> using namespace std; #define KEY_UP 72 #define KEY_DOWN 80 #define KEY_LEFT 75 #define KEY_RIGHT 77 int main() { int c = 0; while (1) { c = getch(); switch (c) { case KEY_UP: cout << endl << "Up" << endl; break; case KEY_DOWN: cout << endl << "Down" << endl; break; case KEY_LEFT: cout << endl << "Left" << endl; break; case KEY_RIGHT: cout << endl << "Right" << endl; break; default: cout << endl << "null" << endl; break; } } return 0; } ``` Let me know if you have any other code snippets you'd like me to review!
gunicorn.errors.HaltServer: <sep> I've installed gunicorn inside my virtualenv. From this directory: <code>manage.py /onbytes/wsgi.py </code> I run the following: <code>gunicorn onbytes.wsgi:application </code> And I get the following error: <code>Traceback (most recent call last): File "/home/ymorin007/.virtualenvs/onbytes.com/bin/gunicorn", line 9, in <module> load_entry_point('gunicorn==19.0.0', 'console_scripts', 'gunicorn')() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 166, in run super(Application, self).run() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 71, in run Arbiter(self).run() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 169, in run self.manage_workers() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 477, in manage_workers self.spawn_workers() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 537, in spawn_workers time.sleep(0.1 * random.random()) File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 209, in handle_chld self.reap_workers() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 459, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> </code> running gunicorn onbytes.wsgi:application --preload will get me this error: <code>Traceback (most recent call last): File "/home/ymorin007/.virtualenvs/onbytes.com/bin/gunicorn", line 9, in <module> load_entry_point('gunicorn==19.0.0', 'console_scripts', 'gunicorn')() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 166, in run super(Application, self).run() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 71, in run Arbiter(self).run() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 57, in __init__ self.setup(app) File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 113, in setup self.app.wsgi() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 66, in wsgi self.callable = self.load() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ymorin007/.virtualenvs/onbytes.com/local/lib/python2.7/site-packages/gunicorn/util.py", line 356, in import_app __import__(module) File "/home/ymorin007/sites/onbytes.com/src/onbytes/wsgi.py", line 8, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi </code>
Probably there is an issue in your application, not in Gunicorn. Try: `gunicorn --log-file=- onbytes.wsgi:application`. Since version R19, Gunicorn doesn't log by default in the console, and the --debug option was deprecated.
how to specify database name in spring data mongoDB <sep> I am using Mongo repositories to perform CRUD operations as in the code below. Although this code works, but the documents and collections are created in a different DB than the one that I want. How can I explicitly specify a DB name to which documents will be stored. The POJO class: <code>@Document(collection = "actors") public class Actor { @Id private String id; ... //constructor //setters & getters } </code> The repository: <code>public interface ActorRepository extends MongoRepository<Actor, String> { public Actor findByFNameAndLName(String fName, String lName); public Actor findByFName (String fName); public Actor findByLName(String lName); } </code> The service that uses the repository: <code>@Service public class ActorService { @Autowired private ActorRepository actorRepository; public Actor insert(Actor a) { a.setId(null); return actorRepository.save(a); } } </code> And I access the service from a REST controller class: <code>@RestController public class Controllers { private static final Logger logger = Logger.getLogger(Controllers.class); private static final ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class); @Autowire private ActorService actorService; @RequestMapping(value="/createActor", method=RequestMethod.POST) public @ResponseBody String createActor(@RequestParam(value = "fName") String fName, @RequestParam(value = "lName") String lName, @RequestParam(value = "role") String role) { return actorService.insert(new Actor(null,fName,lName,role)).toString(); } ... } </code> I have created this spring mongoDB configuration class which has the option of setting DB name, but could not figure out how to use it with the repositories above. <code>@Configuration public class SpringMongoConfig extends AbstractMongoConfiguration { @Bean public GridFsTemplate gridFsTemplate() throws Exception { return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter()); } @Override protected String getDatabaseName() { return "MyDB"; } @Override @Bean public Mongo mongo() throws Exception { return new MongoClient("localhost" , 27017 ); } public @Bean MongoTemplate mongoTemplate() throws Exception { return new MongoTemplate(mongo(), getDatabaseName()); } } </code>
Add to the application.properties a line `spring.data.mongodb.database=your_db_name`. That worked for me; maybe it's too late for you, but this could help someone looking for the same problem. See more properties here!
JavaFX: what is the difference between EventHandler and EventFilter? <sep> I've been googling for a while and I found that basicly, some web pages says there are no big differences. Except for some points: <code>EventFilter</code> is executed before <code>EventHandler</code> <code>EventFilter</code> is not sensible to <code>event.Consume();</code> Let me see If I've understood it: Lets say I have: <code>Button b= new Button("Test"); b.addEventHandler(.....){...}; b.addEventFilter(......){...};</code> Let's say they are both "linked" to an <code>MouseEvent.MOUSE_CLICKED</code>; then, <code>EventFilter</code>'s code will be the first to be executed!? Let's say, now, I have: <code>Button b= new Button("Test"); b.addEventHandler(.....); b.addEventFilter(......){ //some code event.consume(); }; // First filter b.addEventFilter(......){ //some other code event.consume(); }; // Second filter </code> In this case, boath <code>EventFilter</code>s will be executed but the <code>EventHandler</code> will not. Right? Are there any other things to know? Are there situations where I should prefere one or other? should I sometimes use them together in order to solve some problems? Thank you!
Whenever an event happens, it follows a process to determine which node in the scene graph should handle the event. The process takes these steps: **Target Selection** Say that your scene contains a pane with a circle. If you click on the circle, the circle becomes the event target. **Route Construction** Next, JavaFX creates a route (or an event dispatch chain). In our example, the chain would look like: `stage -> scene -> pane -> circle` **Event Capturing** The event gets carried through every event filter on the chain. As soon as one of the filters calls `consume()`, the chain stops, and that node becomes the target. If no filter calls `consume()`, the end of the chain (the circle) remains the target. **Event Bubbling** Next, the event is pushed through the chain again, but this time from the event target to the stage. So, if the pane event filter called `consume()`, the following event handlers will be hit: `pane -> scene -> stage`. So, the difference is not only when these handlers get activated, but also that event filters can prevent child nodes from receiving events.
Changing Developer Tools Font Face (family) <sep> After hours of research, I give up. Is there any straightforward way to hack Dev Tools and change the font family they are using? I'm spending many hours looking at this window so I'd love if I could use a monospaced font of my choice.
I've created a small plugin which provides a collection of editor settings for Chrome Developer Tools, including the ability to set a custom font family enabled on your computer. Install the "DevTools Author Chrome" extension from the Chrome Web Store. Enable Developer Tools experiments in `chrome://flags/#enable-devtools-experiments`. Restart Chrome for the flags to take effect. Open DevTools (cmd + opt + I); Settings > Experiments > check "Allow custom UI themes." This will add an "Author Settings" panel to Chrome Developer Tools, where you can edit the font-family applied to the Chrome Developer Tools.
Efficiently generating random bytes of data in C++11/14 <sep> My requirement is to generate random bytes of data (not random numbers) aka uniformly distributed bits. As such I was wondering what are the correct/efficient ways of doing this using C++11/14 random facilities. I've had a look around at the examples, but they all seem to focus on number generation (ints, floats etc) Current solution I'm using is the following: <code>#include <vector> #include <random> int main() { std::random_device rd; std::uniform_int_distribution<int> dist(0,255); std::vector<char> data(1000); for (char& d : data) { d = static_cast<char>(dist(rd) & 0xFF); } return 0; } </code>
What you're looking for is the `std::independent_bits_engine` adaptor: ```c++ #include <vector> #include <random> #include <climits> #include <algorithm> #include <functional> using random_bytes_engine = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, unsigned char>; int main() { random_bytes_engine rbe; std::vector<unsigned char> data(1000); std::generate(begin(data), end(data), std::ref(rbe)); } ``` Note that the accepted answer is not strictly correct in a general case. Random engines produce unsigned values belonging to a range [ `min()`, `max()` ], which doesn't necessarily cover all possible values of the result type (for instance, `std::minstd_rand0::min() == 1` ). Thus, you may get random bytes that are not uniformly distributed if using an engine directly. However, for `std::random_device` the range is [ `std::numeric_limits<result_type>::min()`, `std::numeric_limits<result_type>::max()` ], so this particular engine would also work well without the adaptor.
How to load an image in prepareForInterfaceBuilder with a IBDesignable UIImageView <sep> I would like to load a sample image in an IB designable <code>UIImageView</code>, to be shown in Interface Builder while editing the interface. The following code does not work, as the view placeholder in IB remains empty (the view area contains only the UIImageView text): <code>@IBDesignable class TestImageView : UIImageView { override func prepareForInterfaceBuilder() { //let bundle = NSBundle.mainBundle() let bundle = NSBundle(forClass: nil) let imagePath = bundle.pathForResource("Test", ofType: "jpg") self.image = UIImage(contentsOfFile: imagePath) } } </code> Note that: in IB the Custom Class class for the view is correct (TestImageView) Test.jpg is present in the project (if I manually set the image property of the <code>UIImageView</code> in IB the image shows up). I tried the two different methods of getting the bundle present in the code This was tested with Xcode 6 beta 3. Update: in both cases the bundle path I get is <code>"/Applications/Temporary/Xcode6-Beta3.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Overlays"</code>. In that path the image is obviously not present.
Updated for Swift 4.2 When you instantiate a UIImage (with `UIImage(named: "SomeName")`, the app will look for the asset in your main bundle, which works fine usually. But when you are at design time, Interface Builder holds the code of the designable views (for compiling while designing) in a separate bundle. So the solution is: Define your bundle dynamically, hence your files can be found in design, compile, and run time: ```swift // DYNAMIC BUNDLE DEFINITION FOR DESIGNABLE CLASS let dynamicBundle = Bundle(for: type(of: self)) // OR ALTERNATIVELY BY PROVIDING THE CONCRETE NAME OF YOUR DESIGNABLE VIEW CLASS let dynamicBundle = Bundle(for: YourDesignableView.self) // AND THEN SUCCESSFULLY YOU CAN LOAD THE RESOURCE let image = UIImage(named: "Logo", in: dynamicBundle, compatibleWith: nil) ```
R: What are operators like %in% called and how can I learn about them? <sep> I know the basics like <code>==</code> and <code>!=</code>, or even the difference (vaguely) between <code>&</code> and <code>&&</code>. But stuff like <code>%in%</code> and <code>%%</code> and some stuff used in the context of <code>sprintf()</code>, like <code>sprintf("%.2f", x)</code> stuff I have no idea about. Worst of all, they're hard to search for on the Internet because they're special characters and I don't know what they're called...
There are several different things going on here with the percent symbol: **Binary Operators** As several have already pointed out, things of the form `%%`, `%in%`, and `%*%` are binary operators (respectively modulo, match, and matrix multiply), just like `+`, `-`, etc. They are functions that operate on two arguments that R recognizes as special due to their name structure (starting and ending with a `%`). This allows you to use them in the form: `Argument1 %fun_name% Argument2` instead of the more traditional: `fun_name(Argument1, Argument2)`. Keep in mind that the following are equivalent: * `10 %% 2 == `%%`(10, 2)` * `"hello" %in% c("hello", "world") == `%in%`("hello", c("hello", "world"))` * `10 + 2 == `+`(10, 2)` R just recognizes the standard operators as well as the `%x%` operators as special and allows you to use them as traditional binary operators if you don't quote them. If you quote them (in the examples above with backticks), you can use them as standard two-argument functions. **Custom Binary Operators** The big difference between the standard binary operators and `%x%` operators is that you can define custom binary operators, and R will recognize them as special and treat them as binary operators: ```R `%samp%` <- function(e1, e2) sample(e1, e2) 1:10 %samp% 2 # [1] 1 9 ``` Here we defined a binary operator version of the `sample` function. The `%` (Percent) is a token in this special function. **The Meaning of "%" in Other Functions** The meaning of `%` in functions like `sprintf` or `format` is completely different and has nothing to do with binary operators. The key thing to note is that in those functions, the `%` character is part of a quoted string and not a standard symbol on the command line (i.e., `%` and `"%" ` are very different). In the context of `sprintf`, inside a string, `"%" ` is a special character used to recognize that the subsequent characters have a special meaning and should not be interpreted as regular text. For example, in: ```R sprintf("I'm a number: %.2f", runif(3)) # [1] "I'm a number: 0.96" "I'm a number: 0.74" "I'm a number: 0.99" ``` `"%.2f"` means a floating-point number (`f`) to be displayed with two decimals (`.2`). Notice how the `"I'm a number: "` piece is interpreted literally. The use of `"%" ` allows `sprintf` users to mix literal text with special instructions on how to represent the other `sprintf` arguments.
Type 'String.Index' does not conform protocol 'IntegerLiteralConvertible' <sep> With Beta 3 all worked fine, now I get a strange error, and I have no clue how to fix it. Tried all the solutions for similiar problems. Here is my code: <code>if !name.isEmpty { var splitted: [String] = name.componentsSeparatedByString(" ") for curPart in splitted { if !curPart.isEmpty { acronym += curPart.substringToIndex(1) //Error } } if (acronym as NSString).length > 2 { acronym = acronym.substringToIndex(2) //Error } } </code> Both marked lines gave me the same error: <blockquote> Type 'String.Index' does not conform protocol 'IntegerLiteralConvertible' </blockquote> Can someone help me? Or is Beta 4 bugged? Thanks!
In beta 4, Swift's `String.Index` handling changed yet again—you now can't supply an `Int` when a `String.Index` is expected. The way to handle it is by creating the `String.Index` you need using the `advance` method: ```swift if !name.isEmpty { let splitted: [String] = name.components(separatedBy: " ") for curPart in splitted { if !curPart.isEmpty { acronym += curPart.substring(to: advance(curPart.startIndex, 1)) } } if countElements(acronym) > 2 { acronym = acronym.substring(to: advance(acronym.startIndex, 2)) } } ``` This is all based on making sure Unicode strings are handled properly—since different Unicode characters can have different sizes, pure integer indexing would hide the fact that Strings aren't random access.
How to insert an element in the middle of a list? <sep> I have a list with several elements, say 10. <code>testList <- split(1:10,1:10) </code> How to insert a new element in the middle of the list, say at position 3? The brute force way of looping through all the elements will work, but just wondering if there is a more elegant way of doing this?
I think the `append` function is what you are looking for: `append(testList, list(x=42), 3)`. $`1` [1] 1 $`2` [1] 2 $`3` [1] 3 $x [1] 42 $`4` [1] 4 #snipped.... For more complex lists you might find the `modifyList` function in the utils package to be of use. It allows targeted modifications. What it does not support is insertions of rows in a dataframe.
~/.profile, ~/.bashrc, and ~/.bash_profile not running on new terminal start up <sep> I am trying to create a permanent alias for my terminal. I put the alias in my ~/.profile, ~/.bashrc, and ~/.bash_profile files, previously empty. When I start a new terminal, bash does not recognize the alias, but if I source any of them, it does. Why are these not getting run when I open a terminal? I am on OSX.
Newer macOS versions use zsh as the default shell for both Terminal and iTerm2. Run `echo $SHELL` to confirm if this is the case for you. Zsh looks for a `~/.zshrc` file upon shell startup, so to continue using zsh while sourcing the contents of your bash profile, you can run the following: `echo "source ~/.bash_profile" >> ~/.zshrc`. Open a new terminal window for the changes to take effect.
How to know Push Notification delivery status <sep> I am using push notification in an app. Everything is going fine. Sometimes message sent from server but in app side it does not receive. In this situation I have to know which message is missing to deliver(app did not receive). Is there any way to know from server side which message is received by app and which are not?
No, push notifications are fire-and-forget. Apple won't tell you: * Whether the message was sent successfully or not * Whether the user has opted out of push notifications There are many other things it won't tell you, but regardless... However, when the user has opted into push notifications, your app can handle this to a certain extent. Basically, you could add logic in the `-didReceiveRemoteNotification:` and `-didFinishLaunchingWithOptions:` methods to contact your server and tell it that the message was received. If it wasn't received within a particular time slot, you could resend it. But as you see, this could lead to a scenario of flooding an innocent user with the same push notifications, essentially harassing them to tap your notification, which might lead them to switch off push notifications for your app entirely, or worse, delete it and maybe even give it a low rating. Anyways, if you go ahead with this, you would need to implement an identification pattern. Insert a unique `message identifier` into the payload of the push notification. When your app receives this push notification, it should send the `message identifier` back to the server. Your server should then log that a particular device token returned a `message identifier`, meaning it received that particular push notification. Your server can check on an hourly/daily basis and resend a particular message to those device tokens that haven't reported back with the relative `message identifier`. Again, this means your server might need to work overtime sometimes. There are other issues with this whole approach: * The user received the push notification but dismissed it rather than opening your app. Your server will assume the user didn't see it and send the notification again. * **Ghost device tokens:** The user accepted push notifications at first but later revoked this privilege. * The user uninstalled the app. Basically, device tokens that once used to receive push notifications but no longer do, most probably due to your message flooding reputation. * The user received the push notification but tapped it at a later time, potentially getting the same notification multiple times (very irritating). * The user received the push notification but tapped it when there was no internet connectivity. * The user received the push notification but your server is down. You can circumvent the last three scenarios by adding even more logic to your app that queues the message IDs to be sent to the server and removes them only when the server responds successfully. So you see, too much work, server-side + client-side. Plus, it's a massive performance degrader on the server-side when dealing with a good volume of users, as well as lowering the performance of your app.
Is there any use for a class to contain only (by default) private members in c++? <sep> Members of a class are by default private in c++. Hence, I wonder whether there is any possible use of creating a class that has all its members (variables and functions) set by default to private. In other words, does there exist any meaningful class definition without any of the keywords <code>public</code>, <code>protected</code> or <code>private</code>?
There is a pattern, used for access protection, based on that kind of class: sometimes it's called the passkey pattern (see also clean C++ granular friend equivalent? (Answer: Attorney-Client Idiom) and How to name this key-oriented access-protection pattern?). Only a friend of the key class has access to `protectedMethod()`: ```c++ class PassKey { friend class Foo; PassKey() {} }; class Bar { public: void protectedMethod(PassKey); }; class Foo { void do_stuff(Bar& b) { b.protectedMethod(PassKey()); } }; class Baz { void do_stuff(Bar& b) { b.protectedMethod(PassKey()); // error, PassKey() is private } }; ```
Removing backslash (escape character) from a string <sep> I am trying to work on my own JSON parser. I have an input string that I want to tokenize: <code>input = "{ \"foo\": \"bar\", \"num\": 3}"</code> How do I remove the escape character <code>\</code> so that it is not a part of my tokens? Currently, my solution using <code>delete</code> works: <code>tokens = input.delete('\\"').split("")</code> <code>=> ["{", " ", "f", "o", "o", ":", " ", "b", "a", "r", ",", " ", "n", "u", "m", ":", " ", "3", "}"]</code> However, when I try to use <code>gsub</code>, it fails to find any <code>\"</code>. <code>tokens = input.gsub('\\"', '').split("")</code> <code>=> ["{", " ", "\"", "f", "o", "o", "\"", ":", " ", "\"", "b", "a", "r", "\"", ",", " ", "\"", "n", "u", "m", "\"", ":", " ", "3", "}"]</code> I have two questions: 1. Why does gsub not work in this case? 2. How do I remove the backslash (escape) character? I currently have to remove the backslash character with the quotes to make this work.
When you write: ```ruby input = "{ \"foo\": \"bar\", \"num\": 3}" ``` The actual string stored in `input` is: ```ruby { "foo": "bar", "num": 3} ``` The escape `\"` here is interpreted by the Ruby parser so that it can distinguish between the boundary of a string (the leftmost and the rightmost `"`), and a normal character `" ` in a string (the escaped ones). `String#delete` deletes a character set specified in the first parameter, rather than a pattern. All characters that are in the first parameter will be removed. So by writing ```ruby input.delete('\\"') ``` you get a string with all `\` and `" ` removed from `input`, rather than a string with all `\" ` sequences removed from `input`. This is wrong for your case and may cause unexpected behavior some time later. `String#gsub`, however, substitutes a pattern (either a regular expression or a plain string). ```ruby input.gsub('\\"', '') ``` means find all `\" ` (two characters in a sequence) and replace them with an empty string. Since there isn't a `\` in `input`, nothing gets replaced. What you need is actually: ```ruby input.gsub('"', '') ```
Is it possible to simulate a GCM receive from the adb shell / am command line? I'm getting an error <sep> I'm trying to simulate as if the device is receiving a GCM push message by using adb and the command line. I've tried this command to broadcast a GCM intent: <code>adb shell am broadcast -c com.myapp -a com.google.android.c2dm.intent.RECEIVE -e data "SomeData" </code> This triggers a "Permission denial" log line though: <code>09-19 12:23:34.820 725-787/? W/BroadcastQueue Permission Denial: broadcasting Intent { act=com.google.android.c2dm.intent.RECEIVE cat=[com.myapp] flg=0x10 (has extras) } from null (pid=21244, uid=2000) requires com.google.android.c2dm.permission.SEND due to receiver com.myapp/com.google.android.gcm.GCMBroadcastReceiver </code> Relevant parts of my manifest: <code><uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <application> <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.myapp" /> </intent-filter> </receiver> </application> </code> Any ideas? Edit / clarification: Push / GCM receive works in production. I'm looking for an easier way to test changes.
```xml <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <application> <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.myapp" /> </intent-filter> </receiver> </application> ```
Does rule of three/five apply to inheritance and virtual destructors? <sep> Let's assume we have a very basic <code>class A</code>: <code>class A { public: void SetName(const std::string& newName) { m_name=newName; } void Print() const { std::printf("A::Print(). Name: %s\n",m_name.c_str()); } private: std::string m_name; }; </code> We want to extend this class with <code>class B</code> so we add our virtual destructor, change a member to <code>virtual</code> and change <code>private</code> to <code>protected</code> for inh: <code>class A { public: virtual ~A() {} void SetName(const std::string& newName) { m_name=newName; } virtual void Print() const { std::printf("A::Print(). Name: %s\n",m_name.c_str()); } protected: std::string m_name; }; class B : public A { public: virtual void Print() const { std::printf("B::Print(). Name: %s\n",m_name.c_str()); } }; </code> Now since we added a destructor in <code>class A</code> do we need to create a copy constructor and copy operator like so? <code>class A { public: virtual ~A() {} A() = default; A(const A& copyFrom){ *this = copyFrom; } virtual A& operator=(const A& copyFrom){ m_name=copyFrom.m_name; return *this; }; void SetName(const std::string& newName) { m_name=newName; } virtual void Print() const { std::printf("A::Print(). Name: %s\n",m_name.c_str()); } protected: std::string m_name; }; </code> To me this seems unnecessary as the default copy operator and copy constructor would do the same thing.
To be prepared for potential future evolution of the language, you should indeed explicitly default the copy/move constructors and assignment operators when you add a virtual destructor. That's because C++11, 12.8/7, makes implicit generation of copy constructors deprecated when the class has a user-declared destructor. Fortunately, C++11's explicit defaulting makes their definition easy: ```c++ class A { public: virtual ~A() {} A() = default; A(const A& copyFrom) = default; A& operator=(const A& copyFrom) = default; A(A&&) = default; A& operator=(A&&) = default; void SetName(const std::string& newName) { m_name = newName; } virtual void Print() const { std::printf("A::Print(). Name: %s\n", m_name.c_str()); } protected: std::string m_name; }; ```
Jest React Example <sep> I am trying to run the React Example from the Jest React tutorial but I am receiving errors <code> npm test > ... > jest Found 1 matching tests... FAIL __tests__\CheckboxWithLabel-test.js (0.551s) npm ERR! Test failed. See above for more details. npm ERR! not ok code 0 </code> I have pretty much copied the code directly from the example. The package.json is as follows: <code>{ "dependencies": { "react": "*", "react-tools": "*" }, "scripts":{ "test": "jest" }, "jest": { "scriptPreprocessor": "<rootDir>/preprocessor.js", "unmockedModulePathPatterns": [ "<rootDir>/node_modules/react" ] }, "devDependencies": { "jest-cli": "~0.1.17" } } </code> Any thoughts on what I can do to resolve these errors and run the example test successfully? It's very possible I'm missing an important detail (or details) but not entirely sure what. Oh and for what it's worth, I'm running this on Windows if that impacts this. I would really like to get some tests on my react components (was having some trouble there too so started with the basic examples) -- any help would be appreciated :)
I created an issue on their GitHub page. Waiting to find out if it is actually a Windows-related issue. In the meantime, I eventually got it working by just specifying the name of the module rather than the relative path: `"unmockedModulePathPatterns": ["react"]`
How to set Xamarin.Forms Label Font Bold <sep> In Xamarin.Forms I am using a Label and trying to set a Font. The following code works:- <code>Label label1 = new Label(); label1.Font = Font.SystemFontOfSize(10); </code> However trying to specify the Font Attributes such like:- <code>Label label1 = new Label(); label1.Font = Font.SystemFontOfSize(10, FontAttributes.Bold); </code> is preventing the ContentPage from rendering with an exception. There is a Font.BoldSystemFontOfSize(), which could be used, however this is meant to be deprecated, so I am trying to now use Font.SystemOfSize instead. How is it done using this?
I guess I'm late for answering, but I'd still like to mention that this can be done using XAML now. The following XAML will give the desired output: `<Label Text="Hello Label" FontSize="20" FontAttributes="Bold"/>` You can refer to the following link for more about working with Fonts in Xamarin.Forms: Working With Fonts in XForms.
How to give custom field name in laravel form validation error message <sep> I was trying form validation in laravel. I have a input text field in my form called 'Category' and i'm given the field name as 'cat' as short. And i defined the validation rules like this. <code>public static $rules=array( "name"=>"required|min:3", "cat"=>"required" ); </code> When the validation fails i'm getting error message like this <code>The name field is required. The cat field is required. </code> But i want to display it as "The category field is required" instead of 'cat'. How can i change 'cat' to 'Category' in error message ?.
You can customize every message, and also change the attribute field names in `validation.php` (resources/lang/en/). To set the attributes in `validation.php`, use the following: ```php 'attributes' => [ 'name' => 'Name', 'cat' => 'Category', 'field_name' => 'Your attribute', ], ```
How do I fix the error:1069 - The service did not start due to logon failure? <sep> I have written my own windows service which interacts with a SQL database and updates it. The service was running fine and seems to be functioning correctly, however of late it seems to go down at random times and cannot restart due to the error designated in the question. I have tried various searches to fix this, but unfortunately I have come up with nothing. The aim is to eventually having this service running on my companies server, but I can't adjust any server settings, I am but a user on the server, so I have restrictions to some settings. Any quick fixes, would be helpful!
Open the Services Manager (Win + R, then type `services.msc`). Then, right-click on the SQL Server process and click Properties. Go to Log On, and select "This account." Click Browse and add your username in the box (Notice it should contain the domain; in my case, it is `AD\myusername`), then click Check Names and accept. Finally, type your password in the other two fields, and you should have permission to start your process now. Cheers!
Does lua have something like python's slice <sep> Like in python I can use slice. Like following <code>b=[1,2,3,4,5] a=b[0:3] </code> Can I do that kind of operation in Lua without a loop. Or Loop is the most efficient way to do that
By creating a new table using the result of `table.unpack` ( `unpack` before Lua 5.2): `for key, value in pairs({table.unpack({1, 2, 3, 4, 5}, 2, 4)}) do print(key, value) end`, this generates: `1 2 2 3 3 4` (Tested in Lua 5.3.4 and Lua 5.1.5).
Gradle Transitive dependency exclusion is not working as expected. (How do I get rid of com.google.guava:guava-jdk5:13.0 ?) <sep> here is a snippet of my build.gradle: <code>compile 'com.google.api-client:google-api-client:1.19.0' compile 'com.google.apis:google-api-services-oauth2:v2-rev77-1.19.0' compile 'com.google.apis:google-api-services-plus:v1-rev155-1.19.0' compile 'com.google.appengine.tools:appengine-gcs-client:0.4.1' compile 'com.google.appengine.tools:appengine-mapreduce:0.8' </code> which imports multiple version of guava as you can see with dependencyInsight: <code>com.google.guava:guava:15.0 (conflict resolution) com.google.guava:guava:14.0.1 -> 15.0 +--- com.googlecode.objectify:objectify:4.1.3 | \--- default \--- net.eusashead.spring:spring-cache-gae:1.0.0.RELEASE \--- default com.google.guava:guava:[15.0,15.99] -> 15.0 +--- com.google.appengine.tools:appengine-gcs-client:0.4.1 | +--- default | +--- com.google.appengine.tools:appengine-mapreduce:0.8 | | \--- default | \--- com.google.appengine.tools:appengine-pipeline:0.2.10 | \--- com.google.appengine.tools:appengine-mapreduce:0.8 (*) +--- com.google.appengine.tools:appengine-mapreduce:0.8 (*) \--- com.google.appengine.tools:appengine-pipeline:0.2.10 (*) com.google.guava:guava-jdk5:13.0 \--- com.google.api-client:google-api-client:1.19.0 +--- default +--- com.google.apis:google-api-services-oauth2:v2-rev77-1.19.0 | \--- default +--- com.google.apis:google-api-services-plus:v1-rev155-1.19.0 | \--- default +--- com.google.appengine.tools:appengine-gcs-client:0.4.1 | +--- default | +--- com.google.appengine.tools:appengine-mapreduce:0.8 | | \--- default | \--- com.google.appengine.tools:appengine-pipeline:0.2.10 | \--- com.google.appengine.tools:appengine-mapreduce:0.8 (*) +--- com.google.api-client:google-api-client-appengine:1.17.0-rc | \--- com.google.appengine.tools:appengine-gcs-client:0.4.1 (*) +--- com.google.apis:google-api-services-storage:v1-rev1-1.18.0-rc | \--- com.google.appengine.tools:appengine-gcs-client:0.4.1 (*) +--- com.google.apis:google-api-services-bigquery:v2-rev154-1.19.0 | \--- com.google.appengine.tools:appengine-mapreduce:0.8 (*) \--- com.google.api-client:google-api-client-servlet:1.17.0-rc \--- com.google.api-client:google-api-client-appengine:1.17.0-rc (*) (*) - dependencies omitted (listed previously) </code> I have tried removing the dependency to : by doing: <code>compile ('com.google.api-client:google-api-client:1.19.0'){ exclude group: 'com.google.guava', module: 'guava-jdk5' } compile ('com.google.api-client:google-api-client:1.19.0'){ exclude group: 'com.google.guava', } </code> but the dependencyInsight remains the same. I also tried <code>compile ('com.google.guava:guava:15.0'){force = true} </code> but again dependency insight remains the same. How do I get rid of com.google.guava:guava-jdk5:13.0 ? Details: I've tried gradle 1.2 and 2.1 on a windows 8.1 box The reason for me to try this is to get rid of this exception: <code>java.lang.NoSuchMethodError: com.google.common.base.Stopwatch.createStarted()Lcom/google/common/base/Stopwatch; </code>
It seems a dependency will not be excluded if there is another dependency somewhere that points to that same dependency without any excludes. You can exclude a dependency through the `configuration` block, however: ``` configurations { all*.exclude group: 'com.google.guava', module:'guava-jdk5' } ```
Multiple selection ain't working in Phpstorm 8 under Ubuntu <sep> New feature in Phpstorm 8 - multiple selection ain't working under Ubuntu 14.04, however, the hotkey ALT+J does work, but i cannot multiple select using ALT+Mouse left click, i have checked the keymap <code>Add or Remove caret is set to ALT+Button1 Click </code> Which seems okay. When i try to hold ALT and left click - nothing happens, i guess it's ubuntu related.
I know this is old, but for anyone else who comes here, if you don't want to remap it, you can hit Cmd (Win key) + Alt + click. It won't be recognized as a move operation, but PhpStorm will just register the Alt + button 1 click.
How can I left justify text in a pandas DataFrame column in an IPython notebook <sep> I am trying to format the output in an IPython notebook. I tried using the to_string function, and this neatly lets me eliminate the index column. But the textual data is right justified. In [10]: <code>import pandas as pd columns = ['Text', 'Value'] a = pd.DataFrame ({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]}) print (a.to_string (index=False)) Text Value abcdef 12.34 x 4.20 </code> The same is true when just printing the dataframe. In [12]: <code>print (a) Text Value 0 abcdef 12.34 1 x 4.20 </code> The justify argument in the to_string function, surprisingly, only justifies the column heading. In [13]: <code>import pandas as pd columns = ['Text', 'Value'] a = pd.DataFrame ({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]}) print (a.to_string (justify='left', index=False)) Text Value abcdef 12.34 x 4.20 </code> How can I control the justification settings for individual columns?
If you're willing to use another library, `tabulate` will do this—`$ pip install tabulate` and then `from tabulate import tabulate df = pd.DataFrame({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]}) print(tabulate(df, showindex=False, headers=df.columns))` Text Value ------- -------- abcdef 12.34 x 4.2 It has various other output formats as well.
How to remove dashed line from HTML context <sep> To draw a dashed line in a canvas context, I use this <code> var canvas = document.getElementById('canv'); ctx = canvas.getContext('2d'); ctx.setLineDash([5]); </code> When I don't want to draw more dashed lines I do this. <code> ctx.setLineDash([0]); </code> Removing the dashs works in desktop browsers, but this is not working in mobile Safari. Is there another way to remove the dashes and draw plain continious solid lines? Thanks
You can pass an empty array. It also makes the line solid. ```javascript ctx.setLineDash([]); const c = document.getElementById("myCanvas"); const ctx = c.getContext("2d"); ctx.setLineDash([5, 3]); ctx.strokeRect(20, 20, 150, 100); button.onclick = () => { ctx.clearRect(15, 15, 200, 200); ctx.setLineDash([]); ctx.strokeRect(20, 20, 150, 100); }; ``` ```html <!DOCTYPE html> <html> <body> <button id="button">Unset Dashed Line</button><br> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas> </body> </html> ```
can't link with a main executable file <sep> Changed my deployment target to from 8.0 to 7.0. Using Xcode 6 with latest iOS8 as base sdk. Getting this error when building for iOS7.1 device: ld: can't link with a main executable file '/Users/Name/Library/Developer/Xcode/DerivedData/Clumsy_Bird-gotvuaeuyvrkzvfqpzsuxpmifimu/Build/Products/Debug-iphoneos/Clumsy Bird.app/Clumsy Bird' for architecture armv7 clang: error: linker command failed with exit code 1 (use -v to see invocation) How to solve this?
I had a mismatch in values between the "Build Active Architecture Only" settings. It was "Yes" for my test app but "No" for my unit test target. Make sure these values are identical.
Why are particular C data types declared in more than one standard header file? <sep> For example, C11 dictates that <code>size_t</code> should be declared in the following header files: stddef.h stdio.h stdlib.h string.h time.h uchar.h wchar.h When reading C11, I found there are many other data types declared in more than one standard header files. Questions Let's say in the case of <code>size_t</code>. Why not just in <code>stddef.h</code> for simplicity? Let's say a C compiler implements <code>size_t</code> in those header files. Are they guaranteed to have the same definition in those header files?
As an example of a function declared in `stdio.h` that requires `size_t` to be predeclared, consider `snprintf()`. As it is, if you want to use it in your code, all you need to do is `#include <stdio.h>`. If `size_t` were declared only in `stddef.h`, you would have to `#include <stddef.h> #include <stdio.h>`. Not only that, but since `stdio.h` declares `snprintf` whether you use it or not, you would have to include both files every time you needed anything in `stdio.h` to avoid compiler errors; `stdio.h` would have an artificial dependency on `stddef.h`. That causes your source code to become longer and more brittle (notice that if you reverse the order of the two directives, it would also break). Instead, we write header files so that they stand alone and do not depend on other headers, and this is what the C standardization committee decided on for the standard library.
npm install is missing modules <sep> Before I can run <code>gulp</code> in my project I need to run <code>npm install</code>. This works except on my computer, because I get the following error: <code>Error: Cannot find module 'socket.io' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) ... </code> I can fix this with <code>$> npm install socket.io </code> Now when I do the install command again I get <code>Error: Cannot find module 'di' ... </code> When I install <code>di</code> and run the install command again I get: <code>Error: Cannot find module 'log4js' </code> I think that this might continue for a very long time. Any suggestions what is going on here and how to fix this ?
I've faced the same problem when bootstrapping a MEAN application. Adding each missing dependency with `npm install packageName --save` was not an option, so I came across npm-install-missing, which has saved my life :) Installation: `npm install -g npm-install-missing` Usage: `npm-install-missing`
Have to click away twice from Calendar in WPF <sep> Edit 2: Thank you all for your feedback. I solved the problem by adding this to my SelectedDatesChanged event: <code>Mouse.Capture(null);</code> When I select a date in my calendar, I want to click my "Go" button. However, I need to click the "Go" button twice: once to de-focus the calendar, and again to actually press it. The mouse leave event does not trigger on the calendar if an item is selected inside of it, and Keyboard.ClearFocus() does not de-focus it either. Please, how can I get rid of the calendar's focus whenever I select a date? Thank you! Edit: Clicking the "Go" button next was merely an example; if I want to select a textbox and I have just selected a date, I would also have to click twice to enter the textbox. The main issue is that, once the calendar is interacted with, it must be clicked out of once before interacting with any other elements.
```csharp private void Calendar_GotMouseCapture(object sender, MouseEventArgs e) { UIElement originalElement = e.OriginalSource as UIElement; if (originalElement is CalendarDayButton || originalElement is CalendarItem) { originalElement.ReleaseMouseCapture(); } } ```
How can I simulate the Apple Watch for development purposes? <sep> I just downloaded the Xcode 6 GM, and I'd like to see how my apps work with an Apple Watch connected to the simulated iPhone. How can I simulate this new device on my MacBook?
Install Xcode (starting from 6.2) (link). Add an Apple Watch target to your project (New -> Target -> Apple Watch -> Watch App). Go to iOS Simulator -> Hardware -> External displays and select any Apple Watch options. Choose the '[your project] Watch App' target and run. Have fun! :)
how to prevent duplicate in array push in angularjs <sep> my code is like this : <code>var arr = []; arr.push(item1,item2); </code> so <code>arr</code> will contain like: ["name","thing1"] But i got problem when pushing element with same exact value, how do i filter same element value but still accepting update/changes. JSFIDDLE
You can use `arr.indexOf`, which returns -1 if it is not found, so you can add it then. E.g., `if (arr.indexOf(item) == -1) { arr.push(item); }`. However, this does not work in old browsers. jQuery has a method (`$.indexOf`) that works in every browser, even very old ones.
What does c do in R? <sep> Consider the code below: <code>k <- c(.5, 1) </code> What does c do here? I think it must be a list or vector. If it is, how can I extend this vector to contain 1024 values?
In R, the `c()` function returns a vector (a one-dimensional array). In your example: ```R k <- c(0.5, 1) # k is a vector k[1] # is 0.5 (remember, R indices start on 1) k[2] # is 1 ``` If you want to create a vector with 1024 entries (assuming 0.5 increments), you have at least two ways to do it: ```R # One way k <- (1:1024) / 2 # this will be 0.5, 1, 1.5, 2, ... , 512 # Another way: k <- seq(0.5, 512, 0.5) ``` Also, you can use `c()` to concatenate two vectors: ```R k <- c(0.5, 1) # k = 0.5, 1 k <- c(k, 1.5) # k = 0.5, 1, 1.5 k <- c(k, c(2, 2.5)) # k = 0.5, 1, 1.5, 2, 2.5 k <- c(k, k) # k = 0.5, 1, 1.5, 2, 2.5, 0.5, 1, 1.5, 2, 2.5 ``` Please check the help for the `c()` and `seq` functions (in R: `?c` and `?seq`). Reference: Quick-R: Data types
Get version number of iOS Universal Framework in client <sep> This is likely not limited to iOS Universal Frameworks but all xxx.framework files. However I can't seem to find documentation on how to get the current version and build of a framework within the client application. Within an app you'd use something like: <code> NSString *name = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]; NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]; NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; </code> That would give you the current information stored in the Info.plist for the app. But how to we find that information for a framework. And in my case, specifically an embedded framework.
Here's a solution that does work with Universal Frameworks. Just replace `SomeFrameworkClass` with a class from the desired framework. `if let sdkVersion = Bundle(for: SomeFrameworkClass.self).infoDictionary?["CFBundleShortVersionString"] { // sdkVersion is available here } `
Swift property override not working <sep> When I try to override a property I get an error "can not override mutable property with read-only property" I have provided get and set in the super class. <code>class Card { var contents:String { get { return self.contents } set { self.contents = newValue } } init() { self.contents = "" } } </code> Here is my Subclass where I am trying to override the "contents" property. <code>class PlayingCard: Card { override var contents:String { //<-- this is where I get the build error get { var rankStrings:Array<String> = PlayingCard.rankStrings() return rankStrings[Int(self.rank)] + self.suit } } } </code> What exactly am I doing wrong?
If the property you're overriding has both a getter and a setter, you need to provide both in your subclass as well. Here's the relevant part from the Swift language guide (emphasis mine): > You can present an inherited read-only property as a read-write property by providing both a getter and a setter in your subclass property override. You cannot, however, present an inherited read-write property as a read-only property. If you're not doing anything special with the value, then you'll typically want to pass the value being set on to the base class: ```swift set { super.contents = newValue } ``` You could also just discard the value with an empty setter (although I can't think of a good reason to do this offhand): ```swift set { } ``` I also wanted to point out that you have an infinite loop in the `contents` property in your `Card` class. When you do this: ```swift get { return self.contents } ``` You're actually just calling that same getter again, creating an infinite loop; you're doing the same with the setter. Swift doesn't create ivars for your properties automatically like Objective-C did, so you need to create them yourself. A more appropriate way to create that property would be to do something like this: ```swift class Card { private var _contents: String var contents: String { get { return _contents } set { _contents = newValue } } init() { _contents = "" } } ``` However, since you're not doing anything other than setting and returning `_contents` in your setter and getter, you can simplify it down to this: ```swift class Card { var contents: String = "" init() { } } ``` Note: `contents` might also be a good candidate for using an optional ( `String?` ) and setting it to `nil` rather than initializing it to an empty string.
Conditional `echo` (or eval or include) in rmarkdown chunks <sep> I would like to create an Rmarkdown document (pdf or html) that has some chunks "executed" conditionally. The particular case I have in mind is that I might want a more verbose and documented version of the output for internal review by colleagues, and a shorter version for external consumers. I may not want or need to show data manipulation steps to a client, but just key graphs and tables. I also do not want to make two separate documents or have to manually indicate what to show or not. Is there a way to set a switch at the beginning of the Rmd that indicates, e.g., verbose=T that will run all chunks or verbose=F that toggles echo=F (or include=F)? Thank you.
``` knitr options can be stated as R expressions. Per the "output" documentation on the knitr webpage: > Note that all options in knitr can take values from R expressions, which brings the feature of conditional evaluation introduced in the main manual. In short, `eval=dothis` means the real value of `eval` is taken from a variable named `dothis` in the global environment; by manipulating this variable, we can turn on/off the evaluation of a batch of chunks. In other words, if you write some chunks like: ```{r label} doNextChunk <- as.logical(rbinom(1,1,.5)) ``` ```{r conditional, eval = doNextChunk} "hello world!" ``` ```
Idiom for long tuple unpacking <sep> Scenario: you have a long tuple as a result of a SQL query and want to unpack it into individual values. What's the best way to do that while conforming to PEP8? So far I have these three options: single assignment, use backslash to split to multiple lines <code>person_id, first_name, last_name, email, \ birth_date, graduation_year, home_street, \ home_city, home_zip, mail_street, mail_city, \ mail_zip = row </code> single assignment, group left-hand side in parantheses and break lines without a backslash <code>(person_id, first_name, last_name, email, birth_date, graduation_year, home_street, home_city, home_zip, mail_street, mail_city, mail_zip) = row </code> split into multiple assignments, each fitting into a single line <code>person_id, first_name, last_name, email = row[0:4] birth_date, graduation_year, home_street = row[4:7] home_city, home_zip, mail_street, mail_city = row[7:11] mail_zip = row[11] </code> Which of the three options is the best? Is there anything better?
Answering your question "Which of the three options is the best?" PEP 8 states: <blockquote> The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets, and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. </blockquote> This means the second option is preferred over the first. The third option is fine, conforming to PEP 8 as well, though personally, I wouldn't recommend it.
What is the difference between: rails vs. bin/rails? <sep> as freshman, I come across many unclear details. One of those is bin-thing. I've been wondering what's the difference between: <code>rails generate... </code> and <code>bin/rails generate... </code> ? They seem to behave the same when I run those commands in console. There is also rake and bin/rake... and many more probably. Thanks for help. -- greetings
If you run `rails`, RubyGems will activate the latest version of the Rails executable it can find in your PATH. This is fine as long as you use this version of Rails in your project. If you have a project that uses an older version of Rails and you run `rails`, you can run into problems when trying to run code that's changed in the latest Rails version. Binstubs fix this problem by ensuring your environment uses the versions specified in your project's Gemfile.
What is busy spin in a multi-threaded environment? <sep> What is "Busy Spin" in multi-threaded environment? How it is useful and how can it be implemented in java in a multi-threaded environment? In what way can it be useful in improving the performance of an application?
Some of the other answers miss the real problem with busy waiting. Unless you're talking about an application where you are concerned with conserving electrical power, then burning CPU time is not, in and of itself, a bad thing. It's only bad when there is some other thread or process that is ready-to-run. It's really bad when one of the ready-to-run threads is the thread that your busy-wait loop is waiting for. That's the real issue. A normal, user-mode program running on a normal operating system has no control over which threads run on which processors; a normal operating system has no way to tell the difference between a thread that is busy waiting and a thread that is doing work, and even if the OS knew that the thread was busy-waiting, it would have no way to know what the thread was waiting for. So, it's entirely possible for the busy waiter to wait for many milliseconds (practically an eternity), waiting for an event, while the only thread that could make the event happen sits on the sideline (i.e., in the run queue) waiting for its turn to use a CPU. Busy waiting is often used in systems where there is tight control over which threads run on which processors. Busy waiting can be the most efficient way to wait for an event when you know that the thread that will cause it is actually running on a different processor. That is often the case when you're writing code for the operating system itself, or when you're writing an embedded, real-time application that runs under a real-time operating system. Kevin Walters wrote about the case where the time to wait is very short. A CPU-bound, ordinary program running on an ordinary OS may be allowed to execute millions of instructions in each time slice. So, if the program uses a spin-lock to protect a critical section consisting of just a few instructions, then it is highly unlikely that any thread will lose its time slice while it is in the critical section. That means, if thread A finds the spin-lock locked, then it is highly likely that thread B, which holds the lock, actually is running on a different CPU. That's why it can be OK to use spin-locks in an ordinary program when you know it's going to run on a multi-processor host.
What is the "_path" method in ruby on rails? <sep> I'm learning RoR, and I'm getting very confused by the "_path" method as it's used in Controllers and Routes. To be more specific, I'm referring to the many different calls that take the syntax "(something)_path". So far as I know, they all seem to either encode or manipulate a URL or link. I'm having a hard time mastering the use of this type of method because I can't figure out what it's core functionality is supposed to be. For example, I could use the following code to redirect an old URL structure to a page of listed Tweet instances in my config/routes.rb file: <code>get '/all' => 'tweets#index', as: 'all_tweets' </code> Only now can I use the following in an .erb file. Notice the "_path" code at the end of the line. <code><%= link_to "All Tweets", all_tweets_path %> </code> I could also use the following code to create a link to an edit page (and another action) in a different .erb file: <code><p><%= link_to tweet.user.name, edit_tweet_path(@tweet) %></p> </code> I've tried reading through my study materials as well as the RoR documentation, but I always end up more lost than when I began. Does anybody know the low-level definition of this "_path" method?
It's called a `route helper`, which means that Rails will generate them to help provide you with resource-based routing structures. I'll explain more in a second. To explain properly, Rails is just a framework. Like all software, it is a series of files loaded in a particular order. As such, Rails creates a series of helper methods in the booting process. These "helper" methods can then be used throughout your application to call functionality or information as you require: > The Rails framework provides a large number of helpers for working with assets, dates, forms, numbers, and model objects, to name a few. These helpers are available to all templates by default. In addition to using the standard template helpers provided, creating custom helpers to extract complicated logic or reusable functionality is strongly encouraged. By default, each controller will include all helpers. These helpers are only accessible on the controller through `.helpers`. The `route` helpers (which are generated from your `config/routes.rb` file) give you the ability to call resourceful routes. These might seem strange at first, but once you understand them, they will be helpful. **Resourceful** To give you more clarity, Rails routes are known as resourceful. This means they are constructed around resources. To give you a brief definition, you need to appreciate that the resources of your application are the pools of data you can add to and pull from. To explain further, because Rails is object-oriented. If you're new, this won't mean very much, but keep it in mind, as when you progress through the language or work, you'll begin to see why this is important. Object-oriented programming puts OBJECTS at the center of the flow. Typically, you'd put logic at the center, but with OOP, it's the objects. This is very important for us, as it means that everything you do in Rails is based around the objects you can create. As per the MVC principle (which, again, is what Rails is built on), you'll create/invoke your objects from your `Models`: This means that if you want to create a series of routes to "CRUD" (Create, Read, Update, Destroy) your objects, Rails is able to create the routes necessary to do that. This is where the `resources` directives come from inside the routes file. Hope this helps!
OS X and rabbitMQ: ERROR: epmd error for host xxx: address (cannot connect to host/port) <sep> I just made to the latest OS X maverick update and I got suprised to see that rabbitMQ is no longueur working. I get the following error: <code>MacBook-Pro-de-Julio:~ julio$ rabbitmq-server ERROR: epmd error for host MacBook-Pro-de-Julio: address (cannot connect to host/port) </code> I use the standalone version of <code>rabbitMQ</code>. I try to re-install it without any success. When I run <code>hostname</code> command I have the following result: <code>MacBook-Pro-de-Julio:~ julio$ hostname MacBook-Pro-de-Julio.local </code> Do you know how to fix this issue? EDIT 1: By turning off the Wifi, I can run with success rabbitMQ. If I turn it on, I can't launch rabbitMQ. EDIT 2: Thanks to @old_sound answer, I fixed the issue by editing my <code>/etc/hosts</code>.
If you're getting an "epmd error for host HostName: timeout (timed out)" error, try the following: 1. Open the `/etc/hosts` file using `sudo mcedit /etc/hosts`. 2. Add a line like this: `127.0.0.1 HostName` (replace "HostName" with the actual hostname of your machine). 3. Find your hostname by running the command `echo $HOSTNAME`.
App Validation on Xcode 6 GM release <sep> When I try to validate my build using xcode 6 GM release I am getting this error. Error : itunes store operation failed no eligible software found. Make sure this software is owned by your developer organization. Can anybody here suggest some solution?
You're probably using a different Apple ID for iTunes Connect than for the Developer Portal. Here's a workaround: Export the archive in Organizer (Save for iOS App Store Deployment) and then use Application Loader (Xcode > Open Developer Tools > Application Loader) to upload it to iTunes Connect. This allows you to input your credentials.
Amazon ssh_exchange_identification: read: Connection reset by peer: when changing permissions <sep> I went on to my amazon ec2 successfully and I have been experimenting around. I found it annoying that I needed to always run sudo on everything so what I decided to do was to go to the route directory and change the permissions of everything to write, write, and execute. I did so doing the following <code>chmod -R 777 . </code> I then exited out of the server. The next time I tried to logon I got <code>"ssh_exchange_identification: read: Connection reset by peer" </code> How can I fix this? Thank you
My solution is probably trivial, but who knows who it could help: I simply rebooted my EC2 instance in the browser (AWS -> EC2 Dashboard -> instances -> (select your instance) -> (click the action dropdown) -> Instance State -> Reboot). You may want to give it a minute before you try your SSH connection command again. Hope that helps someone.
how to install plugin/head for elastic search? <sep> I have installed elastic search and its plugin head but when i enter the <code> **url "localhost:9200/_plugin/head/"** </code> It does not shows any thing? And I have also install marvel/SENSE for monitoring purpose. I have installed plugin/head using <code>sudo elasticsearch/bin/plugin -install mobz/elasticsearch-head </code> But its also not working . Error: console not found on url http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/sense_widget.html?snippets/010_Intro/10_Info.json BTW I am new to elastic search. So if you could tell me why it is not showing anything or have i made any mistake. Thank in advance!
If someone tries with version 5 or earlier: * For Elasticsearch 5.x: plugins are not supported. Run elasticsearch-head as a standalone. * For Elasticsearch 2.x and 4.x: sudo elasticsearch/bin/plugin install mobz/elasticsearch-head * For Elasticsearch 1.x: sudo elasticsearch/bin/plugin -install mobz/elasticsearch-head/1.x * For Elasticsearch 0.9: sudo elasticsearch/bin/plugin -install mobz/elasticsearch-head/0.9 From GitHub
Fibonacci closure in go <sep> I am following the go tour on their official website and I have been asked to write a Fibonacci generator. Here it is: <code> package main import "fmt" // fibonacci is a function that returns // a function that returns an int. func fibonacci() func() int { first := 0 second := 0 return func() int{ if(first == 0) { first = 1 second = 1 return 0 }else { current := first firstc := second second = first + second first = firstc return current } } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } } </code> It works. However I consider it very ugly and I'm sure there has to be a better solution. I have been thinking about posting this on the code-review however since I'm asking for a better approach I thought this is the right place to post it. Is there a better way to write this code? Here is the task: <blockquote> Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers. </blockquote>
My favorite clean way to implement iterating through the Fibonacci numbers is to use `first` as `fi - 1` and `second` as `fi`. The Fibonacci equation states that: `fi + 1 = fi + fi - 1`. Except when we write this in code, in the next round we're incrementing `i`. So we're effectively doing: `fnext i = fcurrent i + fcurrent i - 1` and `fnext i - 1 = fcurrent i`. The way I like to implement this in code is: `first, second = second, first + second`. The `first = second` part corresponds to updating `fnext i - 1 = fcurrent i`, and the `second = first + second` part corresponds to updating `fnext i = fcurrent i + fcurrent i - 1`. Then all we have left to do is return the old value of `first`, so we'll store it in a temp variable out of the way before doing the update. In total, we get: ```go // fibonacci returns a function that returns // successive fibonacci numbers from each // successive call func fibonacci() func() int { first, second := 0, 1 return func() int { ret := first first, second = second, first + second return ret } } ``` See it in action on the Go Playground.
How to remove / dispose a broadcast variable from heap in Spark? <sep> To broadcast a variable such that a variable occurs exactly once in memory per node on a cluster one can do: <code>val myVarBroadcasted = sc.broadcast(myVar)</code> then retrieve it in RDD transformations like so: <code>myRdd.map(blar => { val myVarRetrieved = myVarBroadcasted.value // some code that uses it } .someAction </code> But suppose now I wish to perform some more actions with new broadcasted variable - what if I've not got enough heap space due to the old broadcast variables?! I want a function like <code>myVarBroadcasted.remove() </code> Now I can't seem to find a way of doing this. Also, a very related question: where do the broadcast variables go? Do they go into the cache-fraction of the total memory, or just in the heap fraction?
If you want to remove the broadcast variable from both executors and driver, you have to use `destroy()`. Using `unpersist()` only removes it from the executors: `myVarBroadcasted.destroy()`. This method is blocking.
serialize a datetime as an integer timestamp <sep> I would like for django rest to not convert my DateTime model field into a string date represtation when serializing it. <code>response_date = serializers.DateTimeField(source="updated_at") </code> I would like this to come out as <blockquote> 1411880508 </blockquote> and not <blockquote> "2014-09-28T05:01:48.123" </blockquote>
```python REST_FRAMEWORK = { # if you want with milliseconds or 'DATETIME_FORMAT': '%s.%f', # only with seconds 'DATETIME_FORMAT': '%s', } Result in REST will be string "1517863184.666435" "1517863249" If you want float(or integer) value in API, then you can use monkey patching. Put the file `monkey_patching.py` in any of your `apps` and import it in app's `__init__.py` file. ie: app/monkey_patching.py ```python # app/monkey_patching.py import six from rest_framework import ISO_8601 from rest_framework.fields import DateTimeField from rest_framework.settings import api_settings def to_representation_ext(self, value): if not value: return None output_format = getattr(self, 'format', api_settings.DATETIME_FORMAT) if output_format is None or isinstance(value, six.string_types): return value if output_format.lower() == ISO_8601: value = self.enforce_timezone(value) value = value.isoformat() if value.endswith('+00:00'): value = value[:-6] + 'Z' return value # FOR INTEGER RESULT # 'DATETIME_FORMAT': '%s', # return int(value.strftime(output_format)) # FOR FLOAT RESULT # 'DATETIME_FORMAT': '%s.%f', # return float(value.strftime(output_format)) DateTimeField.to_representation = to_representation_ext ``` app/init.py ```python # app/__init__.py import app.monkey_patching ``` Tested with Django version 2.0.10 and Python 3.5.9
Font color for UILabel not changing <sep> I am trying to display numbers on a UILabel with a bold black font and size 50. After some failed attempts I just realized that no matter what color I set the font to, it always gets set to lightGray. Is there something else I need to do other than the below? <code>[DisplayLabel setFont:[UIFont fontWithName:[NSString stringWithUTF8String:"HelveticaNeue-Bold"] size:50]]; DisplayLabel.textColor = [UIColor brownColor]; DisplayLabel.textAlignment = NSTextAlignmentCenter; </code> I am adding the label using the storyboard to a view.
I encountered the same issue, but it was caused by setting a custom color in the storyboard. Apparently, you must have the color attribute set to `default` in order to change it programmatically. I found this to be true with all `UIView`s.
com.sun.tools.attach.AttachNotSupportedException: Unable to open socket file: target process not responding or HotSpot VM not loaded <sep> I get <code>AttachNotSupportedException</code> while running jmockit tests on linux (ubuntu 64bit). Java version is 1.7.0_51. This JDK is from Oracle. Tests are run using ant(that probably is not relevant) See the stack trace. <code>[junit] [junit] java.lang.RuntimeException: com.sun.tools.attach.AttachNotSupportedException: Unable to open socket file: target process not responding or HotSpot VM not loaded [junit] at mockit.internal.startup.JDK6AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(JDK6AgentLoader.java:89) [junit] at mockit.internal.startup.JDK6AgentLoader.loadAgent(JDK6AgentLoader.java:54) [junit] at mockit.internal.startup.AgentInitialization.initializeAccordingToJDKVersion(AgentInitialization.java:21) [junit] at mockit.internal.startup.Startup.initializeIfNeeded(Startup.java:136) [junit] at mockit.internal.startup.Startup.initializeIfPossible(Startup.java:169) [junit] at junit.framework.TestResult.<clinit>(TestResult.java:15) [junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:356) [junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1165) [junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:1016) [junit] Caused by: com.sun.tools.attach.AttachNotSupportedException: Unable to open socket file: target process not responding or HotSpot VM not loaded [junit] at sun.tools.attach.LinuxVirtualMachine.<init>(LinuxVirtualMachine.java:106) [junit] at mockit.internal.startup.JDK6AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(JDK6AgentLoader.java:79) [junit] ... 8 more [junit] Exception in thread "main" java.lang.ExceptionInInitializerError [junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:356) [junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1165) [junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:1016) [junit] Caused by: java.lang.RuntimeException: com.sun.tools.attach.AttachNotSupportedException: Unable to open socket file: target process not responding or HotSpot VM not loaded [junit] at mockit.internal.startup.JDK6AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(JDK6AgentLoader.java:89) [junit] at mockit.internal.startup.JDK6AgentLoader.loadAgent(JDK6AgentLoader.java:54) [junit] at mockit.internal.startup.AgentInitialization.initializeAccordingToJDKVersion(AgentInitialization.java:21) [junit] at mockit.internal.startup.Startup.initializeIfNeeded(Startup.java:136) [junit] at mockit.internal.startup.Startup.initializeIfPossible(Startup.java:169) [junit] at junit.framework.TestResult.<clinit>(TestResult.java:15) [junit] ... 3 more [junit] Caused by: com.sun.tools.attach.AttachNotSupportedException: Unable to open socket file: target process not responding or HotSpot VM not loaded [junit] at sun.tools.attach.LinuxVirtualMachine.<init>(LinuxVirtualMachine.java:106) [junit] at mockit.internal.startup.JDK6AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(JDK6AgentLoader.java:79) [junit] ... 8 more [junit] Running chs.caf.cap </code> It appears to be related to AttachNotSupportedException while running jMockit tests on IBM JRE. This however is on IBM jre.
I had the same issue while trying to dump threads using `jcmd`. I was getting the same error message even though I was running `jcmd` under the `root` user. You need to run `jcmd <pid> Thread.print` under the same user as the Java process has, otherwise your connections will be dropped. Java doesn't care if you are root or not. So basically: `sudo -u <java_process_user> jcmd <pid> Thread.print`.
Compile-time map and inverse map values <sep> Can someone recommend a more elegant way to achieve these compile-time constants? <code>template <int> struct Map; template <> struct Map<0> {static const int value = 4;}; template <> struct Map<1> {static const int value = 8;}; template <> struct Map<2> {static const int value = 15;}; template <int> struct MapInverse; template <> struct MapInverse<4> {static const int value = 0;}; template <> struct MapInverse<8> {static const int value = 1;}; template <> struct MapInverse<15> {static const int value = 2;}; </code> The values need to be constexpr in my program, yet the inverse mapped values are getting tedious to update (and easy to make mistakes or forget to do even).
```cpp #include <utility> using Item = std::pair<int, int>; constexpr Item map_items[] = { { 6, 7 }, { 10, 12 }, { 300, 5000 }, }; constexpr auto map_size = sizeof(map_items) / sizeof(map_items[0]); static constexpr int findValue(int key, int range = map_size) { return (range == 0) ? throw "Key not present" : (map_items[range - 1].first == key) ? map_items[range - 1].second : findValue(key, range - 1); } static constexpr int findKey(int value, int range = map_size) { return (range == 0) ? throw "Value not present" : (map_items[range - 1].second == value) ? map_items[range - 1].first : findKey(value, range - 1); } static_assert(findKey(findValue(10)) == 10, "should be inverse"); ``` Let me know if you have any other code snippets you'd like me to review!
Python logging time since start of program <sep> I'm using the logging module to create loggers and output data. Instead of using <code>$(asctime)s</code> in <code>logging.Formatter</code>, is there a good way to log the timestamp relative to the creation of the logger?
Using the `%(relativeCreated)d` field in a conventional `Formatter` format string will display the milliseconds elapsed since the `logging` module was loaded. While milliseconds might not be what you want, there's no additional coding required.