INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to create an if/else statement in R based on an open file condition? I've created this function to open a file in `R`: openfasta<-function(DNAseq){ DNASeq <- readline(prompt = "Enter the .fasta file name:") readLines(DNASeq) Now if the file can not be found in the working directory, the script must output a warning message and ask for the file name repetitively until the file is located. I tried this, but it didn't work: if (DNASeq) { return() } else { cat(DNASeq <- readline(prompt = "Enter the .fasta file name:")) } } I think if a For loop would be a reasonable solution too.
You can use a `while` loop to check for file existence. If not found use a `print` statement to display a warning and prompt again. openfasta <- function(DNAseq){ while(!file.exists(DNAseq)){ print("The file you requested was not found.") DNASeq <- readline(prompt = "Enter the .fasta file name:") } readLines(DNASeq) }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "r, file" }
Can I ignore .css files while running >$ git mergetool? Our project has .scss file which we generate to .css and the generated .css files are stored in the repo. There's no point merging our entire site's .min.css or .css.map. When running `$ git mergetool`, can I configure it to ignore these files, whether by directory or file name or file extension?
You can add .min.css .css.map to you .gitignore file. After commiting the .gitignore file with these entries you can ignore the files that have already been pushed by executing the following command git rm -r --cached git add . What the above commands do is that they refresh the index file which contains your already published .min.css, .css.map files (filtered -- sortof) And then commit again after the above two commands to delete the files that are generated. Using Git Attributes, it is possible to ignore remote changes during merge. More details are provided in the link below - <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "git, sass, git merge" }
Display subcategories selectbox on each category page I want to display a select box to switch to SUBCATEGORIES of the current CATEGORY when i'm on a category page. I've the following category structure Category 1 Subcategory 1 Subcategory 2 Subcategory 3 Category 2 Subcategory 1 Subcategory 2 I've created a custom template using the category slug but i need to create a selectbox at the top of the template that loads the subcategory of the current category. How do i achieve this?
If you are referring to the categories from the post type `post` (the blog) then this would do the trick: For a drop-down: wp_dropdown_categories() For a list: wp_list_categories() > `child_of` > Only display categories that are children of the category identified by this parameter. There is no default for this parameter. <?php // Put the parent category ID in place of 9999 // for a drop-down, does not need <select></select> wrapper wp_dropdown_categories('child_of=9999'); // for a list, does need <ul></ul> wrapper wp_list_categories('child_of=9999'); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, templates" }
Fastest way to check the records if exists in the SQL table I have hundreds of thousands of records in my SQL table. If between particular data, if no record is present, it takes so much time to inform us. Currently, I am using this query to check if record exists. select TOP 1 1 AS getRowCount from MYTable where ID IN ('3','5','2','4','1') AND ( datewithTime >= '2015-01-01 07:00:00' AND datewithTime < '2016-01-01 07:00:00' ) In the above query, I am getting the record of 1 year, but records are not present in this time limit. But it is taking too much time to respond. Is there any other way that can show if data exists in the table for this particular time interval ? Will LINQ perform better ?
First, You should use the EXISTS statement instead of selecting top 1: SET @getRowCount = EXISTS(select 1 from MYTable where ID IN ('3','5','2','4','1') AND datewithTime >= '2015-01-01 07:00:00' AND datewithTime < '2016-01-01 07:00:00' ) Second, you should check the execution plan to see if you can improve performance by adding indices or altering existing indices. **update** Sorry, I wasn't paying enough attention to what I'm writing. Exists returns a boolean value, but sql server does not have a boolean data type, this is why you get the incorrect syntax error. Here is the correct syntax: DECLARE @getRowCount bit = 0 IF EXISTS(select 1 from MYTable where ID IN ('3','5','2','4','1') AND datewithTime >= '2015-01-01 07:00:00' AND datewithTime < '2016-01-01 07:00:00' ) SET @getRowCount = 1 SELECT @getRowCount
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql server, linq" }
Extracting NSDictionary from a project I have a `NSDictionary` in a project that was created over time and i need to take all the data from it from this project into another project. Any idea how can i achive it without adding it one by one? I thought about extracting everything into arrays and to pass arrays but its not really a good option
Probaly not the best solution but it will work fine. You can convert the dictionary in to a string using the following steps. Then you log the string and copy it. After that you can do a reverse of these steps in your new project. **Project 1** NSDictionary *dictionary = [NSDictionary alloc]init]; NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error]; NSString *dictionaryString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"%@",dictionaryString); #Copy this string from the debugger **Project 2** NSError *error; NSString *dictionaryString = @"PASTE_DEBUGGER_STRING"; NSData *jsonData = [dictionaryString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "ios, objective c" }
Mark existing variable as candiate for implicit method I try to write a method which should use a variable from the surrounding scope. The problem is that I cannot access the part of the code where the variable is defined. Something like this: object Example extends App { val myvar = 1.0 // cannot change that code def myMethod()(implicit value:Double) = { print(value) } myMethod() } This fails because `myMethod` cannot find a suitable implicit for `value`. is there a way to "mark" `value` as implicit after it has been defined, other than defining a new implicit variable pointing to `value`? Background: We use Spark-Notebook where the `SparkContext` (named `sc`) is created automatically. As `sc` is a commonly known name for this variable in the community, we would prefer not to introduce another variable name.
If you just don't want to have an instance of `SparkContext` that isn't labeled as `sc` you could assign it to an implicit-underscore variable like this: implicit val _: SparkContext = sc That would create an implicit variable of the correct type in scope for your function to use. * * * Alternatively you can always pass implicit variables explicitly, in your example above you could do myMethod()(myvar) and that is the solution that I would use.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 7, "tags": "scala, implicit" }
Qualities of a good relay (besides the obvious) I’m currently working on Roster, a tor project that aims to reward relay operators with good relays. Besides the obvious requirements of a good relay (e.g. speed, geo-diversity, constant uptime), what qualities make a relay valuable to the Tor network and its users? While this may not have a definite answer, I would appreciate all opinions on the matter.
I'll give it a shot: * consistent fast speed being #1 * rewards based on total bandwidth available/consumed per period * total consistent uptime * Identity verification (at least online or via email) * Community involvement (member of tor-relays, tor-talk, etc) * Number of successful responses to complaints * Hosting in a country that the Tor Network needs for geo-diversity * bonus for multiple relays properly configured as a family * rewards for a more open exit policy (e.g. _:_ ) * running latest version of Tor or how fast the system upgrades * running a server following best practices guide checklist (FDE, strong passwords, maintained patch levels, etc) * Optional flags (e.g. HSDir, directory mirror)
stackexchange-tor
{ "answer_score": 3, "question_score": 3, "tags": "relays, bandwidth" }
python: i want to merge different dictionaries by same key and add dictionary name to key i want to merge dictionary and add dictionary name to key key + dictionaryname : value(which is biggest) i have three dictionaries like below mall1_d = {'apple': 1000, 'pineapple': 2} mall2_d = {'apple': 1100, 'pineapple': 5} mall3_d = {'apple': 1200, 'pineapple': 3} malldict = {'mall1':mall1_d, 'mall2':mall2_d, 'mall3':mall3_d} i tried below method def mergedict(): for name,dict_ in malldict.items(): for d in dict_: print({k + name: max(v) for k, v in d.items()}) mergedict() **expected result** {'applemall3':1200, 'pineapplemall2':5} but i got error like this AttributeError: 'str' object has no attribute 'items'
You can make a `dictionary` with values as `tuples` to store the max values. The keys of the dictionary are the _fruit names_. The elements of the tuples(dictionary values) are the _mall names_ and the _max values_ , respectively. mall1_d = {'apple': 1000, 'pineapple': 2} mall2_d = {'apple': 1100, 'pineapple': 5} mall3_d = {'apple': 1200, 'pineapple': 3} malldict = {'mall1':mall1_d, 'mall2':mall2_d, 'mall3':mall3_d} def mergeDict(d): maxDict = dict() for k, v in d.items(): for k1, v1 in v.items(): inDict = k1 in maxDict if (not inDict) or (inDict and v1 > maxDict[k1][1]): maxDict[k1] = (k, v1) result = {k + maxDict[k][0]: maxDict[k][1] for k in maxDict} print(result) mergeDict(malldict)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python" }
Queries frequency stats in Redis? In my application I am implementing a server-side cache using Redis (for mySQL database). When data change in the database, I want to completely clear the cache to invalidate the old data. However, I would like to see some statistics about how often are different keys queried in Redis, so that I can sort of manually pre-fetch frequently queried data for them to be available immediately after clearing the cache. Is there any way how to see these statistics directly in Redis? Or what is a common solution to this problem?
You can use the object command. > OBJECT FREQ returns the logarithmic access frequency counter of the object stored at the specified key. This subcommand is available when maxmemory-policy is set to an LFU policy. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "redis" }
PowerShell on SCOM fails to import module I have a problem I cannot solve without help ) I have SCOM in first PC, and I have SCOM agent in second. When my class discoveries in agent PC, it must run PowerShell script. This script contains command: Import-Module FailoverClusters but this command fails with exception: The following error occurred while loading the extended type data file: Microsoft.PowerShell, C:\Windows\system32\WindowsPowerShell\v1.0\Modules\FailoverClusters\FailoverClusters.Types.ps1xml : File skipped because it was already present from "Microsoft.PowerShell". I dont know what to do.
As this blog post points out, you can ignore extended type data errors when loading modules. It's telling you that the type is already loaded and it can't load it a second time.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "powershell, module" }
Retrieve Data from multiple OBJ to only one OBJ javascript function Hello I need your help I would like to retrieve data from this array of Multiple objects to a single OBJ Current format: [ { "name": "Field 1", "carac": "Format carte mère", "caracvalue": [ "1", "2" ] }, { "name": "Field 2", "carac": "Format carte mère", "caracvalue": [ "3", "4" ] } ] To this format ( For each multiple OBJ.caracvalue into one OBJ ): { "caracvalue": [ "1", "2", "3", "4", ] }
Essentially what you want to achieve is a reduce operation. You can achieve it using the following code; const arrayOfObjects = [ { "name": "Field 1", "carac": "Format carte mère", "caracvalue": [ "1", "2" ] }, { "name": "Field 2", "carac": "Format carte mère", "caracvalue": [ "3", "4" ] } ]; const resultObject = { caracValue: arrayOfObjects.reduce((acc, curr) => { return [...acc, ...curr.caracvalue]; }, []), } console.log(resultObject);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, json" }
can we see an swf file corresponding to an fla online? Actually I donot have flash in my computer.So I want to see the swf of an fla file that is in my desktop. can we do this online?
I think George's solution (download a free trial of Flash CS5) is the best. Otherwise you could try this one or the trial version: < Good luck.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "flash, fla" }
You don't have 'phantomjs' installed I do have PhantomJS installed, but I get the error (you don't have 'phantomjs' installed) when I run my Node.js code: var modules = '/home/engine/node_modules/'; var path = require('path'); var childProcess = require('child_process'); var phantom = require(modules+'phantom'); var binPath = phantom.path; phantom.create(function(browser){ // Error happens here I think because the module is found // browser.createPage(function (page){}); }); If in console.log binPath I get undefined. But in PuTTY, if I: cd ~/phantomjs/ [root@engine phantomjs]# bin/phantomjs phantomjs> Have I installed it in the wrong place?
You need to load your global PhantomJS module and not the local. Loading the local module prevents you application from locating the runnable bin: var phantom = require('phantom'); Plus, adding utnas comment: > Remove **var modules = '/home/engine/node_modules/';**. It's not useful. Node.js knows where to find modules. Mixing both parts of the answer to a logical rule, Node.js will always first load the module from the global installed modules if it exists. You force it to load the local one and that prevents it from finding the bin.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "node.js, path, phantomjs" }
HTML: audio cannot be played in mobile browser The HTML **_audio tag_** play works well on all browsers on computers i.e. desktop as well as laptop. **HTML code.** echo "<audio controls autoplay='autoplay'><source src='images/audio.mp3'></audio>"; When it comes to mobile browsers, sound couldn't play eventhough I turned on browser notification. I have to press play button as shown in image below. How to make it auto start and hidden in mobile browser? ![enter image description here](
Autoplay is not allowed in the mobile browsers. So it won't work. If you must use audio in your app, then you can try this post <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "html" }
Jquerymobile Page Redirecting with URL through PHP? Here i have a problem with redirecting the URL with PHP Form submit the page is Changing But the URL is not Changing....... Here is the Code: <form method="post" action="insert.php"> <input type="text" id="emp" name="emp" /> <input type="submit" value="submit" /> </form> <?php $name =$_POST['name']; if($name != '') { header("Location :sample.php"); } else { header("Location :index.php"); } ?> But It is Redirecting and the url is not changing it is displaying like `http:localhost/sample/addForm.php#/sample/insert.php` actually i want it like `http:localhost/sample/sample.php` or `http:localhost/sample/index.php`
Try, if($name != '') { header("Location: /sample/sample.php"); } else { header("Location: /sample/index.php"); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, jquery mobile" }
Save Uploaded Image as PNG In my Django app, Users can upload images. I want to save every uploaded image as a PNG. I've been trying to do this with PIL but it's not working. It still seems to be saving as the original image type (whatever the user uploaded it as). What am I doing wrong? if form.cleaned_data['dataset_image']: # dataset.dataset_image = form.cleaned_data['dataset_image'] name = 'dataset%s.png' % (dataset.id) size = (200, 200) try: im = Image.open(form.cleaned_data['dataset_image']) im.save(name, 'PNG') print "saved file: ", im except IOError: # dont' save the image pass When I upload a jpg (that I want to convert to png), the print statement gives this: `saved file: <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=628x419 at 0x107354F80>`
The print statement refers to the `Image` object when you opened the file. It used the `JpegImagePlugin` class because it is a jpeg image. However, when you call the method `save()`, you save the image based on the extension of the requested filename, in this case, png. Try this if you aren't convinced. try: im = Image.open(form.cleaned_data['dataset_image']) im.save(name) png_img = Image.open(name) print "saved file: ", png_img # it's more clean to print `png_img.format` By the way, just calling `im.save(name)` will also do in this case, since `name` already has the extension and the method will figure out you want it in that format.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, django, python imaging library" }
Drop-down list in navigation bar iOS I want to implement a drop-down list in the navigation bar, which contains all categories such as in this application: !enter image description here I want to know what its name, and steps to implement it. !enter image description here
YOu can try something like this also ... <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "iphone, ios, uinavigationbar, uinavigationitem" }
Multiple UPDATE or DELETE + INSERT in MySQL? Which of those operations should perform faster in MySQL? Presume I have 999 values to change: DELETE FROM table WHERE id IN(100, ..., 999); INSERT INTO example VALUES (100, 'Peter'), (...), (999, 'Sam'); OR UPDATE table_name SET name='Peter' WHERE person_id=100; ...; UPDATE table_name SET name='Sam' WHERE person_id=999;
Since you have only 900 row values to change then first option will perform fast. Because you will have only two queries to run. But if you go for second option then you will have almost 900 queries to run that will definitely slow. And more better idea to do same would be TRUNCATE FROM table; INSERT INTO example VALUES (100, 'Peter'), (...), (999, 'Sam'); because truncate works faster than delete.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, sql, performance, insert" }
How do I access some sort of OnLoad event in Word 2007 VBA? I am trying to have some code fire when the document is first loaded, but there are two problems. First, I don't know which method to call to get something to fire when the document is first opened. Second, if they have macros disabled, how can I be sure that it gets called when they are enabled? Thanks!
The `Document_Open` event is sent when your document is first loaded. To make use of it, enter the following in the VBA code for `ThisDocument`: Private Sub Document_Open() '// your code goes here' End Sub As for the disabled macros, I'm not aware of a method that will be called as soon as macros are enabled.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "vba, ms word, ms office" }
How to Calculate Area Under the Curve in Spotfire? Can someone assist me in calculate the area under the curve in Spotfire w/o using R or S+? I am looking to rank the data in [K] (1 = largest value) for each Well, and then calculate the cumulative sums of [P] (ranked by descending K) and [K], then calculate and plot (as curves) the % cumulative sum of [P] and [K], calculate the area under each curve, for each Well (what is the expression). I would like to calculate each column in Spotfire, but my main problems are ranking [K] so there are no ties (I was attempting to Rank first by [K] and then by [Depth]), summing the values of [P] and [K] by ranked [K] for each Well, and then calculating the Riemann Sums (Area) under each curve. !Data_Table_and_Curves
At first you need to add a new column (`[period]`) to calculate a unique time, otherwise Spotfire would get confused of different times in the datasets: `[well] & Log10([time] + 1)` Then add a cross table, drag `[well]` to the vertical axis, and enter this expression to cell values: `Sum(([pressure] + Avg([pressure]) over (Next([period]))) / 2 * (Avg([time]) over (Next([period])) - [time]))` Alternatively you can add a new column (`[AUDPC_helper]`) too see step by step calculations: `([pressure] + Avg([pressure]) over (Intersect(NextPeriod([period]),[well]))) / 2 * (Avg([time]) over (Intersect(NextPeriod([period]),[well])) - [time])` Just need to get summary of this column in e.g. a cross table ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "spotfire, integral" }
Converting AVI encoded file with an IMM5 codec As part of a legal matter, I received a copy of a security video encoded using what appears to be an 'IMM5' codec, apparently often used by police. I also received a copy of 'BackupPlayer', which can play this video. Note that no media player I have installed, including VLC, is able to play it. IMM5 does not show up in the standard codec packs, and Google searches are surprisingly fruitless. I would very much like to transcode this into a more common format, as it contains a deeply important moment, and I want the option of viewing this video for decades to come. Handbrake is unable to handle the file, presumably because I do not have the IMM5 codec installed. Anyone have any pointers?
If all else fails, you can try Virtualdub: < It offers the option to export to a series of BMP files, which you can then stitch together using a more common codec. Did some googling, and IMM5 seems like a pretty obscure format, possibly without open-source implementation, too. How about (and this is _really_ the last option) using a desktop recorder tool (Fraps, VLC - yes, it can do that too.) and recording the video as it plays in that "BackupPlayer"? Since it's CCTV footage, it's probably low-resolution and framerate anyway, so you shouldn't have any noticable quality loss when doing that.
stackexchange-superuser
{ "answer_score": 3, "question_score": 8, "tags": "video conversion, codec, video encoding, transcode" }
Continuity of a function depending on parametres - how to tackle such problems? We have $f: \Bbb{R} \rightarrow \Bbb{R}$ defined as follows: $$f(x) = \begin{cases} a, & \mbox{if } x=0 \\\ \sin\frac{b}{|x|}, & \mbox{if } x\neq 0 \end{cases}$$ The problem asks us to tell for which $a,b \in \Bbb{R}$, $f$ is continuous. Intuitively I should find $\lim_{x\rightarrow 0} \sin \frac{b}{|x|}$ and that would be somehow dependent on $b$. Then we can set $a$ equal to that limit, and the function should be continuous. But how to find $\lim_{x\rightarrow 0} \sin \frac{b}{|x|}$ , I don't have a clue - here we have parametrized $\sin$ fuction with an arguement that seems to be approaching $+\infty$ or $-\infty$ depending on $b$. But it doesn't appear that $\sin \frac{b}{|x|}$ would have any limit at all because as $y\rightarrow \infty$, $\sin y$ will always "alternate" between $1$ and $-1$. So maybe the answer is that such $a,b$ don't exist then? So - what should I do with this problem?
Note that as $x\to 0$, $\frac{b}{|x|}\to\infty$ for any $b>0$, and $\frac{b}{|x|}\to-\infty$ for any $b<0$. Also, $\displaystyle\lim_{y\to\infty}\sin(y)$ and $\displaystyle\lim_{y\to-\infty}\sin(y)$ are not defined, as you observe. Therefore, for any $b\ne0$, $\displaystyle\lim_{x\to0}\sin\frac{b}{|x|}$ is not defined, which in turn means that $f$ is not continuous at $0$. So, let us consider the situation where $b=0$. Then $\sin\frac{b}{|x|}=0$ for any $x\ne0$, which means that $\displaystyle\lim_{x\to0}\sin\frac{b}{|x|}=0$. So in order for $f$ to be continuous at $0$, we need $f(0)=0$. Therefore, $f$ is continuous when $a=b=0$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "calculus, limits, continuity" }
Running Play from cygwin - only play.bat is runnable? I'm trying to run Play from within cygwin, and when I run `play dependencies`, I get the following error: Exception in thread "main" java.lang.NoClassDefFoundError: play/deps/DependenciesManager Caused by: java.lang.ClassNotFoundException: play.deps.DependenciesManager... `play.bat dependencies` succeeds, however. Even if I symlink `/usr/local/bin/play` to `.../play.bat`,I get the same error. What's going on here?
The content of play.bat suggest that it calls play with the appropriate location for the play script as first argument. **play.bat content (batch):** @echo off "%~dp0python\python.exe" "%~dp0play" %* Then the python script take the first argument (the/relative/path/to/play) and use it as its root folder to execute all the python script. **play content (python):** ... sys.path.append(os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'framework', 'pym')) ... By invoking `play` directly your python script get executed in your current directory.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "bash, cygwin, playframework" }
why output is 0 here. i am a newbie (20 days experience) *i want to copy inputed array in sum_of_elements function as argument and then sum all the elements of array, but i am getting output 0. #include <stdio.h> int i, num, sum; int sum_of_elements(int arr[]) { for (i = 0; i < num; i++) { for (i = 0; sum = 0, i < num; i++) { sum += arr[i]; } return sum; } } int main() { printf("enter number of digits you want to add\n"); scanf("%d", & num); int arr[num]; for (i = 0; i < num; i++) { printf("enter number %d\n", i + 1); scanf("%d", & arr[i]); } int total = sum_of_elements(arr); printf("%d", total); return 0;
Look at this line of code: for (i = 0; sum = 0, i < num; i++) { This resets `sum` to 0 _every loop_. It should be for (i = 0, sum = 0; i < num; i++) { But it's probably better to do this: sum = 0; for (i = 0; i < num; i++) {
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "arrays, c, function, sum, arguments" }
Activerecord request where has_many relationship is empty I am trying to do a database query where it only returns results where a has_many relationship isn't empty. Below is an example where the has_many :gift_images : Gift.joins(:gift_images).includes(:gift_images, :comments, :category, :user).select("gifts.*, COUNT(gift_images.id) AS gcount").where("gcount > 0") Something like that, but it doesn't work. Any ideas?
You can't use aliases on where statements, try the following Gift.where("(SELECT COUNT(*) FROM gift_images WHERE gift_images.gift_id = gifts.id) > 0")
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, postgresql" }
NSTableView not redrawing under specific conditions I have a NSWindow with two NSTableViews and other NSViews. Since I have changed both NSTableView into view mode one of the tables, does not refresh correctly under specific conditions. When another view is placed on top and then removed and released, one of the nstableviews does not refresh its contents and the removed view remains visible. The tabledata is correctly reloaded and can even be used to select from a (non-visible) row. However a window resize immediately correctly refreshes and displays in both NSTableViews. Can anybody help? Thanks. John
How are you removing the view that's being removed? There are various methods which mention that they don't cause a redisplay and that you have to do that yourself. You probably need to call one of the `-setNeedsDisplay...` methods on either the view being removed, its superview, or if all else fails the table view.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "macos, osx lion, xcode4.3" }
How to keep another user logged in? All users have encrypted home folders on one server I maintain and one of the users (non-human account) has useful resources in its home directory shared via Apache. In order to keep the user's home folder mounted, somebody will have to log in as that user. I achieve this by logging into that server using SSH and `su` that user. However, sometimes I forgot about that and logs out or closes the ssh client and other uses lose access to those files. I am just wondering is there any command I can run to keep that user logged in? I tried `screen`, but it does not work in `su` via ssh: $ screen Cannot open your terminal '/dev/pts/0' - please check. I have also tried `disown` and `nohup`'ing `cat <> /dev/zero` but the process is still terminated after I log out.
`screen` works if you chown your current TTY to the target user, before `su`ing to them. But a better option would be to **mount the home directory manually, using`mount -t ecryptfs`**. (You could also cheat by incrementing the refcount in `/dev/shm/ecryptfs-<user>`, so that it would never reach 0.)
stackexchange-superuser
{ "answer_score": 2, "question_score": 0, "tags": "linux, ubuntu" }
How does the barrier at kings cross tell the difference between a normal passerby muggle and a muggle born witch or wizard? It seems like it would be quite hard to tell the difference between a muggle born witch/wizard and a normal muggle just passing by, they seem to be virtually the same except for the witch/wizards potential or capability to perform magic.
As is explained in some detail in Can a Muggle get through to Platform 9 & 3/4?, _Harry Potter and the Deathly Hallows_ specifically depicts the family Evans on platform 9¾, three of whom were muggles. So either the barrier recognizes the families of muggleborns, or **the barrier does not block muggles at all.** Since we also know that there are plainclothes Ministry of Magic employees on-site to do memory charms anyway, the latter seems far more plausible than the former. If anyone tries to lean on or otherwise passes through the barrier improperly, they can memory charm the muggle and send them on their way. This is presumably much simpler than trying to come up with a set of wards that precisely blocks only those muggles who are not "supposed to" go through.
stackexchange-scifi
{ "answer_score": 5, "question_score": 4, "tags": "harry potter" }
Examples of <link> tag in a HTML using different 'rel' attributes? Could someone provide meaningful examples of HTML `<link>` tag with different values of "rel" attribute? Apart from the possible values explanation for the "rel" attribute, are there any practical uses for the different values (other than stylesheet value)?
To get a number of useful examples, I would recommend looking here: < This looks like a very concise, slightly easier to navigate version of w3: <
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "html, xhtml" }
How do you update a live, busy web site in the politest way possible? When you roll out changes to a live web site, how do you go about checking that the _live_ system is working correctly? Which tools do you use? Who does it? Do you block access to the site for the testing period? What amount of downtime is acceptable?
I tend to do all of my testing in another environment (not the live one!). This allows me to push the updates to the live site knowing that the code should be working ok, and I just do sanity testing on the live data - make sure I didn't forget a file somewhere, or had something weird go wrong. So proper testing in a testing or staging environment, then just trivial sanity checking. No need for downtime.
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 17, "tags": "release management, high availability" }
about a series $\sum_{n \geq1}{\frac{2n^2}{3^n}} $ How is this series ? > $$\sum_{n \geq1}{\frac{2n^2}{3^n}} ?$$ How I made: $$a_{n}=\frac{2n^2}{3^n}$$ and then $$\frac{a_{n+1}}{a_n} \leq 1$$ so the series is convergence . Is ok ? thanks :)
Having ratio $\le 1$ is not enough for convergence. The simplest example is $1+1+1+\cdots$. There are more subtle examples. (By the way, $\dfrac{a_2}{a_1}\gt 1$, though this does not matter.) We want to show that there is a fixed $b$ with $0\le b\lt 1$ such that for large enough $n$, $\dfrac{a_{n+1}}{a_n}\le b$. It will be enough to show that $$\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=\frac{1}{3}.$$
stackexchange-math
{ "answer_score": 5, "question_score": 1, "tags": "sequences and series" }
Prove an inequality containing abolute value and square root ![enter image description here]( (x,y are both greater or equal to zero) I'm trying to prove this inequality, but I'm stuck for a long time. My idea is that because it is in a form that the left part is smaller or equal to a square root thing, I first square the left part get $|\sqrt{x}-\sqrt{y}|^2=|x+y-2\sqrt{xy}$|. Then I tried to find this is smaller than or equal to something that contains $|x-y|$ Thus, I wrote:$|x-y-2\sqrt{xy}+2y|\leq|x-y|+2\sqrt{xy}+2y$. Then I can't move anymore. Any hints? Thanks.
Hint: We know $x,y\geq 0$. Hence, $x-y=(\sqrt{x}-\sqrt{y})(\sqrt{x}+\sqrt{y})$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "inequality" }
how you would write this pymongo/mongodb query, in a way it inclues strings inside an array? (image included) i wanna make a query looking for all documents that have, in their respective havelists, say, string1, string3, string4 < ### Edit I made some progress, i found that if i make this query j = USERS_COLLECTION.find({ 'havelist.0.1': card}, {'havelist':1, 'position':1,'_id':1}) it works, but the issue is that i might eventually have to search on havelist.0.1, havelist.1.1, havelist.2.1, ..., havelist.n.1
Please, David, try this: users = USERS_COLLECTION.find({{'havelist': {'$elemMatch': { '1': card }}}}, {'havelist':1, 'position':1,'_id':1}) Such query uses `$elemMatch` query operator, which matches documents that contain an array field with at least one element that matches all the specified query criteria. Here is the official documentation of `$elemMatch` operator of MongoDB Let me know if this worked, otherwise, tell me what went wrong.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, mongodb, pymongo" }
Submit form with JS do not perform basic validation Why when I am using javascript the basic HTML inputs validation not performed? Say the min max attributes. Here the HTML: <form action="#" method="get">Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5"> <br /> <input type="submit" value="with HTML"> </form> <button id="sender">with JS</button> JS: $("#sender").click(function (event) { $("form").submit(); }); And live example: <
You have to trigger the normal submit button: $("#sender").click(function (event) { $('input[type="submit"]').trigger('click'); event.preventDefault(); }); See this fiddle: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, html" }
Running R on Ubuntu Netbook need help with size of graphical device I'm having small problem with the size of the graphical device when running R on ubuntu netbook. Netbook's screen size is relatively small (1024 x 576), so when I create a chart in R say simply plot(sin) The graph is bigger than my screen size. I have to manually resize it. Solution posted on ubuntu forum doesn't work for some reason. Does anyone know how to fix it? Thanks!
I don't use Ubuntu anymore, but I think the best solution is to put something like this in your .Rprofile file. setHook(packageEvent("grDevices", "onLoad"), function(...) grDevices::X11.options(width = 4, height = 4, pointsize = 8) ) For ref., on my Mac, I have: setHook(packageEvent("grDevices", "onLoad"), function(...) grDevices::quartz.options(dpi = 72))
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 3, "tags": "r, ubuntu" }
Java - How to retrieve all chrome tabs details? I wish to use a class that provides the option to get all open tabs. Unfortunately, I can only find code in js and other.. and I don't really know how to use it in my Java code..
There is no way to find browser physical details with Java other than the request headers. You Cannot. On the other hand you can send the info you found with Javascript to server(Java) through a request.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "java, eclipse, google chrome" }
node socket io - sharing a global object across sockets and between client and server In socket.io, for node.js, is there a way to exchange a global object between client and server by assigning the object to socket? Or do i have to create a emit event to exchange the global object. In my case, the global object is a array.
You need to emit it. However, the resulting object will not maintain state between the client and server. When you emit it, it is serialized, send over the wire, and re-created on the other end. If you were to later add data to that object on the server, the client would not see that new data (nor vice versa). You can use something like Racer to handle this for you.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "node.js, socket.io" }
Bangla font not showing in cakephp when data retrieve from mysql database I am using cakephp version 2.7 . In my view I van show static bangla. But when I get data from database then bangla font not working.
> Check your `layout` file have below line - For **HTML5** <head> <meta charset="utf-8"> </head> Also set your Database `Collation` to `utf8_general_ci` > Search and Uncomment below line from `app/Config/database.php` file //'encoding' => 'utf8', TO 'encoding' => 'utf8',
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, cakephp 2.0" }
How to flatten list in java 8 class Employee { private String name; private List<Employee> members; } List<Employee> emps = Arrays.asList(new Employee("A", Arrays.asList( new Employee("B", null), new Employee("C", null) ))) The code to flatten the `List`: List<Employee> total = emps.stream() .flatMap(emp -> emp.members.stream()) .collect(Collectors.toList()); The `total` `List` should have 3 elements, but it only has 2.
Eran's answer is wrong, there is no `concat` on `Stream` instance. This should work: emps.stream() .flatMap(emp -> Stream.concat(emp.members.stream(), Stream.of(emp))) .collect(Collectors.toList()); `Stream#concat`
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "java, java stream" }
Set Focus on Controls in C# I have repeater control with textboxes and dropdown controls for searching.While user search any content in any textbox the page is postbacked to load the repeater with search criteria.At this time i need to set focus on the particular control.
I found answer for my question and i am posting it. if(!postback){//code here} else { Control cont = this.Page.FindControl(Request.Form["__EVENTTARGET"]); if (cont != null) cont.Focus(); } this helps to set focus on controls if we don't know the id of the target controls
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, asp.net" }
using grails flash object and load balancing In our application we have used `flash` object to transport data from one controller to another by grails `redirect()`. Does it pose any loss of data/threat since our application is using load balancing and non-sticky sessions (we are using memcached for our own session management mechanism) ? I read the grails doc says it " **stores objects within the session for the next request and the next request only** " ? Does it mean `flash` is actually using `session` in the background ?
Yep, you're absolutely right. Flash uses the http session to store stuff so if you're using a load balancer without sticky sessions you shouldn't use flash scope.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "tomcat, grails, cloud" }
How to design a program using the MVVM design pattern? I am new to MVVM and would like to ask if this "layout" is good MVVM. For the start, the app (I use a cloud api for signin a user in and to receive some data) should automatically log a user in, in case he has already entered once the password. And then display other persons(which I receive) on the MainPage. Of course there is also a Login screen for first time users or if he logged out. How should I handle the auto login? MainView <\--> MainViewModel <\---PersonModel LoginView <\--> LoginViewModel
If user already entered the password and you want to Auto-login that user then you can do it on your "MainViewModel". If user is coming first time then based on that you can invoke LoginView. From the LoginViewModel you can create a token object (ex UserInfo) that you can use in your application throughout.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, mvvm, windows phone 8, authentication" }
KDB how to assign a value in root namespace from another namespace? I have a table (feed_exclude) in the root namespace that I would like to reassign without changing to that namespace using \d . >feed_exclude feed table --------------- `feed1 `table1 \d .mon `.[`feed_exclude],:flip enlist each first select feed,tab from 0!`.[`feed_table] '2018.11.26T16:30:51.643 assign How can I assign to a table in the root namespace `. without changing to the namespace using \d . ?? I have already checked that the meta of both sides of the assign operator is equivalent. The code executes correctly when the assign operator(:) is removed. `.[`feed_exclude], flip enlist each first select feed,tab from 0!`[`feed_table] feed table --------------- `feed1 `table1 `feed2 `table2 Any help would be appreciated Thanks
Try the following @[`.;`feed_exclude;,;flip enlist each first select feed,tab from 0!`.[`feed_table]]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "kdb" }
MySQL, sorting before a group by If I issue a query like this: select c1, c2, c3 from table group by c1; i get distinct results for c1, but how do i sort it (e.g. c2 descending) before the group by?
select c1, c2, c3 from (select c1, c2, c3 from table order by c2 desc) t group by c1;
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 2, "tags": "sql, mysql" }
jQuery - traverse dom - array - extract id I'm trying to access the id of the element _nextElementSibling_ in the array presented in the picture below: items[3].item.nextElementSibling.attr('id')) This query does not work. Whereas I can access the id of the item element like so: items[3].item.attr('id')) Can someone explain me why the second works, whereas the first does not work!? Thanks for your help! !enter image description here !enter image description here
`.attr()` is a jQuery function, but you are not testing it on a jQuery object (`$()`). Just get its id directly with normal JavaScipt: items[3].item.nextElementSibling.id Or wrap it in `$()` to access jQuery functions: $(items[3].item.nextElementSibling).attr('id')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery, html, dom" }
Cast not shown correctly In the sample code below, why `a` is assigned as `004609CC` instead of `004609C0`? I was expecting a,b, and c to point to the same address. And why dynamic_Cast(a) changes the address to `004609C0` class A1 {public: unsigned a1; int a2; virtual ~A1() { } }; class B1 {public: unsigned b1; int b2; virtual ~B1() { } }; class C1 : public B1, public A1 {public: unsigned c1; virtual ~C1(){} }; int main() { C1* c = new C1; A1* a = c; B1* b = c; std::cout << static_cast<void*>(a) << "\n"; //004609CC Why not 004609C0? std::cout << static_cast<void*>(b) << "\n"; //004609C0 std::cout << static_cast<void*>(c) << "\n"; //004609C0 std::cout << dynamic_cast<C1*>(a) << "\n"; //004609C0 // delete b; }
When you look at the object layout of objects with multiple inheritance you'll basically have the base subobjects somewhere in the object. For example, the object could look something like this: +-------+ + +---+ + | | B | | | +---+ | | +---+ | | | A | | | +---+ | | C mem | +-------+ When you have a pointer to a `B` or an `A` object it doesn't know that it is embedded into an object with multiple inheritance. Correspondingly either the pointer to the `B` subobject or the pointer to the `A` subobject cannot have the same address as the `C` object. Potentially, neither object has the same address as `C`, e.g., when the ABI specifies that the `C` members have to precede the base class subobjects (I'm not aware of any system which does this, though).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c++" }
How to deploy xamarin ios app with SDK Version 5.0 to use old theme (not iOS 7 Theme) in visual studio 2013 Hello everyone I have a legacy xamarin.iOS project (built with 5.0 SDK) now i need to update some things without changing the look of the app. After some research how to get the older SDKs to show up in the SDK Version dropdown in Visual Studio 2013 I finally got to select the 5.0 SDK (I also changed the Deployment Target to 5.0) But when I deploy the app to my iPhone 5S running iOS 7.1.1. i get the iOS 7 Theme Is there any way to get the app to use the old theme? (If I download the app from the store it works with the old theme, so there should be some way) By the way on my research I read this article Using iOS 6 theme for iOS 7 app Is it true that I cant upload apps using an older SDK? Even for app updates? Thanks in advance for any help.
Submission to the Apple store requires that the product be compiled with the most recent released Tools (Xcode 5.1.1 at this point) and compiled with the most recent SDK (Currently 7.1)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, iphone, xamarin.ios, visual studio 2013, xamarin" }
login/authentication with fingerprint We're implementing an android application that needs to collaborate with the fingerprint sensor. After any installation of the application, a login page will prompt and the user must add a username along with fingerprint. I read something about that the applications can't collaborate with the fingerprint sensor. However, I thought maybe someone has an idea. Thanks in advance. * * * **UPDATE:** The thing that prevents me from achieving that is the `BiometricPrompt` which gives a true/false state. I need the exact value of a fingerprint and send the data to the server for a specific username.
So if you want to store user information with their credentials and their fingerprint then **it's not possible.** Fingerprint data will never be shared with anyone. Google has strict guidelines Check this for more info : Understand fingerprint security This might also help you : How to store fingerprint data along with username, image, email etc in database in android app ?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "java, android, authentication, fingerprint" }
Regular expression for multiple of 100 Can anybody provide me regular expression for multiple of 100. we want to validate value in multiple of 100 . Regards, Pradeep
I'd use this: ^[1-9]+[0-9]*00$ First number must be from 1 to 9, then any number of random digits, and it must end in two 0's. In future looking up a bit of regex would be a good first step, this is very very simple and can be worked out (even by a complete novice) in very little time.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -3, "tags": "html" }
Keeping variable values when the iPhone is shut-down? Lets say i have an application which has three text-fields, and i can type whatever i want into them, lets also assume that i have a checkbox and a button. And if the button is tapped while the checkbox is checked, the nsstring values in these textfields should get saved somehow. Lets say i power down my iPhone and restarted it, opened the app once again and wanted those values to be in their respective textfields. How does one do this? Is this a case for NSUserDefaults or something for Apple's own Keychain API to handle? Cheers. **Edit:** We used local declarations when setting and getting the values of the NSUserDefaults, which of course, doesnt work. It works perfectly now...
Yes you can make use of `NSUserDefaults`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "iphone, objective c" }
Why having .shared.GWT and .client.GWT? Since the Javadoc doesn't make clear the reason for having com.google.gwt.core. **shared**.GWT, which seems to contain a functional subset of the com.google.gwt.core. **client**.GWT, what's the reason for the former to exist?
As its name suggests, `shared.GWT` is usable on the server-side. `GWT.create()` doesn't support much things yet but will soon support I18N for instance, and its pluggable.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "gwt" }
AS3 regex - how to match 2 consecutive matches multiple times? I have the following regex, which will match all the `<br>` and `<br />` tags in a string: /<br[\s|\/]*>/gi I actually want to match every set of two consecutive tags, with valid matches being: <br><br> <br/><br> <br><br/> <br/><br/> (and all variations with a space before the slash) Obviously I can just double up the expression to `/<br[\s|\/]*><br[\s|\/]*>/gi`, but is there a shorter way of taking the first expression and saying "this, but twice"?
Try this one: `/(<br[\s|\/]*>){2}/gi`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "regex, actionscript 3" }
What makes sense to call a quotient of the 2-adic numbers in which every element of a given class shares the same final convergent subsequence? What makes sense to call a quotient (as sets) of the 2-adic numbers in which every element of a given equivalent class shares the same final convergent subsequence, e.g. $-\frac13\sim-\frac23\sim\frac13\ldots$? For example $\overline{01}_2$ is a subsequence of $\overline{10}_2$ and vice versa, since either can be truncated to arrive at the other and therefore they are equivalent. Is there any reason why that's not well-defined? Define these classes by the graphing the orbit of the truncation function. Then you can say two numbers are equivalent if their graph is connected. Is such an object well-studied? Following the comments it is starting to look like say $\mathcal C/\overline{\mathcal C}$ where $\overline {\mathcal C}$ is the endpoints of the removed segments of the Cantor set.
The OP meant $\sum_{n\ge -N} a_n p^n \sim \sum_{m\ge -M} b_m p^m$ iff there is $k,l$ such that $a_n=b_{n+k}$ for all $n\ge l$. * Why didn't the OP phrase it correctly? * $\sum_{n\ge -N} a_n p^n \sim 1+\sum_{n\ge -N} a_n p^n$ iff $\exists n\ge 0, a_n \ne p-1$. So there is a special case for the negative integers --> not good. * Removing this special case, it becomes $a\sim b$ iff $\exists d\in \Bbb{Z},c\in \Bbb{Z}[p^{-1}]$, $a=p^d b+c$, which is the quotient by the action of a group.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "terminology, p adic number theory" }
Difference in BATTLEFIELD 4 endings Has anyone tried the 3 possible endings on BF4? What are the differences between them? Is one preferable because the ending is better?
My recommendation - just replay the last mission multiple (3) times and see for yourself. You will also unlock weapons which you can use in multiplayer. The 3 Weapons are: QBZ-95-1 P90 M249 How to get them: > kill Hannah, let the Valkyrie be destroyed, or kill Irish.
stackexchange-gaming
{ "answer_score": 4, "question_score": 0, "tags": "battlefield 4" }
Wifi connection fail, but web connects with wire connection I can use web Firefox/Chromium with the (home) wire connection, but, since a few days, internet stopped working through wifi (same home) connection. The strange thing is ftp (fireftp) works, and Thunderbird emailer seems also to work properly. Ubuntu 14.04, no proxy, it is at home and has been functioning for years without this problem! Restarted the box (bbox), not solving. Problem is the same under Windows 7, so Ubuntu not in cause.
For an unknown reason, today it worked again, internet connection is ok through the wifi. Maybe an issue from my Internet Service Provider?
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "wireless, wired" }
Android Setting Icon To Notification Builder I am setting the required drawable to Notification.Builder but it says cannot resolve. I have tried to use the `ic_launcher` which would not work so I added my own `wuno_launcher` and that will not work either. private Notification getNotification(String content) { Notification.Builder builder = new Notification.Builder(this); builder.setContentTitle("New Affirmation"); builder.setContentText(content); builder.setSmallIcon(R.drawable.wuno_launcher); // error here cannot resolve symbol return builder.build(); } But I am sure I have the icon added as you can see in the picture below. ![enter image description here](
If you use mipmap folder image so you have use mipmap instead of drawable. Do something like this builder.setSmallIcon(R.mipmap.wuno_launcher)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "android" }
Difference between `if` statements Am newbie in programming, just curious, what is the difference between if(a == 1) { //condition } if(b == 1) { //condition } and if(a == 1 || b == 2) { //condition } I don't have any questions regarding this, all I want is clarification. Don't over think guys, I know you're all pro's. Take note on the "just curious", cause am noob.
The first statement compares the variable 'a' to '1', and if the variable 'a' is equal to '1', then you will execute the block of code enclosed in brackets. Likewise, the first statement also compares the variable 'b' to '1' and if equal will execute a block of code. The second expression evaluates two conditions, 'a' being equal to 1, and 'b' being equal to '2'. If either expression is true, then the block of code enclosed in brackets will execute. The double pipe symbol '||' is synonymous with 'or'.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -6, "tags": "algorithm, if statement, logical operators" }
Use REST to sum a column? I want to retrieve items from a SharePoint list using REST, and then sum one of the columns. I'm brand new to REST, and didn't see a way to do this on MSDN. Is it possible to sum a column in a REST query? I'm using InfoPath to collect the data. Would I be better off submitting it to SQL Server and then building the report from there, instead of submitting the data to a SharePoint list and using REST?
You cannot use aggregate functions with REST. _"This release does not support Aggregate functions (sum, min, max, avg, etc) as they would change the meaning of the ‘/’ operator to allow traversal through sets."Source_ My only suggestion would be to get the items and do calculate the SUM on client side, if possible.
stackexchange-sharepoint
{ "answer_score": 3, "question_score": 2, "tags": "list, infopath, sql server, rest" }
Running PowerSell Commands Remotely From A Linux Machine To Exchange Server Our client has a windows server 2008 with exchange 2010. I have to connect from linux machine to exchange server and search inside mail boxes via powershell. I have searched here and found some solutions, but linkes o solution doesn't work for my issue: Connecting to Exchange PowerShell from a Linux machine [How can I remotely execute commands on a Windows Server from a Linux box? [duplicate] 1]( There is many python libraries for this but I couldnt connect to exchange server with no one of them (paramiko, exchangelib, pyexchange with ip address, username, password) Is there any setting for exchange server for this issue?
The links you found are a little dated in light of events last year when MS started providing Powershell for Linux. < > I am extremely excited to share that PowerShell is open sourced and available on Linux. You can install Powershell on the Linux system and then use the `*-PSSession` cmdLets on the Linux system to get to the Windows system. < New-PSSession Disconnect-PSSession Connect-PSSession Receive-PSSession Get-PSSession Remove-PSSession Enter-PSSession Exit-PSSession Export-PSSession Import-PSSession
stackexchange-serverfault
{ "answer_score": 2, "question_score": 0, "tags": "ssh, powershell, exchange 2010, python" }
Panic Medic Boot Appearing on Mac Since yesterday, my Macbook Pro early 2013 running macOS High Sierra 10.13.1 beta has been randomly shutting down. After shutting down, it would take several tries for it to boot up and login, but then it displays this error message every time I login (see picture attached). I already tried resetting both PRAM and SMC, but the problem still occurs. Booting into safe mode wouldn't work when I pressed shift after the boot chime sound came (safe mode worked before this problem). Is there a way to fix this? ![Panic Medic Boot](
If a safe mode boot fails, you've got a damaged system. Boot to recovery, internet recovery or external bootable media and reinstall the OS on top of all your existing apps and data. This preserves all data that's there. If you suspect storage drive problems, you might check your last backup against another Mac to be sure it's up to date and restorable and possibly seek data recovery if you can't afford to lose the data before reinstalling the macOS. I wouldn't do data recovery unless you have no backups and $300 or so for a professional service would be money well spent to safeguard your data. Most people recover from this with no data loss in about an hour or two after the reinstall starts, but I don't want you to not have the chance to back up before using the drive more if you suspect problems with the hardware and not just a third party extension causing lots of crashes.
stackexchange-apple
{ "answer_score": 3, "question_score": 2, "tags": "macos, mac, boot, high sierra, kernel panic" }
Does OpenSUSE Instlux overwrite Windows? You seem to be able to install OpenSUSE from Windows using Instlux. Does anyone here know what the result is for the Windows installation on the machine? Is it overwritten, or does Instlux work like Ubuntu's Wubi and leave the Windows installation intact? Does it add an item to the Windows bootloader? Does it change the MBR to boot with GRUB?
_(Disclaimer: the answer below is based on Internet research.)_ It is **different from Wubi**. Wubi creates a one-file filesystem inside Windows and you can boot into that as if you installed it into a different partition. Using Instlux just eases the way OpenSUSE can be installed by starting the installer from within Windows. It installs a small „kernel” within the Windows partition and by adding an entry to the Windows boot menu, it allows to boot into that, so you can continue a normal installation even without an installation media or tweaking BIOS settings. After that point the installation process is the same as if you had booted from a CD-ROM. You create partitions beside the Windows partition on your hard disk. You can see a few screenshots guiding through the process in this article.
stackexchange-unix
{ "answer_score": 1, "question_score": 1, "tags": "windows, system installation, opensuse" }
How to create Azure Batch service Application pool with custom image in .Net SDK or PowerShell or ARM Template I am referring this article < And I have my custom VHD file with me and i want to create application pool with custom VHD file (Nodes) through .Net SDK or PowerShell or ARM Template. I am able to create it from Azure portal any examples ?
> You can prepare a managed image from a VHD, from an Azure VM with managed disks, or from a VM snapshot. For Batch, we recommend creating a managed image from a VM with managed disks or a VM snapshot. With the test, it seems you just can make your custom VHD file into a managed image to create the batch backend pool as above. Also from the description of the parameter `--image` for the command `az batch pool create`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "azure, powershell, azure batch" }
Trigger transition to 'loading' route after ember-simple-auth authentication I'd like to display a "loading..." animation to the users logging into my application. Ember automatically transitions to a 'loading' route (if any) if a model returns a promise, so it gives the opportunity to display a 'loading' template till the server responds. Now, I have a login form where submit triggers the 'authenticate' action in my controller (which is defined in the LoginControllerMixin). This seems not to be recognised as a promise by ember, hence the application does not transition to the 'loading' route. Maybe there is a way around this using simple-auth session state, but I can't figure it out any help would be appreciated
I think the loading routes only work nicely when there's a transition and the framework is waiting for the promise returned by the destination route's `model` hook to resolve. That's not the case with Ember Simple Auth's LoginControllerMixin's `authenticate` action though. To display a loading message you can simply override that `authentication` action though: ` export default Ember.Controller.extend(LoginControllerMixin, { actions: { authenticate: function() { var _this = this; this.set('loading', true); this._super().then(function() { _this.set('loading', false); }, function() { _this.set('loading', false); }); } } }); `
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ember.js, ember simple auth" }
not preparing insert query if (insert_statement == nil) { static char *query = "INSERT INTO iteminfo (itemname, friendid) VALUES(?,?) where itemid=?"; if (sqlite3_prepare_v2(database, query, -1, &insert_statement, NULL) != SQLITE_OK) { NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database)); } i am new to Objective C programming.... i am trying this code to insert some values into database based on where condition, but there is a exception in preparing the insert statement the waring which i am getting is **"Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error: failed to prepare statement with message 'near "WHERE": syntax error'.'** " Please help me out of this... issue..
You can't use INSERT INTO with a WHERE clause - INSERT adds a new row, not update an existing one. Perhaps you meant UPDATE?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "objective c, sqlite, exception, insert" }
Is there a way to disable Intel SpeedStep on an Ubuntu Server using a command line application? We cannot disable it using the BIOS, because Turbo gets turned off as well as a side effect (what a crappy BIOS!). I am looking for a simple command line tool for Ubuntu 12.04 LTS Server that can do this. I know on Windows, if you set the Power Options to High Performance, SpeedStep is disabled, but how can I do this on Ubuntu Linux using a command line application? Thanks
To disable SpeedStep, you would run cpufrequtils. It should already be installed on your system if you're running a Gnome desktop. If not you can install it by clicking below ![]( Once you install it, you would run sudo cpufreq-selector -g performance However, running the CPU at full speed, may cause it to shutdown after a few minutes. sudo cpufreq-selector -f <specify speed> To verify your CPU speed, use the "cat" utility: cat /proc/cpuinfo
stackexchange-askubuntu
{ "answer_score": 3, "question_score": 2, "tags": "12.04, server, performance" }
Differences between "propensity", "predilection" and "proclivity" _Propensity_ , _predilection_ and _proclivity_ all have the meaning of _tendency_ , so what's the difference? Are they interchangeable?
_Predilection_ means _tendency to favor_ , not just _tendency_ : > a tendency to think favorably of something in particular; partiality; preference: _a predilection for Bach._ _Propensity_ and _proclivity_ both just mean _tendency_ : > **Propensity** : a natural inclination or tendency: _a propensity to drink too much._ > > **Proclivity** : natural or habitual inclination or tendency; propensity; predisposition: _a proclivity to meticulousness._ So while _propensity_ and _proclivity_ are close synonyms, and interchangeable, _predilection_ means something different, and should not be used as a synonym. There is one major difference between _propensity_ and _proclivity_ , and that is popularity: ![]( _Proclivity_ to me sounds more scholarly than _propensity_ , maybe just because not many people use it.
stackexchange-english
{ "answer_score": 17, "question_score": 20, "tags": "meaning, differences, nouns, synonyms" }
XCode automatic device provisioning - Distribution Certificate failed, Portal says: Error So this just started happening now, I have no idea as to why. I needed a new Distribution certificate because my old on expired. So following the steps I created a Certificate Signing Request and submitted it to the portal. After submitting the request comes up as 'issued' then disappears. Clicking on the 'History' tab says the request returned an Error and nothing else. So try a different method, using Automatic Provisioning via XCode open Xcode's "Window" menu > Organizer > Devices tab > "Provisioning Profile" sidebar under Library. Check the "Automatic Device Provisioning" checkbox and click the "Refresh" button. it says 'You don't have a distribution certificate, want to submit a request?' I say yes and nothing happens. Then Clicking on the 'History' on iOS Provisioning profile tab says the request returned an Error again... I actually suspect something is wrong on Apple's end here...
issue was on Apples end, now resolved
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "ios, distribution, provisioning" }
calling javascript function checking media I have a media query css block for the ipad @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { } and for laptop and desktops @media only screen and (min-width : 1224px) { } I have a js function which needs to have different parameters depending upon which device I am on. So lets say something like this if(@media only screen && (min-width : 1224px)){ function operation(){ var x = 2; } } if(@media only screen and (min-device-width : 768px) and (max-device-width : 1024px)){ function operation(){ var x = 7; } } Conceptually thats what I am trying to achieve which is definitely incorrect syntactically Any help will be highly appriciated
Try the following code. The code you wrote is syntactically wrong. I hope the code below will help you. if (window.matchMedia('only screen and (min-width: 1224px)').matches) { function operation(){ var x = 2; } } if(window.matchMedia('only screen and (min-width: 768px) and (max-width: 1024px)').matches) { function operation(){ var x = 7; } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery" }
Node.js nano library for couchdb: timeout needed I've been working with the nano library, and found myself with a need for having timeouts for my couchdb requests. I'm using db.search/db.get/db.destroy/db.insert and as far as I could tell from the documentation there's no easy way to add a timeout. These are async functions that pass a callback as a parameter. Ideally I would prefer not to modify the callbacks, but i'm open to suggestions.
When using `nano` you can provide a object that is passed to the request object: var db = require('nano')({"requestDefaults" : { "proxy" : " }}); For example, that sets a proxy to ` To change the timeout, you can use the `timeout` property This code should work: var db = require('nano')({ "uri": " "requestDefaults" : { "timeout" : "100" } // in miliseconds }); The default timeout in linux is about `20000`ms, 20 seconds.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "node.js, couchdb, couchdb nano" }
Plotting a smoothed area on a map from a set of points in R how do I plot an area around a set of points on a map in R? e.g. map('world') map.axes() p <- matrix(c(50, 50, 80, 100, 70, 40, 25, 60), ncol=2) # make some points points(p, pch=19, col="red") polygon(p, col="blue") ... which gives me a polygon with a vertex at each of the points, but it looks rather crappy. Is there any way to "smooth" the polygon into some sort of curve?
One option is to make a polygon bounded by a Bézier curve, using the `bezier` function in the `Hmisc` package. However I cannot get the start/end point to join up neatly. For example: ## make some points p <- matrix(c(50, 50, 80, 100, 70, 40, 25, 60), ncol=2) ## add the starting point to the end p2 <- cbind(1:5,p[c(1:4,1),]) ## linear interpolation between these points t.coarse <- seq(1,5,0.05) x.coarse <- approx(p2[,1],p2[,2],xout=t.coarse)$y y.coarse <- approx(p2[,1],p2[,3],xout=t.coarse)$y ## create a Bezier curve library(Hmisc) bz <- bezier(x.coarse,y.coarse) library(maps) map('world') map.axes() polygon(bz$x,bz$y, col=rgb(0,0,1,0.5),border=NA)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "graphics, r, maps, curve" }
Git repo grew after running repack We've been using Subversion and are considering moving to git. So I am very much a git illiterate. I used `git svn clone` to copy the svn history to git and my git folder was 3.1G. I followed some advice from several blogs to shrink it and ran: `git repack -a d -f --window=100` It processed 494,755 objects successfully but when I look at the disk size now it is using 3.7G. So what I thought would shrink it made it significantly larger. I tried running it again with `git repack -a d -f --window=250 --depth=250` but no changes to the size. The `git prune` command also didn't appear to do anything. It took several days to clone this, so I would rather not start over. Is there any way to go back to the smaller size, or any ideas anyone has on why repack made it bigger?
`git-svn` is a good way if you have to copy a repo from SVN to git, but honestly, it is better to work natively in git. That said, I've used this before and this is the best guide I found on the matter. Really, you may want to play around with the revision history you are importing by using the `-r` option. Also I did an: rm -r `find -type d -name .svn` to remove all the .svn folders. I don't plan on commiting from git to svn, so that was good for me, but if you plan to use git locally and commit to your SVN repo, then you'll have to do a little more research on the best way to do that. Also `git-gc` helps to compress objects. See if that helps reduce the size of your repo. Git is great so I hope you find you like it and switch over.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "git, git svn" }
What explains the garbled message "Start Wandows Ngrmadly" in text mode? !Start Wandows Ngrmadly When booting up Windows, why would it say "Start Wandows Ngrmadly", instead of "Start Windows Normally"? I tried googling for an explanation, but came across too many hits of people merely ROFLing at it.
This looks a lot like a memory issue (or at least a glitch, since it doesn't repeat everywhere), a bad video card (I remember having this problem once, turned out to be dying capacitors in the video card) or a corrupted file. What happens is that one of the bits in the character is getting toggled. From an ASCII character table, we can see that `i` is character code 105 (`110 **1** 001` in binary) while `a` is character code 97 (`110 **0** 001` in binary). A difference of 8 (i.e. the 4rd least significant bit). You can notice the same happens for other characters: `d` in ASCII is character code 100 and `l` in ASCII is character code 108.
stackexchange-superuser
{ "answer_score": 32, "question_score": 51, "tags": "windows" }
Groovy: Named parameter constructors I found really cool that one can do: class Foo { String name } def foo = new Foo(name:"Test") But, it only works when my file name matches the class name. If I have a file with a bunch of classes like: class AllClassesInOneFile { class Bar {} class Foo { String name } } def foo = new Foo(name:"Test") Now, it does not work anymore I get a java.lang.IllegalArgumentException: wrong number of arguments I wonder if it is still possible to invoke named parameter argument style with scripts and nested classes. Regards
Seems like Groovy needs explicit reference to an instance of the outer class: class Baz { class Bar {} class Foo { String name } } def baz = new Baz() def f = new Baz.Foo(baz, [name: "john doe"]) assert f.name == "john doe"
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 11, "tags": "groovy" }
Find the sum of the infinite series $1+ \frac{1}{2!}+ \frac{1}{4!}+\dotsb$ I wanted to find the limit of the series $1+ \frac{1}{2!}+ \frac{1}{4!}+\dotsb$. My approach: Let $S$ be the required sum. Then $S= (1+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\dotsb)- (1+ \frac{1}{3!}+...)$ i.e., $S= e - (1+ \frac{1}{3!}+\dotsb)$ But I don't know how to proceed further. I want to work the problem on my own. So please give me hint rather than the whole answer. Thanks in advance.
**HINT:** If we define $$G(x):=\sum_{n=0}^\infty a_n x^n$$ Then what is the series representation of $$G(x)+G(-x)=\sum_{n=0}^\infty \space ?$$
stackexchange-math
{ "answer_score": 7, "question_score": 1, "tags": "sequences and series, limits, summation" }
Regex Expression to match URLs I have the following regex to detect URLS: /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig However, it doesn't detect urls such as `www.google.ca` and `tlk.tc/ApSE`. Is there an regex where I can detect these URLs? I am using javascript.
This expression does what you want. It is not a valid URL which this regexp is matching, but it fits your requirements: /(\b(https?|ftp|file):\/\/|\bwww\.[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])|([\S]+\.([a-z]{2,})+?\/[\S]+)/gi
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, regex" }
Irreducible algebraic sets of $\mathbb A^2(k)$ I want to show that the irreducible algebraic sets of $\mathbb A^2(k)$ are exactly the following: $$\mathbb A^2(k),\emptyset,\text{Singleton and algebraic curves}.$$ Of course all of them are irreducible algebraic sets of $\mathbb A^2(k)$, but how can I show that there are exactly those sets?
Let $X\subseteq \mathbb{A}^2$ be an irreducible algebraic set. If $X$ is finite or the ideal $I(X)$ is zero, then $X$ is $\mathbb{A}^2$, $\emptyset$ or a single point. Here $$ I(X)=\\{ f\in k[X,Y]\mid f(p)=0 \text{ for all } p\in X\\}. $$ Otherwise the ideal $I(X)$ in $k[X,Y]$ is non-zero so there is at least one non-zero polynomial $f\in I(X)$. Now $I(X )$ is prime, because $X$ is irreducible, so it must also contain an irreducible factor of $f$. So w.l.o.g. let $f$ be irreducible. Then we have that $I(X ) = f$. To see this, let $h \in I(X ) \setminus f$. Now $h$ and $f$ are relatively prime, so we can use another result for relatively prime polynomials that $V(f,h)=V(f)\cap V(h)$ is finite, so that $X\subseteq V(f,h)$ is finite, which we have excluded above.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "abstract algebra, algebraic geometry" }
How to integrate Python and Java together for an app in Google Cloud Platform Is it possible to make an application which uses two programming language such as java and python together? I mean if there are two services which one of them is in Java and another in Python, what is the simplest way to integrate them ?
Yep, you can use two programming languages in an GAE app using GAE services. If you want the services to communicate then it would be possible through http requests, task queues. If you want a folder to be available in both the services then create that folder on the project's root directory and do sym-linking inside necessary services. Reference
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "google app engine, google cloud platform" }
Ruby: How to iterate over a range, but in set increments? So I'm iterating over a range like so: (1..100).each do |n| # n = 1 # n = 2 # n = 3 # n = 4 # n = 5 end But what I'd like to do is iterate by 10's. So in stead of increasing `n` by 1, the next `n` would actually be 10, then 20, 30, etc etc.
See < for the full API. Basically you use the `step()` method. For example: (10..100).step(10) do |n| # n = 10 # n = 20 # n = 30 # ... end
stackexchange-stackoverflow
{ "answer_score": 282, "question_score": 178, "tags": "ruby, iterator, increment" }
How to create a diagonal sparse matrix in SciPy I am trying to create a sparse matrix which has a 2D pattern run down the diagonal. This is probably easiest to explain with a quick example. Say my pattern is: [1,0,2,0,1]... I want to create a sparse matrix: [[2,0,1,0,0,0,0...0], [0,2,0,1,0,0,0...0], [1,0,2,0,1,0,0...0], [0,1,0,2,0,1,0...0], [0,0,1,0,2,0,1...0], [...]] The scipy.sparse.dia_matrix seems like a good candidate, however, I simply cannot figure out how to accomplish what I want from the documentation available. Thank you in advance
N = 10 diag = np.zeros(N) + 2 udiag = np.zeros(N) + 1 ldiag = np.zeros(N) + 1 mat = scipy.sparse.dia_matrix(([diag, udiag, ldiag], [0, 2, -2]), shape=(N, N)) print mat.todense() [[ 2. 0. 1. 0. 0. 0. 0. 0. 0. 0.] [ 0. 2. 0. 1. 0. 0. 0. 0. 0. 0.] [ 1. 0. 2. 0. 1. 0. 0. 0. 0. 0.] [ 0. 1. 0. 2. 0. 1. 0. 0. 0. 0.] [ 0. 0. 1. 0. 2. 0. 1. 0. 0. 0.] [ 0. 0. 0. 1. 0. 2. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 2. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0. 2. 0. 1.] [ 0. 0. 0. 0. 0. 0. 1. 0. 2. 0.] [ 0. 0. 0. 0. 0. 0. 0. 1. 0. 2.]]
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "python, numpy, scipy, sparse matrix, diagonal" }
Why does C++20 not allow to call a generic lambda with an explicit type? auto f1 = []<typename T>(T) { return T{}; }; auto f2 = []<typename T>() { return T{}; }; int main() { f1(1); // ok f2<int>(); // err: expected primary-expression before 'int' } Why does C++20 not allow to call a generic lambda with an explicit type?
The correct syntax to invoke overloaded template operator () function supplying template parameters is auto f1 = []<typename T>(T) { return T{}; }; auto f2 = []<typename T>() { return T{}; }; int main() { f1(1); // ok f2.operator ()<int>(); // Ok } <
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 8, "tags": "c++, lambda, c++20" }
I can't get UISlider to slide inside of a UITableViewCell - I think its an iOS 7 issue I was using InAppSettings to manage my settings but it stopped working in iOS 7 and I couldn't figure out why. So I set out to build my own simple settings tableView. In `cellForRowAtIndexPath:` I make a slider and add it to my cell like this: UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(really ugly frame code)]; slider.minimumValue = 0; slider.maximumValue = 7; slider.value = 4; slider.userInteractionEnabled = YES; [slider addTarget:self action:@selector(slide:) forControlEvents:UIControlEventValueChanged]; [cell addSubview:slider]; The slider shows up perfectly, but I can't interact with it! No matter what I do it won't move. And the target action never gets fired either. The exact same bug I was having with InAppSettings to begin with. It feels like I am missing something simple, anybody see this before?
Weird. I guess I was initializing the UISlider incorrectly. This code works.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "ios, iphone, uitableview, uikit, uislider" }
How javascript knows about the current locale in Rails 3? I'm trying to get a **resouce** from my autocomplete.js.coffee(.erb) file. The resource's URL is dependent on the current locale. That is, > /en/ajax/posts or > /he/ajax/posts Please note the /en/. The problem is, I cannot determine the locale from within the .js file. * Rails Guides does not provide enough info * i18n-js gem isn't working for me, i.e. I18n.locale gives me null Please help.
Solved with: def set_locale I18n.locale = params[:locale] || session[:locale] || I18n.default_locale session[:locale] = I18n.locale # store locale to session end It should be noted that the "standard" implementation is: def set_locale I18n.locale = params[:locale] || I18n.default_locale end If you have a better answer, please suggest.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, ruby on rails, url, internationalization, locale" }
jQuery UI Draggable constrain position under dynamically created parent div I have created an input that creates divs to use as menu items. These divs are draggable, constrained to the parent div, and movement limited by a 40px at a time. I need to ensure that when I drag a div, it can only be dragged to 40px past the div above it so the div above it acts as a parent div. For instance the first div it creates should not be draggable at all because it has no parent above it The fiddle is here, < Thanks
This plugin, < suggested by @enloz did the trick.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, jquery ui, jquery ui draggable" }
How to convert string to UInt32? I am a beginner in swift and I am having a problem with convering string to UInt32. let Generator = (ReadableJSON ["People"] [Person]["F1"].string! as NSString).doubleValue if Generator == 1 { NameLabel1 = ReadableJSON ["People"] [Person]["A1"].string as String! NameImeNaObekt = ReadableJSON ["People"] [Person] ["B1"].string as String! Picture = ReadableJSON ["People"] [Person] ["E1"].string as String! } else { let RGen = arc4random_uniform ("\(Generator)") // here is the error } Would you advise me how to fix it. The problem is in the last line, which is red and it says Cannot convert value of type String to UInt32. The main idea is that I am reading the number from a JSON file and I have to populate this number into the arc4random_uniform.
arc4random_uniform(UInt32) accept an UInt32 value but you are passing an String value to it this converts your number to string "\(Generator)" the last line should be like this let RGen = arc4random_uniform (UInt32(Generator)) and if you want to 'RGen' is an String you can do it this way "\(RGen)" String(RGen)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "swift, random, generator" }
What happened to Mr. Morden's Family? !enter image description here One of Babylon 5's classic characters was the mysterious Mr. Morden, but one thing I never totally understood was his back-story and then I read this: > Indoctrinated by the Shadows after his capture during an expedition to Z'ha'dum, the Shadows' homeworld, he has accepted to serve because of the Shadows manipulation of his guilt of the death of his wife and child and because they promise to save his family whom he believes are trapped in hyperspace. I don't remember seeing this part of Morden's back-story in the TV series itself, but it is an awesome twist on a rockin' character. What exactly happened to Mr. Morden's family and why does he believe that the Shadows can save them? Extra Credit: What source materials does this back-story come from?
The book you would need for Morden's back story would be The Shadow Within. In brief, Morden's family die in a jumpgate accident and the Shadows manage to convince him that they are still suffering, and that their pain will be ended in return for his service. This book is described by J. Michael Straczynski as "about 90% canon", so it's by no means definitive, but that's as close as you're going to get. It's referenced in other canon sources, so is probably correct.
stackexchange-scifi
{ "answer_score": 19, "question_score": 21, "tags": "babylon 5" }
DOM remove method in react js I want to change remove a certain tag with an id in the html page, eg.`<div id="theid"><p>sometext</p></div>` Is there any ways to do it with react js? I know I can do it with javascript by `document.getElementById("theid").remove();`, how can I do it in the react way? I don't need a button or anything, just simply remove it when the page loads. I'd prefer methods without importing any modules or libraries if possible. Thank you.
You should likely use a ref: < So you attach the ref to the DOM element, then you can imperatively remove that element just like you specified. So in the component function body: const myRef = useRef(); Then in the component render: <Component ref={myRef} /> Then you can use the code in your question to remove the element from the DOM. ref.remove(); If you need to do it when the page loads look at using useEffect to achieve this. Although if you're removing an element on page load, I question why you even need the element there in the first place ;).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html, reactjs" }
Drupal : Notification of modification to translator of a content In Drupal, i want to know how to notify translator that the content they translated, was modified. What is the easiest way to do it? Is there a module for that? Maybe workflow can help but i think this needs too much adminsitration Bonus Question : Do you already work with the same language in several countries? Exemple : English US, Englis UK, English CA? Thanks.
**Rules** is an excellent module for setting up notifications and other Trigger -> Action relationships. I don't know if it works with translations out-of-the-box, but you may be able to find an applicable extension or write a custom module to finish the job.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "drupal, internationalization, drupal modules" }
How can I download a web page using perl? I'm new to perl. Now I need to write a perl program to download web pages from a web site periodically. I see some useful methods to establish network connections and get content, but I don't know which is better. Can anybody recommend some libraries to download web pages with sample codes, or tutorial sites? I hope it's simple to start with, like the pseudo codes: use library; open a connection; get the content; process if success or handle error. And it's better to have cookie support. Thanks.
I recommend libcurl. It's simple and has full functionality to handle almost everything about http including cookie support. And it has many different language bindings, so it's easy for you to turn to other languages. Using cpan to search for perl's binding. The official website is <
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "perl, http" }
PyCharm "No tests were found" This is my main code def return_first_name(first_name): return first_name This is the unit test code import unittest import profile class TestFunctionFirstName(unittest.TestCase): def first_name(self): answer = profile.return_first_name("jakub") self.assertEqual(answer, "jakub") I really don't understand why it is not finding any unit tests. I have been sitting here for hours messing with it.![enter image description here](
From the docs > Test method names or function names should start with “test_”, as in `test_example`. Methods with names that don’t match this pattern won’t be executed as tests. So in your case you can rename your test method to def test_first_name(self):
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "python, unit testing, syntax, pycharm" }
Can I call a function of a shell script from another shell script? I have 2 shell scripts. The second shell script contains following functions _second.sh_ func1 func2 The first.sh will call the second shell script with some parameters and will call func1 and func2 with some other parameters specific to that function. Here is the example of what I am talking about second.sh val1=`echo $1` val2=`echo $2` function func1 { fun=`echo $1` book=`echo $2` } function func2 { fun2=`echo $1` book2=`echo $2` } first.sh second.sh cricket football func1 love horror func2 ball mystery How can I achieve it?
Refactor your `second.sh` script like this: func1 { fun="$1" book="$2" printf "func=%s,book=%s\n" "$fun" "$book" } func2 { fun2="$1" book2="$2" printf "func2=%s,book2=%s\n" "$fun2" "$book2" } And then call these functions from script `first.sh` like this: source ./second.sh func1 love horror func2 ball mystery **OUTPUT:** func=love,book=horror func2=ball,book2=mystery
stackexchange-stackoverflow
{ "answer_score": 207, "question_score": 140, "tags": "shell, unix" }
Percentage in WHERE CLAUSE in mysql I want to get all records have price 20% Less OR More of a give value. +----+------------+----------+---------+ | ID | Item | Category | price | +----+------------+----------+-----------+ | 1 | Popular | Rock | 1000 | 2 | Classical | Opera | 5000 | 3 | Popular2 | Jazz | 6000 | 4 | Classical2 | Dance | 8000 | 5 | Classical3 | General | 4825 +----+------------+----------+------------+ User has to pass two parameters i - Category ii-Price I need to show all item having same category and price is between 20% less and 20% greater than user's value. Something like this SELECT * FROM Table1 WHERE Categry='ROCK' AND price > (20% less price of user's price) AND price < (20% greater than user's price)
Assuming `@price` represents the user's price: SELECT * FROM Table1 WHERE Categry='ROCK' AND price BETWEEN (0.8 * @price) AND price < (1.2 * @price)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql, where clause, percentage" }
Reverse order of firstname and lastname in SQL column I have a column in a SQL database in the format initial space surname, e.g. "J Smith", and I'd like it to be "Smith J". What is the most efficient way of doing this using T-SQL? The table has many millions of records. Thanks.
Use the substring formulas, but use them to avoid having to use them ever again: ALTER TABLE SillyTable ADD FirstInitial char(1), LastName varchar(50); INSERT INTO SillyTable(FirstInitial, LastName) SELECT SUBSTRING(NameColumn, 1, 1), SUBSTRING(NameColumn, 3, LEN(NameColumn) - 2) FROM SillyTable; SELECT LastName + ' ' + FirstInitial AS WhatMyBossWantsToday FROM SillyTable;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "sql" }
Non Unique Username with ASP.Net Identity 2.0 I have a situation where my username is not unique. Email is used as username and one email can have many different passwords in the database and all are legitimate. How do I use ASP.NET Identity 2.0 in this situation. var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false); Above line expects only one user in the database. If the multiple records are returned - it returns failure. That is exactly what is expected it to do but this logic doesn't work for me. How do I override this logic? Alternatively, I am ready to customize this login but the problem is - I am not sure what all things are done as a part of PasswordSignInAsync. Like adding to cookies etc. Please help.
I made it work. I had to use Username + password combination as a unique Username. These are different situations in industry for different types of needs.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, asp.net identity" }
Git Bash cannot find git directory when git is installed I'm running `cap deploy` to deploy a site to a server. It deploys just fine, except for this last part: export GIT_RECURSIVE=$([ ! \"`git --version`\" \\< \"git version 1.6.5\" ] && echo --recursive) && git submodule -q update --init $GIT_RECURSIVE && (echo b8ce153ac56e3e79eda1e053b922ac48e775321a > /var/www/alkdfjf/releases/20130822204731/REVISION) If I didn't have `git`, I have git installed, as it clones just fine. But at this step, I receive an error stating: bash: "git: No such file or directory.
I think the .git folder those files are in is usually hidden and needs higher privileges. Are you sure you don't need or that you are sudo or whatever the equivalent is on Macs?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "macos, git, bash, ssh, capistrano" }
Is it true that 10 + 0.5 exactly equals to 10.5 in javascript? In C++, according to Is hardcode float precise if it can be represented by binary format in IEEE 754?, 10+0.5 should be exactly equals to 10.5 without rounding because both 10,0.5 and 10.5 are exact values in IEEE 754, which is different from the case in Is floating point math broken? But the first question is about C++, and javascript doesn't have integer type, so I would like to know if the case about exact values also applies in javascript.
Yes. See this related answer which cites the standard specifying JS's adherence to IEEE 754.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, floating point, floating accuracy" }
How to continually communicate with same process with Python Popen() I am new at this so hope you understand... Now I am using python subprocess module for sending the specific command. After I send the command1 with Popen function, I would like to send a command2 to same process one more. Is it possible...? // Example // command1 -> Opening command for text program. // command2 -> Executing the write and save command.(on above text program) popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) // next....? please let me know If I understand it incorrectly.
Check this out. In unix, we can execute multiple commands in one go like cmd_1;cmd_2 We will use same thing with sub-process. Make sure to use `shell=True`. import subprocess all_cmd = "echo a;echo b;echo c" p = subprocess.Popen(all_cmd,stdout=subprocess.PIPE, shell=True) p_stdout,p_err = p.communicate() print p_stdout.strip()
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, unix" }
Mysql Trigger not working. Why? What i'm doing wrong? CREATE TRIGGER `Calc` AFTER INSERT on `test`.`bookings` FOR EACH ROW BEGIN UPDATE `test`.`article` AS `ST` SET `ST`.`stock` = SUM(`test`.`bookings`.`amount`) WHERE `ST`.`articlenr` = `test`.`bookings`.`NEW.article`; END The idea is, to calculate "STOCK" in ARTICLE, after an insert like: Amount: 1 Article: 123 on table bookings. How can this be solved?
WHERE `ST`.`articlenr` = NEW.`article`; New its not a column =(SELECT SUM(`test`.`bookings`.`amount`) FROM `test`.`bookings` GROUP BY article)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, triggers" }
Stored Procedure IDENTITY_INSERT I'm recently change my data table, I remove column and add a new column that define as identity = True and identity seed = 1, identity increment = 1. When i tried to insert data to this table by STORE PROCEDURE i get this exception: An explicit value for the identity column in table 'AirConditioner' can only be specified when a column list is used and IDENTITY_INSERT is ON. I saw that i need to add this lines: SET IDENTITY_INSERT [dbo].[AirConditioner] ON and finally OFF I added and its still throw an exception... My store procedure is attached as a picture!enter image description here
SQL Server will take care of assigning a value to your identity column. You should remove `@ID` from the insert statement and remove the `IDENTITY_INSERT` statements.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "asp.net, sql, sql server, stored procedures, identity insert" }
Heterogenous and Asymmetric Computing's differences The definition of the both architecture looks pretty same. They are parallel computing architecture with different type of cores. What distinguish their definition, actually?
Heterogenous computing as opossite to homogenous or symmetric means that processing units differ, which is exactly the same as asymmetric (which is just not symmetric). But there are more usage differences - asymmetric computing (processing) is more about different CPUs which are used to perform assigned tasks, in embedded systems this is by design, in general purpose by executing in given context, commonly about "local" environment. Heterogenous is used to talk about tasks computed on different processing units (CPU, GPU and dedicated hardware), also used to describe distributed systems where processing takes place on totally random devices connected. To make it full - symmetric means exactly the same vector, while homogenous is less strict and requires the results to be the same among devices (the same floating point representation), but does not require exact devices.
stackexchange-cs
{ "answer_score": 0, "question_score": 1, "tags": "terminology, computer architecture, parallel computing" }
r return ngram from a vector which contains specific string I want to generate `ngram` keywords from a vector, given a specific string. For example, let's say I would need `bigram`, for each element of the vector I want to extract relevant bigrams and concatenate all the bigrams which has the keyword `ncd`. have <- c('add the ncd mse to the website', 'setup new ncd staffs on t&ta for wireless. all new ncd should go to horizon', 'map out current ncd post locations on 1st, 2nd floors') want_bigram <- c('the ncd | ncd mse', 'new ncd | ncd staffs | new ncd |ncd should', 'current ncd | ncd post') Thank you
You can do this with the `tidytext` library. library(tidytext) want <- have %>% as_tibble() %>% mutate(row = row_number()) %>% unnest_tokens(bigrams, value, token = "ngrams", n = 2) %>% filter(str_detect(bigrams, "ncd")) %>% group_by(row) %>% summarize(text = paste0(bigrams, collapse = " | ")) %>% pull(text) Output: > want [1] "the ncd | ncd mse" [2] "new ncd | ncd staffs | new ncd | ncd should" [3] "current ncd | ncd post"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, nlp" }