qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
36,403,604
I need to delete multiple objects from google cloud storage. I have deleted one object at a time. This is my code: ``` var gcloud = require('gcloud')({ projectId: "sampleProject1" }); var gcs = gcloud.storage(); var myBucket = gcs.bucket('sampleBucket1'); var file = myBucket.file('1.png'); file.delete(function (err, apiResponse) { if (err) { console.log(err); } else { console.log("Deleted successfully"); } }); ``` But I need to delete multiple objects simultaneously. Is it possible or not?
2016/04/04
[ "https://Stackoverflow.com/questions/36403604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4182755/" ]
We do have [`bucket#deleteFiles`](https://cloud.google.com/nodejs/docs/reference/storage/latest/Bucket#deleteFiles) that will handle throttling the requests for you. You can use the `prefix` option to target multiple images by a naming convention, like: ``` bucket.deleteFiles({ prefix: 'image-' }, callback); ``` If that doesn't work, we also have a guide that shows how you can do the throttling logic yourself. See "My requests are returning errors instructing me to retry the request": <https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.29.0/guides/troubleshooting> Edit to elaborate on how to do the throttling using [async](http://gitnpm.com/async): ``` var async = require('async'); var PARALLEL_LIMIT = 10; function deleteFile(file, callback) { file.delete(callback); } async.eachLimit(filesToDelete, PARALLEL_LIMIT, deleteFile, function(err) { if (!err) { // Files deleted! } }); ```
``` var gcloud = require('gcloud')({ projectId: "sampleProject1" }); var gcs = gcloud.storage(); var myBucket = gcs.bucket('sampleBucket1'); var collection = gcs.collection("Add file for delete"); collection.insert({'1.png'},{'2.png'}); collection.delete(function (err, apiResponse) { if (err) { console.log(err); } else { console.log("Deleted successfully"); } }); ```
55,625,323
I have a code as below ``` <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/left_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Left" android:textColor="#F40" android:textSize="26sp" android:visibility="gone" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@id/right_text" app:layout_constraintHorizontal_chainStyle="spread_inside" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"/> <TextView android:id="@+id/right_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Right" android:textColor="#F40" android:textSize="26sp" android:fontFamily="serif-monospace" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toEndOf="@id/left_text" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent"/> </android.support.constraint.ConstraintLayout> ``` It looks like below. [![enter image description here](https://i.stack.imgur.com/36Lj8.png)](https://i.stack.imgur.com/36Lj8.png) However, at times I need to set `left_text` to `gone`. But I still want my `Right` to be at the right side of the screen. How could I achieve that? (Currently when `left_text` is `gone`, my `Right` went to middle as per picture below) [![enter image description here](https://i.stack.imgur.com/EOBGl.png)](https://i.stack.imgur.com/EOBGl.png)
2019/04/11
[ "https://Stackoverflow.com/questions/55625323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3286489/" ]
I manage to solve it by setting my `width="0dp"` and `android:textAlignment="viewStart"` or `android:textAlignment="viewEnd"` ``` <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/left_text" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Left" android:textColor="#F40" android:textSize="26sp" android:textAlignment="viewStart" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@id/right_text" app:layout_constraintHorizontal_chainStyle="spread_inside" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"/> <TextView android:id="@+id/right_text" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Right" android:textColor="#F40" android:textSize="26sp" android:textAlignment="viewEnd" android:fontFamily="serif-monospace" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toEndOf="@id/left_text" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent"/> </android.support.constraint.ConstraintLayout> ``` The `width="0dp"` will take up the entire space
You can also use [SequenceLayout](https://github.com/yasharpm/SequenceLayout) to make it work. ```xml <Sequences> <Horizontal> <Span id="@id/left_text" size="wrap"/> <Span size="1w"/> <Span id="@id/right_text" size="wrap"/> </Horizontal> </Sequences> ```
62,042,836
I have a fairly large CSV dataset, around 13.5MB and with approximately 120,000 rows and 13 columns. The code below is the current solution that I have in place. ``` private IEnumerator readDataset() { starsRead = 0; var totalLines = File.ReadLines(path).Count(); totalStars = totalLines - 1; string firstLine = File.ReadLines(path).First(); int columnCount = firstLine.Count(f => f == ','); string[,] datasetTable = new string[totalStars, columnCount]; int lineLength; char bufferChar; var bufferString = new StringBuilder(); int column; int row; using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { string line = sr.ReadLine(); while ((line = sr.ReadLine()) != null) { row = 0; column = 0; lineLength = line.Length; for (int i = 0; i < lineLength; i++) { bufferChar = line[i]; if (bufferChar == ',') { datasetTable[row, column] = bufferString.ToString(); column++; } else { bufferString.Append(bufferChar); } } row++; starsRead++; yield return null; } } } ``` Luckily, as I am running this via a Unity coroutine, the program doesn't freeze up, but this current solution takes 31 minutes and 44 seconds to read the entirety of the CSV file. Is there any other way I can do this? I am trying to target a parse time of less than 1 minute.
2020/05/27
[ "https://Stackoverflow.com/questions/62042836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11742478/" ]
The basic mistake you are making is doing only **1 single line per frame** so you can basically calculate how long you will take for around 60fps: ``` 120,000 rows / 60fps = 2000 seconds = 33.3333 minutes ``` due to the `yield return null;` which basically says "Pause the routine, render this frame and continue in the next frame". --- Of course it would be way faster speaking about absolute time by not using `yield return null` or a Coroutine at all but let the entire thing be parsed in one single go. But then of course it freezes the UI main thread for a moment. To avoid that the **best** way in my opinion would actually be to move the entire thing in a `Thread`/`Task` and only return the result! FileIO and string parsing is always quite slow. --- However, I think you could already speed it up a lot by simply using a [`StopWatch`](https://learn.microsoft.com/dotnet/api/system.diagnostics.stopwatch) like ``` ... var stopWatch = new Stopwatch(); stopWatch.Start(); // Use the last frame duration as a guide for how long one frame should take var targetMilliseconds = Time.deltaTime * 1000f; while ((line = sr.ReadLine()) != null) { .... // If you are too long in this frame render one and continue in the next frame // otherwise keep going with the next line if(stopWatch.ElapsedMilliseconds > targetMilliseconds) { yield return null; stopWatch.Restart(); } } ``` This allows to work off multiple lines within one frame while trying to keep a 60fps frame-rate. You might want to experiment a bit with it to find a good trade off between frame-rate and duration. E.g. maybe you can allow it to run with only 30fps but importing faster since like this it can handle more rows in one frame. --- In general I wouldn't read "manually" through each byte/char. Rather use the builtin methods for that like e.g. `String.Split`. I am actually using a bit more advanced [`Regex.Matches`](https://learn.microsoft.com/dotnet/api/system.text.regularexpressions.regex.matches) since if you export a CSV from Excel it allows special cases like one cell itself containing a `,` or other special characters like e.g. linebreaks(!). Excel does it by wrapping the cell in `"` in this case. Which adds a second special case, namely a cell itself containing a `"`. The `Regex.Marches` is quite complex of course and slow itself but covers these special cases. (See also [Basic CSV rules](https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules) for more detailed explanation on special cases) If you know the format of your CSV well and don't need it you could/should probably rather just stick to ``` var columns = row.Split(new []{ ','}); ``` to split it always just on `,` which would run faster. ``` private const char Quote = '\"'; private const string LineBreak = "\r\n"; private const string DoubleQuote = "\"\""; private IEnumerator readDataset(string path) { starsRead = 0; // Use the last frame duration as a guide how long one frame should take // you can also try and experiment with hardcodd target framerates like e.g. "1000f / 30" for 30fps var targetMilliseconds = Time.deltaTime * 1000f; var stopWatch = new Stopwatch(); // NOTE: YOU ARE ALREADY READING THE ENTIRE FILE HERE ONCE!! // => Instead of later again read it line by line rather re-use this file content var lines = File.ReadLines(path).ToArray(); var totalLines = lines.Length; totalStars = totalLines - 1; // HERE YOU DID READ THE FILE AGAIN JUST TO GET THE FIRST LINE ;) string firstLine = lines[0]; var firstLineColumns = GetColumns(firstLine); columnCount = firstLineColumns.Length; var datasetTable = new string[totalStars, columnCount]; stopWatch.Start(); for(var i = 0; i < totalStars; i++) { string row = lines[i + 1]; string[] columns = GetColumns(row); var colIndex = 0; foreach(var column in columns) { if(colIndex >= columnCount - 1) break; datasetTable[i, colIndex] = colum; colIndex++; } starsRead = i + 1; // If you are too long in this frame render one and continue in the next frame // otherwise keep going with the next line if (stopWatch.ElapsedMilliseconds > targetMilliseconds) { yield return null; stopWatch.Restart(); } } } private string[] GetColumns(string row) { var columns = new List<string>(); // Look for the following expressions: // (?<x>(?=[,\r\n]+)) --> Creates a Match Group (?<x>...) of every expression it finds before a , a \r or a \n (?=[...]) // OR | // ""(?<x>([^""]|"""")+)"" --> An Expression wrapped in single-quotes (escaped by "") is matched into a Match Group that is neither NOT a single-quote [^""] or is a double-quote // OR | // (?<x>[^,\r\n]+)),?) --> Creates a Match Group (?<x>...) that does not contain , \r, or \n var matches = Regex.Matches(row, @"(((?<x>(?=[,\r\n]+))|""(?<x>([^""]|"""")+)""|(?<x>[^,\r\n]+)),?)", RegexOptions.ExplicitCapture); foreach (Match match in matches) { var cleanedMatch = match.Groups[1].Value == "\"\"" ? "" : match.Groups[1].Value.Replace("\"\"", Quote.ToString()); columns.Add(cleanedMatch); } // If last thing is a `,` then there is an empty item missing at the end if (row.Length > 0 && row[row.Length - 1].Equals(',')) { columns.Add(""); } return columns.ToArray(); } ```
30 minutes is insanely slow! There seems to be a few issues: * `bufferString` never gets cleared. See below for an updated version. Clearing it down allows the code to run in <1s on my machine with a 23MB 130,000 row input file. * `row` gets reset at the endof each loop iteration, meaning that only `datasetTable[0, col]` gets populated. If this is intentional you can probably simplify some of the startup code. * As people have mentioned, code to *correctly* parse CSV is insanely tricky, but if you can be confident of the format of your input files this should be ok. ``` if (bufferChar == ',') { datasetTable[row, column] = bufferString.ToString(); column++; bufferString.Clear(); // <-- Add this line } else { bufferString.Append(bufferChar); } ```
30,631,286
Android Studio is giving me a Gradle build error that looks like this: ``` Error:(3, 22) compileSdkVersion android-22 requires compiling with JDK 7 ``` Now it gives me these clickable prompts: ``` Download JDK 7 Select a JDK from the File System Open build.gradle File ``` And I have already downloaded and installed JDK 7. The problem is when I go to select it in the "File System" i can only find a directory named 1.6.0 JDK. Furthermore, the installation of JDK 7 skipped the bullet point where I would've selected the install directory, so I'm really not sure where it is. My java control panel says I have "Java 7 Update 79" so I'm pretty sure I'm close, I just need to tell android studio where it is. I also ran the `java -version` command in the terminal and it says my version is "1.7.0\_79". Any help would be appreciated!
2015/06/03
[ "https://Stackoverflow.com/questions/30631286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4851777/" ]
You can use `cmd` + `;` for Mac or `Ctrl` + `Alt` + `Shift` + `S` for Windows/Linux to pull up the Project Structure dialog. In there, you can set the JDK location as well as the Android SDK location. ![Project Structure Dialog](https://i.stack.imgur.com/FHsOe.png) To get your JDK location, run `/usr/libexec/java_home -v 11` in terminal. Send 1.7 for Java 7, 1.8 for Java 8, or 11 for Java 11.
In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case: ``` Android Studio 4.0.1 Build #AI-193.6911.18.40.6626763, built on June 25, 2020 Runtime version: 1.8.0_242-release-1644-b01 amd64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Windows 10 10.0 GC: ParNew, ConcurrentMarkSweep Memory: 1237M Cores: 8 Registry: ide.new.welcome.screen.force=true Non-Bundled Plugins: com.google.services.firebase ```
17,429,591
I have three ViewControllers: ``` RootViewController FirstViewController SecondViewController ``` From the RootViewController I create a TabBarController with the other two ViewControllers. So I need to do something like: ``` FirstViewController *viewController1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil]; SecondViewController *viewController2 = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; ``` And then add the controllers to the TabBarController. In that moment, my two ViewControllers are instantiated. To update the data I have tried this in my `FirstViewController.m`: ``` SecondViewController *test = [[SecondViewController alloc] init]; [test.tableView reloadData]; ``` But nothing happens, I suppose because my SecondViewController has been allocated before, and am creating a new instance of it. How can I update the data of my Table in the SecondViewController from my FirstViewController?
2013/07/02
[ "https://Stackoverflow.com/questions/17429591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/613265/" ]
Have your root view controller pass the value of viewController2 down to viewController1 when it creates them. Describe the properties as weak, as you want rootController to own them, not the other viewController.
This will help you. You can access secondViewController this way. ``` UITabBarController *tabController = (UITabBarController *)[self parentViewController]; [tabController.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj isKindOfClass:[SecondViewController class]]) { SecondViewController *secondController = obj; [secondController.tableView reloadData]; *stop = YES; } }]; ```
63,445,198
I'm trying to create a web server that allow users to oauth their IB accounts. To obtain a request token, you first need to get a consumer key. I tried to follow their instruction, but there is no details on how to make a call to get the `consumer_key`. What exactly should the endpoint be? Is it a `POST` or `GET` call? how do params / body looks like? [![enter image description here](https://i.stack.imgur.com/4j23c.png)](https://i.stack.imgur.com/4j23c.png)
2020/08/17
[ "https://Stackoverflow.com/questions/63445198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4168649/" ]
Even though you registered your consumer\_key in InteractiveBroker settings page, OAuth flow for the consumer\_key will not be worked because IB Web API OAuth flow is not ready to work. Their customer service doesn't have the ability to solve the problem because the OAuth flow should be ready by the developers for IB Service Provider. All of documents for the OAuth flow of InteractiveBroker is not correct and the customer service said they don't know about the issues. It will be the losing of the time if you are going to solve the problem for OAuth flow of InteractiveBroker. InteractiveBroker Web API is not ready yet. Don't lose your time.
If your talking about the web trading API you have to submit several things to IB in order to get your application registered. Onboarding instructions can be found in their OAuth document at: <https://www.interactivebrokers.com/webtradingapi/oauth.pdf>
14,840,310
``` def regexread(): import re result = '' savefileagain = open('sliceeverfile3.txt','w') #text=open('emeverslicefile4.txt','r') text='09,11,14,34,44,10,11, 27886637, 0\n561, Tue, 5,Feb,2013, 06,25,31,40,45,06,07, 19070109, 0\n560, Fri, 1,Feb,2013, 05,21,34,37,38,01,06, 13063500, 0\n559, Tue,29,Jan,2013,' pattern='\d\d,\d\d,\d\d,\d\d,\d\d,\d\d,\d\d' #with open('emeverslicefile4.txt') as text: f = re.findall(pattern,text) for item in f: print(item) savefileagain.write(item) #savefileagain.close() ``` The above function as written parses the text and returns sets of seven numbers. I have three problems. 1. Firstly the 'read' file which contains exactly the same text as text='09,...etc' returns a `TypeError expected string or buffer`, which I cannot solve even by reading some of the posts. 2. Secondly, when I try to write results to the 'write' file, nothing is returned and 3. thirdly, I am not sure how to get the same output that I get with the print statement, which is three lines of seven numbers each which is the output that I want.
2013/02/12
[ "https://Stackoverflow.com/questions/14840310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1478335/" ]
This should do the trick: ``` import re filename = 'sliceeverfile3.txt' pattern = '\d\d,\d\d,\d\d,\d\d,\d\d,\d\d,\d\d' new_file = [] # Make sure file gets closed after being iterated with open(filename, 'r') as f: # Read the file contents and generate a list with each line lines = f.readlines() # Iterate each line for line in lines: # Regex applied to each line match = re.search(pattern, line) if match: # Make sure to add \n to display correctly when we write it back new_line = match.group() + '\n' print new_line new_file.append(new_line) with open(filename, 'w') as f: # go to start of file f.seek(0) # actually write the lines f.writelines(new_file) ```
You're sort of on the right track... You'll iterate over the file: [How to iterate over the file in python](https://stackoverflow.com/questions/5733419/how-to-iterate-over-the-file-in-python) and apply the regex to each line. The link above should really answer all 3 of your questions when you realize you're trying to write 'item', which doesn't exist outside of that loop.
18,516,137
I am using `regex` to capture hashtags from a string like this: ``` var words = "#hashed words and some #more #hashed words"; var tagslistarr = words.match(/#\S+/g); console.log(tagslistarr); ``` this will return an array like this; ``` ["#hashed", "#more", "#hashed"] ``` question: how can i remove the `#` hash sign from each of the array items? this is what i would like in the end ``` ["hashed", "more", "hashed"] ```
2013/08/29
[ "https://Stackoverflow.com/questions/18516137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1057045/" ]
Try: ``` words.match( /#\S+/g ).map( function(x) { return x.replace(/^#/,''); } ); ``` A better way to do this would be zero-width assertions; unfortunately, JavaScript does not support look-behind assertions, only look-ahead. (As an aside, here is a blog post about [mimicking lookbehind assertions in JavaScript](http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript). I can't say as I care much for any of the solutions, but it's good reading nonetheless. I sure hope lookbehind assertions make it into ES6.) As pointed out by SimonR in the comments below, `Array.prototype.map` is not available in IE8 and below. However, it's easy enough to polyfill: ``` if( !Array.prototype.map ) { Array.prototype.map = function(f) { var r = []; for( var i=0; i<this.length; i++ ) r[i] = f(this[i]); return r; } } ```
``` var words = "#hashed words and some #more #hashed words"; var regexp = /#(\S+)/g; // Capture the part of the match you want var results = []; var match; while((match = regexp.exec(words))) // Loop through all matches results.push(match[1]); // Add them to results array console.log(results); ```
48,126,328
Why it doesn't work? When I'm trying to call example.example() I'm getting TypeError: example.example is not a function. ``` var example = class { constructor(){ this.example = false; } id(){ this.example = !this.example; return this.example; } }; ```
2018/01/06
[ "https://Stackoverflow.com/questions/48126328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5157656/" ]
> > When I'm trying to call example.example() I'm getting TypeError: > example.example is not a function. > > > `example` is a reference to an anonymous class, and **its constructor can only be invoked with `new`** You need to call it as ``` var a = new example(); a.example; //false ``` **Demo** ```js var example = class { constructor() { this.example = false; } id() { this.example = !this.example; return this.example; } }; var a = new example() console.log(a.example); ```
You have created class so you need to make an object of this.It should work by calling like this. ```js var example = class { constructor(){ this.example = false; } id(){ this.example = !this.example; return this.example; } }; console.log((new example()).id()); var obj = new example(); console.log(obj.id()); ```
36,919,825
How to send a pandas dataframe to a hive table? I know if I have a spark dataframe, I can register it to a temporary table using ``` df.registerTempTable("table_name") sqlContext.sql("create table table_name2 as select * from table_name") ``` but when I try to use the pandas dataFrame to registerTempTable, I get the below error: ``` AttributeError: 'DataFrame' object has no attribute 'registerTempTable' ``` Is there a way for me to use a pandas dataFrame to register a temp table or convert it to a spark dataFrame and then use it register a temp table so that I can send it back to hive.
2016/04/28
[ "https://Stackoverflow.com/questions/36919825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4057016/" ]
I guess you are trying to use pandas `df` instead of [Spark's DF](https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#module-pyspark.sql.functions). Pandas DataFrame has no such method as `registerTempTable`. you may try to create Spark DF from pandas DF. **UPDATE:** I've tested it under Cloudera (with installed [Anaconda parcel](https://repo.continuum.io/pkgs/misc/parcels/), which includes Pandas module). Make sure that you have set `PYSPARK_PYTHON` to your anaconda python installation (or another one containing Pandas module) on all your Spark workers (usually in: `spark-conf/spark-env.sh`) Here is result of my test: ``` >>> import pandas as pd >>> import numpy as np >>> df = pd.DataFrame(np.random.randint(0,100,size=(10, 3)), columns=list('ABC')) >>> sdf = sqlContext.createDataFrame(df) >>> sdf.show() +---+---+---+ | A| B| C| +---+---+---+ | 98| 33| 75| | 91| 57| 80| | 20| 87| 85| | 20| 61| 37| | 96| 64| 60| | 79| 45| 82| | 82| 16| 22| | 77| 34| 65| | 74| 18| 17| | 71| 57| 60| +---+---+---+ >>> sdf.printSchema() root |-- A: long (nullable = true) |-- B: long (nullable = true) |-- C: long (nullable = true) ```
I converted my pandas df to a temp table by 1) Converting the pandas dataframe to spark dataframe: ``` spark_df=sqlContext.createDataFrame(Pandas_df) ``` 2) Make sure that the data is *migrated* properly ``` spark_df.select("*").show() ``` 3) Convert the spark dataframe to a temp table for querying. ``` spark_df.registerTempTable("table_name"). ``` Cheers..
3,274,968
The follow http post request send data using multipart/form-data content type. ``` -----------------------------27311326571405\r\nContent-Disposition: form-data; name="list"\r\n\r\n8274184\r\n-----------------------------27311326571405\r\nContent-Disposition: form-data; name="list"\r\n\r\n8274174\r\n-----------------------------27311326571405\r\nContent-Disposition: form-data; name="list"\r\n\r\n8274178\r\n-----------------------------27311326571405\r\nContent-Disposition: form-data; name="antirobot"\r\n\r\n2341234\r\n-----------------------------27311326571405\r\nContent-Disposition: form-data; name="votehidden"\r\n\r\n1\r\n-----------------------------27311326571405--\r\n ``` List is an input name. 8274184, 8274174, 8274178 etc are input value. But what is 27311326571405, 27311326571405...etc? I want to send same request using c# but i really donnt know where i can to get this numbers.
2010/07/18
[ "https://Stackoverflow.com/questions/3274968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/290082/" ]
`---27311326571405` is called boundary and it is a random string that should never appear in the data you are sending and is used as separator between the values. Here's an example of sending such a request to a given address: ``` class Program { static void Main() { var data = new List<KeyValuePair<string, string>>(new[] { new KeyValuePair<string, string>("list", "8274184"), new KeyValuePair<string, string>("list", "8274174"), new KeyValuePair<string, string>("list", "8274178"), new KeyValuePair<string, string>("antirobot", "2341234"), new KeyValuePair<string, string>("votehidden", "1"), }); string boundary = "----MyAppBoundary" + DateTime.Now.Ticks.ToString("x"); var request = (HttpWebRequest)WebRequest.Create("http://example.com"); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST"; using (var requestStream = request.GetRequestStream()) using (var writer = new StreamWriter(requestStream)) { foreach (var item in data) { writer.WriteLine("--" + boundary); writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", item.Key)); writer.WriteLine(); writer.WriteLine(item.Value); } writer.WriteLine(boundary + "--"); } using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) using (var reader = new StreamReader(responseStream)) { Console.WriteLine(reader.ReadToEnd()); } } } ```
If you like to remove `---27311326571405` boundary value in response, please use the following code ``` var multiplarty = require('multiparty') var util = require('util') if ( req.method === 'POST') { var form = new multiplarty.Form(); form.parse(req, function(err, fields, files) { res.writeHead(200, {'content-type': 'text/plain'}); res.write('received upload:\n\n'); res.end(util.inspect({fields: fields})); }); return; } ```
15,372,940
I was wondering how to set up my `UICollectionView` so that up to 1 cell can be selected per section. I see that there is the `allowsMultipleSelection` property for UICollectionView but I'm wondering how to prevent multiple cells from being selected in the same section. Do I need to implement logic in the `– collectionView:shouldSelectItemAtIndexPath:` and `collectionView:shouldDeselectItemAtIndexPath:` methods or is there a simpler way? Thanks!
2013/03/12
[ "https://Stackoverflow.com/questions/15372940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508642/" ]
In Swift 5.0: ``` override func viewDidLoad() { super.viewDidLoad() self.collectionView.allowsMultipleSelection = true } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { (collectionView.indexPathsForSelectedItems ?? []) .filter { $0.section == indexPath.section && $0.item != indexPath.item && $0.row != indexPath.row } .forEach { self.collectionView.deselectItem(at: $0, animated: false) } } ``` if you want it to toggle between items in section use this: ``` override func viewDidLoad() { super.viewDidLoad() self.collectionView.allowsMultipleSelection = true } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { (collectionView.indexPathsForSelectedItems ?? []) .filter { $0.section == indexPath.section && $0.item } .forEach { self.collectionView.deselectItem(at: $0, animated: false) } } ``` I think that makes better user experience but it's your call
You'll probably need to do logic in `-shouldSelect` and `-shouldDeselect`. Maybe keep **a dictionary of number of cells selected per section**? ``` NSMutableDictionary *dict; - (BOOL)collectionView:(UICollectionView *)view shouldSelectItemAtIndexPath:(NSIndexPath *)path { NSInteger *section = path.section; if (!dict) { dict = [[NSMutableDictionary alloc] init]; } NSNumber *numberSelected = [dict objectForKey:[NSNumber numberWithInteger:section]]; if (numberSelected > 0) { return NO; } else { [dict setObject:[NSNumber numberWithDouble:numberSelected.doubleValue - 1] forKey:[NSNumber numberWithInteger:section]]; return YES; } } - (BOOL)collectionView:(UICollectionView *)view shouldDeselectItemAtIndexPath:(NSIndexPath *)path { NSInteger *section = path.section; if (!dict) { dict = [[NSMutableDictionary alloc] init]; } NSNumber *numberSelected = [dict objectForKey:[NSNumber numberWithInteger:section]]; numberSelected = [NSNumber numberWithDouble:numberSelected.doubleValue - 1]; [dict setObject:numberSelected forKey:[NSNumber numberWithInteger:section]]; return YES; } ``` That should work.
29,407,453
I am currently working on a big WPF project which is already been developed and structured, furthermore it is expected to grow. However it doesn't have any of the MVVM pattern architecture components. One of our goals now is to restructure contained UIs to support the MVVM pattern components. Due the design of MVVM view layer development separation, removing virtually all UI "code-behind", we raised the above idea. The above idea takes advantage of the restructure to future development, so we consider to split the current project to two: * UI Project - contains and manages present and future UI codes (Views and ViewModels). * Logic Project - contains and manages present and future logic codes (Models). Is it correct to apply such splitting? will it be overkill for future development, debug and testing?
2015/04/02
[ "https://Stackoverflow.com/questions/29407453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4188683/" ]
I don't see any problem in what you're proposing. If you follow the MVVM pattern 'correctly' then it should provide complete separation between your Views and your ViewModels. As such it might also make sense to put all of your Views in a separate project to your ViewModels. Your ViewModels *should* all function perfectly well without Views, giving you a really clean separation between UI production tasks and logic production tasks. Your Views can make use of design time data to simulate the behaviour of the ViewModels without actually having any logic present.
we use prism and we have our views and viewmodel split into 5 separate projects, not to mention other projects (infrastructures, data layer etc). We use prism to manage those 5 (4 of them are prism modules - wpf class libraries) and one of them is the main wpf project which loads the others into a shell.
231,124
I want to build a liquor shelf similar to this: [![enter image description here](https://i.stack.imgur.com/YF8Y6.jpg)](https://i.stack.imgur.com/YF8Y6.jpg) I've seen metal piping and flanges like this at my local big box store, and it usually comes in two flavors: galvanized steel or black iron pipe. The problem with the black iron pipe though is that its always coated in some type of grease, which would obviously be problematic for us in furniture such as what I want to build. So I ask: what type of black metal could I use for this, where could I find it, and does it come with fittings (such as the elbow joints and the flanges) that I could use to reproduce this liquor shelf? Also, any suggestions about attaching it to the wall?
2021/07/30
[ "https://diy.stackexchange.com/questions/231124", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/87068/" ]
What's in the photo is **painted**. Any pipe you use will require surface preparation for paint to *last a long time* and not chip off easily. * Galvanized pipe will require either the galvanizing to be removed chemically or by harsh mechanical removal... or you can leave galvanized stuff outdoors for a year, and it will gain a zinc oxide layer paint will stick to. Don't sand or scrub that oxide off! * Black pipe needs to have that oily anti-rust coating removed with solvent and brushing (the eco "paint thinners" are fine for this). That will leave a black mill scale, but you can ignore it if the finished product will live indoors. Just scuff-sand with a green 3M Scotchbrite pad. --- And by the way, you can take a screen shot of any *part of* your Mac screen with command-shift-4, and immediately click-drag across the rectangle that you want a screen shot of. It lands on your Desktop as a PNG file, that can be easily posted to StackExchange with the image tool. If the file is too big for some reason, double-click it to open it in Preview, and hit "Save As..." to save it as a JPEG. Choose quality 5 or 6 for a sane sized file. Or, use Preview's features to downscale it to half size (probably a good idea on a Retina display).
As @alephzero mentioned, you can get anodized aluminum in any color. The texture looks more like bare metal than paint if that is what you want. Here is a picture of the 2020 aluminum extrusion. [![enter image description here](https://i.stack.imgur.com/RD6Je.jpg)](https://i.stack.imgur.com/RD6Je.jpg)
12,734,435
I'm trying to get the text size on my landing page to scale linearly with the viewport size. If you look at my site at <http://alexanderwhill.com/site2/> you will see what I'm saying. I would like the font size to scale fluidly instead of overflowing. Is this even possible?
2012/10/04
[ "https://Stackoverflow.com/questions/12734435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1713593/" ]
While it generates HTML on the fly, it still use the same CSS as everything else. So just add on required page `<style>` tag with required css which will override default styles or prepare few css files, with css rules overriding default styles, which you will attach to your page when you need that.
One thing you could consider is having no CSS for the colorbox itself, but instead having the content of the pop up in its own page and call it via ajax. Have all the CSS for the particular pop up in its own page. I've used this method before. The only CSS you need in the colorbox file is the background colour/transparency/image.
34,512,646
I've constructed the following little program for getting phone numbers using google's place api but it's pretty slow. When I'm testing with 6 items it takes anywhere from 4.86s to 1.99s and I'm not sure why the significant change in time. I'm very new to API's so I'm not even sure what sort of things can/cannot be sped up, which sort of things are left to the webserver servicing the API and what I can change myself. ``` import requests,json,time searchTerms = input("input places separated by comma") start_time = time.time() #timer searchTerms = searchTerms.split(',') for i in searchTerms: r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query='+ i +'&key=MY_KEY') a = r1.json() pid = a['results'][0]['place_id'] r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+pid+'&key=MY_KEY') b = r2.json() phone = b['result']['formatted_phone_number'] name = b['result']['name'] website = b['result']['website'] print(phone+' '+name+' '+website) print("--- %s seconds ---" % (time.time() - start_time)) ```
2015/12/29
[ "https://Stackoverflow.com/questions/34512646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5037442/" ]
Use sessions to enable persistent HTTP connections (so you don't have to establish a new connection every time) Docs: [Requests Advanced Usage - Session Objects](https://requests.readthedocs.io/en/latest/user/advanced/#session-objects)
Most of the time isn't spent computing your request. The time is spent in communication with the server. That is a thing you cannot control. However, you may be able to speed it along using parallelization. Create a separate thread for each request as a start. ``` from threading import Thread def request_search_terms(*args): #your logic for a request goes here pass #... threads = [] for st in searchTerms: threads.append (Thread (target=request_search_terms, args=(st,))) threads[-1].start() for t in threads: t.join(); ``` Then use a thread pool as the number of request grows, this will avoid the overhead of repeated thread creation.
234,084
I have some code that kills processes and their children/grandchildren. I want to test this code. Currently I'm doing `$ watch date > date.txt`, which creates a process with a child. Is there any way to create a **parent -> child -> grandchild** tree? What command can make that happen?
2015/10/05
[ "https://unix.stackexchange.com/questions/234084", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137147/" ]
You can create a recursive script. eg in file `/tmp/run` ``` #!/bin/bash depth=${1:-3} f(){ let depth-- if [ $depth -gt 0 ] then $0 $depth else sleep 999 fi } f ``` then `chmod +x /tmp/run` and do `/tmp/run 3`.
The `ps` command on freebsd doesn't seem to be able to produce a process tree. Fortunately there is a package called `pstree` which contains a program that will do precisely that.
6,742,938
I have a few queues running with RabbitMQ. A few of them are of no use now, how can I delete them? Unfortunately I had not set the `auto_delete` option. If I set it now, will it be deleted? Is there a way to delete those queues now?
2011/07/19
[ "https://Stackoverflow.com/questions/6742938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/498313/" ]
Another option would be to enable the management\_plugin and connect to it over a browser. You can see all queues and information about them. It is possible and simple to delete queues from this interface.
I was struggling with finding an answer that suited my needs of manually delete a queue in rabbigmq. I therefore think it is worth mentioning in this thread that it is possible to delete a single queue without `rabbitmqadmin` using the following command: ``` rabbitmqctl delete_queue <queue_name> ```
125,864
I am comparing traditional stock markets with the Forex market here. I have noticed stock market have relatively limited leverage but have more change % as well as as volatility. On the other hand, 1% change is a big thing in forex market but they are highly leveraged. Are their pros and cons of trading one type of instrument over other?
2020/05/26
[ "https://money.stackexchange.com/questions/125864", "https://money.stackexchange.com", "https://money.stackexchange.com/users/98607/" ]
Speaking generally: * Lower leverage means risk is better controlled. In the simplest case, an unleveraged long stock position (no matter how volatile) cannot lose more than what you put in. Higher leverage on a less volatile asset may be calibrated so that your *expected* exposure to volatility is the same, but there is more room for *unexpected* volatility to wipe you out. * A less volatile asset may be less likely to move enough in a short time to overcome the bid-ask spread, making trading less profitable. However, your particular example (forex) is highly liquid (small spreads) so this is not much of a problem.
Forex is like trading two stocks against each other in a way. * Where stocks have a company's financial reports, forex has a country's report. But stocks can also be affected by a country's economical health (Apple for example since it is a large part of the SP500 index) * There is a US Dollar Index (58% is EURUSD) which can be traded as "the USD". * The forex market doesn't close except on weekends. * Stocks are generally only traded on one exchange, forex is traded on multiple exchanges. This means that volume can't be calculated easily for forex. * Forex is way more liquid and will have much tighter spreads in general.
51,447,779
I want to fetch json from a url <https://api.myjson.com/bins/mxcsl/> using retrofit and rxjava. Sample json is this : ``` { "data": [ { "itemId": "1", "desc": "Batcave", "audio": "https://storage.googleapis.com/a/17.mp3" }, { "itemId": "2", "desc": "Fight Club rules", "audio": "https://storage.googleapis.com/a/2514.mp3" }, { "itemId": "3", "desc": "Make an offer", "audio": "https://storage.googleapis.com/a/47.mp3" }]} ``` And here is my code : Data Model : ``` public class Data { private String itemId; private String desc; private String audio; public String getItem() { return itemId; } public String getDesc() { return desc; } public String getAudio() { return audio; }} ``` This is the Interface : ``` public interface RequestInterface { @GET("/bins/mxcsl/") Observable<List<Data>> register(); ``` } I'm loading something like this : ``` private void loadJSON() { RequestInterface requestInterface = new Retrofit.Builder() .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build().create(RequestInterface.class); mCompositeDisposable.add(requestInterface.register() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(this::handleResponse,this::handleError)); } private void handleResponse(List<Data> androidList) { mAndroidArrayList = new ArrayList<>(androidList); mAdapter = new DataAdapter(mAndroidArrayList); mRecyclerView.setAdapter(mAdapter); } private void handleError(Throwable error) { Toast.makeText(this, "Error "+error.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } ``` But Also I'm getting the error **expected BEGIN\_ARRAY but was BEGIN\_OBJECT** I don't know where this is going wrong. Please help.
2018/07/20
[ "https://Stackoverflow.com/questions/51447779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6349540/" ]
Your type ``` Observable<List<Data>> register(); ``` is wrong. Because Json's first level is not Array (But object with field `data`, that is array). You should create class for outer structure ``` public class Outer{ List<Data> data; } ``` And specify in retrofit, as observable: ``` @GET("/bins/mxcsl/") Observable<Outer> register(); ```
The error is because Retrofit is expecting a json array to be deserialized as a List ``` public interface RequestInterface { @GET("/bins/mxcsl/") Observable<List<Data>> register(); } ``` But the json response is an object with a field named *data* that is an array ``` { "data": [ { "itemId": "1", "desc": "Batcave", "audio": "https://storage.googleapis.com/a/17.mp3" }, { "itemId": "2", "desc": "Fight Club rules", "audio": "https://storage.googleapis.com/a/2514.mp3" }, { "itemId": "3", "desc": "Make an offer", "audio": "https://storage.googleapis.com/a/47.mp3" }]} ```
38,393,822
I have a Spring MVC form for inputting a date, the input gets sent to a Controller and validated via standard Spring MVC validation. Model: ``` public class InvoiceForm { @Future private LocalDate invoicedate; } ``` Controller: ``` public String postAdd(@Valid @ModelAttribute InvoiceForm invoiceForm, BindingResult result) { .... } ``` When submitting the form I get the following error: ```java javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Future' validating type 'java.time.LocalDate'. Check configuration for 'invoicedate' at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.throwExceptionForNullValidator(ConstraintTree.java:229) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping(ConstraintTree.java:310) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping(ConstraintTree.java:244) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator(ConstraintTree.java:163) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:116) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:617) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:580) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:524) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:492) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:457) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:407) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:205) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final] at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:108) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.validation.DataBinder.validate(DataBinder.java:866) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:164) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:111) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:99) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.0.36.jar:8.0.36] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at com.balticfinance.jwt.StatelessAuthenticationFilter.doFilter(StatelessAuthenticationFilter.java:46) ~[classes/:na] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) ~[tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:676) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520) [tomcat-embed-core-8.0.36.jar:8.0.36] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476) [tomcat-embed-core-8.0.36.jar:8.0.36] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.0.36.jar:8.0.36] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91] ``` I implemented my own `ConstraintValidator` for this case. But somehow Spring Boot does not pick it up for validation. ``` @Component public class LocalDateFutureValidator implements ConstraintValidator<Future, LocalDate> { @Override public void initialize(Future future) { } @Override public boolean isValid(LocalDate localDate, ConstraintValidatorContext constraintValidatorContext) { LocalDate today = LocalDate.now(); return localDate.isEqual(today) || localDate.isAfter(today); } } ``` I know I could simply write my own annotation and specify the validator there, but isn't there a cleaner and easier way?
2016/07/15
[ "https://Stackoverflow.com/questions/38393822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4096682/" ]
I'd agree with Miloš that using the `META-INF/validation.xml` is probably the cleanest and easiest way, but if you do really want to set it up in a Spring `@Confguration` class then it is possible and here's one way you can do it. The beauty of Spring Boot is that does a lot of configuration on your behalf so you don't have to worry about it. However, this can also cause problems when you want to specifically configure something yourself and it's not terribly obvious how to do it. So yesterday I set about trying to add a `CustomerValidator` for `@Past` and `LocalDate` using the `ConstraintDefinitionContributor` mechanism that Hardy suggests (and is referred to in the Hibernate documentation). The simple bit was to write the implementing class to do the validation, which for my highly specific purposes consisted of: ``` public class PastValidator implements ConstraintValidator<Past, LocalDate> { @Override public void initialize(Past constraintAnnotation) {} @Override public boolean isValid(LocalDate value, ConstraintValidatorContext context) { return null != value && value.isBefore(LocalDate.now()); } } ``` Then I got lazy and just instantiated a `@Bean` in my configuration, just on the off-chance that one of Spring's auto-configuration classes would just pick it up and wire it into the Hibernate validator. This was quite a long shot, given the available documentation (or lack thereof) and what Hardy and others had said, and it didn't pay off. So I fired up a debugger and worked backwards from the exception being thrown in `org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree` which was telling me that it couldn't find a validator for `@Past` and `LocalDate`. Looking at the type hierarchy of the `ConstraintValidatorFactory` I discovered that there were two implementing classes in my Spring MVC application: `SpringConstraintValidatorFactory` and `SpringWebConstraintValidatorFactory` which both just try and get a bean from the context of the correct class. This told me that I do have to have my validator registered with Spring's `BeanFactory`, however when I stuck a breakpoint on this but it didn't get hit for my `PastValidator`, which meant that Hibernate wasn't aware that it should be even requesting this class. This made sense: there wasn't any `ConstraintDefinitionContributor` anywhere to do tell Hibernate it needed to ask Spring for an instance of the PastValidator. The example in the documentation at <http://docs.jboss.org/hibernate/validator/5.2/reference/en-US/html_single/#section-constraint-definition-contributor> suggests that I'd need access to a `HibernateValidatorConfiguration` so I just needed to find where Spring was doing its configuring. After a little bit of digging I found that it was all happening in Spring's `LocalValidatorFactoryBean` class, specifically in its `afterPropertiesSet()` method. From its javadoc: ``` /* * This is the central class for {@code javax.validation} (JSR-303) setup in a Spring * application context: It bootstraps a {@code javax.validation.ValidationFactory} and * exposes it through the Spring {@link org.springframework.validation.Validator} interface * as well as through the JSR-303 {@link javax.validation.Validator} interface and the * {@link javax.validation.ValidatorFactory} interface itself. */ ``` Basically, if you don't set up and configure your own Validator then this is where Spring tries to do it for you, and in true Spring style it provides a handy extension method so that you can let it do its configuration and then add your own into the mix. So my solution was to just extend the `LocalValidatorFactoryBean` so that I'd be able to register my own `ConstraintDefinitionContributor` instances: ``` import java.util.ArrayList; import java.util.List; import javax.validation.Configuration; import org.hibernate.validator.internal.engine.ConfigurationImpl; import org.hibernate.validator.spi.constraintdefinition.ConstraintDefinitionContributor; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; public class ConstraintContributingValidatorFactoryBean extends LocalValidatorFactoryBean { private List<ConstraintDefinitionContributor> contributors = new ArrayList<>(); public void addConstraintDefinitionContributor(ConstraintDefinitionContributor contributor) { contributors.add(contributor); } @Override protected void postProcessConfiguration(Configuration<?> configuration) { if(configuration instanceof ConfigurationImpl) { ConfigurationImpl config = ConfigurationImpl.class.cast(configuration); for(ConstraintDefinitionContributor contributor : contributors) config.addConstraintDefinitionContributor(contributor); } } } ``` and then instantiate and configure this in my Spring config: ``` @Bean public ConstraintContributingValidatorFactoryBean validatorFactory() { ConstraintContributingValidatorFactoryBean validatorFactory = new ConstraintContributingValidatorFactoryBean(); validatorFactory.addConstraintDefinitionContributor(new ConstraintDefinitionContributor() { @Override public void collectConstraintDefinitions(ConstraintDefinitionBuilder builder) { builder.constraint( Past.class ) .includeExistingValidators( true ) .validatedBy( PastValidator.class ); } }); return validatorFactory; } ``` and for completeness, here's also where I'd instantiated by `PastValidator` bean: ``` @Bean public PastValidator pastValidator() { return new PastValidator(); } ``` **Other springy-thingies** I noticed in my debugging that because I've got quite a large Spring MVC application, I was seeing two instances of `SpringConstraintValidatorFactory` and one of `SpringWebConstraintValidatorFactory`. I found the latter was never used during validation so I just ignored it for the time being. Spring also has a mechanism for deciding which implementation of `ValidatorFactory` to use, so it's possible for it to not use your `ConstraintContributingValidatorFactoryBean` and instead use something else (sorry, I found the class in which it did this yesterday but couldn't find it again today although I only spent about 2 minutes looking). If you're using Spring MVC in any kind of non-trivial way then chances are you've already had to write your own configuration class such as this one which implements `WebMvcConfigurer` where you can explicitly wire in your `Validator` bean: ``` public static class MvcConfigurer implements WebMvcConfigurer { @Autowired private ConstraintContributingValidatorFactoryBean validatorFactory; @Override public Validator getValidator() { return validatorFactory; } // ... // <snip>lots of other overridden methods</snip> // ... } ``` **This is wrong** As has been pointed out, you should be wary of applying a `@Past` validation to a `LocalDate` because there's no time zone information. However, if you're using `LocalDate` because everything will just run in the same time zone, or you deliberately want to ignore time zones, or you just don't care, then this is fine for you.
A custom [`LocalValidatorFactoryBean`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/beanvalidation/LocalValidatorFactoryBean.html) bean can configured with the custom mapping and then be wired as a Spring Bean, replacing the default autowired Spring Boot validator: ```java @Configuration public class ValidationConfig { @Bean public LocalValidatorFactoryBean defaultValidator() { return new CustomValidatorFactoryBean(); } private static class CustomValidatorFactoryBean extends LocalValidatorFactoryBean { @Override protected void postProcessConfiguration(Configuration<?> configuration) { HibernateValidatorConfiguration hibernateConfiguration = (HibernateValidatorConfiguration) configuration; ConstraintMapping constraintMapping = hibernateConfiguration.createConstraintMapping(); constraintMapping .constraintDefinition(Future.class) .validatedBy(LocalDateFutureValidator.class) .includeExistingValidators(true); hibernateConfiguration.addMapping(constraintMapping); } } } ``` Note that Spring does not automatically inject or otherwise automatically handle validators as beans, so the `@Component` annotation on `LocalDateFutureValidator` is not needed, is not accomplishing anything, and is misleading. It should therefore be removed. Note also that newer versions of Hibernate Validator have `LocalDate` `@Future` functionality by default, so this approach is no longer necessary for `LocalDate` validation. However, this approach is still useful for custom `ConstraintValidator`s for types that are not built in. Explanation ----------- First, note that Spring does not automatically inject or otherwise handle validators as beans, so the `@Component` annotation on `LocalDateFutureValidator` is not needed, is not accomplishing anything, and is misleading. It should therefore be removed. The [Hibernate Bean Validation reference guide](https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single) has [a section](https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-constraint-definition-contribution) devoted to adding constraint definitions. It discusses two ways of adding constraint definitions: via Java's [`ServiceLoader`](http://docs.oracle.com/javase/8/docs/api/?java/util/ServiceLoader.html) and programmatically. For this answer, I will discuss how to add them programmatically. Using this approach, your new constraint could be added to the Hibernate configuration as follows: ```java HibernateValidatorConfiguration hibernateConfiguration = [...]; ConstraintMapping constraintMapping = hibernateConfiguration.createConstraintMapping(); constraintMapping .constraintDefinition(Future.class) .validatedBy(LocalDateFutureValidator.class) .includeExistingValidators(true); hibernateConfiguration.addMapping(constraintMapping); ``` In order to do this, we need to modify the `HibernateValidatorConfiguration` used by the application's validator. The [`LocalValidatorFactoryBean`](https://docs.spring.io/spring-framework/docs/5.3.3/javadoc-api/org/springframework/validation/beanvalidation/LocalValidatorFactoryBean.html) class is the bean factory type used by Spring: > > This is the central class for `javax.validation` (JSR-303) setup in a Spring application context: It bootstraps a `javax.validation.ValidationFactory` and exposes it through the Spring [`Validator`](https://docs.spring.io/spring-framework/docs/5.3.3/javadoc-api/org/springframework/validation/Validator.html) interface as well as through the JSR-303 [`Validator`](https://docs.oracle.com/javaee/7/api/javax/validation/Validator.html?is-external=true) interface and the [`ValidatorFactory`](https://docs.oracle.com/javaee/7/api/javax/validation/ValidatorFactory.html?is-external=true) interface itself. > > > Spring Boot provides a bean of this type through the `defaultValidator` bean per [`ValidationAutoConfiguration.defaultValidator()`](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.html#defaultValidator--). This bean definition is annotated with `@ConditionalOnMissingBean(Validator.class)`, which means your Boot app can replace it by declaring its own `Validator` bean, such as a `LocalValidatorFactoryBean`. To add custom mappings, one can extend `LocalValidatorFactoryBean` and override the protected [`postProcessConfiguration`](https://docs.spring.io/spring-framework/docs/5.3.3/javadoc-api/org/springframework/validation/beanvalidation/LocalValidatorFactoryBean.html#postProcessConfiguration-javax.validation.Configuration-) method: ```java public class CustomValidatorFactoryBean extends LocalValidatorFactoryBean { @Override protected void postProcessConfiguration(Configuration<?> configuration) { HibernateValidatorConfiguration hibernateConfiguration = (HibernateValidatorConfiguration) configuration; ConstraintMapping constraintMapping = hibernateConfiguration.createConstraintMapping(); constraintMapping .constraintDefinition(Future.class) .validatedBy(LocalDateFutureValidator.class) .includeExistingValidators(true); hibernateConfiguration.addMapping(constraintMapping); } } ``` All that's left at this point is to wire it into the Spring context so that it replaces the default `Validator` bean. This can be done by using a `@Configuration` class with a `@Bean` definition method, or by annotating the `CustomValidatorFactoryBean` class as a `@Component`.
19,780,029
Here is the code. 5000 bouncing spinning red squares. (16x16 png) On the pygame version I get 30 fps but 10 fps with pyglet. Isnt OpenGl supposed to be faster for this kind of thing? pygame version: ``` import pygame, sys, random from pygame.locals import * import cProfile # Set FPS FPS = 60.0 clock = pygame.time.Clock() # Set window WINDOWWIDTH= 800 WINDOWHEIGHT = 600 pygame.init() screen = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT)) screen.fill((0,0,0)) background = screen.copy().convert() image = pygame.image.load("square.png").convert() class Square(object): def __init__(self,x,y): self.x = x self.y = y self.v_x = random.randint(1,100) self.v_y = random.randint(1,100) self.v_r = random.randint(-100,100) self.rotation = 0 def __rep__(self): return "Square %d,%d"%(self.x,self.y) def update(self,dt): if self.x > WINDOWWIDTH: self.v_x *= -1 elif self.x < 0: self.v_x *= -1 if self.y > WINDOWHEIGHT: self.v_y *= -1 elif self.y < 0: self.v_y *= -1 self.x += self.v_x * dt self.y += self.v_y * dt self.rotation += self.v_r * dt def draw(self): screen.blit(pygame.transform.rotate(image,self.rotation),(self.x,self.y)) sqrs = [] for _ in range(5000): sqrs.append( Square(random.randint(0,WINDOWWIDTH-1),random.randint(0,WINDOWHEIGHT-1)) ) def main_loop(): tick = 0.0 elapsed = 0.0 while elapsed < 10.0: dt = tick/1000.0 # Events for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # Logic for s in sqrs: s.update(dt) # Drawing screen.blit(background,(0,0)) for s in sqrs: s.draw() pygame.display.update() pygame.display.set_caption('test program FPS: %s'%(clock.get_fps() ) ) tick = clock.tick(FPS) elapsed += tick/1000.0 pygame.quit() cProfile.run("main_loop()") i = input("...") ``` pyglet version: ``` import cProfile import pyglet, random # Disable error checking for increased performance pyglet.options['debug_gl'] = False from pyglet import clock clock.set_fps_limit(60) WINDOWWIDTH = 800 WINDOWHEIGHT = 600 FPS = 60.0 batch = pyglet.graphics.Batch() window = pyglet.window.Window(WINDOWWIDTH,WINDOWHEIGHT) fps_display = pyglet.clock.ClockDisplay() image = pyglet.resource.image("square.png") class Square(pyglet.sprite.Sprite): def __init__(self,x,y): pyglet.sprite.Sprite.__init__(self,img = image,batch=batch) self.x = x self.y = y self.v_x = random.randint(1,100) self.v_y = random.randint(1,100) self.v_r = random.randint(-100,100) def update(self,dt): if self.x > WINDOWWIDTH: self.v_x *= -1 elif self.x < 0: self.v_x *= -1 if self.y > WINDOWHEIGHT: self.v_y *= -1 elif self.y < 0: self.v_y *= -1 self.x += self.v_x * dt self.y += self.v_y * dt self.rotation += self.v_r * dt sqrs = [] for _ in range(5000): sqrs.append( Square(random.randint(0,WINDOWWIDTH-1),random.randint(0,WINDOWHEIGHT-1)) ) elapsed = 0.0 def update(dt): global elapsed elapsed += dt if elapsed >= 10.0: clock.unschedule(update) window.close() else: for s in sqrs: s.update(dt) @window.event def on_draw(): window.clear() batch.draw() fps_display.draw() clock.schedule_interval(update, 1.0/FPS) if __name__ == '__main__': cProfile.run("pyglet.app.run()") c = input("...") ``` cProfile result for pygame: ``` 5341607 function calls in 9.429 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 9.429 9.429 <string>:1(<module>) 1335000 2.259 0.000 2.259 0.000 pygame-test.py:32(update) 1335000 1.323 0.000 5.969 0.000 pygame-test.py:46(draw) 1 0.772 0.772 9.429 9.429 pygame-test.py:55(main_loop) 1 0.000 0.000 9.429 9.429 {built-in method exec} 267 0.020 0.000 0.020 0.000 {built-in method get} 1 0.237 0.237 0.237 0.237 {built-in method quit} 1335000 3.479 0.000 3.479 0.000 {built-in method rotate} 267 0.013 0.000 0.013 0.000 {built-in method set_caption} 267 0.067 0.000 0.067 0.000 {built-in method update} 1335267 1.257 0.000 1.257 0.000 {method 'blit' of 'pygame.Surface' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 267 0.000 0.000 0.000 0.000 {method 'get_fps' of 'Clock' objects} 267 0.001 0.000 0.001 0.000 {method 'tick' of 'Clock' objects} ``` Pyglet cProfile output: - Very long, this is partial output, full version [here](http://pastebin.com/s52Vvdfy). ``` 9982775 function calls (9982587 primitive calls) in 10.066 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 123 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:1596(_handle_fromlist) 1 0.000 0.000 10.067 10.067 <string>:1(<module>) 11 0.000 0.000 0.000 0.000 __init__.py:1055(_ensure_string_data) 11 0.000 0.000 0.000 0.000 __init__.py:1061(_get_gl_format_and_type) 58 0.000 0.000 0.000 0.000 __init__.py:1140(clear) 75 0.000 0.000 0.012 0.000 __init__.py:1148(dispatch_event) 1 0.000 0.000 10.067 10.067 __init__.py:115(run) ... 1 0.000 0.000 0.000 0.000 lib.py:124(decorate_function) 1108 0.005 0.000 0.005 0.000 lib_wgl.py:80(__call__) 285000 1.409 0.000 9.872 0.000 pyglet-test.py:29(update) 58 0.105 0.002 9.982 0.172 pyglet-test.py:49(update) ... 855000 5.436 0.000 7.551 0.000 sprite.py:378(_update_position) 285000 0.172 0.000 2.718 0.000 sprite.py:441(_set_x) 851800 0.177 0.000 0.177 0.000 sprite.py:445(<lambda>) 285000 0.174 0.000 2.670 0.000 sprite.py:451(_set_y) 851115 0.155 0.000 0.155 0.000 sprite.py:455(<lambda>) 285000 0.182 0.000 2.692 0.000 sprite.py:461(_set_rotation) 285000 0.051 0.000 0.051 0.000 sprite.py:465(<lambda>) ... 4299 0.007 0.000 0.025 0.000 vertexattribute.py:308(get_region) 1 0.000 0.000 0.000 0.000 vertexattribute.py:380(__init__) 116 0.000 0.000 0.000 0.000 vertexattribute.py:384(enable) 116 0.000 0.000 0.000 0.000 vertexattribute.py:387(set_pointer) 1 0.000 0.000 0.000 0.000 vertexattribute.py:461(__init__) 116 0.000 0.000 0.000 0.000 vertexattribute.py:466(enable) 116 0.000 0.000 0.000 0.000 vertexattribute.py:469(set_pointer) 1 0.000 0.000 0.000 0.000 vertexattribute.py:501(__init__) 116 0.000 0.000 0.000 0.000 vertexattribute.py:508(enable) 116 0.000 0.000 0.000 0.000 vertexattribute.py:511(set_pointer) 3 0.000 0.000 0.000 0.000 vertexbuffer.py:293(__init__) 348 0.000 0.000 0.001 0.000 vertexbuffer.py:311(bind) 348 0.000 0.000 0.001 0.000 vertexbuffer.py:314(unbind) 3 0.000 0.000 0.000 0.000 vertexbuffer.py:381(__init__) 348 0.001 0.000 0.004 0.000 vertexbuffer.py:388(bind) 4299 0.006 0.000 0.016 0.000 vertexbuffer.py:420(get_region) 3 0.000 0.000 0.000 0.000 vertexbuffer.py:424(resize) 4299 0.002 0.000 0.002 0.000 vertexbuffer.py:460(__init__) 855232 0.735 0.000 1.053 0.000 vertexbuffer.py:466(invalidate) ... 855058 0.687 0.000 1.762 0.000 vertexdomain.py:581(_get_vertices) ... 4300 0.002 0.000 0.002 0.000 {built-in method POINTER} ... 841451 0.162 0.000 0.162 0.000 {built-in method cos} ... 2417/2415 0.000 0.000 0.000 0.000 {built-in method len} 855489 0.142 0.000 0.142 0.000 {built-in method max} 855469 0.176 0.000 0.176 0.000 {built-in method min} 465/407 0.000 0.000 0.000 0.000 {built-in method next} ... 841451 0.072 0.000 0.072 0.000 {built-in method radians} 62 0.000 0.000 0.000 0.000 {built-in method setattr} 841451 0.120 0.000 0.120 0.000 {built-in method sin} ... ```
2013/11/05
[ "https://Stackoverflow.com/questions/19780029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2953823/" ]
You can find more detailed information about the Ignore() function in the [SCons man pages](http://www.scons.org/doc/production/HTML/scons-man.html). Here is the signature according to the man pages: ``` Ignore(target, dependency) env.Ignore(target, dependency) ``` You should be able to do the following: ``` # assuming aTarget, bTarget, cTarget, and F are set accordingly Ignore(aTarget, F) Ignore(bTarget, F) Ignore(cTarget, F) ``` There are several different ways to handle Command Line options in SCons, [here](http://www.scons.org/doc/production/HTML/scons-user/c2092.html#sect-command-line-options) is an overview: The simplest way is [this](http://www.scons.org/doc/production/HTML/scons-user/x2445.html), that would allow you to do the following: ``` useF = ARGUMENTS.get('includeF', 0) if not int(useF): Ignore(aTarget, F) Ignore(bTarget, F) Ignore(cTarget, F) ``` And the command line would look something like this: ``` #scons includeF=1 ```
Well, I thought of a workaround. I made a commandline variable that I use to determine whether the build is rooted at F. It seems like there is probably a "SCons" way to do it that I'm missing, but I think this is fine. ``` do_abc = False for key, value in ARGLIST: if key == "do_abc": do_abc = bool(value) if do_abc: ABCbuilder = Builder(action = build_abc) env = Environment(BUILDERS = {'abc' : ABCbuilder,...} env.abc([A,B,C],[F]) else: env = Environment(BUILDERS = {...}) ```
129,990
So recently I decided to create a Star Wars D&D campaign. It starts out with the group as Mandalorian bounty hunters. However, before I make this officially start, I need to know if I can use other races for the players such as Zabraks, Trandoshans, Rodians, etc. Do Mandalorians consist of humans only or are there aliens in their ranks? If not, can there be aliens or will I have to think of a new start?
2016/06/04
[ "https://scifi.stackexchange.com/questions/129990", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/67074/" ]
Choice of race will never restrict you in any way to play through any storyline in swtor. As for story/lore/RPG i direct you to [this wiki page.](http://swtor.wikia.com/wiki/Mandalorian) > > *"An **interspecies** warrior culture stretching back thousands of years, the Mandalorians live for one purpose: to challenge the > greatest opponents in combat and claim victory, for honor and glory."* > > >
Legends: -------- In Legends, Mandalorians used to all be aliens, comprised of the [Taung](http://starwars.wikia.com/wiki/Taung). Many different species later went on to join them. > > Here's why you can't exterminate us, aruetii. We're not huddled in one place—we span the galaxy. We need no lords or leaders—so you can't destroy our command. We can live without technology—so we can fight with our bare hands. We have no species or bloodline—so we can rebuild our ranks with others who want to join us. We're more than just a people or an army, aruetii. We're a culture. We're an idea. And you can't kill ideas—but we can certainly kill you. > > > * [Mandalore the Destroyer](http://starwars.wikia.com/wiki/Mandalore_the_Destroyer) Canon: ------ Prior to Grogu, we only ever see human Mandalorians. However, it is never explicably stated that aren't any other non-humans and no one seems perturbed by Grogu's species. --- In the end, it's your campaign. You can do whatever you want.
7,969,109
As I've pointed out - [here](https://stackoverflow.com/questions/5587140/any-tutorial-on-how-to-use-clang-for-syntax-highlighting-and-code-completion/7250322#7250322) - it seems clang's libclang should be great for implementing the hard task that is C/C++ code analysis and modifications ([check out video presentation and slides](https://stackoverflow.com/questions/5587140/any-tutorial-on-how-to-use-clang-for-syntax-highlighting-and-code-completion/7250322#7250322)). Do you know of **any** C/C++ refactoring tool based on libclang ? "Any" includes even simple alpha state project, with support of one refactoristation technique. It can be without preprocessor support. As an example of the functionally about which I'm talking: changing method names, whether it supports multiple files or only one file at a time. You might be wondering what the goal is of asking for even small working examples My thought is that *creating a list of code examples and small tools that are in one place will provide a better resource to learn how to implement refactorisation with libclang*. I believe that from simple projects might grow bigger projects - in a proper opensource manner :).
2011/11/01
[ "https://Stackoverflow.com/questions/7969109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544721/" ]
Google have been working on a tooling library for Clang. [In since the 3.2 release](http://llvm.org/svn/llvm-project/cfe/branches/release_32/include/clang/ASTMatchers/). It includes a ASTMatchers library so you can just build up a query and don't have to walk the AST. There is a [great video talk](http://www.youtube.com/watch?v=yuIOGfcOH0k) on the subject that walks through a simple rename example. (This is from the same guy as the [MapReduce talk](https://www.youtube.com/watch?v=mVbDzTM21BQ) posted above but is newer and more about a simple practical implementation rather than the internal design and enterprise scale stuff Google have going on). The source for that example that renames a method is available in the [tooling branch](http://llvm.org/svn/llvm-project/cfe/branches/tooling/examples/rename-method/). It may be somewhere in the trunk but I can't find it. Also Rename the getDeclAs function to getNodesAs as the other is [apparently deprecated](http://clang.llvm.org/doxygen/classclang_1_1ast__matchers_1_1BoundNodes.html#a748143159c4cf50c2b01ed799f62d337).). There is a more [advanced example that removes duplicated c\_str calls](http://llvm.org/svn/llvm-project/clang-tools-extra/trunk/remove-cstr-calls/) (which is in trunk and someone posted above). Here is documentation for [LibASTMatchers](http://clang.llvm.org/docs/LibASTMatchers.html) and [LibTooling](http://clang.llvm.org/docs/LibTooling.html). EDIT: Some better docs for ASTMatcher. [Here](http://clang.llvm.org/docs/LibASTMatchers.html) and [here](http://clang.llvm.org/docs/LibASTMatchersReference.html). EDIT: [Google are now working on something called Clangd](http://www.phoronix.com/scan.php?page=news_item&px=MTEyMTE) which aims to be some kind of Clang server for refactoring.
Google made a Clang based refactoring tool for their C++ code base and plans to release it. I don't know the current state of the project, but you can see this demo presented on the 2011 LLVM Developers Meeting: <https://www.youtube.com/watch?v=mVbDzTM21BQ>. Also, XCode's (4+) built-in auto-completion and refactoring functions are based on libclang.
45,018
My Sony earphones are damaged, I've got other earphones (non-SONY) but are not accepted by the phone. Is there a way to make them work ??
2013/05/07
[ "https://android.stackexchange.com/questions/45018", "https://android.stackexchange.com", "https://android.stackexchange.com/users/33574/" ]
There are different standards for headset plugs, and Sony has started using the CTIA layout for it's smartphones since 2012. I couldn't find the official documentation on the differences, but it's pretty well explained [here](http://www.martzell.de/2012/12/pin-belegung-headset-iphone-omtp-ctia.html) (In german, but the pictures speak for themselves). The gist is, on regular headsets the order of the pins is ground-mic-right-left, but on CTIA it's mic-ground-right-left. To get regular headsets working, you'll have to use an adapter, but if I'm understanding this correctly, headphones (that is, without a microphone) should work normally.
You can try Nokia's headphones. I think they will work with them.
18,928,216
It may be asked somewhere but I could not find it. Please tell me the exact difference between: ``` ArrayList list = new ArrayList(); ``` and ``` ArrayList<?> list = new ArrayList(); ``` I cannot figure out what is the exact difference between these two. Thanks...
2013/09/21
[ "https://Stackoverflow.com/questions/18928216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2801200/" ]
``` ArrayList list = new ArrayList(); ``` We are declaring an array list that can accept any type of objects. For example: ``` list.add(new Dog()); list.add(new Person()); list.add("Test"); ``` For `ArrayList<?> list = new ArrayList();` We are declaring an array list using generics that can accept any object using the wild card **?** The catch here is that we cannot add elements to that array list. This code will not even compile: ``` ArrayList<?> list = new ArrayList(); list.add("test"); ``` **Update**: I think the only purpose of the ? wild card in generics is to be coupled by the extends keyword. ``` ArrayList<? extends Animal> list = new ArrayList<Dog>(); ``` In that case we add any object to **list** that extends the **Animal** object or to be passed to as a parameter to a method. ``` public void foo(List<?> list) { } ``` In that case the method **foo** cannot add objects to the parameter **list**
ArrayList < ? > means array list of type unknown. it is called a wildcard type. Using the wild card, the following occurs ``` Collection<?> c = new ArrayList<String>(); c.add(new Object()); // Compile time error ``` Without the wildcard you can add whatever you like to your array
66,866,092
I'm exploring what's possible to do in Python and recently came across this question: after running a function, is it possible to programmatically determine whether it has referenced anything out-of-scope? For example: ``` import module1 y = 1 def foo1(x): return y + x # yes - it has referenced 'y' which is out of foo1 scope def foo2(x): return module1.function1(x) # yes - it has referenced 'module1' which is out of foo2 scope def foo3(x): return x*x # no - it has only referenced 'x' which is an input to foo3, so the code executed within the scope of foo3 ``` Are there some reflection / analysis tools for this? Maybe this could be achieved with the 'trace' module somehow?
2021/03/30
[ "https://Stackoverflow.com/questions/66866092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9223023/" ]
You can use [`inspect.getclosurevars`](https://docs.python.org/3/library/inspect.html#inspect.getclosurevars): > > Get the mapping of external name references in a Python function or > method func to their current values. A named tuple > ClosureVars(nonlocals, globals, builtins, unbound) is returned. > nonlocals maps referenced names to lexical closure variables, globals > to the function’s module globals and builtins to the builtins visible > from the function body. unbound is the set of names referenced in the > function that could not be resolved at all given the current module > globals and builtins. > > > Let's see what it returns for your examples: **Case 1:** ```py def foo1(x): return y + x # yes - it has referenced 'y' which is out of foo1 scope inspect.getclosurevars(foo1) # ClosureVars(nonlocals={}, globals={'y': 1}, builtins={}, unbound=set()) ``` Here it detected you are using variable in the global scope. **Case 2:** ```py import colorsys def foo2(x): return colorsys.rgb_to_hsv(*x) # yes - it has referenced 'colorsys' which is out of foo2 scope inspect.getclosurevars(foo2) # ClosureVars(nonlocals={}, globals={'colorsys': <module 'colorsys' from '...\\lib\\colorsys.py'>}, builtins={}, unbound={'rgb_to_hsv'}) ``` Here it detected you are using a module's function. **Case 3:** ```py def foo3(x): return x*x # no - it has only referenced 'x' which is an input to foo3, so the code executed within the scope of foo3 inspect.getclosurevars(foo3) # ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) ``` Here we see "nothing unusual". Therefore, we can wrap this procedure in a function which looks if `any` of the fields (except for built-ins; i.e. `foo` can use `abs` and no problem) is non-empty: ```py import inspect def references_sth_out_of_scope(fun): closure_vars = inspect.getclosurevars(fun) referenced = any(getattr(closure_vars, field) for field in closure_vars._fields if field != "builtins") return referenced ``` Usage: ```py >>> references_sth_out_of_scope(foo1) True >>> references_sth_out_of_scope(foo2) True >>> references_sth_out_of_scope(foo3) False >>> references_sth_out_of_scope(references_sth_out_of_scope) # :) True ```
Check the builtin [locals()](https://docs.python.org/3/library/functions.html#locals) function. This will return a dictionary of the variables in the local scope. ```python global_var = "Hello" def foo(): local_var = "world" if "local_var" in locals(): print(c) if "global_var" in locals(): print(global_var) >>> foo() world ```
18,072,759
I have this nested list: ``` l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']] ``` I want to convert each element in `l` to `float`. I have this code: ``` newList = [] for x in l: for y in x: newList.append(float(y)) ``` How can I solve the problem with a nested list comprehension instead? --- See also: [How can I get a flat result from a list comprehension instead of a nested list?](https://stackoverflow.com/questions/1077015)
2013/08/06
[ "https://Stackoverflow.com/questions/18072759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1214293/" ]
I wanted to share how the list comprehension actually works, especially for nested list comprehensions: ``` new_list= [float(x) for x in l] ``` is actually the same as: ``` new_list=[] for x in l: new_list.append(float(x)) ``` And now for the nested list comprehension: ``` [[float(y) for y in x] for x in l] ``` is the same as: ``` new_list=[] for x in l: sub_list=[] for y in x: sub_list.append(float(y)) new_list.append(sub_list) print(new_list) ``` output: ``` [[40.0, 20.0, 10.0, 30.0], [20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0], [30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0], [100.0, 100.0], [100.0, 100.0, 100.0, 100.0, 100.0], [100.0, 100.0, 100.0, 100.0]] ```
In case a flattened list is needed: ``` [y for x in l for y in x] ``` In case a nested list (list in list) is needed: ``` [[float(y) for y in x] for x in l] ```
2,900,904
I'm working on a Linux kernel module for a 2.6.x kernel and I need to view the assembly output, though it's currently being done as a temporary file an deleted afterwords. I'd like to have the assembly output mixed with my C source file so I can easily trace where my problem lies. This is for an ARMv6 core and apparently objdump doesn't support this architecture. I've included my makefile below. ``` ETREP=/xxSourceTreexx/ GNU_BIN=$(ETREP)/arm-none-linux-gnueabi/bin CROSS_COMPILE := $(GNU_BIN)/arm-none-linux-gnueabi- ARCH := arm KDIR=$(ETREP)/linux-2.6.31/ MAKE= CROSS_COMPILE=$(CROSS_COMPILE) ARCH=$(ARCH) make obj-m += xxfile1xx.o all: $(MAKE) -C $(KDIR) M=$(PWD) modules clean: $(MAKE) -C $(KDIR) M=$(PWD) clean ```
2010/05/24
[ "https://Stackoverflow.com/questions/2900904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99065/" ]
Assuming gcc and the gnu assembler a more readable output than `objdump` can be had. Tell the assembler to retain its intermediate code using flags to gcc: ``` -Wa,-alh=basename.s ``` And to get `basename` to be the actual source filename you need to tell make: ``` -Wa,-alh=$<.s ``` which will leave piles of foo.c.s files laying around your source directory. The big problem here is that the way gcc works it uses temporary files between code generation and assembly. I can't find a way to make gcc save its intermediates but the assembler is happy to stash a listing for you. Getting that argument into the Makefile CFLAGS is left as an exercise for the reader (because I kinda hate "make" and hate "gnu info" even more.
To get an assembly language listing of my Linux kernel modules, I added the assembler switches to the kernel scripts/Makefile.build. ``` #cmd_cc_o_c = $(CC) $(c_flags) -c -o $(@D)/.tmp_$(@F) $< cmd_cc_o_c = $(CC) $(c_flags) -c -Wa,-alh=$<.lst -o $(@D)/.tmp_$(@F) $< ```
2,508,073
greetings all, when trying to commit into tortoise svn using cruise control i am getting an exception ``` [SVN commit: warn] source control failure (GetModifications): Unable to execute file [ c:\sand\doc\svn ]. The file may not exist or may not be executable. ``` where "c:\sand\doc" is my working directory. In this dir structure nowhere i have a dir named svn. The structure only contains "**.svn**" folder. can any one help in resolving this exception... regards. **pratap**
2010/03/24
[ "https://Stackoverflow.com/questions/2508073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300529/" ]
You need to add the folder containing svn.exe to your path on the CC server, or specify a full path to the exe where you attempt the commit.
It sounds like it's trying to find the svn executable in the c:\sand\ folder, so I'm guessing that you've mixed up your configuration somewhere?
44,374,074
So my issue is pretty simple. I have some files that I want to be copied to the build output directory whether it is a debug build or a release publish. All of the information I can find is about the old json config approach. Anyone have an example using the csproj with dotnetcore?
2017/06/05
[ "https://Stackoverflow.com/questions/44374074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3887945/" ]
I had the requirement for a selection of HTML templates to be consumable both client-side and server-side (Handlebars js) ```xml <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp2.0</TargetFramework> </PropertyGroup> <ItemGroup> <Content Update="wwwroot\html-templates\**\*.*"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> </Project> ```
```xml <PropertyGroup> <PostBuildEvent>xcopy "$(ProjectDir)Xml" "$(ProjectDir)$(OutDir)Xml" /S /F /I /R /Y</PostBuildEvent> </PropertyGroup> ``` or ```xml <PropertyGroup> <PostBuildEvent>copy /Y "$(ProjectDir)MyXml.xml" "$(ProjectDir)$(OutDir)Xml"</PostBuildEvent> </PropertyGroup> ```
32,427,921
I have a Spring MVC application (Spring Boot v. 1.2.5) that uses JPA to interact with a popular Sql Database. Thus, I have several entities mapping all the tables in the db. Clearly, these classes are having only getters/setters and annotations for the relations between entities. E.g.: ``` @Entity @Table public class Article { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonView(View.Private.class) private Long id; @Column(nullable = false) @JsonView(View.Public.class) private String name; @ManyToOne(optional = false, fetch = FetchType.LAZY) @JoinColumn(name = "categoryId", nullable = false, updatable = false) @JsonIgnore private Category category; //Constructors Getters and Setters ... } ``` My question is: should I unit test these classes? What should I test? How
2015/09/06
[ "https://Stackoverflow.com/questions/32427921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1983997/" ]
You should test functionality not class. If you are not sure if mapping is working correctly, then maybe testing save/load of objects of this class is suitable test for you. However, unit testing should also isolate persistence layer, so you can test your business logic instead of persistence layer.
JUnit test for JPA entity with code coverage ``` public class ArticleTest { public Article crateTestSuite(){ return new Article (); } @Test public void testGetId() { Long id= 0; Xyz xyz =null; xyz = crateTestSuite(); id = xyz.getId() } @Test public void setId(Integer id) { Long id= 0; Xyz xyz =null; xyz = crateTestSuite(); xyz.setId(id) } } ```
25,762
Every letter a decimal digit, different letters for different digits: ``` BASE + BALL -------- GAMES ``` Which digit does each letter represent?
2016/01/25
[ "https://puzzling.stackexchange.com/questions/25762", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/9404/" ]
Assuming numbers can't start with 0, `G` is 1 because two four-digit numbers can't sum to 20000 or more. `SE`+`LL`=`ES` or `1ES`. If it is `ES`, then `LL` must be a multiple of 9 because `SE` and `ES` are always congruent mod 9. But `LL` is a multiple of 11, so it would have to be 99, which is impossible. So `SE`+`LL`=`1ES`. `LL` must be congruent to 100 mod 9. The only multiple of 11 that works is 55, so `L` is 5. `SE`+55=`1ES`. This is possible when `E`+5=`S`. The possibilities for `ES` are 27, 38, or 49. `BA`+`BA`+1=`1AM`. `B` must be at least 5 because `B`+`B` (possibly +1 from a carry) is at least 10. If `A` is less than 5, then `A`+`A`+1 does not carry, and `A` must be even. Inversely, if `A` is greater than 5, it must be odd. The possibilities for `A` are 0, 2, 4, 7, or 9. * 0 does not work because `M` would have to be 1. * 2 and 7 don't work because `M` would have to be 5. * 9 doesn't work because `M` would also have to be 9. So `A` is 4, `M` is 9, and `B` is 7. This leaves `38` as the only possibility for `ES`. The full equation is: ``` 7483 + 7455 -------- 14938 ```
There are in total three solutions (with unique numbers): ``` G A M E S B L ------------- 0 4 9 1 6 2 5 0 4 9 3 8 2 5 1 4 9 3 8 7 5 ``` So apart from the solution in @f''s answer, we have ``` 2483 + 2455 -------- 04938 ``` and ``` 2461 + 2455 -------- 04916 ```
3,673,388
I tried to prove this: [equation](https://i.stack.imgur.com/NQvLG.png) And I came to: [u=1-x](https://i.stack.imgur.com/N4E6r.png) But now if I replace u by x-1, I get the same equation that needed to be proven. So I do not know actually what to do... Could someone help me?
2020/05/13
[ "https://math.stackexchange.com/questions/3673388", "https://math.stackexchange.com", "https://math.stackexchange.com/users/787890/" ]
You are done with the problem and you do not have to do anything else. Note that x or u are dummy variables and you may simply change u to x as your last step.
The integral $$\int\_a^b f(x) dx$$ is the area under the curve of $f(x)$ as $x$ goes from $a$ to $b$. The integral $$\int\_a^b f(u) du$$ is the area under the curve of $f(u)$ as $u$ goes from $a$ to $b$. These are the same area: $x$ and $u$ are called dummy variables because it doesn't matter which letter you use, the area is the same, because you're adding up the same values of the same function in your Riemann sum. In a similar way, $$\sum\_{n=1}^\infty a\_n = \sum\_{k=1}^\infty a\_k,$$ because again, $n$ and $k$ are simply dummy variables. One last example to make this notion clear: if you add up $$\sum\_{n=1}^3 n \qquad \textrm{or} \qquad \sum\_{k=1}^3 k$$ you will get $$1+2+3=6$$ from both sums. The takeaway: It does not matter what the dummy variable is called. It is irrelevant whether we already used a letter for a previous substitution.
49,424,179
The actual JSON,that I need to parse in swift4 is, ``` { "class": { "semester1": [ { "name": "Kal" }, { "name": "Jack" }, { "name": "Igor" } ], "subjects": [ "English", "Maths" ] }, "location": { "Dept": [ "EnglishDept", ], "BlockNo": 1000 }, "statusTracker": { "googleFormsURL": "beacon.datazoom.io", "totalCount": 3000 } } ``` The code that I'd tried but failed to execute is, ``` struct Class: Decodable { let semester: [internalComponents] let location: [location] let statusTracker: [statusTracker] enum CodingKeys: String, CodingKey { case semester = "semester1" case location = "location" case statusTracker = "statusTracker" } } struct location: Decodable { let Dept: [typesSubIn] let BlockNo: Int } struct statusTracker: Decodable { let googleFormsURL: URL let totalCount: Int } struct internalComponents: Decodable { let semester1: [semsIn] let subjects: [subjectsIn] } struct semsIn: Decodable { let nameIn: String } struct subjectsIn: Decodable { let subjects: String } struct Dept: Decodable { let Depts: String } ``` I know it's completely wrong can someone give the actual format? I'm actually confused with the format for "subjects".It's not compiling as a whole too.
2018/03/22
[ "https://Stackoverflow.com/questions/49424179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8374099/" ]
There are many issues. You are making a common mistake by ignoring the root object partially. Please take a look at the JSON: On the top level there are 3 keys `class`, `location` and `statusTracker`. The values for all 3 keys are dictionaries, there are no arrays. Since `class` (lowercase) is a reserved word, I'm using `components`. By the way please conform to the naming convention that struct names start with a capital letter. ``` struct Root : Decodable { let components : Class let location: Location let statusTracker: StatusTracker enum CodingKeys: String, CodingKey { case components = "class", location, statusTracker } } ``` There are many other problems. Here a consolidated version of the other structs ``` struct Class: Decodable { let semester1: [SemsIn] let subjects : [String] } struct Location: Decodable { let dept : [String] let blockNo : Int enum CodingKeys: String, CodingKey { case dept = "Dept", blockNo = "BlockNo" } } struct SemsIn: Decodable { let name: String } struct StatusTracker: Decodable { let googleFormsURL: String // URL is no benefit let totalCount: Int } ``` Now decode `Root` ``` do { let result = try decoder.decode(Root.self, from: data) } catch { print(error) } ```
There are a few things here causing your issue. * You have no top level item, I added Response struct * Location, class and statusTracker are both at the same level, not under class. * In your class struct, your items are set as arrays but they aren't arrays * To debug these types of issues, wrap your decode in a do catch block and print out the error. it will tell you the reason it failed to parse Try this code from my playground: ``` let jsonData = """ { "class": { "semester1": [{ "name": "Kal" }, { "name": "Jack" }, { "name": "Igor" }], "subjects": [ "English", "Maths" ] }, "location": { "Dept": [ "EnglishDept" ], "BlockNo": 1000 }, "statusTracker": { "googleFormsURL": "beacon.datazoom.io", "totalCount": 3000 } } """.data(using: .utf8)! struct Response: Decodable { let cls: Class let location: Location let statusTracker: statusTracker enum CodingKeys: String, CodingKey { case cls = "class" case location case statusTracker } } struct Class: Decodable { let semester: [SemesterStudents] let subjects: [String] enum CodingKeys: String, CodingKey { case semester = "semester1" case subjects } } struct Location: Decodable { let dept: [String] let blockNo: Int enum CodingKeys: String, CodingKey { case dept = "Dept" case blockNo = "BlockNo" } } struct statusTracker: Decodable { let googleFormsURL: URL let totalCount: Int } struct SemesterStudents: Decodable { let name: String } struct Dept: Decodable { let Depts: String } do { let result = try JSONDecoder().decode(Response.self, from: jsonData) print(result) } catch let error { print(error) } ```
36,813,780
``` import {Component} from 'angular2/core'; @Component({ selector: 'app', styleUrls: ['./app.component.less'], templateUrl: './app.component.html' }) export class AppComponent { name:string = 'Demo' } ``` When using the relative path for templateUrl and styleUrls, I get: error 404, file not found: zone.js: 101 GET <http://localhost/app.component.html> 404 (Not Found) code: <https://github.com/Dreampie/angular2-demo> I think this is not good design,because under different circumstances may build directory is not the same, can I change it to relative current path? `raw-loader` can resolve this,but `html-loader`,`less-loader` not work for `template`,`styles`,it only work in `string`,so why not suport them? ``` import {Component} from 'angular2/core'; @Component({ selector: 'app', styles: [require('./app.component.less')], template: require('./app.component.html') }) export class AppComponent { name:string = 'Demo' } ``` get other error: ``` browser_adapter.js:77 EXCEPTION: Error during instantiation of Token Promise<ComponentRef>!.BrowserDomAdapter.logError browser_adapter.js:77 ORIGINAL EXCEPTION: Expected 'styles' to be an array of strings. ```
2016/04/23
[ "https://Stackoverflow.com/questions/36813780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5540773/" ]
The `./` (single dot) notation works for ts paths only, it doesn't work with html or css paths. These paths are relative to index.html, so according to your file structure, this should work ```ts @Component({ selector: 'app', styleUrls: ['app.component.less'], templateUrl: 'app.component.html' }) ```
You need to try ``` @Component({ selector: 'app', template: require('./app.component.html'), styles: [ require('./app.component.less').toString() or String(require('./app.component.less')) or add css-to-string in your webpack conf ({test: /\.css$/, loaders: ['css-to-string', 'style', 'css']}) }) ```
67,168,344
I have a database table as below. Id 1 and 4 are old members and their data is updated (as seen in updated date column). Id 2 and 3 new members. So now how we can query in SQL Server and get list of members updated/registered for a given date range? [![enter image description here](https://i.stack.imgur.com/gv1ef.png)](https://i.stack.imgur.com/gv1ef.png)
2021/04/19
[ "https://Stackoverflow.com/questions/67168344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14674517/" ]
`coalesce()` would be a good fit here. If `[updated date]` is `NULL`, it will then look at `[registration date]` ``` select * from yourtable where coalesce([updated date],[registration date]) between '2021-01-01' and '2021-01-05' ```
``` select * from your_table where [registration date] between '20210101' and '20220101' ```
6,209,042
Here is my sample code: ``` var http = require('http'); var options1 = { host: 'www.google.com', port: 80, path: '/', method: 'GET' }; http.createServer(function (req, res) { var start = new Date(); var myCounter = req.query['myCounter'] || 0; var isSent = false; http.request(options1, function(response) { response.setEncoding('utf8'); response.on('data', function (chunk) { var end = new Date(); console.log(myCounter + ' BODY: ' + chunk + " time: " + (end-start) + " Request start time: " + start.getTime()); if (! isSent) { isSent = true; res.writeHead(200, {'Content-Type': 'application/xml'}); res.end(chunk); } }); }).end(); }).listen(3013); console.log('Server running at port 3013'); ``` What i found out is that, if I connect to other server, (google or any other), the response will get slower and slower to few seconds. It doesn't happen if I connect to another node.js server within the same network. I use JMeter to test. 50 concurrent per sec with 1000 loop. I have no idea what the problem is... ========================= Further investigation: I run the same script on Rackspace, and also on EC2 for testing. And the script will use http.request to connect to: Google, Facebook, and also my another script that simply output data (like hello world) which is hosted by another EC2 instance. The test tool I just is jMeter on my desktop. Pre-node.js test: jMeter -> Google Result: fast and consistent. jMeter -> Facebook result: fast and consistent. jMeter -> My Simple Output Script Result: fast and consistent. Then I make a 50 Concurrent Threads /sec , with 100 loops, testing to my Rackspace nodejs, and then EC2 node.js which has the same king of performance issue jMeter -> node.js -> Google Result: from 50 ms goes to 2000 ms in 200 requsets. jMeter -> node.js -> Facebook Result: from 200 ms goes to 3000 ms after 200 requsets. jMeter -> node.js -> My Simple Output Script Result: from 100 ms goes to 1000 ms after 200 requsets. The first 10-20 requests are fast, then start slowing down. Then, when I change to 10 Concurrent Threads, things start changing.. The response is very consistent, no slow down. Something to do with # of concurrent threads that Node.js (http.request) can handle. ------------ **More** -------------- I did more test today and here it is: I used http.Agent and increase the max socket. However, the interesting this is that, on one testing server (EC2), it improves a lot and no more slow down. HOwever, the other server (rackspace) only improves a bit. It still shows slow down. I even set "Connection: close" in the request header, it only improves 100ms. if http.request is using connection pooling, how to increase it? in both server, if I do "ulimit -a", the # of file open is 1024. ------------- \*\* **MORE AND MORE** \*\* ------------------- It seems that even I set maxSockets to higher number, it only works at some limit. There seems to be a internal or OS dependent socket limitation. However to bump it up? ------------- \*\* AFTER EXTENSIVE TESTING \*\* --------------- After reading lots of post, I find out: --- --- quoted from: <https://github.com/joyent/node/issues/877> --- 1) If I set the headers with connection = 'keep-alive', the performance is good and can go up to maxSocket = 1024 (which is my linux setting). ``` var options1 = { host: 'www.google.com', port: 80, path: '/', method: 'GET', **headers: { 'Connection':'keep-alive' }** }; ``` If I set it to "Connection":"close", the response time would be 100 times slower. Funny things happened here: 1) in EC2, when I first test with Connection:keep-alive, it will take about 20-30 ms. Then if I change to Connection:Close OR set Agent:false, the response time will slow down to 300 ms. WIHTOUT restarting the server, if I change to Connection:keep-alive again, the response time will slow down even further to 4000ms. Either I have to restart server or wait for a while to get back my 20-30ms lighting speed response. 2) If I run it with agent:false, at first, the response time will slow down to 300ms. But then, it will get faster again and back to "normal". My guess is connection pooling still in effect even you set agent:false. However, if you keep connection:keep-alive, then it will be fast for sure. just don't switch it. --- --- --- Update on July 25, 2011 I tried the latest node.js V0.4.9 with the http.js & https.js fix from <https://github.com/mikeal/node/tree/http2> the performance is much better and stable.
2011/06/01
[ "https://Stackoverflow.com/questions/6209042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196874/" ]
I solved the problem with ``` require('http').globalAgent.maxSockets = 100000 ``` or ``` agent = new http.Agent() agent.maxSockets = 1000000 # 1 million http.request({agent:agent}) ```
Github issue 877 may be related: <https://github.com/joyent/node/issues/877> Though it's not clear to me if this is what you're hitting. The "agent: false" workaround worked for me when I hit that, as did setting a "connection: keep-alive" header with the request.
12,040,387
I have a JSON associate array ``` [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}] ``` and I want to make it so that it becomes an array where ``` { theatre = Test time = 5:00pm }, { theatre = Testing2 time = 4:30 pm } ``` But I can't figure out how to take a key name and make it a value... Any help? I was looking at `Object.keys` but I couldn't find a suitable solution.
2012/08/20
[ "https://Stackoverflow.com/questions/12040387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150062/" ]
You have an array with object values. You'd need to loop over them: ``` var oldArray = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]; var newArray = []; for (var i = 0; i < oldArray.length; i++) { var keys = Object.keys(oldArray[i]); newArray.push({ theatre: keys[0], time: oldArray[i][keys[0]] }); } ``` <http://jsfiddle.net/FNAtw/> This will give you an array stored in `newArray` with two elements. The first element is an object with kvps `theatre: 'Test'` and `time: '5:00pm'`. The second element is an object with kvps `theatre: 'Testing2'` and `time: '4:30pm'`.
``` var result = []; var str = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]; for (var i = 0; i < str.length; i++) { var obj = {}; foreach (var key in str[i]) { obj.theatre = key; obj.time = str[i][key]; } result.push(obj); } ```
35,819,410
I have a code that should do exactly this: ``` A = [2;3;4;5;6;7]; b = 2; B(10).b = zeros(6,1); for i = 1:10 C = A; B(i).b = C.*(b^i); if i>1 if B(i).b(1,1)-B(i-1).b(1,1)>50 C(7) = b; end end end ``` The problem is that in every iteration C matrix is replaced with the values in matrix A. This is simplified version of my code, but the essence is here, and the code should do exactly this, at some point if a criteria is met, add another row to matrix C and continue executing the code with that row in matrix C. Is it possible to do that? I'd appreciate ideas very much. Thank you.
2016/03/05
[ "https://Stackoverflow.com/questions/35819410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5178805/" ]
You can append b to C and overwrite the value of C with the newly created value: ``` if i>1 if B(i).b(1,1)-B(i-1).b(1,1)>50 C = [C; b]; end end ``` This should work just fine as long as C & b are not too large.
It is not recommended to change the matrix size during execution because you loose runtime. The best solution is to estimate the size of the matrix at the very beginning. If there is no other possibility, you can add a row by the following code: ``` A = [1 2; 3 4]; A = vertcat(A,[2 3]); ``` The same works also for columns: ``` A = [1 2; 3 4]; A = horzcat(A,[2; 3]); ``` To take away a row, just write (here for row 2): ``` A(2,:) = []; ``` The same works with columns: ``` A(:,2) = []; ``` To change only selective parts of a matrix, the following can be done (some examples): ``` A(1:2,1) = [2 3]; % change row A(1,1:2) = [2;3]; % change column A(2,1) = 5; % change single cell ``` This is exactly what Rashid does with the statement C(1:6) = A;. Because it is only a column vector, the indices refer to the columns. It is equivalent to C(1,1:6)=A; Then it is only a question of implementation to put around an if-statement with your desired condition. Best regards
18,769,368
I have a QT dialog which I need to have access to from anywhere in the program. Basically what I need to do is something like creating a static instance of it somewhere in my program, something like: '''Note''': This is just an example of what I am trying to do, not actual code (which is too long to post here) ``` class Core { public: static DialogType *MyDialog; }; DialogType *Core::MyDialog = NULL; // later in main.cpp int main(int argc, char *argv[]) { try { Core::Init(); QApplication a(argc, argv); Core::MyDialog = new DialogType(); ... ``` However, despite this would work for any other type, it just doesn't work for classes that are inherited from QDialog. The compiler just return: DialogType does not name a type (and yes I do #include that .h file with declaration of DialogType) What am I doing wrong? Why QT doesn't allow that? How could I make it possible to access single instance of my dialog from ANY class anywhere in the program?
2013/09/12
[ "https://Stackoverflow.com/questions/18769368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514983/" ]
The short answer is there is no way to accurately do this, especially with just pure SQL. You can find exact matches, and you can find wildcard matches using the `LIKE` operator or a (potentially huge) series of regular expressions, but you cannot find *similar* matches nor can you find potential misspellings of matches. There's a few potential approaches I can think of to solve this problem, depending on what type of application you're building. **First, normalize the merchant data in your database.** I'd recommend *against* storing the exact, unprocessed string such as *Bruger King* in your database. If you come across a merchant that doesn't match a known set of merchants, ask the user if it already matches something in your database. When data goes in, process it then and match it to an existing known merchant. **Store a similarity coefficient**. You might have some luck using something like a [Jaccard index](http://en.wikipedia.org/wiki/Jaccard_index) to judge how *similar* two strings are. Perhaps after stripping out the numbers, this could work fairly well. At the very least, it could allow you to create a user interface that can attempt to guess what merchant it is. Also, some database engines have full-text indexing operators that can descibe things like *similar to* or *sounds like*. Those could potentially be worth investigating. **Remember merchant matches per user**. If a user corrects *bruger king 123 main st* to *Burger King*, store that relation and remember it in the future without having to prompt the user. This data could also be used to help other users correct their data. **But what if there is no UI?** Perhaps you're trying to do some automated data processing. I really see no way to handle this without some sort of human intervention, though some of the techniques described above could help automate this process. I'd also look at the source of your data. Perhaps there's a distinct merchant ID you can use as a key, or perhaps there exists *somewhere* a list of all known merchants (maybe credit card companies provide this API?) If there's boat loads of data to process, another option would be to partially automate it using a service such as Amazon's [Mechanical Turk](https://www.mturk.com/).
It depends a bit on what database you use, but most have some kind of REGEXP\_INSTR or other function you can use to check for the first index of a pattern. You can then write something like this ``` SELECT SubStr(merchant, 1, REGEXP_INSTR(merchant, '[0-9]')), count('x') FROM Expenses GROUP BY SubStr(merchant, 1, REGEXP_INSTR(merchant, '[0-9]')) ``` This assumes that the merchant name doesn't have a number and the store number does. However you still may need to strip out any special chars with a replace (like \*, -, etc).
51,153,030
Up to now, PDFs were opened by Acrobat Reader. When I did this... ``` Dim iProcIDPDF As Integer = System.Diagnostics.Process.Start(PATH_TO_PDF_FILE).Id ``` ... all was fine, I got the process ID. Now I let Microsoft Edge open up the PDF for me with the same code, the PDF is opened up, but I get the error "System.NullReferenceException: Object wasn't set to any instance. System.Diagnostics.Process.Start(...) returned Nothing." This also gives the same error: ``` Dim iProcIDPDF As Integer = System.Diagnostics.Process.Start("microsoft-edge:" & PATH_TO_PDF_FILE).Id ``` How could I get the process ID of Edge? Thank you.
2018/07/03
[ "https://Stackoverflow.com/questions/51153030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1390192/" ]
The `processid` of Microsoft Edge is the `processid` of the application managing Edge's tabs as each tab is a process and you won't get that value using Process.Start(). You will have to check how to get the processes from a HostedApplication as Edge is a modern app. If Internet Explorer is the one showing the PDF you will not be able to get the process showing it, is that simple (in case it matters).
See the System.Diagnostics.Process.Start(String fileName) documentation for the return value: > > A new Process that is associated with the process resource, or null if > no process resource is started. > > > In your case you get a null return value (and since don't test for this and reference the Id property you get the 'Object wasn't set to any instance' error). You likely get a null value since Edge was already running and hence no new process was started. To retrieve the Process Id for a running process you might want to use System.Diagnostics.Process.GetProcessesByName.
8,529,017
This is probably a bad example, but I think it's quite simple. Let's say a web search engine (e.g. [Google](http://www.google.com)) is retrieving results (links to websites) of a search performed by the user and it's supposed to order them according to a given priority of languages **and** countries at the same time. Say, Language priorities ``` 1. English 2. Spanish 3. Italian ... ``` Country priorities ``` 1. USA 2. England 3. Canada 4. Spain 5. Mexico ... ``` So, the result would be something ordered like ``` Websites in english and from the USA Websites in spanish and from the USA or in english and from England ... Websites in italian and from Mexico (?). ``` A query like ``` SELECT url FROM websites WHERE ( language = english OR language = spanish OR language = italian ) AND ( country = USA OR country = England OR country = Canada OR country = Spain OR country = Mexico) ``` obviously wouldn't work because it provides a condition, not a priority. Using `ORDER BY language` or `ORDER BY timezone` wouldn't work either because it orders it alphabetically. So, how is the best way to go about this in SQL?
2011/12/16
[ "https://Stackoverflow.com/questions/8529017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2612112/" ]
Assuming that the languages and countries are in their own tables and that the websites table references those two, you `order by` the two fields that hold the priority of each table.. something like ``` SELECT wesbites.url FROM websites INNER JOIN languages on websites.languageId = languages.id INNER JOIN countries on websites.countryId = countries.id ORDER BY languages.priority, countries.priority ```
This is a thought experiment, so the answer is a big, "It depends." If you *really* want to complicate things, then you would also be aware of that person's geolocation (or at least geopreference for those crazy ex-pats) and language. At any rate, you'd at least have a many-to-many relationship between language and country (for example, USA would have English and Spanish). Then you would sort by language preference and *then* country (because as an English speaker, I'm much more interested in English sites from the UK than I am in Spanish sites from the USA). So, you'd have a URL table then a Country table and then a Language table. You could have a rank in your Language table if you actually had user preference--Google wouldn't do this, since they're international. You'd have countries listed by Lat and Long, and then you could do simple distance calculations in your order by to get to the nearest countries as you. Or, if you wanted custom relationships, you could give a Country-Country mapping table that would map countries to its cousins (e.g.-US to UK). But in reality, Google doesn't do this. They search for the relevance of your query (they can parse what language it is based on their substantial translation engine), and then feed those back to you based on a whole slew of variables. They don't do this with simple relational database modelling, but rather complex statistical analysis. As conjecture (I don't work at Google), your links get a relevance to query score and a relevance to you score. Results are then ordered by the summation of the two, descending. It calculates those things very fast based on statistical models it already has in place (it simply plugs in your values and gets the result--data mining models can do this prediction incredibly fast, as it takes much longer to compile the model).
56,976,845
I have installed Atom editor natively on Windows 10 by downloading an running the installer. Now I start WSL Ubuntu distro and want to start Atom (atom-editor) from there with the command `atom .` or VSCode (visual-studio-code) with the command `code .` Atom starts, but not in the directory where the command was executed, instead it shows files from `C:\\Windows`. Moreover Ubuntu WSL terminal shows following error message: ``` atom . grep: /etc/wsl.conf: No such file or directory "\\wsl$\Ubuntu-18.04\home\wlad\projects\udemy\flask-bootcamp\Flask-Bootcamp-master" CMD.EXE wurde mit dem oben angegebenen Pfad als aktuellem Verzeichnis gestartet. UNC-Pfade werden nicht unterstützt. Stattdessen wird das Windows-Verzeichnis als aktuelles Verzeichnis gesetzt. ``` Sorry it's German localized but it says something like `UNC-paths are not supported` (haven't tested VSCode yet) **So how can I use Atom or VSCode editor installed on Windows 10 from within WSL?** \*\* **UPDATE** \*\* As of today (April 2020) there is a much better way to use VSCode on Windows w/ WSL, VirtualMachines (VM) and even Containers. Check out [remote-development plugin](https://code.visualstudio.com/docs/remote/remote-overview) for VSCode.
2019/07/10
[ "https://Stackoverflow.com/questions/56976845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4445175/" ]
I wrote a bash script to open atom with and without files from WSL2. It can handle any number (including 0) of file arguments, on any drive. Both relative and absolute paths are supported, but it can't handle path name containing .. or ~. Pointing atom to a director also works as expected. Here's my script: ``` #!/bin/bash atom_cmd="/mnt/c/Users/`whoami`/AppData/Local/atom/atom.exe" for i in "$@"; do if [[ $i == /mnt* ]]; then linPath="$i" #for absolute file paths else linPath="`pwd`/$i" #for relative file paths fi if [[ $linPath == *".."* || $linPath != "/mnt"* || $i == "/home"* ]] ; then echo "atom script is unacceptable file path $linPath" continue 1 fi winPath="\""`echo $linPath | sed -e 's|\/mnt\/\([a-z]\)|\u\1:|' -e 's:\/:\\\\:g'`"" atom_cmd="$atom_cmd $winPath\"" done unset linPath unset winPath echo "command:" "$atom_cmd" eval "$atom_cmd" unset atom_cmd ``` (I'm sure there are things to improve about this, like edge cases and better use of language features. I'd welcome suggestions.)
this can be a little bit outdated but you can simply run a powershell and use: ``` wsl.exe -d Ubuntu-20.04 //In my case ubuntu ``` This should open a ubuntu session or whatever wsl you have set on your own. A little bit nooby on this but trying to help. =)
6,553,804
Imagine a long rectangle (maybe with size 200x20). All sides have straight edges. In my iOS app, this is easy for me to draw: ``` CGContextFillRect(context, CGRectMake(xLoc, yLoc, 200, 20)); ``` Now what if I wanted the shorter ends (on the left and right side of the rectangle) to be slightly curved, rather than straight edges. What would the code look like to do this? (Note that I am relatively inexperienced with CGContext drawing)
2011/07/01
[ "https://Stackoverflow.com/questions/6553804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/412082/" ]
Something like this (untested, so beware of bugs!): ``` - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]); CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0); CGRect rrect = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect), CGRectGetWidth(rect)-30, CGRectGetHeight(rect)-30); CGFloat radius = 0.5f; CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect); CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect); CGContextMoveToPoint(context, minx, midy); CGContextAddArcToPoint(context, minx, miny, midx, miny, radius); CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius); CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius); CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius); CGContextClosePath(context); CGContextDrawPath(context, kCGPathFillStroke); } ```
You may find Jeff LaMarche's RoundedRectView class useful, whether to use instances of directly or even to see how he makes them: <http://iphonedevelopment.blogspot.com/2008/11/creating-transparent-uiviews-rounded.html>
19,180,578
I am trying to learn specflow and right now. Currently I have 2 feature files. In the second feature file, I am reusing a step from the first feature file. Specflow automatically recognizes the step from the first feature file and when specflow generated the steps for my second feature, it was smart and did not regenerated the step I am reusing. But this step is a Given step and it initializes a member field of the feature class. Without using scenario context, how can I reuse a step from another feature file that initialize a member of the class ? Edit ---- For example, if you have a Given I am logged in that is used in several feature file. This "Given" creates a user object which is logged and store it as a member in .cs feature file. When you use the same Given in another .feature, Specflow does not regenerate it in the correspond .cs file. When you debug the a scenario which is using it, it executes it from the first .cs file. But I can't access the member of the first .cs feature file. I am planning to use a static member but perhaps there is another solution ? Thanks a lot.
2013/10/04
[ "https://Stackoverflow.com/questions/19180578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2846391/" ]
One thing I've done is used a single, massive `partial class` split up between various \*.cs files. This lets you keep relevant things separated in their own files, but still gives you plenty of options in re-using your fixture code. e.g. (Feature1Steps.cs) ``` namespace YourProject.Specs { [Binding] // This can only be used once. public partial class YourProjectSpecSteps { // Feature 1 methods ... } } ``` And for the next feature (Feature2Steps.cs) ``` namespace YourProject.Specs { public partial class YourProjectSpecSteps // same class, already bound { // Feature 2 methods ... } } ```
I know you mentioned you have two feature files but you might also want to think about creating one feature file with two scenarios where the scenarios use a common step as well as two identically named steps with different implementations. (overloaded functions) ``` Ex: Login.featue file Feature: Login Test the login functionality of the application. Will verify if the username and password combination is working as expected. Scenario: Verify if the login functionality is working Given I have navigated to the application # user name and password are hard coded When I fill in my form | username | password | |name@xyz.com | pwd | .... Scenario: Verify if the login functionality is working for sql server data Given I have navigated to the application # gets the user name and password from the database When I fill in my form .... LoginSteps.cs file [Binding] public class LoginSteps { [Given(@"I have navigated to the application")] public void GivenIHaveNavigatedToTheApplication() { // this code is used by both scenarios Browser.Navigate().GoToUrl(ConfigurationManager.AppSettings["TestUrl"]); } // hard coded username and password [When(@"I fill in my form")] public void WhenIFillInMyForm(Table table) { dynamic credentials = table.CreateDynamicInstance(); LoginFunction(credentials.username, credentials.password); } // gets the username and password from the database [When(@"I fill in my form")] public void WhenIFillInMyForm() { string username = ""; string password = ""; string sql = <select statement>; using (SqlConnection connection = new SqlConnection()) { connection.ConnectionString = ConfigurationManager.ConnectionStrings["SQLProvider"].ConnectionString; connection.Open(); SqlCommand myCommand = new SqlCommand(sql, connection); using (SqlDataReader myDataReader = myCommand.ExecuteReader()) { while (myDataReader.Read()) { username = myDataReader["name"].ToString(); password = myDataReader["pwd"].ToString(); } } } LoginFunction(username, password); } ```
1,092,805
I can't seem to understand why I cant pass any values with the following code: ``` <div class="menu"> Por favor seleccione os conteúdos: <form name="Categorias" action="Elementos_Descritivos.php" method="post"> <?php $Categorias = array ("Nome", "Data", "Cliente", "Observacoes"); foreach( $Categorias as $key => $value){ echo "<div class=\"cb-row\"> <label for=\"$value\">$value:</label> <input id=\"$value\" $value=\"$value\" type=\"checkbox\" value=\"$value\" checked /> </div>"; } ?> <div class="submit"> <input type="submit" value="Seguinte" /> </div> </form> </div> </div> ``` In the Elemento\_Descritivos.php page All the code i have is: ``` <?php print("<pre>"); print_r($_POST); print("</pre>"); ?> ``` It simply outputs: Array ( )
2009/07/07
[ "https://Stackoverflow.com/questions/1092805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133641/" ]
You need to set the **name** attribute on all your inputs for a form post to work. The **ID** is not posted when a form is submitted. ``` <input id=\"$value\" name=\"$value\" .../> ``` Do the same for your submit button. It will allow you to figure out which submit button was pressed in case you have many in the same form.
As Wadih pointed out - you need to assign a name attribute to your inputs. I've rewritten your code in hopes it becomes a little more clear what is going on. I've also removed the attribute $value=\"$value\". ``` <div class="menu"> Por favor seleccione os conteúdos: <form name="Categorias" action="Elementos_Descritivos.php" method="post"> <?php $Categorias = array ("Nome", "Data", "Cliente", "Observacoes"); foreach( $Categorias as $category){ ?> <div class="cb-row"> <label for="<?=$category;?>"> <?=$category;?> </label> <input id="<?=$category;?>" name="<?=$category;?>" type="checkbox" value="<?=$category;?>" checked /> </div> <? } //foreach ?> <div class="submit"> <input name="categories" type="submit" value="Seguinte" /> </div> </form> </div> ```
20,655,612
I want to use Back button programmaticaly, when i pressed back button: ``` onback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); ``` i want to display previous page same as i do by Clicking Back on device. Then i do: ``` onback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub super.onBackPressed(); } }); ``` gives 'undefined type for Object' error. Then i tried: ``` onback.setOnClickListener(new View.OnClickListener() { public void onBackPressed(View v) { // Do something super.onBackPressed(); } }); ``` No functioning. I checked several question and answers, no answer for onClick and without 'finish()' the activity. Thank you for your suggestions.
2013/12/18
[ "https://Stackoverflow.com/questions/20655612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3009341/" ]
Don't call `super`. Just do: ``` onback.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Do something onBackPressed(); } }); ```
Try like this .. ``` @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); finish(); } ``` If U need back functionality on press of button on your UI then try like this .. ``` back.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub finish(); } }); Button back = (Button) findViewById(R.id.back); ``` Here calling finish(); in itself kills current activity and initiates previous activity... No need for over head .
3,391,117
I'm currently trying to implement a LALR parser generator as described in "compilers principles techniques and tools" (also called "dragon book"). A lot already works. The parser generator is currently able to generate the full goto-graph. ``` Example Grammar: S' --> S S --> C C C --> c C C --> d Nonterminals: S', S, C Terminals: c, d Start: S' ``` The goto-graph: ``` I[0]---------------+ I[1]-------------+ | S' --> . S , $ |--S-->| S' --> S . , $ | | S --> . C C , $ | +----------------+ | C --> . c C , c | | C --> . c C , d | I[2]--------------+ | C --> . d , c | | S --> C . C , $ | I[3]--------------+ | C --> . d , d |--C-->| C --> . c C , $ |--C-->| S --> C C . , $ | +------------------+ | C --> . d , $ | +-----------------+ | | +-----------------+ | | +--c--+ | | | | | | c | | | | v v | | | I[4]--------------+ | | c | C --> c . C , c | | | | | C --> c . C , d | | | | | C --> c . C , $ | d | | | C --> . c C , c | | | +---->| C --> . c C , d | | | | C --> . c C , $ | | d | C --> . d , c |--+ | | +-----| C --> . d , d | | | | | | C --> . d , $ | | | | | +-----------------+ | | | C | | | | I[6]--------------+ | | | | | C --> c C . , c | d | | +---->| C --> c C . , d | | | | | C --> c C . , $ | | | | +-----------------+ | | | | | | I[5]------------+ | | | | C --> d . , c |<---+ | +------->| C --> d . , d | | | C --> d . , $ |<-----+ +---------------+ ``` I have trubbles with implementing the algorithm to generate the actions-table! My algorithm computes the following output: ``` state | action | c | d | $ ------------------------ 0 | s4 | s5 | ------------------------ 1 | | | acc ------------------------ 2 | s4 | s5 | ------------------------ 3 | | | r? ------------------------ 4 | s4 | s5 | ------------------------ 5 | r? | r? | r? ------------------------ 6 | r? | r? | r? ``` sx... shift to state x rx... reduce to state x The r? means that I don't know how to get the state (the ?) to which the parser should reduce. Does anyone know an algorithm to get ? using the goto-graph above? If anything is describe no clearly enough, please ask and I will try to explain it better! Thanks for your help!
2010/08/02
[ "https://Stackoverflow.com/questions/3391117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/268127/" ]
A shift entry is attributed by the next state, but a reduce entry indicates a production. When you shift, you push a state reference onto your stack and proceed to the next state. When you reduce, this is for a specific production. The production was responsible for shifting n states onto your stack, where n is the number of symbols in that production. E.g. one for S', two for S, and two or one for C (i.e. for the first or second alternative for C). After n entries are popped off the stack, you return to the state where you started processing that production. For that state and the nonterminal resulting from the production, you lookup the goto table to find the next state, which is then pushed. So the reduce entries identify a production. In fact it may be sufficient to know the resulting nonterminal, and the number of symbols to pop. Your table thus should read ``` state | action | goto | c | d | $ | C | S ------------------------------------ 0 | s4 | s5 | | 2 | 1 ------------------------------------ 1 | | | acc | | ------------------------------------ 2 | s4 | s5 | | 3 | ------------------------------------ 3 | | | r0 | | ------------------------------------ 4 | s4 | s5 | | | 6 ------------------------------------ 5 | r3 | r3 | r3 | | ------------------------------------ 6 | r2 | r2 | r2 | | ``` where rx indicates reduce by production x.
You need to pop the stack and and find the next state from there.
43,090,063
I am using Laravel 5.4 and I want to view my data in database from my view page (`listpetani.blade.php`). Here is the code of my project: HTML: ``` <div class="table-responsive"> <table class="table table-striped table-hover table-condensed"> <thead> <tr> <th><strong>No</strong></th> <th><strong>Nama Petani</strong></th> <th><strong>Alamat</strong></th> <th><strong>No. Handphone</strong></th> <th><strong>Lokasi</strong></th> </tr> </thead> <tbody> <tr> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </tbody> </table> </div> ``` PHP: In my `listpetani.blade.php` I have an empty table and I want to show data from [database tbl\_user](https://i.stack.imgur.com/NJcU9.jpg): ``` Route::get('listpetani', function () { $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi'); return view('listpetani', ['petani' => $petani]); }); ``` And the table in my page: [view in browser](https://i.stack.imgur.com/M8NEU.jpg) I want to show all the data from database into my view in laravel 5.4. Can anybody help me?
2017/03/29
[ "https://Stackoverflow.com/questions/43090063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6402527/" ]
Alternatively you can use @forelse loop inside laravel blade ``` @forelse($name as $data) <tr> <th>{{ $data->id}}</th> <th>{{ $data->name}}</th> <th>{{ $data->age}}</th> <th>{{ $data->address}}</th> </tr> @empty <tr><td colspan="4">No record found</td></tr> @endforelse ```
I hope you already know this, but try use Model and Controller as well, Let the route take the request, and pass it to controller and use Eloquent so your code can be this short: ``` $petani = PetaniModel::all(); return view('listpetani', compact('petani)); ``` and instead using `foreach`, use `forelse` with `@empty` statement incase your `'listpetani'` is empty and give some information to the view like 'The List is Empty'.
6,860,560
I am going through my style sheets in an attempt to make my CSS for IE friendly and I am running into an issue with my padding-left for some reason. It is only applying the padding to the first line of text in my 'span' tag. When the text runs to the next line it goes all the way to the left inside the 'span' element. *(Can't show screenshot for NDA purposes)* BROWSER: IE7 CSS: ``` #rightContent .rightNav a,#rightContent .rightNav a:visited{ color:black; display:block; width:92px; padding-right:12px; height:35px; background:url("../images/nav_off.png"); } #rightContent .rightNav span{ display:table-cell; vertical-align:middle; height:28px; padding-left:13px; font-size:9px; } ``` HTML: ``` <li> <a href=""> <span>This text is too long.</span> </a> </li> ```
2011/07/28
[ "https://Stackoverflow.com/questions/6860560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/386276/" ]
IE7 does not support `display: table-cell`: <http://caniuse.com/css-table> You'll have to find an alternative technique, if only for IE7. Try adding `*float: left` to the `span` - it will [only apply](http://mathiasbynens.be/notes/safe-css-hacks#css-hacks) to IE7 and lower. Maybe that will be a "good enough" fix. It looks like you're using `display:table-cell; vertical-align:middle` for vertical centering. If it's *absolutely vital* to have that in IE7, it is possible without resorting to JavaScript, but it's a pain in the ass.
It seems similar to the question asked here: [Why Doesn't IE7 recognize my css padding styles on anchor tags?](https://stackoverflow.com/questions/2330357/why-doesnt-ie7-recognize-my-css-padding-styles-on-anchor-tags) I'm not sure exactly why it does that, it seems to be an IE bug. I would suggest either wrapping your text in something else(a `div` or a `p` tag), or just putting the text straight in the `a` tag and if you need specific styles for it just give the `a` tag a class.
1,444,112
``` #include <cstdio> class baseclass { }; class derclass : public baseclass { public: derclass(char* str) { mystr = str; } char* mystr; }; baseclass* basec; static void dostuff() { basec = (baseclass*)&derclass("wtf"); } int main() { dostuff(); __asm // Added this after the answer found, it makes it fail { push 1 push 1 push 1 push 1 push 1 push 1 push 1 push 1 push 1 push 1 } printf("%s", ((derclass*)basec)->mystr); } ```
2009/09/18
[ "https://Stackoverflow.com/questions/1444112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175492/" ]
``` basec = (baseclass*)&derclass("wtf"); ``` Here a temporary object of `derclass` is created and destructed immediately when `;` is encountered in `dostuff()` function. Hence, your `basec` pointer points to invalid object.
It creates the temporary variable on the stack because it's a local variable to the dostuff() function. Once the dostuff function exits, the stack rolls back possibly leaving the object on the memory stack exactly as it should be. Now your pointer is pointing to a spot on the stack that hopefully won't get clobbered by the call to printf when it passes in a pointer to stack memory that is no longer being used. Usually stack that isn't being used isn't overwritten if you don't call other functions. You could actually do some damage by calling a few functions, and then changing the value of mystr. The characters of text would then become part of the executable code. Hacker's dream. Try something like this: ``` void breakStuff() { char dummy[3]; strcpy( dummy, "blahblahblahblahblah" ); int i = 7; i = i + 8; i = i + 22; printf( "**%d**", i ); } ``` The strcpy will write PAST the local variable and overwrite the code. It'll die horribly. Good times, noodle salad.
3,983,829
Is there a way, short of actually checking out the parent commit, to determine a submodule's SHA-1 commit ID based on a commit ID in the parent clone? I know I can find the *currently* associated SHA-1 with `git submodule`. Here's an example: * I have a clone with a single submodule `foo` that has changed several times in the last month. * I have a tag in the parent clone that is a few weeks old called `released-1.2.3`. I want to find out what the associated SHA-1 of `foo` was for this tagged commit. * I could simply check out `released-1.2.3` and use `git submodule` to see, but I'm wondering if there's a way to do this *without* affecting the working tree, as I want to script it. I want to do this because I want to construct a script to do a 'diff' on all changes within a submodule between two commits within the parent repository - i.e. "tell me what files changed within the submodule `foo` between these two commits in the parent."
2010/10/21
[ "https://Stackoverflow.com/questions/3983829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143397/" ]
You may use [`git-ls-tree`](http://www.kernel.org/pub/software/scm/git/docs/git-ls-tree.html) to see what the SHA-1 id of a given path was during a given commit: ``` $ git ls-tree released-1.2.3 foo 160000 commit c0f065504bb0e8cfa2b107e975bb9dc5a34b0398 foo ``` (My first thought was `git show released-1.2.3 foo`, but that fails with "fatal: bad object".) Since you are scripting the output, you will probably want to get just the SHA-1 id by itself, e.g.: ``` $ git ls-tree released-1.2.3 foo | awk '{print $3}' c0f065504bb0e8cfa2b107e975bb9dc5a34b0398 ``` Also: When writing scripts around git, try to stick to the [plumbing](http://git-scm.com/docs/git#_low_level_commands_plumbing "Low-level commands (plumbing)") commands, as described in the manual. They have a more stable interface, while the more familiar “porcelain” commands will possibly change in incompatible ways.
I did find one promising avenue: ``` $ git log --raw <since>..<until> --submodule -- <path/to/submodule> ``` With the --raw option, this does print out the (abbreviated) SHA-1 IDs corresponding to the submodule's associated commits. Unfortunately the output is very verbose and will take some work to process in a script. What I really need is a git facility that, given a parent commit ID, gives me the latest change to a submodule prior to that commit. I.e. which submodule SHA-1 'git submodule update' would check out if I were to actually checkout that parent commit.
39,198,561
it is allowed to use custom exception, where the exception can be thrown like below. ``` try { int foo = int.Parse(token); } catch (FormatException ex) { //Assuming you added this constructor throw new ParserException( $"Failed to read {token} as number.", FileName, LineNumber, ex); } ``` But in a normal try catch block, it says , throwing exceptions will clear the stacktrace. ``` try { ForthCall(); } catch (Exception ex) { throw ex; } ``` So in custom exception,how it managed to use throw exception, without clear the stacktrace?
2016/08/29
[ "https://Stackoverflow.com/questions/39198561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/833985/" ]
Issue is with group by .. remove OINV.DocTotal from group by and do sum like below ``` SELECT OSLP.SlpName as Salesman, sum(CAST(OINV.DocTotal as float)) as Achiev, OINV.TaxDate FROM OINV INNER JOIN INV1 ON INV1.DocEntry = OINV.DocEntry INNER JOIN OSLP ON OINV.SlpCode = OSLP.SlpCode INNER JOIN OITM ON INV1.ItemCode = OITM.ItemCode INNER JOIN OMRC ON OITM.FirmCode = OMRC.FirmCode INNER JOIN OCRD ON OINV.CardCode = OCRD.CardCode WHERE OSLP.SlpName like '01-2 Ika' And OINV.TaxDate between '20160804' and '20160806' GROUP BY OSLP.SlpName, OINV.TaxDate ```
If you wanted to display sum of DocTotal against each seales man and also wanted to split it by TaxDate , use the following script ``` SELECT OSLP.SlpName as Salesman, CAST(sum(OINV.DocTotal) OVER(PArtition by OSLP.SlpName Order by OINV.TaxDate) as float) as Achiev OINV.TaxDate FROM OINV INNER JOIN INV1 ON INV1.DocEntry = OINV.DocEntry INNER JOIN OSLP ON OINV.SlpCode = OSLP.SlpCode INNER JOIN OITM ON INV1.ItemCode = OITM.ItemCode INNER JOIN OMRC ON OITM.FirmCode = OMRC.FirmCode INNER JOIN OCRD ON OINV.CardCode = OCRD.CardCode WHERE OSLP.SlpName like '01-2 Ika' And OINV.TaxDate between '20160804' and '20160806' ``` If you wanted to display sum of DocTotal against each seales man use the following script. ``` SELECT OSLP.SlpName as Salesman, CAST(sum(OINV.DocTotal) as float) as Achiev FROM OINV INNER JOIN INV1 ON INV1.DocEntry = OINV.DocEntry INNER JOIN OSLP ON OINV.SlpCode = OSLP.SlpCode INNER JOIN OITM ON INV1.ItemCode = OITM.ItemCode INNER JOIN OMRC ON OITM.FirmCode = OMRC.FirmCode INNER JOIN OCRD ON OINV.CardCode = OCRD.CardCode WHERE OSLP.SlpName like '01-2 Ika' And OINV.TaxDate between '20160804' and '20160806' GROUP BY OSLP.SlpName ```
9,375,585
I have a string array. I need to remove some items from that array. but I don't know the index of the items that need removing. My array is : string[] arr= {" ","a","b"," ","c"," ","d"," ","e","f"," "," "}. I need to remove the " " items. ie after removing " " my result should be arr={"a","b","c","d","e","f"} how can I do this?
2012/02/21
[ "https://Stackoverflow.com/questions/9375585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/799141/" ]
This will remove all entries that is null, empty, or just whitespaces: ``` arr.Where( s => !string.IsNullOrWhiteSpace(s)).ToArray(); ``` If for some reason you only want to remove the entries with just one whitespace like in your example, you can modify it like this: ``` arr.Where( s => s != " ").ToArray(); ```
Using LinQ ``` using System.Linq; string[] arr= {" ","a","b"," ","c"," ","d"," ","e","f"," "," "}. arr.Where( x => !string.IsNullOrWhiteSpace(x)).ToArray(); ``` or depending on how you are filling the array you can do it before ``` string[] arr = stringToBeSplit.Split('/', StringSplitOptions.RemoveEmptyEntries); ``` then empty entries will not be put into your string array in the first place
17,740,790
I have a meteor application that generates images. After they are generated, I want to serve them. But each time I write to the public folder, my meteor server restarts. I searched for a solution and found several workarounds: * Serve files outside of the project folder - At the moment I don't know how to achieve this, would I have to write some kind of middleware that integrates into meteor? * Add a tilde ~ to the folder in `public/` - which seems to make meteor ignore the folder altogether, when trying to access files in the folder I get redirected to my root page. * Run meteor in production mode. Seems like a dirty workaround for me. Right now, `meteor run --production` still restarts my server so I have to bundle my app, reinstall fibers every time, set my environment variables and then run the app. Every time I change something. Are there any other solutions out there?
2013/07/19
[ "https://Stackoverflow.com/questions/17740790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2123714/" ]
It's not that easy. * Writing to `public` is out of question, as Meteor manages this folder and thus restarts itself on every file change. * Writing to ignored folder (starting with `.` or ending with `~`, or even outside of Meteor directory) is an option. However, you'll need to manually serve those files. A small middleware would do the trick: ``` __meteor_bootstrap__.app.stack.splice (0, 0, { route: '/mediaPathOfChoice', handle: function(req, res, next) { /* Read the proper file based on req.url */ res.writeHead(200, { 'Content-Type': /* Put the item MIME type here */ }); res.write(/* Put item contents here */); res.end(); }, }); ``` * For many publishing options, writing files on the application server is not the best solution anyway. Consider setting up a media server for your files - S3 buckets are solid and cheap for this purpose.
This package may help: CollectionFS adds simple yet robust file uploading and downloading abilities to your Meteor web app. It is a mix of Meteor.Collection and MongoDB's GridFS. CollectionFS stores files in your MongoDB database but also provides the ability to easily store files on the server filesystem or a remote filesystem. <https://github.com/CollectionFS/Meteor-CollectionFS>
39,709,500
I have a column *acdtime* that gives me the time on a call in **seconds**. I need to transform those fields to *HH:MM* format. My idea is first to convert the seconds to interval using 3904 as parameter: > > INTERVAL(0:0:0) HOUR TO second + acdtime UNITS second > > > and I get: > > 1:05:04 > > > Then convert this result to char and then make a substring. This is where I get stucked. Any idea? Thanks a lot
2016/09/26
[ "https://Stackoverflow.com/questions/39709500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133654/" ]
The Top 250 is the answer for 50 rows per page and always show five pages, what you need to also do is in your result set for your dataset, make it always return 250 rows where whatever is under 250 has a blank row. Here is an example: ``` Create table #mytable ( firstname varchar(200), lastname varchar(200) ) insert into #mytable select 'person','lastname' union select 'person2','lastname' declare @totalrows int declare @blankrows int declare @currentrow int set @totalrows = count(*) from #Mytable set @blankrows = 250 - @totalrows set @currentrow = 1 while @currentrow<=@blankrows begin insert into #MyTable SELECT '', '' end ``` Your table should now always have 250 rows.
Applicable to Tablix report only. This method will make 50 record per page or even you can customize 100 records to 20 records per page. (However you can make it 250 records anyway by adding blank rows) Steps: 1. Create a group with below expression: `=ceiling(rownumber(nothing)/50)` 2. New group with column will be added, delete the column not group 3. Delete the Sorting option from the created group 4. Go to `Group Properties > Page Breaks> Check Between each instance of group` 5. You are also required to change the `page setup` from the `Report properties` as the default number of rows is 43. Make the height to default 11 to 14.
71,938,691
How do I pass a missing argument to a function using `do.call`? The following does not work: ``` x <- array(1:9, c(3, 3)) do.call(`[`, list(x, , 1)) ``` I expect this to do the same calculation as ``` x[,1] ```
2022/04/20
[ "https://Stackoverflow.com/questions/71938691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5559163/" ]
you can use `quote(expr=)` ```r x <- array(1:9, c(3, 3)) do.call(`[`, list(x, quote(expr=), 1)) #> [1] 1 2 3 identical(x[,1], do.call(`[`, list(x, quote(expr=), 1))) #> [1] TRUE ``` Created on 2022-04-20 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1) `do.call(`[`, alist(x,, 1))` also works. So does `do.call(`[`, list(x, TRUE, 1))` for this specific case, since subsetting rows with `TRUE` keeps all of them.
**Update:** Thanks to @moodymudskipper: ("`is_missing()` is always `TRUE` so you're just subsetting rows and keeping everything. We could do `do.call([, list(x, TRUE, 1))`. This solves this specific issue (perhaps better in fact), but not the general one of dealing with missing arguments.") I meant `rlang`s `missing_arg()`: ``` do.call(`[`, list(x, rlang::missing_arg() , 1)) ``` **First answer:** not good -> see comments moodymudskipper: We could use `rlang`s `is_missing()`: See here <https://rlang.r-lib.org/reference/missing_arg.html> "rlang::is\_missing() simplifies these rules by never treating default arguments as missing, even in internal contexts:" ``` do.call(`[`, list(x, rlang::is_missing() , 1)) ```
1,305,584
This is like when we say that the integer which comes just after $2$ is $3$. Is there a real number which comes just after a particular real number? For example: Is there a number which comes just after $0.5$? > > If any one didn't get me, read Asaf's answer because that explains my question better. > > >
2015/05/30
[ "https://math.stackexchange.com/questions/1305584", "https://math.stackexchange.com", "https://math.stackexchange.com/users/227064/" ]
If you are talking about a rational number or a real number after $\frac{1}{2}$, it is not possible. For suppose $x$ were such a number. Then $\frac{\frac{1}{2}+x}{2}$ is a number after $\frac{1}{2}$, but closer than $x$.
Let $a$ and $b$ be positive reals, and $a \neq b$ To say that $b$ is the number just after $a$ it would mean that there is not any real number between $a$ and $b$. But there is! For example, we can average them: $$a < \frac{a+b}{2} < b$$ Well, maybe the number $\frac{a+b}{2}$ is the inmeadiate number after $a$, right? No. Because we can average again: $$a < \frac{a+ \frac{a+b}{2}}{2} < \frac{a+b}{2}$$ We can actually keep doing this forever. This is because the real numbers are **dense**, meaning that between any two distinct real numbers there is an infinite number of reals. So, there can't be an inmediate next real number to any real number (as Asaf says, in the context of the reals, of course.)
36,205,113
I have functionality for all or any one of these checkboxes being checked. However, when they are all unchecked I get a SQL error saying: Incorrect Syntax near ')'. Incorrect Syntax near the keyword 'OR'. ``` string andOr = string.Format(" {0} (", whereAnd); if ((!box1) || (!box2) || (!box3) { whereAnd = " AND "; if (box1) { sqlCommand.Append(andOr); sqlCommand.Append("(h.object= 0)"); andOr = " OR "; } if (box2) { sqlCommand.Append(andOr); sqlCommand.Append("(h.object= 1)"); andOr = " OR "; } if (box3) { sqlCommand.Append(andOr); sqlCommand.Append("(h.object= 2)"); } sqlCommand.AppendLine(")"); } ``` then it does everything else for my query. I'm stuck at trying to determine how to handle NO boxes being checked. Do I go outside of the first if statement and do an else if (!box1) && (!box2) && (!box3)....If so what does SQL require for me to skip these selections. OR Do I go inside of the if statement and after it checks for box 1, 2 and 3 do I do an else since none of these are checked. Again, if I do this what do I need to tell SQL to not include these selections? **EDIT** Here is the entire SQL command ``` DECLARE @jFN NVARCHAR(MAX)='' DECLARE @sFN NVARCHAR(MAX)='' DECLARE @sd DateTime='2016-02-24T05:00:00' DECLARE @ed DateTime='2016-03-25T03:59:59' DECLARE @jFId INT EXEC dbo.GFId @jFName, @jFId OUTPUT DECLARE @jFDescendants TABLE(fo_id INT) INSERT INTO @jFDescendants EXEC dbo.GetFDescendants @jFId DECLARE @sFId INT EXEC dbo.GFId @sFName, @sFId OUTPUT DECLARE @sFDescendants TABLE(fo_id INT) INSERT INTO @sFDescendants EXEC dbo.GFDescendants @sFId select h.object, h.id, h.se_id, h.co_time, h.ho_time, h.sc_time, h.st_time CASE WHEN h.id <> 0 THEN j.fo_id ELSE u.fo_id END as fo_id from dbo.myDB AS h LEFT OUTER JOIN dbo.Jo AS j ON h.id = j.id LEFT OUTER JOIN dbo.Se AS u ON h.se_id = u.se_id LEFT OUTER JOIN dbo.Fo AS js ON j.fo_id = js.fo_id LEFT OUTER JOIN dbo.Fo AS ss ON u.fo_id = ss.fo_id ) AND ((h.co_time BETWEEN @sd AND @ed) OR (h.ho_time BETWEEN @sd AND @ed) OR (h.sc_time BETWEEN @sd AND @ed) OR (h.st_time BETWEEN @sd AND @ed) ) AND (js.fo_id IN (select fo_id from @jFD) OR ss.fo_id IN (select fo_id from @sFD)) ORDER BY h.co_time DESC ``` Right before the line AND ((h.co\_time BETWEEN @sd AND @ed) is where this sql command goes. It will look like this if only 2 are checked: ``` LEFT OUTER JOIN dbo.Fo AS ss ON u.fo_id = ss.fo_id WHERE ((h.object= 0) OR (h.object = 1)) AND ((h.co_time BETWEEN @sd AND @ed) OR (h.ho_time BETWEEN @sd AND @ed) ...etc ```
2016/03/24
[ "https://Stackoverflow.com/questions/36205113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3715482/" ]
You always add the ")" to the query. You need to refactor your logic to make it work as expected. ``` if (box1 || box2 || box3) { var op = " AND ("; if (box1) { sqlCommand.Append(op); sqlCommand.Append("(h.object= 0)"); op = " OR "; } if (box2) { sqlCommand.Append(op); sqlCommand.Append("(h.object= 1)"); op = " OR "; } if (box3) { sqlCommand.Append(op); sqlCommand.Append("(h.object= 2)"); } sqlCommand.AppendLine(")"); } ```
So I know this was not my best post. This was code that I didn't write that I had to figure out and then fix. I haven't done a lot with ADO.NET but none the less I was able to figure out a solution to what turned out to be a very simple problem. Here is the code that I used to do it ``` string andOr = string.Format(" {0} (", whereAnd); if ((box1) || (box2) || (box3) { whereAnd = " AND "; if (box1) { sqlCommand.Append(andOr); sqlCommand.Append("(h.object= 0)"); andOr = " OR "; } if (box2) { sqlCommand.Append(andOr); sqlCommand.Append("(h.object= 1)"); andOr = " OR "; } if (box3) { sqlCommand.Append(andOr); sqlCommand.Append("(h.object= 2)"); } sqlCommand.AppendLine(")"); } else { whereAnd = " WHERE "; sqlCommand.Append(andOr); sqlCommand.AppendLine("(h.object IS null "); sqlCommand.AppendLine("))"); whereAnd = " AND "; } ``` This will check for each box to be checked. If any are checked it will append each h.object (0, 1 or 2). If none are checked it will jump to the if else and it will return any h.objects that are null (which I don't have any so it will return none). I wanted to post to explain what I was looking to do since OP wasn't very clear.
41,557,733
I am selecting a payment method and making an AJAX call But I am not able to print the `paymentOption` parameter I tried storing it in a cookie ``` if(paymentOption == "default_cod"){ processOrderWithCOD(); optionPayment = Cash; } document.cookie = "$payment_option = $this.optionPayment"; ``` PHP: ``` <?php $paymentOptionDisplay = $_COOKIE['payment_option']; echo $paymentOptionDisplay ?> ``` I am just trying to print paymentOption but later on its value is changed so need to save it and print
2017/01/09
[ "https://Stackoverflow.com/questions/41557733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7191333/" ]
So it turns out that if the `AVMetadataCommonIdentifierDescription` item is nil or an empty string, the image gets hidden. All I had to do to fix it was set the description to " " if there's not text to show. I'm going to file a bug with apple on this because that's obviously not normal.
Not sure what was happening a few years ago around this problem, but the issue now is if you don't convert your image to a `pngData` the image won't show. In other words just sending the Artwork item a UIImage won't work. So it needs to be like this per Apple: ``` if let showImage = image, let pngData = showImage.pngData() { let imageItem = self.makeMetadataItem(AVMetadataIdentifier.commonIdentifierArtwork.rawValue, value: pngData) metadata.append(imageItem) } ```
174,320
I'm creating a physics game involving rigid bodies in which players move pieces and parts to solve a puzzle/map. A hugely important aspect of the game is that when players start a simulation, it runs the same *everywhere*, regardless of their operating system, processor, etc... There is room for a lot of complexity, and simulations may run for a long time, so it's important that the physics engine is completely deterministic with regards to its floating point operations, otherwise a solution may appear to "solve" on one player's machine and "fail" on another. How can I acieve this determinism in my game? I am willing to use a variety of frameworks and languages, including Javascript, C++, Java, Python, and C#. I have been tempted by Box2D (C++) as well as its equivalents in other languages, as it seems to meet my needs, but it lacks floating point determinism, particularly with trigonometric functions. The best option I've seen thus far has been Box2D's Java equivalent (JBox2D). It appears to make an attempt at floating point determinism by using `StrictMath` rather than `Math` for many operations, but it's unclear whether this engine will guarantee everything I need as I haven't built the game yet. Is it possible to use or modify an existing engine to suit my needs? Or will I need to build an engine on my own?
2019/08/03
[ "https://gamedev.stackexchange.com/questions/174320", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/130520/" ]
I'm not sure if this is the type of answer you're looking for, but an alternative *might* be to run the calculations on a central server. Have the clients send the configuration to your server, let it perform the simulation (or retrieve a cached one) and send back the results, which are then interpreted by the client and processed into graphics. Of course, this shuts off any plans you might have to run the client in offline mode, and depending on how computationally intensive the simulations are you might need a very powerful server. Or multiple ones, but then at least you have the option to make sure they have the same hard- and software configuration. A real-time simulation might be hard but not impossible (think of live video streams - they work, but with a slight delay).
I'm going to give a counter-intuitive suggestion that, while not 100% reliable, should work fine most of the time and is very easy to implement. **Reduce precision.** Use a pre-determined constant time-step size, perform the physics over each time-step in standard double-precision float, but then quantise down the resolution of all variables to *single-precision* (or something even worse) after each step. Then most of the possible deviations that floating-point reordering could possibly introduce (compared to a reference run of the same program) will be clipped away because those deviations happen in digits that don't even exist in the reduced precision. Thus the deviation don't get the chance of a Lyapunov buildup (Butterfly Effect) that would eventually become notable. Of course, the simulation will be slightly less accurate than it could be (compared to real physics), but that's not really notable as long as all of your program runs are inaccurate *in the same way*. Now, technically speaking it is of course possible that a reordering will cause a deviation that reaches into a higher-significance digit, but if the deviations are really only float-caused and your values represent continuous physical quantities, this is exceedingly unlikely. Note that there are half a billion `double` values between any two `single` ones, so the vast majority of time-steps in most simulations can be expected to be exactly the same between simulation runs. The few cases where a deviation does make it through quantisation will hopefully be in simulations that don't run so long (at least not with chaotic dynamics). --- I would also recommend you consider the complete opposite approach to what you're asking about: *embrace the uncertainty*! If the behaviour is slightly nondeterministic, then this is actually closer to actual physics experiments. So, why not *deliberately randomise* the starting parameters for each simulation run, and make it a requirement that the simulation succeeds *consistently* over multiple trials? That'll teach a lot more about physics, and about how to engineer the machines to be robust/linear enough, rather than super-fragile ones that are only realistic in a simulation.
30,072
The computer gave me this output in a window: ``` E: Encountered a section with no Package: header E: Problem with MergeList /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_natty_main_binary-i386_Packages E: The package lists or status file could not be parsed or opened. ``` How can I fix this?
2011/03/12
[ "https://askubuntu.com/questions/30072", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
I was running into a similar error: ``` Reading package lists... Error! E: Encountered a section with no Package: header E: Problem with MergeList /var/lib/dpkg/status E: The package lists or status file could not be parsed or opened. ``` I followed similar suggestions to copy `status-old`. ``` $ head /var/lib/dpkg/status $ head /var/lib/dpkg/status-old ``` All of my status files were blank for some reason. Luckily, I found out there are backups of these files: ``` $ ls -l /var/backups/dpkg.status.* -rw-r--r-- 1 root root 444620 Nov 15 06:33 /var/backups/dpkg.status.0 -rw-r--r-- 1 root root 444620 Nov 15 06:33 /var/backups/dpkg.status.1.gz -rw-r--r-- 1 root root 128168 Sep 20 2013 /var/backups/dpkg.status.2.gz -rw-r--r-- 1 root root 112545 Sep 16 2013 /var/backups/dpkg.status.3.gz -rw-r--r-- 1 root root 107767 Sep 14 2013 /var/backups/dpkg.status.4.gz -rw-r--r-- 1 root root 107766 Sep 11 2013 /var/backups/dpkg.status.5.gz -rw-r--r-- 1 root root 94583 Sep 11 2013 /var/backups/dpkg.status.6.gz ``` I checked the latest backup... ``` $ head /var/backups/dpkg.status.0 ``` ...but it was still blank. So I unzipped an older one... ``` $ gunzip /var/backups/dpkg.status.1.gz $ head /var/backups/dpkg.status.1 ``` This time there was content. So I copied it... ``` $ cp /var/backups/dpkg.status.1 /var/lib/dpkg/status ``` Then `apt-get update` ran without problems. [Credit goes to this post.](https://answers.launchpad.net/ubuntu/+source/apt/+question/246884)
I had the same problem. These commands fixed it: ``` sudo mv /var/lib/dpkg/status /var/lib/dpkg/status-new sudo mv /var/lib/dpkg/status-old /var/lib/dpkg/status sudo apt-get update ```
641,326
I read Joe Armstrong's ['Programming Erlang'](https://rads.stackoverflow.com/amzn/click/com/193435600X), and the 'n times faster in n core machine' theory. The efficient way to multicore programming in Erlang is to use lots of processes (threads). I'm a C++ programmer, so I am curious about the difference between making lots of threads in C++ and making lots of processes in Erlang. I understand dealing with threads in C/C++ is not that easy. Also I know locking/unlocking makes the system slow down. But it is not *impossible*, right? So.. why is Erlang a muticore friendly language? Is it just because it's easy to program? I'm making an online game server for a MMORPG, that's why I'm interested in Erlang as an alternative server language. (I already read [this](https://stackoverflow.com/questions/181284/functional-programming-and-multicore-architecture) question but I think it's not the question I'm looking for.)
2009/03/13
[ "https://Stackoverflow.com/questions/641326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59597/" ]
Context switch is extremely expensive. There are none in Erlang. Locks makes traditional programs start to think which thread is going to execute next. That is also extremely expensive.
Well, the nature of the language with variables that can only be set once and the fact that it's a functional language automatically makes programs with lots of parallelism be written and executed "the right way" for multicore. I don't know much about erlang besides those two facts, so there might be something else too. But that's not to say you can't make a C++ program as scalable, but you'll probably go through a lot to achieve the performance, scalability and stability which will come with no cost if you write in erlang.
312,772
Recently I was working on [this](https://salesforce.stackexchange.com/questions/312629/how-to-sync-typeform-to-sfmc-data-extension-via-webhooks/312680#312680) integration and got the solution which I can implement easily, by placing the below SSJS code on a cloud page. [![enter image description here](https://i.stack.imgur.com/n8FRb.png)](https://i.stack.imgur.com/n8FRb.png) However, while I noticed that there is mention about using **Code resource instead of Landing page** will NOT consume Super Message! Reference I found [on this page](https://salesforce.stackexchange.com/questions/286276/how-to-add-a-subscriber-to-a-list-using-ampscript-or-ssjs-in-sms-message/286755#286755). > > So my question is that by using **Code Resource** over a **Landing Page** will be beneficial? what are the pro and cons. > > > [![enter image description here](https://i.stack.imgur.com/IR0Hb.png)](https://i.stack.imgur.com/IR0Hb.png) Also found there is no mention about 'Code Resource' on this document [Marketing Cloud Pricing Sheet](https://a.sfdcstatic.com/content/dam/www/ocms-backup/assets/pdf/misc/marketing_cloud_super_message_bundles.pdf) Note: 1. I am aware of that in scenarios where there is output to be displayed we have to use Landing page; however in my case as there is no need for an output and directly Inserting to my DE. 2. Also I have confirmed that the above SSJS code works fine on a JS code resource.
2020/07/15
[ "https://salesforce.stackexchange.com/questions/312772", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/71982/" ]
Code Resources do not use up your Super Message quota. Your content-type headers are set for you, rather than having to explicitly set the value with SSJS/AMPScript as you would with a CloudPage. SFMC doesn't add its tracking code to the page as it does with CloudPages. Code Resources don't allow you to give the file a friendly name, like "FormSubmit", however. In your use case, TypeForm doesn't mind that.
One more thing to add to this topic, as I have come across it multiple times lately. CloudPagesURL() function works for both Landing Pages and Code Resources. If they are in the same Business Unit as the code employing the function. It's just harder to find the right ID for a Code Resource, as the number shown in the URL is not correct and there is no menu for "page options". You have two options for a Code Resource: Option 1: Output the parameter *%%=v(@tabId)=%%* on the Code resource, and publish it. Access the URL in a browser to see the printed CloudPageID, e.g. *1111*. If your Code resource is already live and you cannot simply republish it, then go for option 2): Option 2: Save your Code Resource. Open another Code Resource; in this one, access the Code Resource Menu on the left and insert your Code Resource, this will show how to access it using CloudPagesURL(); e.g. *%%=CloudPagesURL(1111)=%%*
74,144
I know that air pressure and temperature are inversely proportional. Now I saw in a book that "Atmospheric pressure decreases as we go higher and higher." But at greater heights the temperature becomes low, and so the air pressure would be high. But it is given atmospheric pressure decreases with altitude. I understand that [**air pressure**](http://kids.earth.nasa.gov/archive/air_pressure/) and [**atmospheric pressure**](http://en.wikipedia.org/wiki/Atmospheric_pressure) are different. But I can't understand how they are different.
2013/08/14
[ "https://physics.stackexchange.com/questions/74144", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/28241/" ]
If you simply go outside and hold in your hand something of standard area, like a coin, atmospheric pressure is nothing but the weight of all the air above that coin, in a very slender cylinder, going from the coin up to outer space. Of course, since some of the air can sneak in under it and push up, you don't feel that weight. Temperature of air is like temperature of anything. If you heat it, it gets hotter, and if you cool it, it gets colder. Air gets heated because the sun shines on the ground, making it hot, which raises the temperature of the air. Another way to make air hot is to squeeze it. Like if you take a bicycle tire pump and squeeze some air with it (increasing its pressure), you should notice the pump gets warm. The opposite happens too. If you let it expand, it gets cooler, but those only happen because the air in the pump is sort of insulated from the outside air. (There's a big word for that - "adiabatic".) Now in real outside air, the air doesn't stay still. Some of it moves up, and some moves down. The air that moves up goes to a place of lower pressure because there's less air above it, so it expands and gets cooler. Likewise descending air gets warmer, for the same adiabatic reason. So, for example, the air is much warmer at the bottom of the Grand Canyon than at the top. Put all these together and you'll start to understand how weather works.
Air pressure It can be measured by pressure gauge. It can be changed. Atmospheric pressure. It is measured by barometer. It cannot be changed.
5,828,568
I want to change the position of an item in ListView dynamically.How can I do that?
2011/04/29
[ "https://Stackoverflow.com/questions/5828568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730545/" ]
The ListView is backed up by some data structure (e.g. a `List<String>`). So you can do Pseudocode: ``` List<String> list = ... ListView lv = .. Adapter a = new Adapter(..., list); lv.setOnClickListener(this); onItemPressed(..., int position, ...) { tmp = list.get(0); list.set(0, list.get(position)); list.set(position,tmp); a.notifyDataSetChanged(); } ```
do this for change position of listview in coding ``` ListView.setSelection(position); ```
12,387,691
The system has a page where the user can search through items by specifying a start date and end date. These are plain dates (Without the time component). For the user it seems most intuitive for the end date to be inclusive (so include all items for that end date as well). The `CreateDate` of the items however does contain a time component in the data store. In practice this means that we need to translate this timeless end date to a 0:00:00 hour date for the next day. This way we can write the following query: ```sql SELECT * FROM Items WHERE CreateDate >= @STARTDATE AND CreateDate < @ENDDATE ``` Transforming this end date is as easy as writing this line of code: ```cs endDate.Date.AddDays(1); ``` Nou my question is: ***should I consider this last line of code business logic and should it be placed in the Business Layer, or should I consider this line a piece of 'model binding logic' and should it be placed in the Presentation Layer?*** When it is placed it in the BL, this means that the BL knows about the presentation layer, since the way the value is supplied is something that is interface specific. On the other hand, since the operation is defined as a DTO in the business layer, I could also see this object as interface that should be convenient for the presentation layer. This question might even be philosofical in nature, since there are probably multiple ways to look at this, and the actual conversion code is trivial. I'm interested to hear why you think it should be placed in one layer and not in the other. I don't expect the application's architecture should have any effect on the answer to this question. But to give a more complete picture, the architecture is based on [commands](https://cuttingedge.it/blogs/steven/pivot/entry.php?id=91) and [queries](https://cuttingedge.it/blogs/steven/pivot/entry.php?id=92) and the presentation layer creates a query object that are handled by the business layer. The PL code would typically look like this: ```cs public Action Filter(DateTime start, DateTime end) { var query = new GetItemsByStartEndEndDateQuery { StartDate = start.Date, EndDate = end.Date.AddDays(1) } var items = this.queryProcessor.Handle(query); return this.View(items); } ``` Or when possible, (MVC) model binding is used to simply model bind the command and query objects (which is very convenient): ```cs public Action Filter(GetItemsByStartEndEndDateQuery query) { var items = this.queryProcessor.Handle(query); return this.View(items); } ``` Would your answer change when there are multiple users involded (a WCF layer and a MVC layer, for instance)?
2012/09/12
[ "https://Stackoverflow.com/questions/12387691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264697/" ]
There should be a contract for the semantics of the service exposed by your business layer, and probably automated tests for that contract. This contract should define how the input arguments are interpreted and validated, for example: * What is the result if StartDate > EndDate? * What range of dates is acceptable (e.g. what about dates earlier than 1/1/1753 with SQL Server)? * Are input parameters allowed to have non-zero time of day components, and if so how is the time of day handled (truncate and use date only; throw an exception if the caller includes a time of day component; or allow caller to specify a range that includes a time of day component). * Is the range exclusive or inclusive? * How are time zones handled (e.g. date parameters with Kind = Local, Utc or Unspecified)? If this contract doesn't match the way the presentation layer wants to get input from the user, then it's OK for the presentation layer to do the mapping to match the contract. And of course, if the contract does not match the way the data access layer expects the date range, the business layer can do the mapping to whatever the data access layer expects.
I usually put that line of code and others like it in the business/domain layer or domain service. Whether it is: ``` endDate.Date.AddDays(1); ``` Or: ``` endDate.Date.AddDays(3); ``` It is a business concern and should be in the business layer or in a domain service. Given an application architecture that is decoupled properly, one could simply alter and redeploy the domain layer without affecting other layers (like the presentation layer).
74,594,062
Here's (what I think is) the correct way to layout a (reflowable) html document. The width is capped relative to the font width, and the margin is auto calculated to be symmetric so that the content is centred. This gives a pleasant reading experience on both ultra-wide and mobile. ```css body { max-width: 30em; margin: 0 auto; padding: 2em; } ``` ```html <body> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p> <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p> <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p> </body> ``` However, now I want to add line numbers in the margin/padding while keeping the content centred. And am unsure how to do so. On way to do this is have each paragraph be a grid with the number in the first column and the text in the second column. Is this the best way to do this? If so how do get the same behaviour as before? How to we ensure that the content (in the second column) is centred? Maybe we need javascript to calculate the margins widths in % units. But if be have to use js then maybe we don't need the the line numbers and content in the same html container. Maybe I should just give up and inline the line numbers. ```css div { display:grid; column-gap: 2em } .line-number { grid-column-start:1 } p { grid-column-start:2 } ``` ```html <body> <div> <p class='line-number'>1</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p> </div> <div> <p class='line-number'>2</p> <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p> </div> <div> <p class='line-number'>3</p> <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p> </div> </body> ```
2022/11/27
[ "https://Stackoverflow.com/questions/74594062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11998382/" ]
If you use grid, you may make it 2 columns without gap and the first one of 0 width, or span the text throught both columns. You may then offset the numbers out of the grid. here is a few possible ways: * 2 columns: ```css body { max-width: 30em; margin: 0 auto; padding: 2em; } div { display: grid; grid-template-columns: 0 1fr; } .line-number { grid-column-start: 1; margin-inline-start: -2em; } p { grid-column-start: 2 } /* does stand in the middle ? */ body, p:not([class]) { background: linear-gradient(to left, rgba(0, 0, 0, 0.2) 50%, #0000 50%); } ``` ```html <body> <div> <p class='line-number'>1</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p> </div> <div> <p class='line-number'>2</p> <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p> </div> <div> <p class='line-number'>3</p> <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p> </div> </body> ``` * a single column : ```css div { max-width: 30em; margin: 2em auto; padding: 0 2em; display: grid; } .line-number { margin-inline-start: -2em; /* offset */ position:absolute; /* off the flow */ } p { margin:0 } /* does it stand in the middle ? */ body, div, p:not([class]) { background: linear-gradient(to left, rgba(0, 0, 0, 0.2) 50%, #0000 50%); } ``` ```html <body> <div> <p class='line-number'>1</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p> </div> <div> <p class='line-number'>2</p> <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p> </div> <div> <p class='line-number'>3</p> <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p> </div> </body> ``` No grid, but an absolute pseud ```css body { max-width: 30em; margin: 0 auto; padding: 2em; counter-reset: ps; } p:before { counter-increment: ps; content: counter(ps); position: absolute; margin-inline-start: -2em; } /* does it stand in the middle ? */ body, p { background: linear-gradient(to left, rgba(0, 0, 0, 0.2) 50%, #0000 50%); } ``` ```html <body> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p> <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p> <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p> </body> ```
If you assign a width to the columns through column template, the p will automatically expand and fill the grids second cell. Then add a padding to your liking. You can then justify the text as you like. ```css div { display:grid; grid-template-columns: 20px 1fr; column-gap: 10px; } p { padding-right:30px; } ``` ```html <body> <div> <p class='line-number'>1</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p> </div> <div> <p class='line-number'>2</p> <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p> </div> <div> <p class='line-number'>3</p> <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p> </div> </body> ```
8,124,739
I'm trying to figure out how a method invocation that supplies unusable arguments throw a exception on the calling line of code - before it gets to the method line. Below is an example ``` 1. static Integer x; 2. public static void main(String args[]){ 3. doStuff(x)} //null pointer exception thrown on this line //lines 4-49 50. public static void doStuff(int z){} ``` Here I'm sending a Integer object reference to the method, and due to autoboxing, an Integer object is a valid reference to send. If the invoked method is not loaded onto the stack until the line 50 is reached, why does the JVM throw the null pointer exception on line 3, when it hasn't gotten to the method signature yet?
2011/11/14
[ "https://Stackoverflow.com/questions/8124739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492384/" ]
`null` cannot be `autounboxed` to a valid `int` Might be helpful to look at the actual bytecode generated. ``` public static void main(java.lang.String[]); Code: 0: getstatic #2; //Field i:Ljava/lang/Integer; 3: invokevirtual #3; //Method java/lang/Integer.intValue:()I <--- Your error comes from this line 6: invokestatic #4; //Method doStuff:(I)V 9: return ```
because your method parameter type is "int" not "Integer". so JVM want to convert the Integer Object to "int" primitive type and you object is null. so this conversion throwing the exception.
64,891,226
i use StarUML for 2 weeks now. I can't find the option for showing "in" in the methods parameters. Is there any option? I should look like this: `-foo(in param1:String[0..3], in param2:int = 0): long` Thank you!
2020/11/18
[ "https://Stackoverflow.com/questions/64891226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7175257/" ]
Universal can prerender all components of appmodule, as soon as you will go to route of that page universal will pre-render them as well, not the first page only. If you don't find universal as perfect solution, you can use puppeteer for pre-rendering that page. please find the reference below. <https://developers.google.com/web/tools/puppeteer/articles/ssr>
Inject `$sce` into your controller, and on the element you want to add the rendered html, simply use `ng-bind-html` <https://docs.angularjs.org/api/ng/directive/ngBindHtml>
3,157,454
Essentially, the situation is as follows: I have a class template (using one template parameter `length` of type `int`) and want to introduce a static array. This array should be of length `length` and contain the elements `1` to `length`. The code looks as follows up to now: ``` template<int length> class myClass{ static int array[length]; }; ``` Then I wanted to write a line for initalizing the array ``` // of course, the line below does not work as intended. template<int length> int myClass<length>::array[length]={1,2, ..., length}; ``` (How) can this be achieved?
2010/07/01
[ "https://Stackoverflow.com/questions/3157454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/255688/" ]
You can't do that with C-style arrays because they don't have value semantics. If you use something like `std::tr1::array` however then you could easily do what you want by initialising to a function result, or by using an iterator that generates those values.
It seems tough. The closest approach that i can think of would be the following : ``` template<int length> class myClass { public: myClass() { static InitializeArray<length> initializeArray(&array); } template<int length> class InitializeArray { public: InitializeArray(int* array) { for(int i = 0; i < length ; ++i) array[i] = i; } }; static int array[length]; static myClass instance; }; template<int length> int myClass<length>::array[length]; template<int length> myClass myClass::instance; ```
13,349,689
I am building a calculator that uses two sliders like this: ![enter image description here](https://i.stack.imgur.com/XoqSD.png) I have a range of CPU and RAM data that is stored in an object like this: ``` var CloudPlans = { small: { id: 'small', from: { cpu: 1, ram: 1 }, to: { cpu: 2, ram: 2 }, price: { linux: 3490, windows: 4190 } }, medium: { id: 'medium', from: { cpu: 2, ram: 2 }, to: { cpu: 4, ram: 4 }, price: { linux: 5600, windows: 6300 } }, large: { id: 'large', from: { cpu: 4, ram: 4 }, to: { cpu: 6, ram: 8 }, price: { linux: 9500, windows: 10200 } }, [...more configs here] } ``` Now based on the position and value of the slider, I have to check which plan the user has selected and then calculate the price of the components. Here is the function that checks the price range: ``` checkPlaninRange: function(cpuVal, ramVal) { if(cpuVal >= CloudPlan.small.from.cpu && cpuVal <= CloudPlan.small.to.cpu ) { return "small"; } else if (ramVal >= CloudPlan.small.from.cpu && ramVal <= CloudPlan.small.to.cpu) { return "small"; } } ``` As you can see I will be dealing with almost an endless list of conditionals to return the selected plan. Is there any way to simplify the storage or selection of these plan configs based on code other than conditionals or case statements?
2012/11/12
[ "https://Stackoverflow.com/questions/13349689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/228521/" ]
Well, coming back to this question, I thought I'd throw in my two cents... I would compress your data storage a bit by using an Array so there's no more need for the `min` values. ``` var CloudPlans = [ { id: 'small', maxcpu: 2, maxram: 2, price: { linux: 3490, windows: 4190 } }, {id: 'medium', maxcpu: 4, maxram: 4, price: { linux: 5600, windows: 6300 } }, {id: 'large', maxcpu: 6, maxram: 8, price: { linux: 9500, windows: 10200 } }, // etc ].reverse(); // reverse it so the highest plan is first ``` Notice the `.reverse()`. We're going to compare from the highest down. --- Then use a reduce function: ``` checkPlaninRange: function(cpuVal, ramVal) { return CloudPlans.reduce(function(plan, compare) { return cpuVal <= compare.maxcpu && ramVal <= compare.maxram ? compare : plan; }).id; // remove .id to return the entire object } ``` --- Or if you want something a little more efficient, use a `for` loop in the same way: ``` checkPlaninRange: function(cpuVal, ramVal) { var plan = CloudPlans[0]; for (var i = 1; i < CloudPlans.length; i++) { if (cpuVal <= CloudPlans[i].maxcpu && ramVal <= CloudPlans[i].maxram ) { plan = CloudPlans[i]; } else break; } return plan.id; // remove .id to return the entire object } ``` Not quite as clean, but it lets you break the loop early. --- These are easy to extend with additional similar comparisons.
You can make a more general function from this: ``` function check(plan, values) { for (var prop in values) if (plan.from[prop] <= values[prop] && plan.to[prop] >= values[prop]) return true; // if only one property is met return false; } // yet I guess this is what you want: function check(plan, values) { for (var prop in values) if (plan.from[prop] > values[prop] || plan.to[prop] < values[prop]) return false; // if only one property is not met return true; // if all properties are met } ``` Now your `checkPlaninRange` method could look like that: ``` checkSmallRange: function(cpuVal, ramVal) { if ( check(CloudPlan.small, {cpu:cpuVal, ram:ramVal}) ) return "small"; } ``` Of course you also can loop your cloud plans with that: ``` getPossiblePlans: function(cpuVal, ramVal) { var plans = [] for (var id in CloudPlans) if ( check(CloudPlans[id], {cpu:cpuVal, ram:ramVal}) ) plans.push(id); return plans; } ``` As @Tomasz Nurkiewicz mentioned, an array with a defined loop order would be better here. With `CloudPlans` being an object, the enumeration order is undefined (implementation-dependent) so it might return any plan when their ranges are not distinct.
10,649,151
I am trying to update status onclick. In display function i have given like this ``` if($row['IsActive']=="1") { echo "<td> <a href='managecategories.php?IsActive=0&CategoryID=" .$row['CategoryID']. "'>Active</a></td>"; } else { echo "<td> <a href='managecategories.php?IsActive=1&CategoryID=" .$row['CategoryID']. "'>Deactive</a></td>"; } ``` and on loading the page it should get the database status, for that i have written code like this ``` if (isset($_GET['IsActive'])) { $status = $_GET['IsActive']; $id = $_GET['CategoryID']; if($status =="0") { $sql = "update Categories set IsActive= 0 where CategoryID='$id'"; $result = mysql_query($sql) or die("Could not insert data into DB: " . mysql_error()); } else if($status =="1") { $sql = "update Categories set IsActive= 1 where CategoryID='$id'"; $result = mysql_query($sql) or die("Could not insert data into DB: " . mysql_error()); } } ``` But i am not getting any result not errors... please hel me where i am wrong
2012/05/18
[ "https://Stackoverflow.com/questions/10649151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1321271/" ]
If you are running on a distro like Ubuntu, then AppArmor is probably blocking mysqld from being able to access files in a different directory. If you check your system log files, you'll find a cryptic error message to this effect. Solutions include: 1. Disable AppArmor (not recommended) 2. Edit the AppArmor rules (complicated) 3. Use "mount bind" to make MySQL think that your data files are in the original location while they are actually over on the EBS volume. Revert your changes to datadir. I wrote an article for Amazon years back describing community best practices for exactly what you are trying to do including commands for the mount bind example: > > Running MySQL on Amazon EC2 with EBS > > <http://ec2ebs-mysql.notlong.com> > > > Note that the AMI id in the article is old. Using a modern Ubuntu AMI, you'll need to replace /dev/sdh with /dev/xvdh in the mkfs.xfs and /etc/fstab (but not in the ec2 tools command lines).
Change owner of /data directory to mysqld process owner (chown owner /data ). or (chmod 777 -R /data) very unsafe.
15,277,688
I've migrated an existing django 1.3 to django 1.5. everything seems ok. However, I have a deprecation warning due to localflavor when i lauch `python manage.py runserver` > > ...\env\lib\site-packages\django\contrib\loca lflavor\_\_init\_\_.py:2: > DeprecationWarning: django.contrib.localflavor is deprecated. Use the > separate django-localflavor-\* packages instead. > > warnings.warn("django.contrib.localflavor is deprecated. Use the > separate djan go-localflavor-\* packages instead.", DeprecationWarning) > > > I've read the django 1.5 release note and I understand that this app is now deprecated. My problem is that I don't use the localflavor app in my project. I imagine that another app is loading it somehow (maybe localeurl or modeltranslation?) but I don't ho wto fix this warning. * How to know why this warning is shown? * How to fix it in a clean way?
2013/03/07
[ "https://Stackoverflow.com/questions/15277688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117092/" ]
Update: > > Django now have a single localflavors package: <https://pypi.python.org/pypi/django-localflavor> > > > here is the documentation: <http://django-localflavor.readthedocs.org/en/latest/> > > > I let the rest of the response but it is obsolete now. > > > You have to download ALL local flavors you use ( <https://github.com/django/> ), for now only 3 are on pypi. Then, you can use them with the new ``` from django_localflavor_XX import forms as XX_forms ``` (where xx is your favorite country code) They choosed to put aside all those libs because a lot of commits (in foreign languages) cames in django and the releases cycles was a bit long. Django had natively mexican social security number validation widget! So it's a good move but all those packages need to be managed by local communities as soon as possible to be usable. this is trigered when an import is done, you may want to log a stack trace of the import or to look if you depends on a django app who uses it. So open your django sources, go to your contrib.localflavor `__init__.py` file. print a stacktrace to know where is the bad import. <http://docs.python.org/2/library/traceback.html> Hope it helps
Just dealt with the same issue. I installed the new package (example for US package): pip install <https://github.com/django/django-localflavor-us/zipball/master> then I commented out the old code and changed to the new package: ``` # from django.contrib.localflavor.us.us_states import STATE_CHOICES <= old from django_localflavor_us.us_states import STATE_CHOICES # from django.contrib.localflavor.us.models import USStateField <= old from django_localflavor_us.models import USStateField ``` Seems to have fixed the issue. The other language packages are listed here: <https://github.com/django>
20,347,230
I am using `xmlrpc/client` to work with remote xml-rpc server. I have searched a lot to find something useful, yet failed. The following code for establishing connection is correct? ``` require 'xmlrpc/client' def init parameters = { host: "http://x.x.x.x", port: "1235", user: "x", password: "x" } connection = XMLRPC::Client.new_from_hash(parameters) x = connection.call("user.getUserInfo", :normal_username =>"x") end ``` What kind of response should i expect if things go fine? I get `getaddrinfo: Name or service not known` when run code.
2013/12/03
[ "https://Stackoverflow.com/questions/20347230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2929467/" ]
You can use a generator function: ``` from math import ceil def solve(start, end, step): #http://stackoverflow.com/a/10986098/846892 for i in xrange(int(ceil((end-start)/step))): yield start + step*i print list(solve(80.0, 90.0, 0.5)) #[80.0, 80.5, 81.0, 81.5, 82.0, 82.5, 83.0, 83.5, 84.0, 84.5, 85.0, 85.5, 86.0, 86.5, 87.0, 87.5, 88.0, 88.5, 89.0, 89.5] ``` Or using `NumPy`: ``` >>> import numpy as np >>> np.arange(80., 90., .5) array([ 80. , 80.5, 81. , 81.5, 82. , 82.5, 83. , 83.5, 84. , 84.5, 85. , 85.5, 86. , 86.5, 87. , 87.5, 88. , 88.5, 89. , 89.5]) ```
Someone I respect once said: > > There's no point in floating point. > > > So the actual answer to your question is: You're doing it wrong :) But as that wouldn't exactly count as an answer here on SO, here's a frange function that could work for you. It elevates everything to ints and yields the floats you want. As you probably can tell by the code, `decpl` stands for "decimal places" and defines the resolution of the floating point argument. I don't think there's an easy way to reliably derive that from the value passed to the `step` argument. (Comments are welcome) ``` def frange(start, stop, step, decpl): exp = 10.0 ** decpl for i in xrange(int(start * exp), int(stop*exp), int(step*exp)): yield i / exp print list(frange(80, 90, 0.1, 1)) ```
8,693,024
I wanted to know what is the pythonic function for this : I want to remove everything before the `wa` path. ``` p = path.split('/') counter = 0 while True: if p[counter] == 'wa': break counter += 1 path = '/'+'/'.join(p[counter:]) ``` For instance, I want `'/book/html/wa/foo/bar/'` to become `'/wa/foo/bar/'`.
2012/01/01
[ "https://Stackoverflow.com/questions/8693024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186202/" ]
A better answer would be to use os.path.relpath: <http://docs.python.org/3/library/os.path.html#os.path.relpath> ``` >>> import os >>> full_path = '/book/html/wa/foo/bar/' >>> relative_path = '/book/html' >>> print(os.path.relpath(full_path, relative_path)) 'wa/foo/bar' ```
``` import re path = '/book/html/wa/foo/bar/' m = re.match(r'.*(/wa/[a-z/]+)',path) print m.group(1) ```
35,155,121
Is there an easier and shorter way to code a way to show and hide divs without having to represent each line as a show or hide? ```html function startOver() { $('.box1').hide(); $('.box2').hide(); $('#box3').hide(); $('.box4').show(); $('.box5').show(); $('.box6').show(); $('.box7').show(); $(".aboveDiv").html("Insert Text"); } ```
2016/02/02
[ "https://Stackoverflow.com/questions/35155121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547971/" ]
you can select more than one class using a `,`:- ``` $('.box1, .box2, #box3').hide(); $('.box4, .box5, .box6, .box7').show(); $(".aboveDiv").html("Insert Text"); ```
As others have said doing below will help you $('.box1, .box2, #box3').hide(); $('.box4, .box5, .box6, .box7').show(); but if you have group of such elements which toggle their status then you can apply different classes to both group i.e. '.box1, .box2, #box3' with adding class class\_a '.box4, .box5, .box6, .box7' with adding class class\_b and then you can easily toggle $('.class\_a').hide(); $('.class\_b').show();
1,528,049
I've disabled auto-correction type for my text field, and it does not show any other auto-correction, but it still automatically creates a dot (.) when I press space key twice. For example, if I write "test" and press space key twice, it automatically changes into "test. " Anyone knows how to disable this feature? Thanks a lot.
2009/10/06
[ "https://Stackoverflow.com/questions/1528049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/185242/" ]
I found one solution - it uses UITextFieldTextDidChangeNotification because this occurs after the auto-correction applies. 1. Set the delegate for the text field 2. Set up a notification `- (void) viewDidLoad { ... [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:tfTitle]; }` 3. Then, notification handler `- (void)textFieldDidChange:(NSNotification *)aNotification { if ( [textField.text rangeOfString:@". "].length ) { // Change text textField.text = [textField.text stringByReplacingOccurrencesOfString:@". " withString:@" "]; } }`
Perhaps if you hook up a text field delegate and then implement the following method: ``` -(BOOL)shouldReplaceCharactersInRange:(NSRange)aRage withString:(NSString *)aString ``` You may be able to check aString for the autocorrected string (maybe @". ") and then just return NO. This will hopefully not allow the @" " to be replaced with @". "
53,696,888
My interface is freezing on pressing the button. I am using threading but I am not sure why is still hanging. Any help will be appreciated. Thanks in advance ``` class magic: def __init__(self): self.mainQueue=queue.Queue() def addItem(self,q): self.mainQueue.put(q) def startConverting(self,funcName): if(funcName=="test"): while not self.mainQueue.empty(): t = Thread(target = self.threaded_function) t.start() t.join() def threaded_function(self): time.sleep(5) print(self.mainQueue.get()) m=magic() def helloCallBack(): m.addItem("asd") m.startConverting("test") //this line of code is freezing B = tkinter.Button(top, text ="Hello", command = helloCallBack) B.pack() top.mainloop() ```
2018/12/09
[ "https://Stackoverflow.com/questions/53696888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7315904/" ]
There are lots of ways to go about this. Here's one idea: Make a lookup that maps letters to the their values. Something like: ``` import string lookup = {s: 10**i for i,s in enumerate(string.ascii_uppercase)} ``` Lookup will be a dictionary like: > > { > > 'A': 1, > > 'B': 10, > > 'C': 100, > > 'D': 1000, > > 'E': 10000, > > 'F': 100000, > > ... > > } > > > With that you can use a comprehension and take the sum: ``` >> s = "DDBC" >> sum(lookup[l] for l in s) 2110 ``` This, of course, assumes your string is all uppercase, like the example you posted.
Try searching the string, and every instance of that letter occurring causes you to add to total. For instance: ``` total = 0 input_string = input() for i in len(input_string): if input_string[i] == "A": total += 1 ``` and then you can repeat that for the other instances of the other characters. Hope I helped!
3,889,887
If someone could help with a jscript issue I'd be very grateful! I have two scripts for different sections of the page which I'm placing in the head, but are in conflict on the same page and just can't seem to get them to work together. Both are as follows: ``` <script type="text/javascript"> jQuery.noConflict(); function updatesubcat() { $category = $('topcat').options[$('topcat').selectedIndex].value; if ($category.match(' redir')) { jQuery('#subcategory').html(''); window.location.href='/<%=server.HTMLEncode(Session("PublicFranchiseName"))%>/' + $category.replace(' redir','') + '.html'; } { PagetoDiv("/ajax/home_subcategory.asp?c="+$category,"subcategory"); } } </script> **AND:** <script type="text/javascript"> $(document).ready(function() { //Execute the slideShow, set 4 seconds for each images slideShow(4000); }); function slideShow(speed) { //append a LI item to the UL list for displaying caption $('ul.slideshow').append('<li id="slideshow-caption" class="caption"><div class="slideshow-caption-container"><h3></h3><p></p></div></li>'); //Set the opacity of all images to 0 $('ul.slideshow li').css({opacity: 0.0}); //Get the first image and display it (set it to full opacity) $('ul.slideshow li:first').css({opacity: 1.0}); //Get the caption of the first image from REL attribute and display it $('#slideshow-caption h3').html($('ul.slideshow a:first').find('img').attr('title')); $('#slideshow-caption p').html($('ul.slideshow a:first').find('img').attr('alt')); //Display the caption $('#slideshow-caption').css({opacity: 0.7, bottom:0}); //Call the gallery function to run the slideshow var timer = setInterval('gallery()',speed); //pause the slideshow on mouse over $('ul.slideshow').hover( function () { clearInterval(timer); }, function () { timer = setInterval('gallery()',speed); } ); } function gallery() { //if no IMGs have the show class, grab the first image var current = ($('ul.slideshow li.show')? $('ul.slideshow li.show') : $('#ul.slideshow li:first')); //Get next image, if it reached the end of the slideshow, rotate it back to the first image var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption')? $('ul.slideshow li:first') :current.next()) : $('ul.slideshow li:first')); //Get next image caption var title = next.find('img').attr('title'); var desc = next.find('img').attr('alt'); //Set the fade in effect for the next image, show class has higher z-index next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000); //Hide the caption first, and then set and display the caption $('#slideshow-caption').slideToggle(300, function () { $('#slideshow-caption h3').html(title); $('#slideshow-caption p').html(desc); $('#slideshow-caption').slideToggle(500); }); //Hide the current image current.animate({opacity: 0.0}, 1000).removeClass('show'); } </script> ``` **This editor is not allowing the script tags - but they are placed obviously at the top and bottom of each script** Any help much appreciated! Thanks,
2010/10/08
[ "https://Stackoverflow.com/questions/3889887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470170/" ]
I know my solution is somewhat hardcore, but it works great, doesn't require any external libraries (at least not in your final code) and is extremely fast. 1) Just take an existing SVG loading library, such as for example svg-android-2 (which is a fork of svg-android mentioned in another answer, just with more features and bugfixes): <https://code.google.com/p/svg-android-2/> 2) Write a simple app that will do nothing else but load and display your SVG image. 3) Modify the SVG loading library, so that it prints the Java code that creates the Picture class or saves it in a String variable. 4) Copy-paste the Java code obtained this way into the app you are writing. To get more information about this technique and download sample source code, go to my blog: <http://androiddreamrevised.blogspot.it/2014/06/transforming-svg-images-into-android.html> You can get a working example of this technique from Google Play here: <https://play.google.com/store/apps/details?id=pl.bartoszwesolowski.svgtodrawablesample> Here's an example of a commercial app created using this technique (Milan metro map): <https://play.google.com/store/apps/details?id=pl.bartoszwesolowski.atmmetroplan> Notice how fast the map loads and how pretty it looks, even when magnified.
[Opera Mobile](http://m.opera.com/) for Android supports svg, and [Opera Mini](http://mini.opera.com/) supports static svg content.
112,060
Consider a function which has only jump singularities of the form of the function itself or one of its derivatives jumping. Now let $\hat{f}(k)$ be its Fourier transform/series. We know the [decay of the magnitude](https://math.stackexchange.com/a/10854/2987) of the Fourier series/transform depend on how many times $f$ is continuously differentiable. But now what I am asking is are there any such similar relations which not only tells how many times $f$ is continuously differentiable, but also gives complete information about all the jump singularities of $f$, i.e., the location of the jump $x\_i$, the order of the derivative jumping $k\_i$, and the amount of the jump $D\_i$. Is it unintuitive to ask such a question? Is such a thing not intuitively possible? I have been sincerely working hard for the past two years trying find an answer to this question, and I would sincerely appreciate suggestions and insights on this question. **EDIT** (In view of comment by fedja) We assume we have complete information about all the Fourier series/transform coefficients both magnitude and phase of all the infinite coefficients. I have mentioned the relation to be somewhat like asymptotic with the only reason that no 'finite number of Fourier coefficients can give any information about the singularities. That's why I expect the relations which give information about singularities need to involve all the infinite coefficients, and in this sense I used the word asymptotic, but we essentially assume we can utilize the full information about all the Fourier coefficients. If we assume we do not have information about a finite number of Fourier coefficients, it would still not make any difference to the problem as these finite missing coefficients do not carry any info about the singularities, as they would form addition of a trignometric polynomial which is smooth. **EDIT 2** I am not interested in recontrsucting the function. There could be a lot of functions which could possess the same singularities as the given function but different from the given function. I want a property of the Fourier transform/coefficients which is obeyed by all such functions. **EDIT 3** To make my point more precise, may I add that the method should be amenable to an algorithm with infinite computations. Would it be a legitimate thing? I may be not be quite right here, but let me try to express my interest. I assume we were given all (except some finite) the Fourier coefficients, but not in any closed form expression. Say they were supplied to us as real numbers data. Now I'd like know how to do computations on them to determine the singularities. **EDIT 4** (after the answers by Igor Khavkine and Paul Garret) I am seeking for something as rigorous as this theorem. Let the function $f(\theta)$ be a BV and periodic with period $2\pi$. Let $s\_n(\theta)$ be the $n^{th}$ Fourier series partial sum then, we have $$\lim\_{n\to\infty}\frac{{s'\_n}(\theta)}{n} = \frac{1}{\pi}(f(\theta^+)-f(\theta^-))$$. Not exactly same or similar to this, but it should be as rigorous as this theorem.
2012/11/11
[ "https://mathoverflow.net/questions/112060", "https://mathoverflow.net", "https://mathoverflow.net/users/14414/" ]
Adding something to Igor Khavkine's good answer and examples: the question might be construed as talking about functions (additively) \_modulo\_Schwartz\_functions\_, for example. Thus, two functions with a jump discontinuity at the same finitely-many points, by the same amount, with the same left-and-right behaviors there, perhaps up to some fixed finite order, would fall into the same equivalence class. Fourier transform would respect the decomposition mod Schwartz functions. There are several reasonable choices for prototypes for functions otherwise rapidly decaying but with specified jumps. For example, the family of functions $x^\alpha\cdot e^{-x}$ for $x>0$ (and $0$ for $x<0$) allows specification of behavior at the jump $x=0$, and the Fourier transforms are readily computible: constant multiples of $1/(x+i)^{\alpha+1}$. Translation is obviously compatible. Thus, in this example, the asymptotics of a finite linear combination of the $x^\alpha\cdot e^{-x}$'s (and translates) at infinity (that is, modulo Schwartz) give (a finite amount of) precise information about the jumps.
The question of reconstructing piecewise-smooth (and periodic) functions from their Fourier series coefficients was considered in a series of papers by K.Eckhoff, who developed the so-called "Krylov-Gottlieb-Eckhoff method". See e.g. * K.Eckhoff, "Accurate reconstructions of functions of finite regularity from truncated Fourier series expansions" (*Mathematics of Computation, 64 (1995): 671-690.*) He showed that $\hat{f}(\xi)$ possess full asymptotic expansion, from which it is in principle possible to reconstruct the positions and the magnitudes of the jumps (and subsequently the point-wise values of the functions between the jumps). Recently, in the two papers * D.Batenkov, Y.Yomdin, "Algebraic Fourier reconstruction of piecewise-smooth functions", (*Mathematics of Computation, 81 (2012), 277-318*), <http://arxiv.org/abs/1005.1884> * D.Batenkov, "Complete Algebraic Reconstruction of Piecewise-Smooth Functions from Fourier Data" (*to appear in Mathematics of Computation*), <http://arxiv.org/abs/1211.0680> we have modified this method and actually proved that the new method's rate of convergence is the maximal possible one. In particular, we provide an explicit nonlinear algorithm to compute the singularities. An important note is that **some kind of a-priori information** is necessary in all this business. For instance, you should assume that your jumps are not too small and not too close, otherwise finite number of integral measurements might not distinguish between them. In our papers we provide explicit quantifications of this kind.
46,950,160
``` d = {'Name1': ['Male', '18'], 'Name2': ['Male', '16'], 'Name3': ['Male', '18'], 'Name4': ['Female', '18'], 'Name5': ['Female', '18']} ``` I am trying to find a way to isolate the duplicate keys to a list if any. Like: ``` ['Name1', 'Name3'] ['Name4', 'Name5'] ``` How can I achieve this? Thanks
2017/10/26
[ "https://Stackoverflow.com/questions/46950160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8836514/" ]
An imperative solution would be to just iterate over the dictionary and add the items into another dictionary that uses the gender-age-tuple as a key, for example: ``` # using a defaultdict, which automatically adds an empty list for missing keys when first accesses from collections import defaultdict by_data = defaultdict(list) for name, data in d.items(): # turn the data into something immutable, so it can be used as a dictionary key data_tuple = tuple(data) by_data[data_tuple].append(name) ``` the result will be: ``` {('Female', '18'): ['Name4', 'Name5'], ('Male', '16'): ['Name2'], ('Male', '18'): ['Name1', 'Name3']}) ``` You can filter out entries with only one value, if you are only interested in duplicates
I'm guessing you meant duplicate values and not keys, in which case you could do this with pandas: ``` import pandas as pd df = pd.DataFrame(d).T #load the data into a dataframe, and transpose it df.index[df.duplicated(keep = False)] ``` `df.duplicated(keep = False)` gives you a series of True/False, where the value is `True` whenever that item has a duplicate, and False otherwise. We use that to index the row names, which is `'Name1','Name2'`, etc.
458,249
when I type `qstat -h`, I get the following option ``` [-s {p|r|s|z|hu|ho|hs|hd|hj|ha|h|a}] show pending, running, suspended, zombie jobs, jobs with a user/operator/system/array-dependency hold, jobs with a start time in future or any combination only. h is an abbreviation for huhohshdhjha a is an abbreviation for prsh ``` What in the world is `huhohshdhjha`????
2012/12/14
[ "https://serverfault.com/questions/458249", "https://serverfault.com", "https://serverfault.com/users/149714/" ]
[From the `man` page](http://www.linuxcertif.com/man/1/qstat/): > > -s {p|r|s|z|hu|ho|hs|hd|hj|ha|h|a}[+] > > > Prints only jobs in the specified state, **any combination of states is possible**. -s prs corresponds to the regular qstat output without -s at all. To show recently finished jobs, use -s z. To display jobs in user/operator/system/array-dependency hold, use the -s hu/ho/hs/hd option. The -s ha option shows jobs which where submitted with the qsub -a command. qstat -s hj displays all jobs which are not eligible for execution unless the job has entries in the job dependency list. **qstat -s h is an abbreviation for qstat -s huhohshdhjha** and qstat -s a is an abbreviation for qstat -s psr (see -a, -hold\_jid and -hold\_jid\_ad options to > > > Emphasis added. It's a combination of the `hu`, `ho`, `hs`, `hd`, `hj` and `ha` states, and is abbreviated as `qstat -s h`, which seems much perferable to typing all those options out. **In practical terms, it's the option to print all the jobs that are on hold.** `hu` == user hold, `ho` == operator hold, `hs` == system hold, etc.
I assume `huhohshdhjha` is the combination of the options `hu`, `ho`, `hs`, `hd`, `hj`, and `ha`, as this is a general way of combining command line options. A random other example: ``` netstat -ntlp ``` Then one can ask likewise: "what the heck is the `ntlp` option? It's not in the manpage!"
19,030,972
I have written the below Java program. This program is creating three threads and started them all : ``` public class MyThread implements Runnable { @Override public synchronized void run() { int count = 0; while (true) { System.out.println("" + Thread.currentThread().getName()); if (count == 20 && Thread.currentThread().getName().equals("Thread-1")) { try { Thread.currentThread().sleep(100000000); } catch (Exception ex) { ex.printStackTrace(); } } count++; }//while ennds here }//run ends here }//class ends here public class TestThread { public static void main(String[] args){ Thread t1 = new Thread(new MyThread()); t1.setName("Thread 1"); Thread t2 = new Thread(new MyThread()); t1.setName("Thread 2"); Thread t3 = new Thread(new MyThread()); t1.setName("Thread 3"); t1.start(); t2.start(); t3.start(); } } ``` Second thread goes on sleep after some time. As the run method is synchronized, it is supposed to be accessed only by one thread at a time. Sleep method never releases the lock on the object. But here once the "Thread 1" goes to sleep, after that "Thread 2" and "Thread 3" are successfully able to access the same method and continue there execution. Can anybody explain that what is happening here ? execution should be on hold after "Thread 1" goes on sleep according to the concept of sleep.
2013/09/26
[ "https://Stackoverflow.com/questions/19030972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187257/" ]
Your `synchronized` is on an instance method. It will only be `synchronized` if you were calling the method on the same instance. You aren't doing that. You're calling the `run()` method on 3 different instances.
If you want have synchronization for all threads you need to use some static field. It could be monitor (simple Object used with synchronization) or Lock ``` private static final Lock LOCK = new ReentrantLock(); @Override public void run() { try { LOCK.lock(); // Your code } finally { LOCK.unlock(); } ```
29,058,393
I have a csv I am reading from and am making 4 lists from the first 4 columns of that csv. ``` listofcelebs = (columns['name']) listOfImages = (columns['image']) listOfProfessions = (columns['profession']) listOfBestWork = (columns['bestWork']) ``` I only need to read the items from the first list to run a twitter sentiment analysis on each item and print out the result. However I would like to print out the other lists inbetween as well. How could I print out the the first item of the list listofcelebs, then the first item of list listOfImages, then the first item of list listOfProfessions, then the first item of list listOfBestWork, then the result of the twitter sentiment analysis on the first item of list listofcelebs, a sperator ie. "--------------------------------------------------------------------- \n " then the the second item of the list listofcelebs, then the first item of list listOfImages, etc. etc. In the end I store the results in a new csv with the headings [name,image,profession,bestWork,overallSentiment]) --- Here is my code currently gives the error incorrect indentation ``` import csv import twittersearch from collections import defaultdict c = csv.writer(open("celebritiesBornTodayWithSentiment.csv", "wb")) columns = defaultdict(list) # each value in each column is appended to a list with open('celebritiesBornToday.csv') as f: reader = csv.DictReader(f) # read rows into a dictionary format for row in reader: # read a row as {column1: value1, column2: value2,...} for (k,v) in row.items(): # go over each column name and value columns[k].append(v) # append the value into the appropriate list # based on column name k listofcelebs = (columns['name']) listOfImages = (columns['image']) listOfProfessions = (columns['profession']) listOfBestWork = (columns['bestWork']) zippedListofCelebInfo = zip(listOfNames, listOfImages, listOfProfessions, listOfBestWork) #giving headings to the columns of the final csv file c.writerow(['name','image','profession','bestWork','overallSentiment']) for name in zippedListofCelebInfo: #Printing the Name of the Celebrity print "Name of the celebrity: "+name #Printing the Image of the Celebrity print "Image: "+image #Printing the Profession of the Celebrity print "Profession: "+profession #Printing the BestWork of the Celebrity print "BestWork: "+bestWork #calling twittersearch2 from the other file to derive tweet sentiment, celebrity's full name used as the query overallSentiment = twittersearch.twittersearch2(name) print "Overall Sentiment on Twitter : "+overallSentiment # End of Celebrity Details print "--------------------------------------------------------------------- \n " #saving the name, image, profession, bestWork, overallSentiment of the celebrity into a csv file c.writerow([name,image,profession,bestWork,overallSentiment]) ```
2015/03/15
[ "https://Stackoverflow.com/questions/29058393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4644825/" ]
Put the data in a vector of vectors, and use `std::sort`: ``` vector<vector<int> > vv; // Put data in the vector... vector<int> v3 = {95, 67}; vv.push_back(v3); vector<int> v4 = {76, 25}; vv.push_back(v4); vector<int> v1 = {95, 52}; vv.push_back(v1); vector<int> v2 = {95, 20}; vv.push_back(v2); vector<int> v5 = {76, 250}; vv.push_back(v5); // Sort the data sort(vv.begin(), vv.end()); ``` [Demo.](http://ideone.com/lCUezC) `std::vector` comparison is lexicographic, it works regardless of the number of items in it.
1. If you want to sort the array, taking column 1 as main index, column 2 as secondary, etc, AND GET THE FINAL RESULT. An custom sort function will do the work. ``` struct SortAll { bool operator() (int *item1, int *item2) { for (int i = 0; i < COLUMN_COUNT; ++i) { if (item1[i] < item2[i]) { return true; } else if (item1[i] > item2[i]) { return false; } } return false; } } sort_all; ``` 2. If you want to sort the array, specifying which column to sort, AND GET ONE RESULT EACH TIME. Create a sort object each time you want to sort. ``` struct SortEach { public: SortEach(int column) : column(column) { } bool operator() (int *item1, int *item2) { return item1[column] < item2[column]; } private: int column; } ``` Usage: ``` int arr[LENGTH][COLUMN_COUNT]; SortEach sort_2(2); std::sort(&arr[0], &arr[LENGTH], sort_all); // sort by all column std::sort(&arr[0], &arr[LENGTH], sort_2); // sort by column 2 ```
475,056
When inspecting the boards from electronics made in 1980s and earlier, one distinct feature is the extensive use of axial, electrolytic capacitors as power supply filter. Axial ceramic decoupling capacitors were used as well, to a lesser extent. For example, this is a C64 motherboard. [![One part of a C64 motherboard, shows 3 large axial electrolytic capacitor at the power regulator section.](https://i.stack.imgur.com/kmiKD.jpg)](https://i.stack.imgur.com/kmiKD.jpg) Source: [Wikimedia Common](https://commons.wikimedia.org/wiki/File:C64_ASSY_NO_250425_motherboard_1984.jpg), by Gona.eu, license: CC BY-SA 3.0 This is a Tektronix 1720 vectorscope board. [![One part of a Tektronix 1720 vectorscope motherboard, showing a Signetics 8051 microcontroller, surrounded by axial ceramic decoupling capacitors and axial electrolytic capacitors.](https://i.stack.imgur.com/ZotIv.jpg)](https://i.stack.imgur.com/ZotIv.jpg) Source: [Flickr](https://www.flickr.com/photos/qu1j0t3/26227821248/in/photolist-FXEruC-246GvGP-aqt7A-23ciWBv-pPokFc-qfZ3Js-CPE5n-21Nv7Xj-226SGjr-26kptAt-6nHnUL-q9dyX7-qqMduP-253heQR-q9nfJ4-YARsiH-qqMcKT-qov5kh-ptMXEL-q9kGc4-qrCffE-pu2oST-qov5yU-q9dCJf-ptMW7q-ptMXQ5-qqMcLp-pMpFrD-q9kF9x-pMbzrj-ptMXyo-q9kEYc-ptMYRU-ptN1EJ-qov5T1-qov7DL-qov7mw-q9dAaY-pu2tpt-q9etBC-q9dDFq-2i5QLWL-q9es8W-q9nbdk-q9kFND-q9naAP-ptMWNL-ptMYdu-ptMY9S-q9es23/), by Toby Thain, license: CC BY-NC 2.0 However, although they are still being manufactured, it seems that axial capacitors largely disappeared in most devices since the 90s. Almost none of electronic devices we commonly see have a single axial capacitor. And it's certain that one is going to find something similar to this in a modern device... [![The power supply board from a Tektronix MDO4000 mixed-signal oscilloscope, a lot of radial electrolytic capacitors are visible](https://i.stack.imgur.com/nL8w3.jpg)](https://i.stack.imgur.com/nL8w3.jpg) Source: [Wikimedia Common](https://commons.wikimedia.org/wiki/File:Tektronix_MDO4000_Teardown_(15845729350).jpg), by Dave Jones from Australia, license: CC BY 2.0 Question -------- **Why did Axial Capacitors Fall Out of Use in the Industry?** I can imagine that axial capacitors were optimized for point-to-point wiring back in the pre-PCB era, not PCB assembly, and that the introduction of SMT was another shot. But it was just my imagination, backed by nothing. **What were the exact sequence of events and/or rationale that led to the disuse of axial capacitors?**
2020/01/07
[ "https://electronics.stackexchange.com/questions/475056", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/130447/" ]
PCB area. Axials pre-dated PCBs, their construction was ideal for wiring to tag strips and valve bases, and they were adopted for PCBs because that's what was available. Example of tag strip construction below. (There WERE radial caps in the valve days : they were generally designed for chassis mounting via a ring clamp, and had tags rather than wire leads. The round object bottom centre is the base of one such capacitor) [![enter image description here](https://i.stack.imgur.com/vWoSE.jpg)](https://i.stack.imgur.com/vWoSE.jpg) It's actually quite surprising they lasted as long as they did alongside radials, into the 1980s. Radials use much less PCB space, and standing axials on end is a poor compromise, with a long exposed lead (or the added assembly step of sleeving it) as well as being much less robust.
My recollection of that era was that the **selection**, **size** and **price** of axial leaded electrolytic capacitors was not competitive, so I used radial lead caps in some cases where axial leaded would have been better (production had to lay them down and add a dab of adhesive). You could not find low-leakage caps, for example. Some parts, such as those used in crossover networks, may have been more popular in axial, but I was not involved that area at the time. That was probably a side effect of demand. The radial types just take up significantly less PCB space. Both were available in tape and reel or ammo box so I don't think automation was the issue.
43,485,577
What am i doing wrong here? Here is the code: ``` <script> var points = 1000; document.getElementById(pointsdisplay).innerHTML = "Points:" + points; </script> <p id="pointsdisplay"></p> ``` I want to display the points on the website. I really don't understand why this isn't working. Note that I put the script tag inside of the HTML code. Later, I will make an external js file and put everything in there.
2017/04/19
[ "https://Stackoverflow.com/questions/43485577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There are two mistakes here, 1. You need to surround id with `"` (Double Quotes) 2. You should put script tag after the `dom` element is created, else it may execute before the actual `dom` is created. Even if you keep js code in a separate file, make sure you write it after your `dom`, just before the `body` tag ends. So your code should be like, ``` <p id="pointsdisplay"></p> <script> var points = 1000; document.getElementById('pointsdisplay').innerHTML = "Points:" + points; </script> ``` Working [jsFiddle](https://jsfiddle.net/errhunter/f3s1km1v/)
I think I see two problems here. The first is that the document.getElementById needs to be given a String. You could use: `document.getElementById("pointsDisplay")`. Secondly, I think you will need to put the script underneath the p. The browser will execute the script as soon as it hits the script tag.
15,191,092
I've been trying to make a simple program that fetches a small random number and displays it to the user in a textview. After finally getting the random number to generate (I think) the program throws a fatal exception whenever I run. No errors in code, but I'm a complete newbie and I am starting simple so that I may learn. After hours I've submitted to asking for help. I'm almost certain that my snippet for random numbers is in the wrong area, I just am not sure where to put it. Everywhere I tried throws the same error. This is the .java ``` package com.eai.vgp; import java.util.Random; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } Random pp = new Random(); int a1 = pp.nextInt(10); TextView tv = (TextView)findViewById(R.id.tv);{ tv.setText(a1);} } ``` The XML ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout> ``` LogCat ``` 03-03 16:34:25.313: I/Process(740): Sending signal. PID: 740 SIG: 9 03-03 16:35:02.212: E/Trace(806): error opening trace file: No such file or directory (2) 03-03 16:35:02.802: W/ResourceType(806): No package identifier when getting value for resource number 0x00000001 03-03 16:35:02.813: D/AndroidRuntime(806): Shutting down VM 03-03 16:35:02.813: W/dalvikvm(806): threadid=1: thread exiting with uncaught exception (group=0x40a13300) 03-03 16:35:02.833: E/AndroidRuntime(806): FATAL EXCEPTION: main 03-03 16:35:02.833: E/AndroidRuntime(806): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.eai.vgp/com.eai.vgp.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x1 03-03 16:35:02.833: E/AndroidRuntime(806): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 03-03 16:35:02.833: E/AndroidRuntime(806): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 03-03 16:35:02.833: E/AndroidRuntime(806): at android.app.ActivityThread.access$600(ActivityThread.java:130) 03-03 16:35:02.833: E/AndroidRuntime(806): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 03-03 16:35:02.833: E/AndroidRuntime(806): at android.os.Handler.dispatchMessage(Handler.java:99) 03-03 16:35:02.833: E/AndroidRuntime(806): at android.os.Looper.loop(Looper.java:137) 03-03 16:35:02.833: E/AndroidRuntime(806): at android.app.ActivityThread.main(ActivityThread.java:4745) 03-03 16:35:02.833: E/AndroidRuntime(806): at java.lang.reflect.Method.invokeNative(Native Method) 03-03 16:35:02.833: E/AndroidRuntime(806): at java.lang.reflect.Method.invoke(Method.java:511) 03-03 16:35:02.833: E/AndroidRuntime(806): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 03-03 16:35:02.833: E/AndroidRuntime(806): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-03 16:35:02.833: E/AndroidRuntime(806): at dalvik.system.NativeStart.main(Native Method) 03-03 16:35:02.833: E/AndroidRuntime(806): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1 03-03 16:35:02.833: E/AndroidRuntime(806): at android.content.res.Resources.getText(Resources.java:229) 03-03 16:35:02.833: E/AndroidRuntime(806): at android.widget.TextView.setText(TextView.java:3620) 03-03 16:35:02.833: E/AndroidRuntime(806): at com.eai.vgp.MainActivity.onCreate(MainActivity.java:22) 03-03 16:35:02.833: E/AndroidRuntime(806): at android.app.Activity.performCreate(Activity.java:5008) 03-03 16:35:02.833: E/AndroidRuntime(806): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 03-03 16:35:02.833: E/AndroidRuntime(806): atandroid.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 03-03 16:35:02.833: E/AndroidRuntime(806): ... 11 more 03-03 16:35:05.113: I/Process(806): Sending signal. PID: 806 SIG: 9 ```
2013/03/03
[ "https://Stackoverflow.com/questions/15191092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2129763/" ]
You are trying to set int value to `TextView` so you are getting this issue. To solve this try below one option option 1: ``` tv.setText(no+""); ``` Option2: ``` tv.setText(String.valueOf(no)); ```
This always can happen in DataBinding. Try to stay away from adding logic in your bindings, including appending an empty string. You can make your own custom adapter, and use it multiple times. ``` @BindingAdapter("numericText") fun numericText(textView: TextView, value: Number?) { value?.let { textView.text = value.toString() } } ``` `<TextView app:numericText="@{list.size()}" .../>`
24,610,545
**Scenario**: * I am matching cases up via using the distance between two points (using lat and long). * Everything is done in a table. * I get a list of 'tds' with class 'city', and make an array. * Then I sort the array based on 'data-distance' attribute * I then highlight the top ten, and if two 'data-distance' has the same value, highlight them both, and then highlight, lets say 11 instead of 10, because two have the same 'data-distance' This is a screenshot of what I currently have, and an overview: ![enter image description here](https://i.stack.imgur.com/WuZ6E.png) At the moment, it currently highlights the top ten, and if two values are the same, highlight them the same color, but it does not hightlight another one after 10. **Current Code** ``` var c_tds = $('td.city'); var c_arr = $.makeArray(c_tds); c_arr.sort(function(a,b) { var A = $(a).attr('data-distance'); var B = $(b).attr('data-distance'); return B - A; }); for ( var i = 1; i <= 5; i++ ) { var A1 = $(c_arr[c_arr.length-i]); var A2 = $(c_arr[c_arr.length-(i-1)]); if(A1.attr('data-distance') == A2.attr('data-distance')){ console.log(A1); } A1.addClass('success'); } for ( var i = 6; i <= 10; i++ ) { var B1 = $(c_arr[c_arr.length-i]); var B2 = $(c_arr[c_arr.length-(i-1)]); if(B1.attr('data-distance') == B2.attr('data-distance')){ console.log(i); if(i == 6) { B1.addClass('success'); } else { B1.addClass('warning'); } } else { B1.addClass('warning'); } } ``` **Question** How can I get it so that if two values are the same, then add an extra one to highlight (keeping the minimum highlight count of 10)
2014/07/07
[ "https://Stackoverflow.com/questions/24610545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Deactivating horizontal scrolling may fix the issue. Try running the following at the gnome-terminal: ``` synclient HorizEdgeScroll=0 HorizTwoFingerScroll=0 ``` Or the following in the MATLAB [console](http://in.mathworks.com/help/matlab/matlab_external/run-external-commands-scripts-and-programs.html): ``` !synclient HorizEdgeScroll=0 HorizTwoFingerScroll=0 ``` (source: <http://www.mathworks.com/matlabcentral/answers/112528-mevent-case-when-two-finger-scrolling>)
GNOME 3.20 ::SYNCLIENT IS OBSOLETE, Fixing the MEvent. CASE! error in MATLAB for xinput The suggested solution is to run ``` !synclient HorizTwoFingerScroll=0 ``` as part of your startup file to disable horizontal scrolling. This however does not work on more recent linux versions because the synaptics touchpad driver is being deprecated in favour of libinput. The new solution to this problem is slightly more complex however. First we need to find the id of the touchpad device with the xinput list command from a terminal (not the MATLAB command window). You should see something like: ``` ~$ xinput list ⎡ Virtual core pointer id=2 [master pointer (3)] ⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)] ⎜ ↳ SynPS/2 Synaptics TouchPad id=13 [slave pointer (2)] ⎜ ↳ ELAN Touchscreen id=11 [slave pointer (2)] ``` We are interested in the SynPS/2 Synaptics TouchPad which in this case has id=13. We can see the configuration options supported by this device by running : ``` ~$ xinput list-props 13 ``` Remember to change 13 to the id of the touchpad on your machine ! In the output you should see a line like: ``` Synaptics Two-Finger Scrolling (283): 1, 1 ``` This tells you that two finger scrolling is enabled in the vertical and horizontal directions. To change this run : ``` ~$ xinput set-prop 13 "Synaptics Two-Finger Scrolling" 1 0 ``` If you couldn't find the "Two-Finger Scrolling" line all is not lost. Look for a line related to horizontal scrolling. In my case that was: ``` libinput Horizonal Scroll Enabled (266): 1 ``` and the command used to disable this property is: ``` ~$ xinput set-prop 13 "libinput Horizonal Scroll Enabled" 0 ``` To have this run automatically every time you run MATLAB you can add ``` !xinput set-prop 13 "libinput Horizonal Scroll Enabled" 0 ``` to your startup file.
740,151
After making a few changes in my application, my textures are no longer showing. So far I've checked the following: * The camera direction hasn't changed. * I can see the vectors (when colored instead of textured). Any usual suspects?
2009/04/11
[ "https://Stackoverflow.com/questions/740151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47775/" ]
You may want to check the following: * `glEnable(GL_TEXTURE_2D);` presence * `glBindTexture(GL_TEXTURE_2D, texture[i]);` and `glBindTexture(GL_TEXTURE_2D, 0);` when you don't need texture anymore
A few more things to check: * glColorMaterial(...); To make sure colors aren't overwriting the texture * glEnable/glDisable(GL\_LIGHTING); Sometimes lighting can wash out the texture * glDisable(GL\_BLEND); Make sure that you're not blending the texture out * Make sure the texture coordinates are set properly.
19,405,600
I'm in the process of learning javascript and get confused by regular expressions (regex). It can sometimes be the syntax but mostly my understanding of regex is very poor. for instance `var pattern = /^0+$/;` just looks like crap to me. Can this jQuery if/else statement be converted to a regex method? and if so, how/why? ``` // Set header link widths based on how many there are var nav = $('#nav_header a'); var navlinks = $('#nav_header').children('a').length; if (navlinks == 1) { nav.css('width', '100%'); } else if (navlinks == 2) { nav.css('width', '50%'); } else if (navlinks == 3) { nav.css('width', '32%'); } else if (navlinks == 4) { nav.css('width', '25%'); } else if (navlinks == 5) { nav.css('width', '20%'); } else if (navlinks == 6) { nav.css('width', '16.6%'); } else if (navlinks == 7) { nav.css('width', '14.25%'); } else if (navlinks == 8) { nav.css('width', '12%'); } else if (navlinks == 9) { nav.css('width', '11%'); } else if (navlinks == 10) { nav.css('width', '10%'); } else { nav.css('width', '8%'); } ``` Are there specific techniques to writing regex JS, things to consider and to try and keep it human-readable? Thanks for your help and advice :)
2013/10/16
[ "https://Stackoverflow.com/questions/19405600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2326886/" ]
My advice, create a simple look-up array: ``` var percents = ["100%", "50%", "32%", "25%", "20%", "16.6%", "14.25%", "12%", "11%", "10%", "8%"]; var nav = $('#nav_header a'); var navlinks = $('#nav_header').children('a').length; navlinks == 0 ? nav.css("width", "8%") : nav.css("width", percents[navlinks - 1]); ```
> > var pattern = /^0+$/; just looks like crap to me. > > > Actually that is an easy one, it only matches a string if that string contains only `0`s. > > Can this jQuery if/else statement be converted to a regex method? and if so, how/why? > > > No it can't. Regular expressions are used to find patterns in text or split the text around a given pattern or replace a given pattern. They can't be used instead of conditional statements.
7,563,169
I am building a JS script which at some point is able to, on a given page, allow the user to click on any word and store this word in a variable. I have one solution which is pretty ugly and involves class-parsing using jQuery: I first parse the entire html, split everything on each space `" "`, and re-append everything wrapped in a `<span class="word">word</span>`, and then I add an event with jQ to detect clicks on such a class, and using $(this).innerHTML I get the clicked word. This is slow and ugly in so many ways and I was hoping that someone knows of another way to achieve this. PS: I might consider running it as a browser extension, so if it doesn't sound possible with mere JS, and if you know a browser API that would allow that, feel free to mention it ! A possible owrkaround would be to get the user to highlight the word instead of clicking it, but I would really love to be able to achieve the same thing with only a click !
2011/09/27
[ "https://Stackoverflow.com/questions/7563169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/725182/" ]
The only cross-browser (IE < 8) way that I know of is wrapping in `span` elements. It's ugly but not really that slow. This example is straight from the jQuery .css() function documentation, but with a huge block of text to pre-process: <http://jsfiddle.net/kMvYy/> Here's another way of doing it (given here: [jquery capture the word value](https://stackoverflow.com/questions/6181002/jquery-capture-the-word-value) ) on the same block of text that doesn't require wrapping in `span`. <http://jsfiddle.net/Vap7C/1>
As with the [accepted answer](https://stackoverflow.com/a/9304990/712526), this solution uses `window.getSelection` to infer the cursor position within the text. It uses a regex to reliably find the word boundary, and does not restrict the [starting node](https://developer.mozilla.org/en-US/docs/Web/API/Range/startContainer) and [ending node](https://developer.mozilla.org/en-US/docs/Web/API/Range/endContainer) to be the same node. This code has the following improvements over the [accepted answer](https://stackoverflow.com/a/9304990/712526): * Works at the beginning of text. * Allows selection across multiple nodes. * Does not modify selection range. * Allows the user to override the range with a custom selection. * Detects words even when surrounded by non-spaces (e.g. `"\t\n"`) * Uses vanilla JavaScript, only. * No alerts! ```js getBoundaryPoints = (range) => ({ start: range.startOffset, end: range.endOffset }) function expandTextRange(range) { // expand to include a whole word matchesStart = (r) => r.toString().match(/^\s/) // Alternative: /^\W/ matchesEnd = (r) => r.toString().match(/\s$/) // Alternative: /\W$/ // Find start of word while (!matchesStart(range) && range.startOffset > 0) { range.setStart(range.startContainer, range.startOffset - 1) } if (matchesStart(range)) range.setStart(range.startContainer, range.startOffset + 1) // Find end of word var length = range.endContainer.length || range.endContainer.childNodes.length while (!matchesEnd(range) && range.endOffset < length) { range.setEnd(range.endContainer, range.endOffset + 1) } if (matchesEnd(range) && range.endOffset > 0) range.setEnd(range.endContainer, range.endOffset - 1) //console.log(JSON.stringify(getBoundaryPoints(range))) //console.log('"' + range.toString() + '"') var str = range.toString() } function getTextSelectedOrUnderCursor() { var sel = window.getSelection() var range = sel.getRangeAt(0).cloneRange() if (range.startOffset == range.endOffset) expandTextRange(range) return range.toString() } function onClick() { console.info('"' + getTextSelectedOrUnderCursor() + '"') } var content = document.body content.addEventListener("click", onClick) ``` ```html <div id="text"> <p>Vel consequatur incidunt voluptatem. Sapiente quod qui rem libero ut sunt ratione. Id qui id sit id alias rerum officia non. A rerum sunt repudiandae. Aliquam ut enim libero praesentium quia eum.</p> <p>Occaecati aut consequuntur voluptatem quae reiciendis et esse. Quis ut sunt quod consequatur quis recusandae voluptas. Quas ut in provident. Provident aut vel ea qui ipsum et nesciunt eum.</p> </div> ``` Because it uses [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), this code doesn't work in IE; but that is easy to adjust. Furthermore, because it allows the user selection to span across nodes, it may return text that is usually not visible to the user, such as the contents of a script tag that exists within the user's selection. (Triple-click the last paragraph to demonstrate this flaw.) You should decide which kinds of nodes the user should see, and filter out the unneeded ones, which I felt was beyond the scope of the question.
12,793,435
How do you ensure that you don't send out real http requests while running tests. I'm having a hard time finding documentation for this.
2012/10/09
[ "https://Stackoverflow.com/questions/12793435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1042382/" ]
This is only available in Play 2.3.x, but a MockWS client is available: <https://github.com/leanovate/play-mockws> ``` val ws = MockWS { case (GET, "http://dns/url") => Action { Ok("http response") } } await(ws.url("http://dns/url").get()).body == "http response" ```
WS.url is static. So you need to use powermock to test static methods. [See this tutorial](http://code.google.com/p/powermock/wiki/MockStatic)
43,898,447
I've been trying to GET a HTML file and assign it to a variable as a jQuery object. To no avail. I'm not sure if Stack Snippets allow GET requests, so here is a [JSFiddle link](https://jsfiddle.net/k3s3xz2x/) as well. ```js var html = '<!DOCTYPE html><html lang="en"><head><title>Template</title></head><body itemscope itemtype="http://schema.org/WebPage"><main><header itemscope itemtype="http://schema.org/Country" itemprop="about"><h1 itemprop="name">Dummy heading</h1><p><span class="capital" title="Capital" itemprop="containsPlace"></span><span title="Dummy title" itemprop="additionalProperty" itemscope itemtype="http://schema.org/PropertyValue"><meta itemprop="name" content="Member of the EU since"><span itemprop="value" class="member-since">Dummy year</span></span></p></header><div itemprop="mainEntity" itemscope itemtype="http://schema.org/ItemList"><meta itemprop="description" content=""><article class="recipe loading" itemprop="itemListElement" itemscope itemtype="http://schema.org/Recipe"><meta itemprop="position" content=""><aside class="media"><div class="img-gallery" itemscope itemtype="http://schema.org/ImageGallery"></div><div itemscope itemtype="http://schema.org/VideoObject" class="youtube"><a itemprop="contentUrl" href="#" title=""><meta itemprop="name" content=""><meta itemprop="uploadDate" content=""><meta itemprop="description" content=""><img itemprop="thumbnailUrl" src="#" alt=""></a><div class="youtube-player"></div></div></aside><div class="text"><div class="wiki-text"><h1 itemprop="name">Dummy heading</h1><p itemprop="description"></p><p class="read-more">For more information about <span class="recipe-name"></span>, read the <a href="#" title="" itemprop="sameAs">Wiki</a>.</p></div><div class="rating" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">Rated <span itemprop="ratingValue">3.5</span>/5 based on <span itemprop="reviewCount">11</span> customer reviews</div><div class="cooking"><h2>Bake it yourself!</h2><div><meta itemprop="cookTime" content=""><span>Bake time: <span class="bake-time"></span></span></div><div class="ingredients-wrapper"><h3>Ingredients <small>for <span itemprop="recipeYield"></span></small></h3><div class="ingredients"><h4>Dummy heading</h4><ul></ul></div></div><div class="how-to"><h3>Steps</h3><ol></ol></div></div></div></article></div></main></body></html>'; $.ajax({ type: 'post', url: "/echo/html/", dataType: "html", data: { html: html, delay: 1 } }).done(function(data) { // string console.log(data); // array console.log($(data)); // array console.log($.parseHTML(data)); // array console.log($($.parseHTML(data))); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ``` The HTML is valid. Yet, I can't get it in an object. The returned data is, as expected, a string. But when I try to parse that string as HTML using `$.parseHTML()` or putting it in a jQuery selector `$()` or even try both I always get the same result: an array containing the title and main element. So some way some how jQuery still parses it and makes an array of the element in the head and the one element in the body. But *why*? And how can I remedy this, and transform it into a jQuery object? I am only interested in the contents of the body. There is [a similar question](https://stackoverflow.com/questions/20007721/parsing-returned-html-from-jquery-ajax-request), but the accepted solution doesn't help as it goes into JSFiddle and I'm also experiencing this problem locally with XAMPP.
2017/05/10
[ "https://Stackoverflow.com/questions/43898447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1150683/" ]
Set [`jQuery.ajax()`](https://meta.stackoverflow.com/questions/288902/does-stack-overflow-have-an-echo-page-to-test-ajax-requests-inside-a-code-sni/290948#290948) `processData` option to `false`. Use `DOMParser()` to parse string to an `html` `document`; `XMLSerizlizer()` to get `DOCTYPE` declaration; `document.write()` to write `DOCTYPE` and parsed `document` `.documentElement.outerHTML` to current or other `html` `document`. > > **processData** (default: `true`) > > > Type: Boolean > > > By default, data passed in to the `data` option as an object > (technically, anything other than a string) will be processed and > transformed into a query string, fitting to the default content-type > "application/x-www-form-urlencoded". If you want to send a > DOMDocument, or other non-processed data, set this option to `false`. > > > --- > > I'm not sure if Stack Snippets allow GET requests > > > Yes. It is possible to echo `GET` request by setting `url` to `data URI` or `Blob URL` representation of resource at `$.ajax()`, `XMLHttpRequest()` or `fetch()`, see [Does Stack Overflow have an “echo page” to test AJAX requests, inside a code snippet?](https://meta.stackoverflow.com/questions/288902/does-stack-overflow-have-an-echo-page-to-test-ajax-requests-inside-a-code-sni/290948#290948) ```js var html = `<!DOCTYPE html> <html lang="en"> <head> <title>Template</title> </head> <body itemscope itemtype="http://schema.org/WebPage"> <main> <header itemscope itemtype="http://schema.org/Country" itemprop="about"> <h1 itemprop="name">Dummy heading</h1> <p><span class="capital" title="Capital" itemprop="containsPlace"></span><span title="Dummy title" itemprop="additionalProperty" itemscope itemtype="http://schema.org/PropertyValue"><meta itemprop="name" content="Member of the EU since"><span itemprop="value" class="member-since">Dummy year</span></span> </p> </header> <div itemprop="mainEntity" itemscope itemtype="http://schema.org/ItemList"> <meta itemprop="description" content=""> <article class="recipe loading" itemprop="itemListElement" itemscope itemtype="http://schema.org/Recipe"> <meta itemprop="position" content=""> <aside class="media"> <div class="img-gallery" itemscope itemtype="http://schema.org/ImageGallery"></div> <div itemscope itemtype="http://schema.org/VideoObject" class="youtube"> <a itemprop="contentUrl" href="#" title=""> <meta itemprop="name" content=""> <meta itemprop="uploadDate" content=""> <meta itemprop="description" content=""><img itemprop="thumbnailUrl" src="#" alt=""></a> <div class="youtube-player"></div> </div> </aside> <div class="text"> <div class="wiki-text"> <h1 itemprop="name">Dummy heading</h1> <p itemprop="description"></p> <p class="read-more">For more information about <span class="recipe-name"></span>, read the <a href="#" title="" itemprop="sameAs">Wiki</a>.</p> </div> <div class="rating" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">Rated <span itemprop="ratingValue">3.5</span>/5 based on <span itemprop="reviewCount">11</span> customer reviews</div> <div class="cooking"> <h2>Bake it yourself!</h2> <div> <meta itemprop="cookTime" content=""><span>Bake time: <span class="bake-time"></span></span> </div> <div class="ingredients-wrapper"> <h3>Ingredients <small>for <span itemprop="recipeYield"></span></small></h3> <div class="ingredients"> <h4>Dummy heading</h4> <ul></ul> </div> </div> <div class="how-to"> <h3>Steps</h3> <ol></ol> </div> </div> </div> </article> </div> </main> </body> </html>`; $.ajax({ type: "GET", url: "data:text/html," + html, processData: false }) .then(function(data) { // string console.log(data); var parser = new DOMParser(); // document var d = parser.parseFromString(data, "text/html"); // `document`, `document` as jQuery object console.log(d, $(d)); // get elements having `itemscope` attribute console.log($(d).find("[itemscope]")); // do stuff var dt = new XMLSerializer().serializeToString(d.doctype); document.write(dt, d.documentElement.outerHTML); }) .fail(function(jqxhr, textStatus, errorThrown) { console.log(errorThrown); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ``` It is also possible to import an `html` `document` to current `document` using `<link>` element with `rel` attribute set to `"import"`, see [How to append a whole html file with jquery](https://stackoverflow.com/questions/43404728/how-to-append-a-whole-html-file-with-jquery/43405004#43405004).
> > I always get the same result: an array containing the title and main element. > > > What exactly is the problem? > > jQuery still parses it and makes an array of the element in the head and the one element in the body. But why? > > > What are you expecting? That seems to be the behavior of parseHtml. Here's another example: ``` $.parseHTML("<div>Hello<span>World</span></div>") ``` It returns an array with one element: `div` If you look at the [docs for parseHTML](http://api.jquery.com/jQuery.parseHTML/) it says: > > Parses a string into an array of DOM nodes. > > > So it seems to be doing exactly what it's supposed to. > > I am only interested in the contents of the body. > > > The content of the body is `main` which as you have noted is the second element. What do you want to do with it? You can wrap it in a jQuery object by passing it to the jQuery constructor. ``` var html = '<!DOCTYPE html><html lang="en"><head><title>Template</title></head><body itemscope itemtype="http://schema.org/WebPage"><main><header itemscope itemtype="http://schema.org/Country" itemprop="about"><h1 itemprop="name">Dummy heading</h1><p><span class="capital" title="Capital" itemprop="containsPlace"></span><span title="Dummy title" itemprop="additionalProperty" itemscope itemtype="http://schema.org/PropertyValue"><meta itemprop="name" content="Member of the EU since"><span itemprop="value" class="member-since">Dummy year</span></span></p></header><div itemprop="mainEntity" itemscope itemtype="http://schema.org/ItemList"><meta itemprop="description" content=""><article class="recipe loading" itemprop="itemListElement" itemscope itemtype="http://schema.org/Recipe"><meta itemprop="position" content=""><aside class="media"><div class="img-gallery" itemscope itemtype="http://schema.org/ImageGallery"></div><div itemscope itemtype="http://schema.org/VideoObject" class="youtube"><a itemprop="contentUrl" href="#" title=""><meta itemprop="name" content=""><meta itemprop="uploadDate" content=""><meta itemprop="description" content=""><img itemprop="thumbnailUrl" src="#" alt=""></a><div class="youtube-player"></div></div></aside><div class="text"><div class="wiki-text"><h1 itemprop="name">Dummy heading</h1><p itemprop="description"></p><p class="read-more">For more information about <span class="recipe-name"></span>, read the <a href="#" title="" itemprop="sameAs">Wiki</a>.</p></div><div class="rating" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">Rated <span itemprop="ratingValue">3.5</span>/5 based on <span itemprop="reviewCount">11</span> customer reviews</div><div class="cooking"><h2>Bake it yourself!</h2><div><meta itemprop="cookTime" content=""><span>Bake time: <span class="bake-time"></span></span></div><div class="ingredients-wrapper"><h3>Ingredients <small>for <span itemprop="recipeYield"></span></small></h3><div class="ingredients"><h4>Dummy heading</h4><ul></ul></div></div><div class="how-to"><h3>Steps</h3><ol></ol></div></div></div></article></div></main></body></html>'; var parsed = $.parseHTML(html) var main = parsed[1] var $main = $(main) // $main is a jQuery object console.log("h4 content:", $main.find('h4').text()) ```
18,770,100
My app is compatible with iOS5 and iOS6. Until now I had no problem using: ``` NSString DeviceID = [[UIDevice currentDevice] uniqueIdentifier]; ``` Now with iOS7 and with uniqueIdentifier not working anymore I changed to: ``` NSString DeviceID = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; ``` The problem is, this would not work for iOS5. How can I achieve backward compatibility with iOS5? I tried this, with no luck: ``` #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000 // iOS 6.0 or later NSString DeviceID = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; #else // iOS 5.X or earlier NSString DeviceID = [[UIDevice currentDevice] uniqueIdentifier]; #endif ```
2013/09/12
[ "https://Stackoverflow.com/questions/18770100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773538/" ]
The best and recommend option by Apple is: ``` NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; ``` Use it for every device above 5.0. For 5.0 you have to use uniqueIdentifier. The best to check if it's available is: ``` if (!NSClassFromString(@"ASIdentifierManager")) ``` Combining that will give you: ``` - (NSString *) advertisingIdentifier { if (!NSClassFromString(@"ASIdentifierManager")) { SEL selector = NSSelectorFromString(@"uniqueIdentifier"); if ([[UIDevice currentDevice] respondsToSelector:selector]) { return [[UIDevice currentDevice] performSelector:selector]; } //or get macaddress here http://iosdevelopertips.com/device/determine-mac-address.html } return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; } ```
As hard replacement of static macro, you can try dynamic if statement to check it. UIDevice has property named 'systemVersion' and you can check [this](https://developer.apple.com/library/ios/documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/occ/instp/UIDevice/systemVersion).
11,833,905
How do you handle a "cannot instantiate abstract class" error in C++? I have looked at some of the similar errors here and none of them seem to be exactly the same or problem that I am having. But, then again, I will admit that there are several to go over. Here is the compile error: ![[IMG]http://i67.photobucket.com/albums/h292/Athono/cannotinstantiateabstractclass.png[/IMG]](https://i.stack.imgur.com/7idT9.png) This leads me to this page: <http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(C2259);k(VS.ERRORLIST)&rd=true> Compile Error C2259 is from a C++ program but the page calls the abstract class an "interface": > > Whenever you derive from an interface and implement the interface methods in the derived class with access permissions other than public, you may receive C2259. This occurs because the compiler expects the interface methods implemented in the derived class to have public access. When you implement the member functions for an interface with more restrictive access permissions, the compiler does not consider them to be implementations for the interface methods defined in the interface, which in turn makes the derived class an abstract class. > > > There are two possible workarounds for the problem: > > > Make the access permissions public for the implemented methods. > > > Use the scope resolution operator for the interface methods implemented in the derived class to qualify the implemented method name with the name of the interface. > > > The bad news is that I have already made all of the methods public in the class: ``` class AmbientOccluder: public Light { public: AmbientOccluder(void); ```
2012/08/06
[ "https://Stackoverflow.com/questions/11833905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54760/" ]
Visual Studio's *Error List* pane only shows you the first line of the error. Invoke `View`>`Output` and I bet you'll see something like: ``` c:\path\to\your\code.cpp(42): error C2259: 'AmbientOccluder' : cannot instantiate abstract class due to following members: 'ULONG MysteryUnimplementedMethod(void)' : is abstract c:\path\to\some\include.h(8) : see declaration of 'MysteryUnimplementedMethod' ```
I have answered this question here..[Covariant virtual functions return type problem](https://stackoverflow.com/questions/5076226/covariant-virtual-functions-return-type-problem/27813060#27813060) See if it helps for some one.
130,647
Of these buildings, what building(s) should I save in the event of any enemy ubercharge (Medi Gun/Kritzkrieg/Quick-Fix/Vaccinator)? 1) Sentry Gun Level 1/2/3 2) Dispenser Level 1/2/3 3) Teleporter Entrance/Exit Level 1/2/3
2013/09/12
[ "https://gaming.stackexchange.com/questions/130647", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/55174/" ]
I can't think of a single situation where you wouldn't want to protect your level 3 sentry. Yes, you and your nest might be doomed, but every second of invincibility spent on your nest is a second of invincibility not spent on the rest of your team. Even on offence, where your teleporter is more important than your sentry, you want to tank the sentry that's protecting your teleporter. Stand by your sentry, aim at the enemy pocket, crouch, use the wrangler to multiply your sentry's hit points by six, then wrench it to heal it, then wrangle again, rely on your team to counter the uber with you. Stickies? Shoot rockets at the ground directly below the sentry, pushing them away - possibly onto you. Heavy? Crouch. Kritz soldier? Take cover behind dispenser. etc. The single worst move you can do is actually pick up a building. An unmanned level three building is typically easy pray of uber combos, and if you really don't care about that sentry - maybe it was level 2 and truly doomed - then the next best thing is to get yourself out of there alive, and get out of there fast -possibly even before the uber arrives. A dead teleporter is a bummer, but a dead teleporter and a dead engineer is worse. Picking up buildings makes you slower and all the more unlikely that the enemy team will give you a chance to survive. All of this, of course, applies to actual sentries. Mini sentries vs ubers is a no brained; just get the hell out of there for the next eight seconds, then plop down seventy more minis. The uber isn't coming for you, so this should be rather more feasible.
I would recommend running away with the dispenser. While your sentry will be doomed for sure, you will be able to quickly rebuild it with the metal stored in your dispenser. As for your teleporter, you didn't just leave that lying in plain sight, right? The important thing is, your buildings are all doomed to explode some time or the other. But after the rest of your team drives them back, you can quickly get your sentry back to level three.
45,061,615
I have a text here in anchor tag which says add to cart but on mobile view I want to change it to fa fa-cart mobile view ``` <a class="product"><?php echo $button_add_to_cart ?></a> ``` Now this $button\_add\_to\_cart has text Add to cart and a cart(fa fa-cart). On mobile view I want [![enter image description here](https://i.stack.imgur.com/WuZEc.png)](https://i.stack.imgur.com/WuZEc.png) on mobile view I just want a cart CSS : ``` .thumbnail a.product{ background: #00A1CB; color: #fff; float: right; padding: 5px; font-size: 13px; text-transform: uppercase; position: relative; } .thumbnail a.product:before { position: absolute; font-family: FontAwesome; font-size: 16px; content: "\f07a"; top: 5px; right: 8px; } ``` I tried to replace text with: ``` @media only screen and (max-width: 479px) { .thumbnail a.product{ content:"\f07a"; }} ``` Its not working
2017/07/12
[ "https://Stackoverflow.com/questions/45061615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8065971/" ]
**Solution1:** ``` <a class="product desktop-screen"><?php echo $button_add_to_cart ?></a> <a class="product mobile-screen"><?php echo $cart ?></a> ``` css: ``` desktop-screen{display:block;} mobile-screen{display:none;} @media only screen and (max-width: 479px) { desktop-screen{display:none;} mobile-screen{display:block} } } ``` **Solution2:** using jQuery ``` <a class="product"><?php echo $button_add_to_cart ?></a> <script> $(window).on('resize', function(){ var win = $(this); var a_tag_text = "add to cart"; var icon = "<i class="fa fa-cart"></i>" if (win.width() <= 479) { $(".product").html(icon); }else{ $(".product").html(a_tag_text + icon); } }); </script> ```
I have added `span` and removed positioning on the pseudo element, also added text in the `content`. It works for me. ```css .thumbnail a.product { background: #00A1CB; color: #fff; float: right; padding: 5px; font-size: 13px; text-transform: uppercase; position: relative; } .thumbnail a.product span:before { font-family: FontAwesome; font-size: 16px; content: "add to cart \f07a"; } @media only screen and (max-width: 479px) { .thumbnail a.product span:before { font-family: FontAwesome; font-size: 16px; content: "\f07a"; } } ``` ```html <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"/> <div class="thumbnail"> <a class="product"><span></span></a> </div> ```
562,925
I am creating a model that utilize the output probability distribution of another model, as an input. The model outputs a probability of an event occurring per year, the distribution is a probability between (between 0 and 1) and right skewed, it is defined by Mean = 0.019, Mode = 0.009, 90% confidence interval: 5th percentile = 0.0002, 95th percentile = 0.07. I want to use a beta distribution so I can perform a Bayesian update using a binomial likelihood for the update. However, I am uncertain of 1) if it is appropriate to use a beta distribution (as opposed to a lognormal) and how to prove if it is appropriate or not, and 2) how to determine the parameters of the beta distribution from the available information. In relation to 2) I have looked at several articles on cross validate which seem related but I cannot quite work out how to implement: [Calculate the confidence interval for the mean of a beta distribution](https://stats.stackexchange.com/questions/82475/calculate-the-confidence-interval-for-the-mean-of-a-beta-distribution) [Calculating the parameters of a Beta distribution using the mean and variance](https://stats.stackexchange.com/questions/12232/calculating-the-parameters-of-a-beta-distribution-using-the-mean-and-variance) This one seems the closest and easiest to implement: [Selecting alpha and beta parameters for a beta distribution, based on a mode and a 95% credible interval](https://stats.stackexchange.com/questions/327062/selecting-alpha-and-beta-parameters-for-a-beta-distribution-based-on-a-mode-and) In the model I am creating it is possible to define a reparametrized beta distribution according to Mean and standard deviation, so I thought that I would be able to solve equations with the above mentioned values to obtain the standard deviation and define the beta distribution but now I am not sure if this is possible.
2022/02/03
[ "https://stats.stackexchange.com/questions/562925", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/261092/" ]
Your understanding is only half correct. PCA (Principal Component Analysis) is a dimensionality reduction technique that finds underlying patterns in data to reduce the number of features in a dataset. It does not make predictions; rather, it generates new dimensions from existing data for further analysis or visualization. PCA can be reversed (or "back-transformed") to reconstruct the original data, but this does not imply predicting a new point in the PCA space. To do so, you would need to use a supervised learning algorithm, such as a regression model trained on the PCA-transformed data, predict a new point (in the PC space), and then use the inverse transform to project the predicted principal components to the original space. I'm not as familiar with UMAP, but it appears to be similar in that it can be used to reduce the dimensionality of a dataset and then inverted to reconstruct the original data. This is not, once again, the same as making a prediction. I hope this helps!
You're missing a step: fitting some kind of predictive model. Once you transform your PCA feature space into the original features (which need not be unique unless you use all of the PCs), you have to have some way of interpreting that. For the MNIST digits to which you allude, that could be a convolutional neural network, through which you pass the $28\times 28$ picture you derive from your point in the PCA space. For other data, you might prefer another model. Ditto for UMAP.