text
stringlengths
64
89.7k
meta
dict
Q: Rate of growth of exponential functions I have difficulties about proving the following: Prove that exponential functions $a^n$ have different orders of growth for different values of base $a>0$. It looks obvious that when $a=3$ it grows faster when compared to $a=2$. But how do i make a formal proof for this? Thanks for your help. A: Here's a sketch of a proof: suppose $a,b>0$, and $a\neq b$. Without loss of generality, $a>b$. We want to show that $O(a^n)\neq O(b^n)$, or equivalently, that $a^n\notin O(b^n)$ (why are these equivalent?) To show that $a^n\notin O(b^n)$, it suffices to show (again, why?) that $$ \lim_{n\rightarrow\infty}\frac{a^n}{b^n}=\infty $$ Using the fact that $a>b>0$, this limit should be easy to show.
{ "pile_set_name": "StackExchange" }
Q: Mass-Energy Equivalence theory energy or momentum is not conserved? The famous equation for mass energy equivalence: $E=mc^2$ It cannot conserve energy or momentum without some loss in one way or another. To elaborate further if I take $1kg$ of mass and I also take electromagnetic radiation with same energy as the $1kg$ mass and ensuring its accuracy using the above equation. Then use this radiation and I use it to smash it into a "crash" mat I would get this: $$E=mc^2$$ $$E=1.c^2$$ $$E=89,401,000,000,000,000$$ Approx. That being the energy we then use this to calculate the momentum of the electromagnetic radiation transferred onto the "crash" mat which would be: $$p=mv$$ $$p=mc$$ $$p=e/c^2 . c $$ $$p=e/c$$ $$p=89,401,000,000,000,000/c$$ $$p=299,000,000$$ Approx. where as if I now take $1kg$ of matter and accelerate it to high velocity (say, 10,000 kilometers per hour ) to measure its momentum we get roughly $10,000 kg.m/sec$ That being said, momentum cannot be conserved, why is that? Next, Energy cannot be conserved. For example if I used the same $1kg$ and I shoot it into space at a $x$ velocity and after say 1000 years I recieve it and measure mass of the object it would weigh exactly the same as 1000 years before therefore I can conclude it has same energy in its mass however if I use the mass-equivalent of electromagnetic radiation and do the same but my conclusion would be vastly different as first due to travelling in long fabric of space it would get slightly or even highly redshifted due to doppler effect. That being said the observer would get different energy reading to that of 1000 years ago. That in mind where did that energy go? A: If you have a massive object of mass $m$ which spontaneously decays into electromagnetic radiation, then indeed the total energy of that electromagnetic radiation is $E=mc^2$. However the total momentum of that radiation would be $0$ due to momentum conservation. From this, we can conclude that it is impossible that all that mass is converted into a single photon, because a single photon would indeed have the momentum $p=mc \ne 0$, which is forbidden by momentum conservation. However it is in principle allowed (depending on spin and other conserved quantities) that the massive object of mass $m$ decays into two photons of energy $E=mc^2/2$ each, both going into opposite direction (and thus having $\vec p_1=-\vec p_2$, thus $\vec p_1+\vec p_2=\vec 0$) and each having as absolute value of the momentum $p_i=mc/2$. However for a body of mass 1kg (which, to be completely converted to electromagnetic radiation, would have to consist of 0.5kg matter and 0.5kg antimatter), you'd rather expect quite a lot of electromagnetic radiation going into all directions. However the total momentum of all that radiation would still be zero. Similarly, electromagnetic radiation going into one direction cannot spontaneously convert into a massive object, because that also would violate energy or momentum conservation. It the radiation interacts with matter, it can pass a bit of its energy and momentum to that object, and then conversion into massive particles can be possible because that extra energy and momentum transfer allows to conserve both energy and momentum. Now, as soon as we take General Relativity, and especially the expansion of the universe, into account, energy conservation indeed doesn't hold any longer on a global scale (it still holds locally, though).
{ "pile_set_name": "StackExchange" }
Q: Performing operations in dataframe and lists in R Here is a data snippet from a csv file. The list contains names of cities where John traveled and hours he stayed there. sno City hours stayed 1 London 5 2 London 4 3 Dubai 2 4 Mumbai 8 5 Sydney 16 6 Sydney 16 7 Dubai 2 8 London 8 9 London 9 10 Paris 17 I need help in calculating the following: Name of most visited city by john (by number of visits); Name of City where he stayed for longest (cumulative stay) hour; Name of city where he stayed for longest time in a single visit , how many hours and which city; average number of hours in each of the city (cumulative hours). A: library(dplyr) df <- tbl_df(df) I. Name of most visited city by john (by number of visits) df %>% select(City) %>% table() %>% sort(decreasing=T) # London Dubai Sydney Mumbai Paris # 4 2 2 1 1 # 2nd alternative df %>% group_by(City) %>% summarise(n=n()) %>% arrange(desc(n)) # Source: local data frame [5 x 2] # City n # (fctr) (int) # 1 London 4 # 2 Dubai 2 # 3 Sydney 2 # 4 Mumbai 1 # 5 Paris 1 II. Name of City where he stayed for longest (cumulative stay) hour df %>% group_by(City) %>% mutate(cumsum(hours_stayed)) %>% arrange(City) # Source: local data frame [10 x 4] # Groups: City [5] # sno City hours_stayed cumsum(hours_stayed) # (int) (fctr) (int) (int) # 1 3 Dubai 2 2 # 2 7 Dubai 2 4 # 3 1 London 5 5 # 4 2 London 4 9 # 5 8 London 8 17 # 6 9 London 9 26 # 7 4 Mumbai 8 8 # 8 10 Paris 17 17 # 9 5 Sydney 16 16 # 10 6 Sydney 16 32 df %>% group_by(City) %>% summarise(sum(cumsum(hours_stayed))) # Source: local data frame [5 x 2] # City sum(cumsum(hours_stayed)) # (fctr) (int) # 1 Dubai 6 # 2 London 57 # 3 Mumbai 8 # 4 Paris 17 # 5 Sydney 48 III. Name of city where he stayed for longest time in a single visit , how many hours and which city df %>% group_by(City) %>% summarise(max(hours_stayed)) # Source: local data frame [5 x 2] # City max(hours_stayed) # (fctr) (int) # 1 Dubai 2 # 2 London 9 # 3 Mumbai 8 # 4 Paris 17 # 5 Sydney 16 IV. Average number of hours in each of the city (cumulative hours) df %>% group_by(City) %>% summarise(sum(mean(hours_stayed))) # Source: local data frame [5 x 2] # City sum(mean(hours_stayed)) # (fctr) (dbl) # 1 Dubai 2.0 # 2 London 6.5 # 3 Mumbai 8.0 # 4 Paris 17.0 # 5 Sydney 16.0
{ "pile_set_name": "StackExchange" }
Q: Gremlin.net 3.3.1 ValueMap I am building a social querying system using a graph database. I am using janusgraph database to achieve that. I am using .net as server side language, I found a library (Gremlin.net v3.3.1) that provide client for a gremlin server. In gremlin there exist a keyword valueMap to get key value of properties for a selected vertex. In gremlin.Net library there exist a similar function called ValueMap<{Tkey, Tvalue>, i can't found what the mean by Tkey and Tvalue. I there any documentation or example about gremlin.net library their documentation is very weak. I put { in the ValueMap because when i put <> it will be omitted by stackoverflow. Thanks in advance. A: Just to expand on what Brandon said in his comment: ValueMap is a step that returns a map (Dictionary in .NET) of property keys with their values: gremlin> g.V().valueMap() ==>[name:[marko],age:[29]] ==>[name:[vadas],age:[27]] ==>[name:[lop],lang:[java]] ==>[name:[josh],age:[32]] ==>[name:[ripple],lang:[java]] ==>[name:[peter],age:[35]] (Taken from the respective section of the TinkerPop docs which contains more information and examples.) Now you need to tell Gremlin.Net the type of the Dictionary keys and its values so that it can deserialize the results received by your graph system (JanusGraph in this case). For the example above, the keys are always strings, but the values are either a collection of integers or of strings. So the query from above would look like this in Gremlin.Net: g.V().ValueMap<string, IList<object>>().ToList() (ToList() is necessary to actually iterate the traversal which is something that the Gremlin Console does automatically for you.) Also note that JanusGraph currently only supports TinkerPop 3.2.z, so the recommended version of Gremlin.Net is 3.2.7.
{ "pile_set_name": "StackExchange" }
Q: How to resolve unresolved dependency (with another/latest version perhaps)? Apparently the version of a transitive dependency within my sbt project has been bumped - but the direct dependency has not "caught up" with that change. [error] (*:update) sbt.ResolveException: unresolved dependency: net.sf.py4j#py4j;0.7: not found The updated (and only available) version is 0.8 (why did they do that is another question.. ) I have attempted to remedy this temporarily by installing the new version into my local maven repo under the old version number of 0.7 - in order to attempt to mollify the dependent library. mvn org.apache.maven.plugins:maven-install-plugin:2.5.1:install-file \ -Dfile=c:\shared\py4j-0.8.1.jar -DgroupId=net.sf.py4j -DartifactId=py4j -Dversion=version=0.7 -Dpackaging=jar However, when running sbt yet again, the same error persists. So I need another strategy for dependency resolution. A: What about declaring the new version as the dependency in your build and force it (but guess you won't need it as "By default, the latest revision is selected")? libraryDependencies += "net.sf.py4j" % "py4j" % "0.8" force() It assumes you've your local Maven repository set up in resolvers - see Resolvers: sbt can search your local Maven repository if you add it as a repository: resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository"
{ "pile_set_name": "StackExchange" }
Q: Sass convert multiple scss files to css My first day of using SASS and I am already stuck. I have a directory with a bunch of .scss files and some sub-directories containing more .scss files. I have to convert them all to .css, maintaining the same directory structure. Here is the directory structure- src |-scss |- _base.scss |- _reset.scss |- themes |- _light.scss |- _dark.scss |-css I want to compile all .scss files in scss dir to.css files in css dir, keeping the same directory structure. I can do it one file at a time but not all in one shot. I have tried- sass --watch scss:css sass --update scss:css sass --update `pwd`/scss:`pwd`/css compass watch scss:css but none worked. I haven't tried sass-globbing yet. I am sure I am missing something very basic here but I am not able to find any help with this. What is that stupid thing that am missing here? A: When you start the filename of a Sass-file with undescore this means that it is not to be compiled to a CSS-file. To duplicate the structure you need to remove the underscore from the filenames. You use underscore to structure your sass-code and then include it in a non-underscored file which is then compiled to CSS. If you want to use sass this way you could add a file like this: scss/main.scss: @import "base"; @import "reset"; @import "themes/light"; @import "themes/dark";
{ "pile_set_name": "StackExchange" }
Q: Converting very small numbers how can I convert very small numbers in lua? example 1.75245E-09 or 7.73411E-08 it works to e-04 from lua interpreter: 1> 1.75245E-05 1.75245e-05 1> 1.75245E-04 0.000175245 A: What you want is string.format which works almost exactly as the C print-into-string function sprintf. Thus string.format("%f",7.73411E-08) should yield the desired output. If it is useful to have that many leading zeros is another question. I did not test this, the default length might be limited. If so use string.format("%20f",7.73411E-08) to provide sufficient space.
{ "pile_set_name": "StackExchange" }
Q: R symbol suddenly stopped working - Android Studio i haven't done anything and suddenly it doesnt recognize R symbol, also showing me the Manifest which has been built under the build folder which is for debug. ive been looking for an answer over an hour, none of the existing solution on stack worked for me A: The solution was AppTheme.Main which is a Transition Theme doesnt work with Android >21 so you have to set the MinSDK in gradle on 21 then it will be ok. Mainly the R problem is for XML files. so I've set the MinSDK on 21 and it's got ok.
{ "pile_set_name": "StackExchange" }
Q: Incorrect version of node.js and npm during gulp plugins installation in visual studio When I open my project downloaded from git in VS2015, it runs npm install to install my Gulp plugins. But the point is that VS using old versions of node.js and npm: npm WARN engine [email protected]: wanted: {"node":">=0.12.0"} (current: {"node":"v0.10.31","npm":"1.4.9"}) So it causes some errors with the project. How to update them inside VS? A: If you're sure there are actual errors and not just warnings, you'll want to update NPM and nodejs. Installation Steps: Download the Windows installer from the Nodes.js® website. Run the installer (the .msi file you downloaded in the previous step.) Follow the prompts in the installer (Accept the license agreement, click the NEXT button a bunch of times and accept the default installation settings). installer Restart your computer. You won’t be able to run Node.js® until you restart your computer. Note: If node or NPM already exists, this will overwrite the files and dispose of old, unnecessary files. Reference: http://blog.teamtreehouse.com/install-node-js-npm-windows
{ "pile_set_name": "StackExchange" }
Q: Meteor mongo: Untrusted code may only update documents by ID. [403] The following snippet gives me the error: Households.update({ _id: Meteor.user().profile.myHousehold, "shoppingList.name" : this.name}, {"$set" : { "shoppingList.$.checked" : checked } }); Wot? I am updating by id. As a workaround, I could of course simply replace the whole array shoppingList, but that would be brute force. A: The proper pattern for using complex update/delete selectors with latency compensation is to use a Meteor method. Shared code: Meteor.methods({ setHouseholdChecked: function(shoppingListName, checked) { check(this.userId, String); check(shoppingListName, String); check(checked, Boolean); Households.update({ _id: Meteor.user().profile.myHousehold, "shoppingList.name" : shoppingListName }, { $set: { "shoppingList.$.checked" : checked } }); } }); Client code: Meteor.call('setHouseholdChecked', this.name, checked);
{ "pile_set_name": "StackExchange" }
Q: ExtJS: How to override custom minimize behavior of Ext.window.Window? There is a minimizable boolean config which fires minimize event. The question is, how can I override and define a new position on DOM for this event? My aim is minimize the window to footer panel of application. Below stated minimize function of Ext.window.Window; minimize: function () { this.fireEvent('minimize', this); return this; } A: You can try this like below:- "minimize": function (window, opts) { window.collapse(); window.setWidth(150); window.alignTo(Ext.getBody(), 'bl-bl') } Working fiddle Note: You can read more about alignTo options here.
{ "pile_set_name": "StackExchange" }
Q: PyQGIS QgsVectorLayer() Loading Invalid Layer in Standalone Python Script? In my standalone python 3 script, QgsVectorLayer() is loading an invalid layer. When I use the exact same function and inputs in the QGIS GUI python console, the layer loads fine. I am not sure what is missing in my standalone script. I have double checked the paths and made sure they are correct. I used QgsApplication.prefixPath() to check the correct path for input in the QgsApplication.setPrefixPath() function within my standalone script. The path and inputs I use in the QgsVectorLayer() function in my standalone script are the same as those used in the GUI python console. I'm not sure why loading a vector layer in my standalone script it failing. The vector object is created, but .isValid() returns False. Here is my standalone script: import sys, os, time sys.path.extend([r'C:\OSGeo4W\apps\qgis\python',r'C:\OSGeo4W\apps\Python37\Lib\site-packages']) #modify environment variables to find qgis and qt plugins during qgis.core import os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\OSGeo4W\apps\Qt5\plugins' os.environ['QT_PLUGIN_PATH'] = r'%QT_PLUGIN_PATH%;C:\OSGeo4W\apps\Qt5\plugins;C:\OSGeo4W\apps\qgis\qtplugins;C:\OSGeo4W\apps\qgis\plugins' os.environ['PATH'] += r';C:\OSGeo4W\apps\qgis\bin;C:\OSGeo4W\apps\Qt5\bin;C:\OSGeo4W\\bin' from qgis.core import * from qgis.gui import * # supply path to qgis install location QgsApplication.setPrefixPath(r'C:\OSGeo4W\apps\qgis', True) #QgsApplication.setPluginPath('C:\\OSGeo4W\\apps\Qt5\\plugins\\platforms') #print(QgsApplication.systemEnvVars()) # create a reference to the QgsApplication # setting the second argument to True enables the GUI, which we need to do # since this is a custom application qgs = QgsApplication([], True) # load providers qgs.initQgis() ########################## # Write your code here to load some layers, use processing algorithms, etc. canvas = QgsMapCanvas() canvas.show() layer = QgsVectorLayer(r'C:\Users\Matt\OneDrive\FarmProject\Kankakee_Parcels\K3_TaxParcels.shp', 'Kankakee', 'ogr') if not layer.isValid(): print('Failed to open the layer') # add layer to the registry add_layers = QgsProject.instance().addMapLayer(layer) # set extent to the extent of our layer canvas.setExtent(layer.extent()) # set the map canvas layer set canvas.setLayers([add_layers]) canvas.refresh() time.sleep(30) ######################## # When your script is complete, call exitQgis() to remove the provider and # layer registries from memory qgs.exitQgis() A: Per the solution found at this link: https://github.com/OSGeo/homebrew-osgeo4mac/issues/197 The QgsApplication.setPrefixPath() is not correctly setting the prefix. Therefore, the vector layer cannot load properly. A workaround is to set the QGIS prefix environment variable directly using the os module in Python: os.environ['QGIS_PREFIX_PATH'] = r'prefix\path' Once the prefix path is correctly set, the vector layer should load properly and .isValid() should yield 'True'
{ "pile_set_name": "StackExchange" }
Q: Get PID of a timed process, along with the output of time I have this line of code: { time cp $PWD/my_file $PWD/new_file ; } 2> my_log.log I need to know how long it takes to execute the 'cp' command and I also need to get the PID of the 'cp'. I just want to print the PID of the 'cp' process and get the following in the my_log.log file: <output of time> I have tried PID=$! but this does not provide PID of the cp process. A: First, you need to send your (timed) cp command to the background with a trailing &, so you can inspect the running processes after launching it. (I suspect you're already doing this, but it's not currently reflected in the question). $!, the special variable that contains the PID of the most recently launched background job, in this case reflects the subshell that runs the time command, so we know that it is the parent process of the cp command. To get the (one and only, in this case) child process: If your platform has the nonstandard pgrep utility (comes with many Linux distros and BSD/macOS platforms), use: pgrep -P $! Otherwise, use the following POSIX-compliant approach: ps -o pid=,ppid= | awk -v ppid=$! '$2 == ppid { print $1 }' To put it all together, using prgep for convenience: # Send the timed `cp` command to the background with a trailing `&` { time cp "$PWD/my_file" "$PWD/new_file"; } 2> my_log.log & # Get the `cp` comand's PID via its parent PID, $! cpPid=$(pgrep -P $!)
{ "pile_set_name": "StackExchange" }
Q: Parameters in "use [database]" clause I want to use parameters in use [database] command, but it runs successfully without changing the database under usage. How can I fix it? Thanks a lot declare @database varchar(100) SET @database = 'transform' declare @sqlstring nvarchar(500) set @sqlstring = 'use '+ @database exec sp_executesql @sqlstring A: It changes the database, but within context of sp_executesql Try this to confirm: set @sqlstring = 'use '+ @database + '; select DB_NAME()'
{ "pile_set_name": "StackExchange" }
Q: Retrieve specific columns in a csv file efficiently I am trying to retrieve 7 specific columns in a csv file 100 times for each column. This is what I've been doing. I know it's inefficient, but it seems like it's gonna work if I only know how to append them 100 times. data_file_path = '2001-1.csv' counter = 0 col0 = [] col1 = [] col2 = [] col13 = [] col16 = [] col17 = [] col18 = [] with open(data_file_path, 'r', encoding="latin-1") as fin: splitted = csv.reader(fin, delimiter = ',') next(splitted) for col in splitted: counter += 1 col0.append(col[0]) if(counter == 100): counter = 0 col1.append(col[1]) if(counter == 100): counter = 0 col2.append(col[2]) if(counter == 100): counter = 0 col13.append(col[13]) if(counter == 100): counter = 0 col16.append(col[16]) if(counter == 100): counter = 0 col17.append(col[17]) if(counter == 100): counter = 0 col18.append(col[18]) if(counter == 100): counter = 0 break flight_data = [col0, col1, col2, col13, col16, col17, col18] But it would be great to know how to do it efficiently. A: col here is a misnomer, since you're iterating over rows and cherrypicking columns. Use a dictionary, and keep a list of columns. You can then reduce your code to a nice little nested loop. idx = [0, 1, 2, 13, 16, 17, 18] data = {k : [] for k in idx} with open(data_file_path, 'r', encoding="latin-1") as fin: reader = csv.reader(fin, delimiter = ',') next(reader) for row in reader: for i in idx: data[i].extend([row[i]] * 100)
{ "pile_set_name": "StackExchange" }
Q: How to reset/emptying to a std::wstring? How to reset/emptying to a std::wstring? It seems that my function is making a delay when using these line: std::wstring currentUrl; // <--- I declare this as global. currentUrl = _bstr_t(url->bstrVal); Any idea how can I resolve this? A: How did you measure that delay? The only reliable way is through a profiler, and a profiler would also show you how that time was spent. That said, assigning to a string often (unless the string can reuse its old buffer or small string optimization kicks in) involves deleting the old buffer and allocating a new buffer. And dynamic memory is slow. I don't know _bstr_t, but since std::wstring does only have assignment operators to assign from another std::wstring and const wchar_t*, I assume this is the latter. If that is the case, the string doesn't know the size of the string it will get assigned, so if the string is big, it might have to incrementally increase its buffer, which again involves allocation and deallocation plus copying characters, so this might be quite expensive. You could try to use an assign() member function instead of the assignment operator. I think there's an overload of assign() that takes a const wchar_t* and the size of the string, allowing it to know the exact buffer size before-hand. However, as always with performance problems, you need to measure using a profiler. Guessing will not get you far.
{ "pile_set_name": "StackExchange" }
Q: Continue building Docker image after error occured I have a Dockerfile that install Ubuntu and some packages over it and then proceeds to use these packages. Let's say I need to run 'wget' command, but forgot to issue install of the 'wget' package. I add the package to install command and continue with my execution. However I have to start over - install Ubuntu, install package, etc., or do I? Is there ability to save what I did until error occurred and continue from that point after I did my fixes instead of downloading everything again? A: Sometimes for this instance you might want to subdivide your build into a chain of images. Each successive step picks up the previous step at the FROM command.
{ "pile_set_name": "StackExchange" }
Q: creating a custom function to replace values in R I would like to replace some values in a matrix using a custom function. What I want to do is to create a function called "replace.mixed" that replaces, specifically, "7 to 0" and "8 and 9 to NA". I tried the following but it did not work. "replace.mixed" <- function (x) { if(x = 7) {x == 0} if(x == 8 || 9) {x == NA} } ### test function data <- matrix(1:12,3,4) # create a matrix replace.mixed(data) I would appreciate any suggestion. A: We can use ifelse replace.mixed <- function(x) { x[] <- ifelse(x==7, 0, ifelse(x %in% c(8,9), NA, x)) x} replace.mixed(data) # [,1] [,2] [,3] [,4] #[1,] 1 4 0 10 #[2,] 2 5 NA 11 #[3,] 3 6 NA 12 This could be also code-golfed (data!=7)*data *NA^(data %in% 8:9) # [,1] [,2] [,3] [,4] #[1,] 1 4 0 10 #[2,] 2 5 NA 11 #[3,] 3 6 NA 12
{ "pile_set_name": "StackExchange" }
Q: Dzil Release Clobbers Jar File I have created a Perl module to provide an interface with the RNG-processing Java library Jing. The code is located here. I use [Inline::Java][3] to compile and load a small class which utilizes jing.jar, both located in the java directory, which is shared via [File::ShareDir][4]. Running prove -vl or dzil test, the module works perfectly fine, and the tests all pass: >prove -vl t\0-use.t ............. 1..1 ok 1 - use XML::Jing; ok t\01-validates_xml.t .. 1..3 ok 1 - successfully reads a valid RNG ok 2 - returns nothing when XML file is valid ok 3 ok t\02-exceptions.t ..... 1..5 ok 1 - warning for nonexistent RNG file ok 2 - constructor returns nothing for non-existent RNG file ok 3 - warning for bad RNG file ok 4 - constructor returns nothing for bad RNG file ok 5 - warning for nonexistent XML file ok All tests successful. Files=3, Tests=9, 6 wallclock secs ( 0.11 usr + 0.05 sys = 0.16 CPU) Result: PASS Tests also pass when a distro is built using dzil build: dzil build cd XML-Jing-0.x perl Build.PL build build test However, using dzil release, Inline::Java croaks when it tries to load jing.jar. We get these crazy errors below: BEGIN failed--compilation aborted at t/01-validates_xml.t line 5. t/01-validates_xml.t .......... Dubious, test returned 1 (wstat 256, 0x100) No subtests run A problem was encountered while attempting to compile and install your InlineJava code. The command that failed was: "C:\Program Files\Java\jdk1.7.0_21\bin\javac.exe" -deprecation -d "C:\strawberry\cpan\build\XML-Jing-0.01-Skydfp\_Inline\lib\auto\XML\Jing_706b" RNGValidator.java > cmd.out 2>&1 The build directory was: C:\strawberry\cpan\build\XML-Jing-0.01-Skydfp\_Inline\build\XML\Jing_706b The error message was: error: error reading C:\strawberry\cpan\build\XML-Jing-0.01-Skydfp\blib\lib\auto\share\dist\XML-Jing\jing.jar; invalid END header (bad central directory offset) Currently I load the jar using a begin block to edit the CLASSPATH variable: BEGIN{ use Env::Path; my $classpath = Env::Path->CLASSPATH; $classpath->Append(path(dist_dir('XML-Jing'),'jing.jar')); } Using jarsigner, I verified that the jar is corrupted in the build folder created by dzil release but not in the one created by dzil build: In the build created via dzil build: jarsigner -verify java/jing.jar jar is unsigned. (signatures missing or not parsable) In the build created via dzil release: jarsigner -verify java/jing.jar jarsigner: java.util.zip.ZipException: invalid END header (bad central directory offset) To summarize, dzil release clobbers a jar in my shared directory, while dzil build does not. Can anyone tell me what I need to do to make this module work properly? A: Its a bug. The kind that happens often and that has happened before in dzil. Dist-Zilla-4.300034\lib\Dist\Zilla\Dist\Builder.pm line 388 replace open my $fh, '<', $filename; with open my $fh, '<:raw', $filename;
{ "pile_set_name": "StackExchange" }
Q: Separar primeros dos dígitos en una función, para luego operar con ellos Necesito separar los dos primeros dígitos de un número para luego sumarle 1. Por ejemplo, si en la función recibo 1980 necesito separar 19 para luego sumarle 1. ¿Alguna idea? function numero(año) { return año; } A: Una manera de lograrlo sería utilizar Math.floor(numero) pasandole como parámetro el cociente entre el año y (asumiendo numeros de solo 4 dígitos) 100 Esta función retorna el numero entero mas cercano y menor o igual al recibido por parámetro, por lo que el comportamiento sería análogo a realizar la división entera, quedándonos solo con el cociente despreciando el resto. Dividiendo entre 100 un número de cuatro dígitos obtenemos un valor de 2 cifras enteras. Luego puedes sumarle 1. function numero(año) { var firstTwoDigits = Math.floor(año/100); return firstTwoDigits + 1; } console.log(numero(1980)); Otra alternativa, útil también para números de más dígitos, es convertir a string el año, tomar la subcadena desde el inicio hasta la posición 2, convertir ese valor a number y sumarle 1. function numero(año) { var firstTwoDigits = año.toString().substring(0,2); return Number(firstTwoDigits) + 1; } console.log(numero(1980));
{ "pile_set_name": "StackExchange" }
Q: How do I realize this problem with a digital circuit? I'm trying to design an indicating system for a vehicle if it crosses its speed limit. Of course I'd be using a potentiometer to realize the action of increasing speed. The input is given to the base of a transistor through a zener diode so that I can get a digital output(OFF below the set value and ON if input exceeds the set value). I need to have another indicator if the vehicle maintains that speed for more than say 2 seconds. I can feed the output of this transistor to a 555 timer set to produce pulses every two seconds and this clock output will be given to a counter. The problem is that, I am supposed to have a digital equivalent of the first part of this system(As mentioned in the guidelines for the project). Is there any way to realize the switching action of transistor with the help of digital component. I don't think it's possible to use a digital component as there is no particular level of voltage above/below which we can consider the output as high/low. This problem can be solved by using a transistor and a zener diode as mentioned above. Since the input is continuous, I don't think any digital circuit can serve this purpose. Please correct me if this is possible. Is the remaining part of my design(using a timer to produce pulse when the transistor switches on and feeding the clock pulse to a counter) right? A: Here's a circuit that'll give you a 2Hz output whenever a speed threshold is exceeded and will continue to output 2Hz as long as the threshold is exceeded. Here's how it works: U1 is a 555 wired as an astable multivibrator with a period of about 1/2 second, with its RESET input controlled by U2, a voltage comparator. A voltage comparator works by having its output go high when its + input is more positive than its - input, and in this case I've chosen the voltage on the - input to be half of the supply voltage by connecting it to the junction of R1 and R2, a voltage divider comprising two resistors with equal values. For the purpose of this exercise, I set the supply voltage (12 volts) to be equal to 120 miles per hour and to vary linearly from zero MPH with U2- equal to zero volts, to 120 MPH with U2- equal to 12 volts. Thus, with U2- sitting at 6 volts, the speed detection threshold is set at 60 MPH. The voltage on U2+ comes from V1, which is the output voltage from the pot you mentioned earlier, and varies linearly from zero to 12 volts, corresponding to a vehicle speed of from zero to 120 MPH. With the voltage on U2+ lower than the voltage on U2-, then, U2's output will be low and will keep U1 RESET, forcing U1-3 low. As the vehicle speeds up and V1's output goes more and more positive, eventually it'll get more positive than the 6 volt reference on U2-, which will cause U2's output to go high, taking U1 out of RESET and allowing it to oscillate at about 2Hz, giving you the output you want for your counter. So, When the vehicle's speed is higher than 60 MPH U1 will oscillate, but when it's lower than 60MPH, U1 won't do anything. Self-help 555 and comparator tutorials are all over the web, so I won't go into them here but, if you're interested, there's a nice, free simulator program here, and I've posted the schematic as a file which you can run to play with the circuit here.
{ "pile_set_name": "StackExchange" }
Q: expanded parameter list for variadic template I'm working on an Event based architecture for a research project. The system currently uses Qt signalling, but we are trying to move away from Qt, so I need something that will work almost as well as the Qt event loop and signals across threads. Probably against my better judgement, I've chosen to use variadic templates to create a generic event that will be used to perform the callback in the destination thread. template<typename dest, typename... args> class Event { public: Event(dest* d, void(dest::*func)(args...), args... a) : d(d), func(func), pass(a...) { } virtual void perform() { (d->*func)(pass...); } protected: dest* d; void(dest::*func)(args...); args... pass; }; I haven't found anything that indicates if this is possible. However, I have a hard time believing that it isn't. Given that, I was wondering if there is a way to do something like this and if there isn't, why? Also, if anybody has a better way of doing this I would welcome the suggestion. A: Hm. I think I got something nasty. The code is not very pretty or good, but you probably get the idea. You should be able to use templates to recursively store objects of any type, and also recurse through them when calling the function. #include <iostream> template<typename first_arg, typename... args> class Event { public: Event(void (*fn)(first_arg, args...), first_arg first, args... in) : m_func(fn), var(first, in...) {} void operator()() { var(m_func); } private: void (*m_func)(first_arg, args...); template <typename t_arg, typename... t_args> struct storage; template <typename t_arg> struct storage<t_arg> { storage(t_arg t) : m_var(t) {} template<typename t_func, typename... tt_args> void operator()(t_func fn, tt_args... p) { fn(p..., m_var); } t_arg m_var; }; template <typename t_arg, typename t_arg2, typename... t_args> struct storage<t_arg, t_arg2, t_args...> { storage(t_arg t, t_arg2 t2, t_args... p) : m_var(t), m_storage(t2, p...) {} template<typename t_func, typename... tt_args> void operator()(t_func fn, tt_args... p) { m_storage(fn, p..., m_var); } t_arg m_var; storage<t_arg2, t_args...> m_storage; }; storage<first_arg, args...> var; }; void test(int a, float b) { std::cout << a << std::endl << b << std::endl; } int main() { Event<int, float> event(test, 10, 100.0); event(); } Also, I think std::bind does something similar, but not sure :D
{ "pile_set_name": "StackExchange" }
Q: RegEx for number greater than 1120 I know there are plenty of examples of this but I cannot seem to get this working. Could you guys please help me create a regex that will match any number greater than 1120? A: RegEx is not a good method to solve this problem. Having said that, something like this might work: 112[1-9]|11[3-9][0-9]|1[2-9][0-9][0-9]|[2-9][0-9][0-9][0-9]
{ "pile_set_name": "StackExchange" }
Q: C# InvalidEnumArgumentException in Java Is there something similar to the InvalidEnumArgumentException in java? Usecase: public FigureType determinateFigureType(int row, int column) throws ??? { switch (globalSheet[row][column]) { case FIELD_FREE: return FigureType.Free; case FIELD_A: return FigureType.A; case FIELD_B: return FigureType.B; default: throw new ???(); } } A: maybe IllegalArgumentException? Java API: Thrown to indicate that a method has been passed an illegal or inappropriate argument. There is also an EnumConstantNotPresentException, however, this doesn't seem to be what you are looking for.
{ "pile_set_name": "StackExchange" }
Q: Write a regular expression to get a substring in Python I apologize for the non-descriptive title, but I couldn't think of a better one. I am trying to write a script that parses a sub string from some file names. So, for example, here is one such file name: [Anime-Koi] GJ-bu - 07 [h264-720p][A8557259].mkv-00_07_33_00001.jpg (This is quite obviously a screenshot from an anime.) What I want from this name is the GJ-bu - 07 substring. I know very little about regular expressions so I have been scratching my head trying to come up with a regular expression to do that. I thought that finding the inverse of an expression would be really easy so I came up with: '(\[[a-zA-Z0-9_-]*\]?[.a-zA-Z0-9_-]*)' Python's findall() for the above returns: ['[Anime-Koi]', '[h264-720p]', '[A8557259].mkv-00_07_33_00001.jpg'] Unfortunately, I could not figure out how to get the inverse and no matter how hard I scratch my brain, I can't come up with a regular expression that does what I need. So, uhh, could you guys help me come up with an expression that returns GJ-bu - 07? I know I could cheat and just do this: f = "[Anime-Koi] GJ-bu - 07 [h264-720p][A8557259].mkv-00_07_33_00001.jpg" reg_ex = r'(\[[a-zA-Z0-9_-]*\]?[.a-zA-Z0-9_-]*)' p = re.compile(reg_ex) l = p.findall(f) for st in l: f = f.replace(st, '') but that's cheating so I'd rather not do that. Thanks for your time. ( Note: I am using Python 2.7 for this, but I have no qualms with using 3.2, though I doubt it makes a difference here.) A: Try this (s is the input). re.search(r'(?:^|\s)([^[]*)(?=(?:\s|$))', s).group(1) It essentially means, a space followed by any number of non [ characters, and then a space. A: try this: p = re.compile('\[.*\](\s.*\s)\[.*\].*\.jpg') l = p.findall("[Anime-Koi] GJ-bu - 07 [h264-720p][A8557259].mkv-00_07_33_00001.jpg") print l
{ "pile_set_name": "StackExchange" }
Q: Invariants/monovariants: numbers on a board The numbers from $1$ through $2008$ are written on a blackboard. Every second, Dr. Math erases four numbers of the form $a, b, c, a+b+c$, and replaces them with the numbers $a+b, b+c, c+a$. Prove that this can continue for at most $10$ minutes. A: Observe that both the sum of the numbers and the sum of their squares is invariant under the process. Let $n=2008$. Let $m$ be the number of integers on the board. Then by Cauchy-Schwarz, we have $\dfrac{n(n+1)(2n+1)}{6} \geq \dfrac{n^2(n+1)^2}{4m}$, i.e. $m \geq \dfrac{3n(n+1)}{2(2n+1)}$ and hence the number of times the process can continue is at most $n-m=\dfrac{n^2-n}{2(2n+1)}$ which is less than 502 for $n=2008$.
{ "pile_set_name": "StackExchange" }
Q: Beginner books for music appreciation for music-theory illiterate adult I'm a married adult with a full-time occupation. A long time ago, I took some lessons for the keyboard but have since forgotten almost everything. Could you please recommend me a few books given the following 2 goals: A basic understanding of music theory and an ability to play a few basic songs on the keyboard (piano). I still have a basic keyboard at home. A basic ability to appreciate (classical) music on an intellectual level. This includes a basic ability to verbalize certain musical patterns and effects. The things I have learned properly in life almost always begin with some reading materials and then practice. Please also advise if this is a proper way to go as far as some basic music understanding is aimed for. Thank you very much. A: ABRSM Music Theory books are very well put together. I prefer the Josephine Koh books above all the others. When you do the music theory you will learn all the ways and manners in which musicians use to portray feelings and emotions. You can find out more at ABRSM USA, then scroll down to the page for 'Publications'. Alternatively, see this list for all Music Theory publications by ARBSM.
{ "pile_set_name": "StackExchange" }
Q: Format the data read from the sql query in powershell I was trying to format the data read from my query. The data's are sorted in lines and I need it in a table format $objdataset = Invoke-Sqlcmd -query "select ord,ord_i,ORD_PRCS from F_ord where ord_i in ($ord1);" -server $($SQLServer) -Database $($SQLDBName) foreach($item in $objdataset) { "ID" +$item.ord "order " +$item.ord_i "pro"+$item.ORD_PRCS } So how I can format it like ID Order pro 123 ff Done 145 dd Progress 567 cc Done Please help me with this.. A: There's no need to do any special formatting yourself. Printing $objdataset should give you a table format automatically, but you can force it with $objdataset | Format-table -autosize
{ "pile_set_name": "StackExchange" }
Q: where should I put the code for reading device unique ID in iOS? I have the following code for reading the unique device id. Since this will be used in more than 20 different views (.m files), I'm just questioning myself that is there a cleaning and efficient way of doing this? So I just comes up with 3 options: Option One: Just do a copy/paste of these codes into any place I need them to be executed. I think this would be the worst way of doing this. Option Two: Put it into AppDelegate.m. This will just run these once per launch (may save a tiny amount of time if I'm right). Then just call the string "stringDeviceID" whenever I need. Option Three: Create another class and get these codes into a class function. However, this still have the "problem" of executing the code every time. And my question is which is the best/better option I have to go with? And if there is another option that would even better than any of these, please let me know. Thanks in advance. NSString *stringDeviceID; if ([UIDevice instancesRespondToSelector:@selector(identifierForVendor)]) { stringDeviceID = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; } else { stringDeviceID = [[UIDevice currentDevice] uniqueIdentifier]; } A: I would implement it as a category on UIDevice: @iumplementation UIDevice (backwardCompatibleIdentifier) - (NSString *)backwardCompatibleIdentifier { // your code } @end Then, all you have to do is: NSString *myid = [[UIDevice currentDevice] backwardCompatibleIdentifier]; I seriously doubt the performance cost of calling this 20 times will make any real performance difference. If you're worried, test it. If it is a problem, you can stick a cache inside the implementation. If even calling currentDevice is too slow, you can make it a class method instead of an instance method. Your other alternatives are mostly reasonable, except for one: do not copy and paste this 20 times. At some point, you're going to want to remove the uniqueIdentifier call (whether because Apple forces you, or just because you want to drop iOS 5 compatibility). You may want to add OpenUDID or some other third-party library. Whatever you do, you want to be able to change it in 1 place, not change it in 19 places and then 6 months later debug the 1 place you forgot…
{ "pile_set_name": "StackExchange" }
Q: switch statement running before ajax is finished Question: Is there any way to pause javascript until after ajax has finished executing its success function? Relevant Code: function validateinput (name, parent, access) { //we assume that the input does not exist exists = false; //validate with server, expected response is true or false $.post("AJAXURL", {action: "category", name: name, parent: parent}, function (data, textStatus, xhr) { //if returned true, the entry does exist for that parent if (data == "true") { alert("AJAX"); exists = true; } else exists = false; }); switch (true) { //If the name field is blank (still displaying hint) case (name == 'Subcategory Name' || name == 'Category Name'): alert("Please enter a name"); break; //if the name already exists for that parent /*****/ case (exists == true): alert("SWITCH"); break; //if the parent field is displaying hint, assume parent is blank case (parent == 'Parent Category'): parent = ''; break; //if the usergroup field is blank, assume value of parent case (access == 'UserGroup Allowed To View'): //if parent is also blank, assume lowest level usergroup access if (parent == '') access = "UserGroupTicketWorkers"; else $.post("AJAXURL", {action: "specificcat", name: parent}, function (data, textStatus, xhr) { access = data['access']; } ); break; default: return true; } return false; } Detailed Explanation Of Issue: User clicks a link in page to fire this function. function will return true or false whether there is an error with the user input When this code executes, I receive alert("SWITCH"); BEFORE I receive alert("AJAX"); (the condition of the second case is currently correct, I inverted it in my debugging to figure out what was happening) I have a temporary fix for it which is moving the second case directly before the default, but my guess is that a faster computer may execute the switch comparisons faster than the server will provide a response, and therefore not a permanent solution. (unless it doesn't work that way), and that if I put in a timer to wait for a preset amount of time, that the same issue could occur if the server is running slower than normal I'm aware that I'm not getting the new value from the ajax call because there is the time spent communicating with server, so, my first thought is to find a way to pause the function until the ajax success function is completed. I cannot put the switch inside the ajax call since this function needs to return a value. Resolution I used the async setting and it worked like a charm. Just had to change my code from $.post() to $.ajax() and set it up to post $.ajax( { url: "plugins/actions/edittickets/libs/changetickets.php", type: 'POST', data: { action: "category", name: name, parent: parent }, async: false, success: function (data, textStatus, xhr) { //if returned true, the entry does exist for that parent if (data == "true") exists = true; } }); A: You can send your AJAX query in a synchronous way if that's what your really want by adding 'async':false in your list of parameters. See the documentation for more info : http://api.jquery.com/jQuery.ajax/ But as other people pointed out in comments this is NOT how switch works so you still have to understand the switch statement et change the corresponding code. See here for more info : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/switch
{ "pile_set_name": "StackExchange" }
Q: Passing POST type of parameter and receiving it on another page in AEM/CQ5 I have created webpage in AEM having login functionality (username and password) and I need to pass these 2 paramaters using POST method. I am able to do the same using GET but when I try with POST, I get error stating that Content is modified/created. I am passing the parameters using html <form action="destination.html" method="POST"> I read that I need to create a Sling Servlet which will manage my POST method. But the question is how to do so? and where to create that servlet file? Thanks. A: You can use the same servlet and override the doPost method. @SlingServlet( methods = { "POST","GET" }, name="com.tti.tticommons.service.servlets.LeadTimeTrendsServlet", paths = { "/services/processFormData" } ) public class CommonServlet extends SlingAllMethodsServlet{ ... @Override protected void doPost(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,IOException { .... } I have listed an example here AEM 6.1 Sightly basic form submit and redirect to same page
{ "pile_set_name": "StackExchange" }
Q: Setting multiple visual states in one go? I have four visual states defined each affecting different child controls within the same silver-light control. Is it possible for me to create other visual states which invoke a combination of these others? So if I have Visual_Group_1, Visual_Group_2, Visual_Group_3, Visual_Group_4 Is it possible to make, say a Visual_Comb_1 group which uses the states in Visual_Group_1 and Visual_Group_3? Then make another one called Visual_Comb_2 which uses Visual_Group_4 and Visual_Group_3? I'm happy to implement a solution in xaml or codebehind or a combination of both. The alternative I'm looking at currently involves tonnes of code copy+paste and I'm not too keen to do that. Some more detail per request: This is what I roughly have right now: <VisualState x:Name="State1"> <ColorAnimation Storyboard.TargetName="Path1" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="Blue" Duration="0:0:0.5" /> // fade out the rest of the paths... <ColorAnimation Storyboard.TargetName="Path2" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> <ColorAnimation Storyboard.TargetName="Path3" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> <ColorAnimation Storyboard.TargetName="Path4" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> </VisualState> <VisualState x:Name="State2"> <ColorAnimation Storyboard.TargetName="Path3" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="Red" Duration="0:0:0.5" /> // fade out the rest of the paths... <ColorAnimation Storyboard.TargetName="Path2" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> <ColorAnimation Storyboard.TargetName="Path1" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> <ColorAnimation Storyboard.TargetName="Path4" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> </VisualState> <VisualState x:Name="State3"> <ColorAnimation Storyboard.TargetName="Path4" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="Pink" Duration="0:0:0.5" /> // fade out the rest of the paths... <ColorAnimation Storyboard.TargetName="Path2" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> <ColorAnimation Storyboard.TargetName="Path1" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> <ColorAnimation Storyboard.TargetName="Path3" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> </VisualState> My objective is to have a control which when you click on cycles from state1 to state3, each state fades in a different path while fading out the other paths. My problem is that there is a tonne of copy+paste in the 'fade out the rest of the paths' section, so if I wanted to add a Path5 it would mean adding it to every single visual state already defined, or if I wanted to change the fadeoff colour or animation I would have to do it to every visual state. A: Thanks for providing the XAML. This is how I would tackle the problem. First off, create the VisualStates individually for each Path. (I would recommend using a Style instead to save you re-coding a very similar VisualState into each Path, but I'm not familiar enough with them to know if you can apply different colours to each.) <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="Path1States"> <VisualState x:Name="Activate"> <Storyboard> <ColorAnimation Storyboard.TargetName="Path1" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="Blue" Duration="0:0:0.5" /> </Storyboard> </VisualState> <VisualState x:Name="Deactivate"> <Storyboard> <ColorAnimation Storyboard.TargetName="Path1" Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)" To="#00000000" Duration="0:0:0.5" /> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="Path2States"> <!-- ... etc ... --> </VisualStateGroup> </VisualStateManager.VisualStateGroups> Now, create a List in the code-behind that contains each of the related objects, and then right your own GoToState function such that it turns on the in state for one object, and calls the off state for the rest. List<Path> pathList; public Page() // constructor { InitializeComponent(); pathList = new List<Path>(); pathList.Add(Path1); // and so forth } // Call this function when you want to change the state private void ActivatePath(Path p) { foreach (Path listItem in pathList) { // If the item from the list is the one you want to activate... if (listItem == p) VisualStateManager.GoToState(listItem, "Activate", true); // otherwise... else VisualStateManager.GoToState(listItem, "Deactivate", true); } } If I were better at XAML and styling I might have a cleaner way of creating the VisualStates. However, my forte is more on the logic and coding side. That being said, it's much cleaner that writing out the same VisualState four or five times! :) Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: How to tell a lambda function to capture a copy instead of a reference in C#? I've been learning C#, and I'm trying to understand lambdas. In this sample below, it prints out 10 ten times. class Program { delegate void Action(); static void Main(string[] args) { List<Action> actions = new List<Action>(); for (int i = 0; i < 10; ++i ) actions.Add(()=>Console.WriteLine(i)); foreach (Action a in actions) a(); } } Obviously, the generated class behind the lambda is storing a reference or pointer to the int i variable, and is assigning a new value to the same reference every time the loop iterates. Is there a way to force the lamda to grab a copy instead, like the C++0x syntax [&](){ ... } // Capture by reference vs. [=](){ ... } // Capture copies A: What the compiler is doing is pulling your lambda and any variables captured by the lambda into a compiler generated nested class. After compilation your example looks a lot like this: class Program { delegate void Action(); static void Main(string[] args) { List<Action> actions = new List<Action>(); DisplayClass1 displayClass1 = new DisplayClass1(); for (displayClass1.i = 0; displayClass1.i < 10; ++displayClass1.i ) actions.Add(new Action(displayClass1.Lambda)); foreach (Action a in actions) a(); } class DisplayClass1 { int i; void Lambda() { Console.WriteLine(i); } } } By making a copy within the for loop, the compiler generates new objects in each iteration, like so: for (int i = 0; i < 10; ++i) { DisplayClass1 displayClass1 = new DisplayClass1(); displayClass1.i = i; actions.Add(new Action(displayClass1.Lambda)); } A: The only solution I've been able to find is to make a local copy first: for (int i = 0; i < 10; ++i) { int copy = i; actions.Add(() => Console.WriteLine(copy)); } But I'm having trouble understanding why putting a copy inside the for-loop is any different than having the lambda capture i. A: The only solution is to make a local copy and reference that within the lambda. All variables in C# (and VB.Net) when accessed in a closure will have reference semantics vs. copy/value semantics. There is no way to change this behavior in either language. Note: It doesn't actually compile as a reference. The compiler hoists the variable into a closure class and redirects accesses of "i" into a field "i" inside the given closure class. It's often easier to think of it as reference semantics though.
{ "pile_set_name": "StackExchange" }
Q: PHP merging two arrays by Numeric Value I have two arrays. $array1 : Array ( [0] => Array ( [time] => 100 [text] => Hello ) [1] => Array ( [time] => 200 [text] => World! ) [3] => Array ( [time] => 300 [text] => Array1's There ) ) and more... $array2 : Array ( [0] => Array ( [time] => 50 [text] => Hello ) [1] => Array ( [time] => 150 [text] => World! ) [3] => Array ( [time] => 300 [text] => Array2's There ) ) and more ... $desiredResult : Array ( [0] => Array ( [time] => 50 [text] => Hello ) [1] => Array ( [time] => 100 [text] => Hello ) [2] => Array ( [time] => 150 [text] => World ) [3] => Array ( [time] => 200 [text] => World ) [4] => Array ( [time] => 300 [text] => Array1's There ) [5] => Array ( [time] => 300 [text] => Array2's There ) ) I need to merge two array by time's numeric value, and if time's value the same, Array1's data first. A: With below code you will get the result you want. $finalArray = array(); if(count($array1) == count($array2)){ for ($icount = 0; $icount < count($array1); $icount++) { if( ($array1[$icount] < $array2[$icount]) || ($array1[$icount] == $array2[$icount])){ $finalArray[] = $array1[$icount]; $finalArray[] = $array2[$icount]; } else if($array1[$icount] > $array2[$icount]){ $finalArray[] = $array2[$icount]; $finalArray[] = $array1[$icount]; } } } Also i have created function which can gives you result if anyone array contains more value then other array. function mapArray($array1, $array2, $minCount, $maxCount, $maxCountFrom = ''){ for ($icount = 0; $icount < $minCount; $icount++) { if( ($array1[$icount] < $array2[$icount]) || ($array1[$icount] == $array2[$icount])){ $finalArray[] = $array1[$icount]; $finalArray[] = $array2[$icount]; } else if($array1[$icount] > $array2[$icount]){ $finalArray[] = $array2[$icount]; $finalArray[] = $array1[$icount]; } } if(!empty($maxCountFrom)){ if($maxCountFrom == '1'){ for ($jcount = $icount; $jcount < $maxCount; $jcount++) { $finalArray[] = $array1[$jcount]; } } else if($maxCountFrom == '2'){ for ($jcount = $icount; $jcount < $maxCount; $jcount++) { $finalArray[] = $array2[$jcount]; } } } return $finalArray; } $array1Count = count($array1); $array2Count = count($array2); if($array1Count > $array2Count){ $result = mapArray($array1, $array2, $array2Count, $array1Count, '1'); } elseif($array1Count < $array2Count){ $result = mapArray($array1, $array2, $array1Count, $array2Count, '2'); } elseif($array1Count == $array2Count){ $result = mapArray($array1, $array2, $array2Count, $array2Count); } In this function where you can pass 2 array, count of the both array by minimum count and maximum count, and last parameter is to define which array has maximum value and from that array fetch all the remaining values to the final array.
{ "pile_set_name": "StackExchange" }
Q: Why would I get a 404 on "Authoring Information" autocomplete? Below is a screenshot of a 404 I'm receiving on the standard author autocomplete, and I can't figure out, for the life of me, why this would be happening. A: Most likely because your autocomplete isn't actually using the standard path for the user autocomplete. From the image, your autocomplete is pointing to /login/autocomplete, a path that doesn't exist in a standard Drupal installation (or indeed one with about 200 contrib modules enabled, I just grepped a couple of large projects). The correct path for the user autocomplete is /user/autocomplete. Presumably there's some custom/contrib code changing the autocomplete to a different path, but failing to actually implement that path. The best thing to do would be to search your codebase for the string login/autocomplete and go from there. UPDATE The change might be being made by the User Tweaks module: function user_tweaks_form_alter(&$form, &$form_state, $form_id) { if (user_access('view login autocomplete')) { switch ($form_id) { case 'user_login_block': case 'user_login': case 'user_pass': $form['name']['#autocomplete_path'] = 'user/login/autocomplete'; break; } } }
{ "pile_set_name": "StackExchange" }
Q: How to return Javascript as partial response? As response to an Ajax-request I want to return Javascript that is executed on the client immediately. I tried it like this but it doesn't work: <html xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <h:head></h:head> <h:body> <h:form> <h:commandButton value="js"> <f:ajax event="click" listener="#{myBean.js}"/> </h:commandButton> </h:form> </h:body> </html> the bean: package mypackage; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.PartialResponseWriter; import javax.inject.Named; @Named public class MyBean { public void js() { System.out.println("called"); FacesContext ctx = FacesContext.getCurrentInstance(); ExternalContext extContext = ctx.getExternalContext(); if (ctx.getPartialViewContext().isAjaxRequest()) { try { extContext.setResponseContentType("text/xml"); extContext.addResponseHeader("Cache - Control ", "no - cache"); PartialResponseWriter writer = ctx.getPartialViewContext() .getPartialResponseWriter(); writer.startDocument(); writer.startEval(); writer.write("alert(’Works!’);"); writer.endEval(); writer.endDocument(); writer.flush(); ctx.responseComplete(); } catch (Exception e) { System.out.println(e); } } } } A: writer.write("alert(’Works!’);"); Curly quotes are not a valid string delimiter in JS. Use straight quotes. writer.write("alert('Works!');"); Unrelated to the concrete problem, based on your question history you're using PrimeFaces, or at least familiar with it. In that case, just use RequestContext#execute() instead of this mess.
{ "pile_set_name": "StackExchange" }
Q: Inserir vídeo embed com mysql Boa tarde, estou desenvolvendo um site para simplificar a busca de vídeos educacionais para meu TCC. Fiz um sistema com dois combo box para pesquisar as disciplinas no banco de dados e os conteúdos, sendo conteúdos uma foreign key de disciplinas. <h2 class="title">Selecione a disciplina</h2> <form action="" method="get"> <div class="box"> <select name="disciplina" id="disciplina"> <option value="" selected = selected>Selecione uma disciplina</option> <?php if($num_logar > 0) { do { echo "<option value='".$fet_logar['disciplina_id']."'>".$fet_logar['disciplina_nome']."</option>"; }while($fet_logar = mysqli_fetch_assoc($exe_logar)); } ?> </select> </div> </div> <div class="col-md-4 offset-md-4"> <h2 class="title">Selecione o conteúdo</h2> <div class="box"> <select name="conteudo" id="conteudo"> </select> </form> <ul class="dropdown-menu"> <script type="text/javascript"> $(document).ready(function(){ $('#disciplina').change(function(){ $('#conteudo').load('conteudo.php?disciplina='+$('#disciplina').val()); }); }); </script> </ul> </div> Ou seja, após o usuário selecionar uma disciplina, aparecerá seus respectivos conteúdos em outra combo box, sendo feita com javascript. Porém a partir que o usuário selecionou o conteúdo quero que apareça de forma automática, buscado do mysql, o link do vídeo embed do youtube. Fiz isso de forma não automática para uma representação. Segue o código abaixo. <figure> <div class="boxVideo"> <iframe width="700" height="450" src="https://www.youtube.com/embed/F9Bo89m2f6g" frameborder="0" allowfullscreen></iframe> </div> </figure> Como eu faço para que de forma automática, o link de vídeo embed, após selecionar o conteúdo de determinada disciplina, apareça abaixo da página? Ilustração do BD: Tabela disciplina, assim como o combo box que demonstra as disciplinas Tabela conteúdo, com uma FK, para que ao selecionar a disciplina o conteúdo a ser mostrado prevalecerá a partir de qual disciplina foi selecionada OBSERVAÇÃO: A partir de uma resposta anterior, foi observado que: 1- O select de conteúdo é puxado a partir de um javascript, ou seja, o value dele equivale ao conteudo_id e seguindo ao value name. 2- Uma ideia de solução seria um campo como eu fiz na tabela "conteudo", conteudo_video, que neste campo entraria o código embed do vídeo, exemplo "wjwudahw12" que entraria em "youtube.com/embed/wjwudahw12", como posso editar o "frame", para que ele percorresse por este campo, após selecionar disciplina e conteúdo, e inserir o código embed respectivo. A: Amigo, parece que o problema está em solucionar problemas de client-side com programação server-side. Você está tentando carregar um conteúdo dentro do select, para fazer isso utilize a função $.get do jQuery: var conteudos = $.get('conteudo.php?disciplina='+$('#disciplina').val()); Esta pagina conteudo.php deve retornar um JSON: [ { value: "F9Bo89m2f6g", name: "Video 1" }, { value: "AF7M17QX4QE", name: "Video 2" } ] Para assim, você conseguir popular o select desta forma: $.each(conteudos, function (key, conteudo) { $("#conteudo") .append( "<option value=" + conteudo.value + ">" + conteudo.name + "</option>" ); }); Para mostrar o video você pode utilizar o value do select dos conteúdos, assim: $("#conteudo").change(function () { var codigoVideo = $("#conteudo").val(); var videoContainer = $("#video_container"); videoContainer.html(` <iframe width="700" height="450" src="https://www.youtube.com/embed/${codigoVideo}" frameborder="0" allowfullscreen></iframe>`); }); Aqui está um exemplo funcionando: https://codepen.io/kleberoliveira/pen/gOpNwYP
{ "pile_set_name": "StackExchange" }
Q: How do I change the rotation of a directional light? (C#, Unity 5.5) I am trying to make my directional light rotate at a constant speed. This is the code that I have: using System.Collections; using UnityEngine; public class LightRotator : MonoBehaviour { void Update () { transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y + 1.0f, transform.rotation.z); } } However, this simply puts the light in a weird spot and leaves it there. What am I doing wrong? This is the rotation of the light before I run the game (should be the start position): Once the game starts, it changes to (and stays at) this: A: Maybe try transform.localEulerAngles transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y + 1.0f, transform.localEulerAngles.z); But I suggested you add Time.deltaTime to that, or your light will spin at the frame rate of the computer running it. So if you want a constant speed, modify it by that value. I've edited the following to make a complete example. The OP was saying on one axis it stops at a certain degree. I've expanded this to show with the following code, it will work on whatever axis and in whatever direction, modifiable at runtime. using UnityEngine; public class rotate : MonoBehaviour { public float speed = 100.0f; Vector3 angle; float rotation = 0f; public enum Axis { X, Y, Z } public Axis axis = Axis.X; public bool direction = true; void Start() { angle = transform.localEulerAngles; } void Update() { switch(axis) { case Axis.X: transform.localEulerAngles = new Vector3(Rotation(), angle.y, angle.z); break; case Axis.Y: transform.localEulerAngles = new Vector3(angle.x, Rotation(), angle.z); break; case Axis.Z: transform.localEulerAngles = new Vector3(angle.x, angle.y, Rotation()); break; } } float Rotation() { rotation += speed * Time.deltaTime; if (rotation >= 360f) rotation -= 360f; // this will keep it to a value of 0 to 359.99... return direction ? rotation : -rotation; } } Then you can modify speed, axis and direction at runtime to find what works for you. Though be sure to set it again after you stop the game, as it won't be saved.
{ "pile_set_name": "StackExchange" }
Q: XML extracting attributes using XMLDocument i am trying to parse an xml element using XMLDocument (DItem >> Title) below is my code but somehow i am not getting hold of it.... any help? XmlDocument xmldoc = new XmlDocument(); XmlNamespaceManager xmlns = new XmlNamespaceManager(xdoc.NameTable); xmlns.AddNamespace("DItems", "http://namespace.xsd"); xmldoc.Load(url); var title = xmldoc.SelectNodes("content", xmlns); foreach (XmlNode node in title) { string title = node.Attributes["Title"].Value; //this.ddlTitle.Items.Add(new ListItem(title)); } here is my XML: <?xml version='1.0'?> <root xmlns="http://www.w3.org/2005/Atom"> <title type="text">title</title> <entry> <content type="application/xml"> <Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd"> <CatalogSource Acronym="ABC" OrganizationName="organization name" /> <Item Id="28466" CatalogUrl="url"> <DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title1"> <content:Source Acronym="ABC" OrganizationName="ABC" /> </DItem> </Item> </Items> </content> </entry> <entry> <content type="application/xml"> <Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd"> <CatalogSource Acronym="ABC" OrganizationName="organization name" /> <Item Id="28466" CatalogUrl="url"> <DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title2"> <content:Source Acronym="ABC" OrganizationName="ABC" /> </DItem> </Item> </Items> </content> </entry> <entry> <content type="application/xml"> <Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd"> <CatalogSource Acronym="ABC" OrganizationName="organization name" /> <Item Id="28466" CatalogUrl="url"> <DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title3"> <content:Source Acronym="ABC" OrganizationName="ABC" /> </DItem> </Item> </Items> </content> </entry> </root> A: var xmldoc = new XmlDocument(); var xmlns = new XmlNamespaceManager(xmldoc.NameTable); xmlns.AddNamespace("DItems", "http://www.namespace.xsd"); xmldoc.Load(url); var titleNodes = xmldoc.SelectNodes("//DItems:DItem/@Title", xmlns); var result = titleNodes.Cast<XmlAttribute>().Select(a => a.Value).ToList(); Output (list of objects): my title1 my title2 my title3
{ "pile_set_name": "StackExchange" }
Q: how to use multiple times the stage event in as3 this is my code: stop(); import gs.*; import gs.easing.*; import gs.TweenMax; stage.addEventListener(MouseEvent.CLICK, rijden); // Add the button click function rijden(e:MouseEvent):void { TweenLite.to(auto, 4, {x:666.15, y:375.6}); } var grav:Number = 7.5; var jumping:Boolean = false; var jumpPow:Number = 0; stage.addEventListener(MouseEvent.CLICK, spring); // Add the button click stage.addEventListener(Event.ENTER_FRAME, update); function spring(e:MouseEvent):void { if(jumping != true) { TweenLite.to(man, 0.5, {rotation:360}); jumpPow = -50; jumping = true; } } function update(evt:Event):void { if(jumping) { man.y += jumpPow; jumpPow += grav; if(man.y >= 375) { jumping = false; man.y = 375; } } } but now if I click on the stage both the objects start to tween or something. but it needs to be like this: if I click the stage: first function rijden needs to be activated, on a second Click on the stage function spring needs to be activated. Can someone help me?? A: Reformat your code like this: //... stage.addEventListener(MouseEvent.CLICK, rijden); // Add the button click function rijden(e:MouseEvent):void { stage.removeEventListener(MouseEvent.CLICK, rijden); // unplug "rijden" handler stage.addEventListener(MouseEvent.CLICK, spring); // Add the button click TweenLite.to(auto, 4, {x:666.15, y:375.6}); } var grav:Number = 7.5; var jumping:Boolean = false; var jumpPow:Number = 0; stage.addEventListener(Event.ENTER_FRAME, update); function spring(e:MouseEvent):void { stage.removeEventListener(MouseEvent.CLICK, spring); // unplug "spring" handler if(jumping != true) { TweenLite.to(man, 0.5, {rotation:360}); jumpPow = -50; jumping = true; } } //...
{ "pile_set_name": "StackExchange" }
Q: using wildcards for projectCP in evosuite test case generation I use evosuite 1.0.1 for automated test case generation for several open source projects. I use java 1.8 on a unix platform (ubuntu 14.04). Is there a way to use wildcards for dependencies in the -projectCP tag? Some of my projects depend on a huge number of libraries and this could save me heaps of time. If you have a solution for either terminal or ant build script (no IDE) I would be very thankful! A: It is (currently) not possible to use wildcards in -projectCP. A workaround is to use first the -setup option to create the classpath (in which using wildcards is possible) on a configuration file on disk, and then run EvoSuite without -projectCP (as the CP will be taken by the previously generated file). For more info, look at the documentation on http://www.evosuite.org/documentation/commandline/
{ "pile_set_name": "StackExchange" }
Q: How to 'watermark' a PDF file? OK, I'm familiar with the whole concept and I've already managed to 'watermark' an NSImage. This is how I'm doing it : - (void)maskOne:(NSString*)filename atTarget:(NSString*)folder { NSString* target = [self getTargetPathForFile:filename path:folder]; NSImage* newImage; NSImage* oldImage = [[NSImage alloc] initWithContentsOfFile:filename]; newImage = [self maskImage:oldImage withMask:[self imageWithSubviews]]; [self saveImage:newImage asPNG:target]; } where [self imageWithSubviews] returns an NSImage from an embedded black-bg box with some transparent text in it. Now, in an bigger app of mine, as a sub-project, I'm trying to 'protect' exported PDFs by applying a watermark (nothing complicated, just a simple piece of text in the middle of each page, or something). How would you go about it? A: You can use the CoreGraphics framework for modifying PDF content - read Apple's official documentation on the topic.
{ "pile_set_name": "StackExchange" }
Q: Checking condition while Exception handling in python This is part of my code in python. I want to check the error message and if HTTPError() then I want to add the host to the file ok.txt. But it doesn't work. what is the problem here? except urllib2.URLError, e: print '%-15s\t%15r' % (url.strip(), e) if e == 'HTTPError()': OK.write('%-15s' % (url.strip()) + '\n') OK.flush() When I run whole script the output is something like this: http://a.com HTTPError() http://b.com URLError(timeout('timed out',),) http://c.com URLError(timeout('timed out',),) http://d.com URLError(error(111, 'Connection refused'),) http://e.com 200 A: Use isinstance() to check whether or not your error is of type HTTPError: except urllib2.URLError as e: # use the "as e" instead of the old style comma delimitation. print '%-15s\t%15r' % (url.strip(), e) if isinstance(e, HTTPError): OK.write('%-15s' % (url.strip()) + '\n') OK.flush()
{ "pile_set_name": "StackExchange" }
Q: Bash - how to put each line within quotation I want to put each line within quotation marks, such as: abcdefg hijklmn opqrst convert to: "abcdefg" "hijklmn" "opqrst" How to do this in Bash shell script? A: Using awk awk '{ print "\""$0"\""}' inputfile Using pure bash while read FOO; do echo -e "\"$FOO\"" done < inputfile where inputfile would be a file containing the lines without quotes. If your file has empty lines, awk is definitely the way to go: awk 'NF { print "\""$0"\""}' inputfile NF tells awk to only execute the print command when the Number of Fields is more than zero (line is not empty). A: I use the following command: xargs -I{lin} echo \"{lin}\" < your_filename The xargs take standard input (redirected from your file) and pass one line a time to {lin} placeholder, and then execute the command at next, in this case a echo with escaped double quotes. You can use the -i option of xargs to omit the name of the placeholder, like this: xargs -i echo \"{}\" < your_filename In both cases, your IFS must be at default value or with '\n' at least. A: This sed should work for ignoring empty lines as well: sed -i.bak 's/^..*$/"&"/' inFile or sed 's/^.\{1,\}$/"&"/' inFile
{ "pile_set_name": "StackExchange" }
Q: Как стилизовать input type = "password"? Мне нужно стилизовать input вот таким образом http://prntscr.com/r46e70 Как можно это сделать БЕЗ замены типа инпута на text? Спасибо!!! A: let $input = $('input[type="password"]'), $wrapperMask = $('.wrapper-mask'); $input.on('keydown', function(e) { if (e.keyCode == 8) { $('.wrapper-mask').find('span').last().remove(); } else { if ($('.wrapper-mask').find('span').length > 7) return; $wrapperMask.append('<span class="star"></span>'); } }) input[type="password"]{color:#fff;height:30px;width:250px} .wrapper{display:flex;align-items:center;max-width:250px;overflow:hidden} .wrapper-mask{position: absolute;padding:0 5px} .star{display:inline-block;background-image:url('https://toppng.com/uploads/preview/3d-gold-star-png-11552726957tpyco0iryc.png');background-size:contain;width:30px;height:30px} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="wrapper"> <span class="wrapper-mask"></span> <input type="password"/> </span>
{ "pile_set_name": "StackExchange" }
Q: "Top tags without excerpts" query returning incorrect values, likely using it incorrectly A few days ago, I noticed the "Top tags requiring a wiki" question. For those unfamiliar, it is an old post, directing users to update the wiki for popular tags. In the answer, there is a useful list of the "Top 20", with a link to the query used to determine the 20 most used tags that do not have wiki excerpts. After adding a few excerpts, and seeing they were approved, I ran the query and updated the list. I since noticed another user adding back in the tags I had completed, and removing other tags, that I confirmed to have no wiki. I rolled back the edit, and left a comment explaining my actions. I have gone back in, today, having pushed a wiki to the mortal-kombat-x tag. I click on the query, and I click "Run Query", confirming I am a human with a Capthca. However, the query still shows tags that have wikis. In fact, the supposed "top 2" are ff-record-keeper and mortal-kombat-x. I added these both, myself. I have since been awarded reputation for the approvals, and there is no comment on either wiki to note that they are still awaiting approval. Am I missing something that I potentially lucked out on, the first time? Or is there a different reason this query is no longer returning accurate data? A: The query given on the 'Top Tags without a Wiki' post can be up to a week out of date. The Stack Exchange Data Explorer from which the query is run isn't updated in realtime: Therefore, the best day to check and update the query is on Mondays. However, if you click on the tags in the query, it will take you to the Arqade page for that tag: Which will show an updated wiki in realtime. This is how I check when adding new tags to the answer. I doubt there's any malice here, just a simple misunderstanding. I've edited in a warning to the post in question, hopefully in future, situations like this one will not crop up as often.
{ "pile_set_name": "StackExchange" }
Q: Store files in mongodb with Nodejs I was saving my files on the FS of my server and now I want to save them in the mongodb.(for easier backup and stuff).I want to store files like 4-5Mb maximum and I tried save them with mongoose with Buffer type.I successfully saved them and retrieved them but I noticed a significant slow performance when i save and retrieve files like 4 or 5Mb. My schema: let fileSchema = new Schema({ name: {type: String, required: true}, _announcement: {type: Schema.Types.ObjectId, ref: 'Announcements'}, data: Buffer, contentType: String }); How I retrieve them from the expressjs server: let name = encodeURIComponent(file.name); res.writeHead(200, { 'Content-Type': file.contentType, 'Content-Disposition': 'attachment;filename*=UTF-8\'\'' + name }); res.write(new Buffer(file.data)); My question is should I use some zlib compress functions like 'deflate' to compress buffer before saving them in the mongodb and then uncompress the binary before sending them to the client? Would this make the whole proccess faster?Am I missing something? A: It seems that you are trying to save a really big amount of information with mongoDb. I can think in 3 diferent options for your case Cloud Services As other people already comment here, if the file that you are saving is a compressed one, even if its a small file, the new compression wont help you. In this cases, my recomendation is to use some web cloud service that is already optimized for the kind of information that you are trying to save and retrive, if its an image you could use Cloudinary that also has a free service so you can test it. Local Storage and saving routes in DB Other solution could be storing the encoded data in a .txt file, storing it in a cloud or in your file sistem, and then only save the routing in the database. This way you will not depend on the mongoDB speed for retriving it but you will have a good way to know where the files are located. Using MongoDB and GridFS This way you can use a specific method to store information in MongoDB that is recomended when you are dealing with files that are 16mb. As the Official Documentation says: Instead of storing a file in a single document, GridFS divides the file into parts, or chunks [1], and stores each chunk as a separate document. By default, GridFS uses a default chunk size of 255 kB; that is, GridFS divides a file into chunks of 255 kB with the exception of the last chunk. And next they say in what situations you may use this way of storing information: In some situations, storing large files may be more efficient in a MongoDB database than on a system-level filesystem. If your filesystem limits the number of files in a directory, you can use GridFS to store as many files as needed. When you want to access information from portions of large files without having to load whole files into memory, you can use GridFS to recall sections of files without reading the entire file into memory. When you want to keep your files and metadata automatically synced and deployed across a number of systems and facilities, you can use GridFS. When using geographically distributed replica sets, MongoDB can distribute files and their metadata automatically to a number of mongod instances and facilities. Hope it was useful :)
{ "pile_set_name": "StackExchange" }
Q: ProgressDialog not closing This is my code, seems like everything is good but when the app start doesn´t close the ProgressDialog, it´s cancelable but don´t dissapear and it´s showing since the app starts, and it´s not suposed to be like that private void displayView(int position) { final int thePos=position; final ProgressDialog myProgressDialog = ProgressDialog.show(MainActivity.this, "", "Procesando...", true); myProgressDialog.setCancelable(true); new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // update the main content by replacing fragments Fragment fragment = null; switch (thePos) { /*case 0: fragment = new HomeFragment(); break;*/ case 1: fragment = new HomeFragment(); break; case 2: fragment = new CalendarioFragment(); break; case 5: fragment = new ContactoFragment(); break; case 6: fragment = new OnclickFragment(); break; default: break; } if (fragment != null) { try{ FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit(); // update selected item and tit|le, then close the drawer mDrawerList.setItemChecked(thePos, true); mDrawerList.setSelection(thePos); setTitle(navMenuTitles[thePos]); mDrawerLayout.closeDrawer(mDrawerList); } catch(Exception E) { Log.e("MainActivity", "Error in creating fragment"); } } else { // error in creating fragment Log.e("MainActivity", "Error in creating fragment"); } }}); } catch (Throwable t) { // just end the background thread Log.i("Animation", "Thread exception " + t); } } private void threadMsg(String msg) { if (!msg.equals(null) && !msg.equals("")) { Message msgObj = handler.obtainMessage(); Bundle b = new Bundle(); b.putString("message", msg); msgObj.setData(b); handler.sendMessage(msgObj); } } // Define the Handler that receives messages from the thread and update the progress private final Handler handler = new Handler() { public void handleMessage(Message msg) { String aResponse = msg.getData().getString("message"); if ((null != aResponse)) { myProgressDialog.dismiss(); } } }; }) .start(); } //After call start method thread called run Method can anybody see the error? show me please A: Well, after a couple hours, i realized that the progress dialog i´ts wrong, i add it into the onItemClick and do the switch in a class, so there's the answer to add a ProgressDialog into a NavigationDrawer private class SlideMenuClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final int thePos=position; final ProgressDialog myProgressDialog = ProgressDialog.show(MainActivity.this, "", "Procesando...", true); myProgressDialog.setCancelable(true); new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // display view for selected nav drawer item displayView(thePos); myProgressDialog.dismiss(); }}); } catch (Throwable t) { // just end the background thread Log.i("Animation", "Thread exception " + t); } } private void threadMsg(String msg) { if (!msg.equals(null) && !msg.equals("")) { Message msgObj = handler.obtainMessage(); Bundle b = new Bundle(); b.putString("message", msg); msgObj.setData(b); handler.sendMessage(msgObj); } } // Define the Handler that receives messages from the thread and update the progress private final Handler handler = new Handler() { public void handleMessage(Message msg) { String aResponse = msg.getData().getString("message"); if ((null != aResponse)) { myProgressDialog.dismiss(); } } }; }) .start(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // toggle nav drawer on selecting action bar app icon/title if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle action bar actions click switch (item.getItemId()) { case R.id.action_settings: return true; default: return super.onOptionsItemSelected(item); } } /* * * Called when invalidateOptionsMenu() is triggered */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // if nav drawer is opened, hide the action items boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); menu.findItem(R.id.action_settings).setVisible(!drawerOpen); CreaMenu(); return super.onPrepareOptionsMenu(menu); } /** * Diplaying fragment view for selected nav drawer list item * */ private void displayView(int position) { final int thePos=position; // update the main content by replacing fragments Fragment fragment = null; switch (thePos) { /*case 0: fragment = new HomeFragment(); break;*/ case 1: fragment = new HomeFragment(); break; case 2: fragment = new CalendarioFragment(); break; case 5: fragment = new ContactoFragment(); break; case 6: fragment = new OnclickFragment(); break; default: break; } if (fragment != null) { try{ FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit(); // update selected item and tit|le, then close the drawer mDrawerList.setItemChecked(thePos, true); mDrawerList.setSelection(thePos); setTitle(navMenuTitles[thePos]); mDrawerLayout.closeDrawer(mDrawerList); } catch(Exception E) { Log.e("MainActivity", "Error in creating fragment"); } } else { // error in creating fragment Log.e("MainActivity", "Error in creating fragment"); } } //After call start method thread called run Method
{ "pile_set_name": "StackExchange" }
Q: Error using std::set to implement a sparse 3D grid I'm trying to implement a sparse 3D grid with std::set container, but I can't understand the error returned from the compiler, this is the minimal example I'm trying to run: #include <iostream> #include <vector> #include <limits> #include <set> #include <Eigen/Core> using namespace std; class Cell { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW Cell(const Eigen::Vector3i idx=Eigen::Vector3i::Zero()):_idx(idx) { _center = Eigen::Vector3f::Zero(); _parent = 0; _distance = std::numeric_limits<int>::max(); } inline bool operator < (const Cell& c){ for (int i=0; i<3; i++){ if (_idx[i]<c._idx[i]) return true; if (_idx[i]>c._idx[i]) return false; } return false; } inline bool operator == (const Cell& c) { return c._idx == _idx;} private: Eigen::Vector3i _idx; Eigen::Vector3f _center; vector<Eigen::Vector3f> _points; Cell* _parent; size_t _closest_point; float _distance; int _tag; }; int main(int argc, char* argv[]) { set<Cell> grid; float max = 1, min = -1; int dim = 5; float delta = (max-min)/(dim-1); for(int k = 0; k < dim; k++) for(int j = 0; j < dim; j++) for(int i = 0; i < dim; i++) grid.insert(Cell(Eigen::Vector3i(i,j,k))); return 0; } and this is the compiler error: In file included from /usr/include/c++/4.8/string:48:0, from /usr/include/c++/4.8/bits/locale_classes.h:40, from /usr/include/c++/4.8/bits/ios_base.h:41, from /usr/include/c++/4.8/ios:42, from /usr/include/c++/4.8/ostream:38, from /usr/include/c++/4.8/iostream:39, from /home/dede/build/sparse_grid/main.cpp:1: /usr/include/c++/4.8/bits/stl_function.h: In instantiation of 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Cell]': /usr/include/c++/4.8/bits/stl_tree.h:1324:11: required from 'std::pair std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_get_insert_unique_pos(const key_type&) [with _Key = Cell; _Val = Cell; _KeyOfValue = std::_Identity; _Compare = std::less; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::key_type = Cell]' /usr/include/c++/4.8/bits/stl_tree.h:1377:47: required from 'std::pair, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(_Arg&&) [with _Arg = Cell; _Key = Cell; _Val = Cell; _KeyOfValue = std::_Identity; _Compare = std::less; _Alloc = std::allocator]' /usr/include/c++/4.8/bits/stl_set.h:472:40: required from 'std::pair, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(std::set<_Key, _Compare, _Alloc>::value_type&&) [with _Key = Cell; _Compare = std::less; _Alloc = std::allocator; typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator = std::_Rb_tree_const_iterator; std::set<_Key, _Compare, _Alloc>::value_type = Cell]' /home/dede/build/sparse_grid/main.cpp:53:57: required from here /usr/include/c++/4.8/bits/stl_function.h:235:20: error: passing 'const Cell' as 'this' argument of 'bool Cell::operator<(const Cell&)' discards qualifiers [-fpermissive] { return __x < __y; } ^ make[2]: * [CMakeFiles/sparse_grid.dir/main.cpp.o] Error 1 make[1]: * [CMakeFiles/sparse_grid.dir/all] Error 2 make: *** [all] Error 2 I would really appreciate if someone could tell me what I'm doing wrong. Thanks, Federico A: You should declare your boolean operator functions as const members: inline bool operator < (const Cell& c) const { // ^^^^^ for (int i=0; i<3; i++){ if (_idx[i]<c._idx[i]) return true; if (_idx[i]>c._idx[i]) return false; } return false; } inline bool operator == (const Cell& c) const { return c._idx == _idx;} // ^^^^^ Otherwise these cannot be used with rvalue objects of Cell.
{ "pile_set_name": "StackExchange" }
Q: Ошибка в сортировке двумерного массива void main(void) { srand(time(NULL)); int A[N][M], circles = N + M, swap; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { A[i][j] = 3 + rand() % 100; } } while (circles) { for (int i = 0; i < (circles - 1); i++) { if (*(A + i) > *(A+i+1)) /*ругается на этот if*/ { swap = *(A + i); *(A + i) = *(A + i + 1); *(A + i + 1) = swap; } } circles--; } } Пишет ошибку: Error 3 error C2106: '=' : left operand must be l-value В чём может быть дело? A: Вы пытаетесь сравнивать строки матрицы и менять их между собой, однако оператора сравнения строк матрицы и оператора присваивания int[] к int[] у вас не существует. На то и ругается.
{ "pile_set_name": "StackExchange" }
Q: Range of balls needed in lottery for 0 and 1 match to be equally likely with 5 balls drawn The question is if there is a lottery in which 5 balls are drawn randomly without replacement, what is the number range of the balls needed so that matching exactly 0 of those balls or matching exactly 1 of them is equally likely (or as close to equally likely as possible)? Assume all balls are numbered sequentially from 1 to n (such as 1,2,3...n). Solve for n. I know this can be solved by trial and error but is there a mathematical way to get the answer without first guessing and then making corrections/adjustments? I was also able to solve it using wolframalpha but how can someone solve it mathematically, either getting an exact same probability for matching exactly 0 or 1 ball(s) or such that the probability of matching exactly 0 or 1 is the closest it can be? The idea is a hypothetical lottery wants to make it easier to match at least 1 ball so maybe more people play or people that play continue to do so. So the lottery designer is interested to first find out where 0 and 1 matches are about equal, then adjust it slightly to favor at least 1 match. A: Here's what I think you're asking, generalized slightly. There are $n$ balls numbered $1, \ldots, n$. Lottery players choose $k$ distinct numbers with $k < n$, then $k$ balls are drawn. Tickets are rewarded according to the number of matches. Each ticket should have the same probability distribution, so wlog assume that the player chooses $1, \ldots, k$. Then: The number of zero-match drawings is $\binom{n-k}{k}$, the number of $k$-element subsets of $\{k+1, \ldots, n\}$. Note that at least one match is guaranteed unless $2k \leq n$. The number of one-match drawings is $k \binom{n-k}{k-1}$, the number of one-element subsets of $\{1, \ldots, k\}$ times the number of $k-1$-element subsets of $\{k+1, \ldots, n\}$. Solving for $n$: \begin{align*} \binom{n-k}{k} &= k \binom{n-k}{k-1} \\ \frac{(n-k)!}{k! (n-2k)!} &= \frac{k (n-k)!}{(k-1)! (n-2k+1)!} \\ \frac{(k-1)!}{k(k!)} &= \frac{(n-2k)!}{(n-2k+1)!} \\ \frac{1}{k^2} &= \frac{1}{n - 2k + 1} \\ n &= k^2 + 2k - 1 \end{align*} So $n = 34$ for $k = 5$. If you have the R programming language and the tidyverse package installed, then the following function will let you simulate the lottery. balls and draws are the total number of balls and the number of balls drawn ($n$ and $k$ in my notation above), and trials is the number of simulations to run. The output is a data frame with two columns: num_matches lists integers from 0 to draws, and num_trials shows the number of trials that gave that number of matches with a ticket marked 1, ..., draws. lottery <- function(balls, draws, trials) { tibble(trial=rep(1:trials, each=draws), result=as.vector(replicate(trials, sample(1:balls, draws)))) %>% group_by(trial) %>% mutate(match=(result<=draws)) %>% summarize(num_matches=sum(match)) %>% ungroup() %>% group_by(num_matches) %>% summarize(num_trials=n()) } I tried running this with 200,000 trials and got good results: > lottery(34, 5, 2e5) # A tibble: 5 x 2 num_matches num_trials <int> <int> 1 0 85350 2 1 85338 3 2 26260 4 3 2941 5 4 111 > lottery(62, 7, 2e5) # A tibble: 6 x 2 num_matches num_trials <int> <int> 1 0 82073 2 1 82850 3 2 29922 4 3 4777 5 4 364 6 5 14 I'll note that as $k$ increases, the outcomes of this lottery seem to reproduce the Poisson distribution for $\lambda = 1$, and the probabilities of $0$ and $1$ matches approach $1/e$. I can't think of a quick explanation for this immediately. The probability of zero matches in this lottery is \begin{align*}\frac{ \binom{k^2 + k - 1}{k}}{\binom{k^2 + 2k - 1}{k}} &= \frac{ \frac{(k^2 + k - 1)!}{k! (k^2-1)!}} {\frac{(k^2 + 2k-1)!}{k! (k^2 + k + 1)!}} \\ &= \frac{(k^2 + k + 1)!^2}{(k^2 + 2k - 1)!(k^2 - 1)! } \\ &= \frac{k^2 (k^2 + 1) (k^2 + 2) \cdots (k^2 + k - 1)}{(k^2 + 2k) (k^2 + 2k + 1) \cdots (k^2 + 2k - 1)} \\ &= \prod_{i=0}^{k-1} \frac{k^2+i}{k^2 + 2k + i} \\ &= \exp \left( -\sum_{i=1}^{k} \log \left( 1 - \frac{2k}{k^2 + 2k + i} \right) \right)\end{align*} and perhaps that last sum could be shown to go to $1$ by a clever use of asymptotics.
{ "pile_set_name": "StackExchange" }
Q: jQuery not functioning without document.ready on a cfm page I'm pretty new to jQuery, and I am converting a page from "regular" javascript to jQuery on a coldfusion page. The page is driven off a stored procedure, which, based on it's result sets, changes the page and number of input fields. On my page, the input tags look like this. <cfinput name="#trim(characteristic_id)#_fund" id="#trim(characteristic_id)#_fund" value="#fund#" size="11" onFocus="getCurrentValue(this)" onblur="checkChange(this,'c')"> <cfinput name="#trim(characteristic_id)#_benchmark" id="#trim(characteristic_id)#_benchmark" value="#benchmark#" size="11" onFocus="getCurrentValue(this)" onblur="checkChange(this,'c')"> The onFocus event just saves the current value, and the onBlur event checks to see if the value has changed, and if it has save it in a array for further processing. Personally, I feel like jQuery is suited very well for this kind of processing, and it is on of the main reason I am trying it. To my issue. Right now I am replacing the onFocus event handler with: $("input").focus(function(){ alert($(this).val()); }); simple, but when I try i, nothing happens, no javascript errors, nothing. Nothing happens at all. So, all of the other jQuery code that I have written, I have used $(document).ready..., and when I used that, it worked fine. From what I've read, the UI is rendered before the DOM is ready, but to compound that issue the coldfusion is running prior to everything else. My question is this; Do I have to put all of my jQuery code inside the $(document).ready... function or is there another way around it. Thanks in advance. A: You do need to put your code in $(document).ready() or $(window).load() if you want to attach handlers to DOM objects. That being said, you can call code in a script block that loads after the element you want to manipulate and that should work, too. However, it is good practice to use the ready/load handlers. If you don't wait for the DOM to load, the elements don't exist yet. You do not have to stuff all of your code in one ready block if you don't want to. You can have multiple $(document).ready() blocks. Each will simply be called in succession once the document loads. $(window).load(), by the way, waits for the elements themselves to load, such as images.
{ "pile_set_name": "StackExchange" }
Q: Can you use phpmyadmin to put wordpress posts to an external site? I know it may be a stupid question. I have a website that I have built in PHP and I have a section that I would like 3 responsive posts to pull in from Wordpress. I have tried using API and JSON curls and not having any luck, mostly because I lack knowledge on those things. Didn't know if it could be easier to pull into PHPMyAdmin then I could code to pull in the info from that and make it responsive? A: So here is my revised php <section id="blog"> <div class="container-fluid"> <div class="row"> <div id="featured_posts"> <?php // output RSS feed to HTML output_rss_feed('http://www.bmcsquincy.com/featured_posts/feed', 20, true, true, 200); // Check http://www.systutorials.com/136102/a-php-function-for-fetching-rss-feed-and-outputing-feed-items-as-html/ for description // RSS to HTML /* $item_cnt: max number of feed items to be displayed $max_words: max number of words (not real words, HTML words) if <= 0: no limitation, if > 0 display at most $max_words words */ function get_rss_feed_as_html($feed_url, $max_item_cnt = 10, $show_date = true, $show_description = true, $max_words = 0, $cache_timeout = 7200, $cache_prefix = "/tmp/rss2html-") { $result = ""; // get feeds and parse items $rss = new DOMDocument(); $cache_file = $cache_prefix . md5($feed_url); // load from file or load content if ($cache_timeout > 0 && is_file($cache_file) && (filemtime($cache_file) + $cache_timeout > time())) { $rss->load($cache_file); } else { $rss->load($feed_url); if ($cache_timeout > 0) { $rss->save($cache_file); } } $feed = array(); foreach ($rss->getElementsByTagName('item') as $node) { $item = array ( 'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue, 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue, ); $content = $node->getElementsByTagName('encoded'); // <content:encoded> if ($content->length > 0) { $item['content'] = $content->item(0)->nodeValue; } array_push($feed, $item); } // real good count if ($max_item_cnt > count($feed)) { $max_item_cnt = count($feed); } $result .= '<ul class="feed-lists">'; //ADDED THIS FOR POST AMOUNT $max_item_cnt = 3; for ($x=0;$x<$max_item_cnt;$x++) { $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']); $link = $feed[$x]['link']; $result .= '<li class="feed-item">'; $result .= '<div class="feed-title"><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong></div>'; if ($show_date) { $date = date('l F d, Y', strtotime($feed[$x]['date'])); $result .= '<small class="feed-date"><em>Posted on '.$date.'</em></small>'; } if ($show_description) { $description = $feed[$x]['desc']; $content = $feed[$x]['content']; // find the img $has_image = preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $content, $image); // no html tags $description = strip_tags($description, ''); // whether cut by number of words if ($max_words > 0) { $arr = explode(' ', $description); if ($max_words < count($arr)) { $description = ''; $w_cnt = 0; foreach($arr as $w) { $description .= $w . ' '; $w_cnt = $w_cnt + 1; if ($w_cnt == $max_words) { break; } } $description .= " ..."; } } // add img if it exists //ADDED THE P IN DESCRIPTION LINE TO FOR A BREAK BY IMAGE if ($has_image == 1) { $description = '<p> <img class="feed-item-image" src="' . $image['src'] . '" /></p>' . $description; } $result .= '<div class="feed-description">' . $description; //ADDED THE P IN THIS TO LINE BREAK CONTINUE READING $result .= '<p> <a href="'.$link.'" title="'.$title.'">Continue Reading &raquo;</a></p>'.'</div>'; } $result .= '</li>'; } $result .= '</ul>'; return $result; } function output_rss_feed($feed_url, $max_item_cnt = 10, $show_date = true, $show_description = true, $max_words = 0) { echo get_rss_feed_as_html($feed_url, $max_item_cnt, $show_date, $show_description, $max_words); } ?> </div><!--END FEATURED POSTS--> </div><!--END ROW--> </div><!--END CONTAINER--> </section><!--END SECTION BLOG--> Here is my css #blog { background-color: yellow; color: #dbdbdb; width: 100%; padding-top: 100px; padding-bottom: 100px; margin: 0px auto 0px auto; } #featured_posts { background-color: pink; max-width: 1200px; margin: 0px auto 0px auto; padding: 5px; } #featured_posts ul { display: inline-block; margin: 0px auto 0px auto; text-align: center; padding: 0px; } #featured_posts li { list-style-type: none; text-align: left; padding: 30px; float: left; font-family: pathwaygothic; font-size: 1em; background-color: purple; max-width: 1200px; margin-left: 25px; } .feed-lists { background-color: aqua; width: 100%; } .feed-title a { color: red; } .feed-date { color: aqua; } .feed-description { width: 300px; } .feed-lists li { background-color: green; }
{ "pile_set_name": "StackExchange" }
Q: Client caching overrides custom Last-Modified when rendering a View I recently started working on a MVC.NET project and soon noticed there was no caching of the front-page. Setting [OutputCache(Duration = 60), Location = Client] on the Index() method added the right Expires headings, but since Last-Modified was set to the time the page was created the caching would never kick in. As an experiment, I then manually tried setting the Last-Modified header to some time in the past, to see how that worked, but it seems as if is being overwritten somewhere! I added this code to the end of my Index() action: DateTime dt = DateTime.Parse("2015-12-01"); var timeString = dt.ToUniversalTime().ToString("R"); var v = View("Index", homeViewModel); Response.AddHeader("Last-Modified", timeString); return v; Even though I could debug and inspect the headers in the Response and see the header being added, the returned page in the browser still had Last-Modified: Wed, 09 Mar 2016 15:34:12 GMT (the current time). My manually set header was thus overwritten by some other code after the action returned. What is causing this behaviour, and how can I manually set the last-modified timestamp to enable caching? Addendum using Location = ServerAndClient will make client caching work again, which beats me as somewhat odd ... If, so what use is the Client option? How can it ever work? A: It is the OutputCache attribute that is overwriting the relevant headers I pass along. Removing that will make it possible to set whatever headers I like. And to answer the second question of when the Client option makes sense, be aware that you will never see any effect when refreshing the browser window. It is only when you click links that the browser will decide if it should reuse the cached version.
{ "pile_set_name": "StackExchange" }
Q: How to get Intellij to launch browser automatically after spring-boot webapp is ready I just switched a Spring Boot webapp from an external war deploy in Tomcat to a direct jar deploy with Spring Boot (and its internal Tomcat). For Tomcat Run/Debug Configurations, Intellij gives you the to open browser after launch and go to http://localhost:8080/. How can I do something similar with a a Spring Boot RUn/Debug Configuration. It runs the main class and just waits until I go to localhost:8080 from the browser myself. A: edit your run/debug configurations in the bottom - click on '+' right above 'Build' select 'launch web browser', put your app url, for example http://localhost:8181 so you will have click apply/ok, with that when you click Run/play button, it will launch browser with your url after the build
{ "pile_set_name": "StackExchange" }
Q: How can I better optimize networking on iOS? I have created a project on GitHub so I can learn how to optimize networking for my iOS apps. I have used blocks and GCD heavily and after watching WWDC 2012 videos and videos from past years I learned that I may be able to do more with NSOperationQueue. Specifically I can control the number of concurrent operations (network connections) as well as provide cancellation of operations. I am experimenting with allowing 1, 2, 4, 8 and 16 concurrent operations and I am seeing interesting results that I did not totally expect. I am measuring the results but I wonder if there is more that I should be measuring. You can find sample project here: https://github.com/brennanMKE/OptimizedNetworking Since I am using the async API of NSURLConnection there is plenty of benefit to having many concurrent connections because the API spends a fair amount of time waiting for HTTP packets. Previously my code would start with an array of items to download and request them all sequentially, which is prevents the benefits of concurrency. I have also been using notifications to cancel network connections. Now I can do that with this project through operations and I have set them up to use a value for priority and a category so that I can prioritize and sort downloads and cancel a category of operations. I may choose to use a category for each view and when a user leaves a view all operations for that view will be cancelled using the category. This will free up resources for the active view. One concern with using more concurrent operations is CPU usage as well as I/O, but I am not aware of a way to measure these values with iOS. The equivalent of the "w" command in iOS to show CPU usage could be useful. I am less concerned about I/O but measuring it would be more comprehensive. My main issue with how I was doing networking was a responsive UI. I found that what I have been doing has made the UI sluggish. This new approach may help a great deal, but only if I keep the number of concurrent operations down. The optimal number of operations may vary by the type of connection (3G, WiFi, etc) so checking the connection type may lead to some optimizations. If you are interested in better ways to speed up network communications in your app please try out this sample project and suggest other ways that I can measure performance and offer ways to further optimize communications. (Also note that I am referencing the Apple sample project MVCNetworking as well as the ASIHTTPRequest project. What I may do next is to total up the amount of data downloaded and keep a log of that amount along with the total time to complete the download. The README file should help explain the project and how it works. A: If this helps Mugunth Kumar actually checks the type of connection using the reachability class before setting the NSOperationQueue max connection size in the MKNetworkKit
{ "pile_set_name": "StackExchange" }
Q: How can I calculate the effect of my equipment on my sport's performance? I'm doing a stationary sport like golf, so the details matter. I'm recording each of my scores with detailed information about the equipment I'm using, and the weather conditions. So 1 score has 2-3 pieces of equipment attached to it. I can plot averages for may main piece of equipment, but then how do I isolate the effect of the others(performance accessories/safety equipment)? A: You can apply multiple factor ANOVA with your score as dependant variable and equipment and weather conditions as factors. You would need to meet certain assumptions: 1) scores should be normally distributed under each factor 2) ratios of variance between groups should not exceed 3 or be less then 1/3 3) most importantly: all scores must be independent among and within groups
{ "pile_set_name": "StackExchange" }
Q: How to set an image to the really top of app? i try to set an image to the very top of my android app. But there is always space to the left/right/top even if margin is zero. code: <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" android:layout_margin="0dp" android:layout_marginBottom="0dp" android:layout_marginLeft="0dp" android:layout_marginRight="0dp" android:layout_marginStart="0dp" android:layout_marginTop="0dp" android:background="@drawable/bgColor" android:gravity="top" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <LinearLayout android:id="@+id/topBar" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="25dp" android:src="@drawable/ic_launcher" /> Where is my error? Thanks =) A: Check your dimens.xml file (res/values directory) for the activity_vertical_margin and activity_horizontal_margin dimen resources. You are using those for your parent RelativeLayout as padding: android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"
{ "pile_set_name": "StackExchange" }
Q: Need properties in Configuration class I have spring boot application and application.properties file in resources folder. I need some properties in a configuration class. I cant use getClass().getClassLoader().getResourceAsStream() because null pointer. How do I get the properties in configuration class? Property class: @Configuration @PropertySource("classpath:application.properties") public class AppProperties { @Value("${server.ssl.key-store}") private String serverSSLKeyStore; @Value("${server.ssl.trust-store}") private String serverSSLTrustStore; @Value("${server.ssl.key-store-password}") private String serverSSLKeyStorePwd; @Value("${server.ssl.trust-store-password}") private String serverSSLTrustStorePwd; @Value("${rabo.api.url}") private String raboApiUrl; @Value("${tpp.certificate}") private String TPPCertificate; @Value("${rabo.client.id}") private String raboClientId; @Value("${rabo.key.id}") private String raboKeyId; @Value("${rabo.private.key}") private String raboPrivateKey; @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("application.properties")); return propertySourcesPlaceholderConfigurer; } // Getters } Configuration class: @Configuration public class RetrofitConfiguration { private static final Logger LOG = LoggerFactory.getLogger(RetrofitConfiguration.class); @Bean SSLTrustManagerHelper provideSSLTrustManagerHelper(AppProperties properties) { try { LOG.error(properties.getServerSSLKeyStore()); // PRINTS NULL InputStream keystore = new FileInputStream(properties.getServerSSLKeyStore()); InputStream truststore = new FileInputStream(properties.getServerSSLTrustStore()); String keystorePwd = properties.getServerSSLKeyStorePwd(); String truststorePwd = properties.getServerSSLTrustStorePwd(); SSLTrustManagerHelper ssl = null; try { ssl = new SSLTrustManagerHelper(keystore, keystorePwd, truststore, truststorePwd); } catch (Exception e) { LOG.error("error occured while creating ssl trust manager helper!", e); } return ssl; } catch (FileNotFoundException e) { LOG.error("file not found ", e); return null; } } // Other config } The AppProperties class is created but properties return null. A: What you want to do is setup a @ConfigurationProperties rather than a property source. This feature of Spring Boot allows you to read properties into a POJO that can be used elsewhere in code. So the AppProperties would be something like: @Configuration @ConfigurationProperties class AppProperties { private String serverSSLKeyStore; // the other properties public void setServerSslKeyStore(String value) { this.serverSSLKeyStore = value; } public String getServerSslKeyStore() { return this.serverSSLKeyStore; } } Every field must have a corresponding property with the same name in the application.properties file. Note that each field should have getter and setter methods for this to work. You can then initialize it in your Spring boot application using: @SpringBootApplication @EnableConfigurationProperties(AppProperties.class) // not needed in later spring version class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
{ "pile_set_name": "StackExchange" }
Q: MySQL count(col) that returns null I have 3 tables : Teams (id_team, name, id_season) Teams_Stats (id_stats, id_game, id_team, victory, defeat) Seasons (id_season, name, nbr_teams) I'm trying to pull out the number of victories for each team for a specific season (2015 in this case). That's what I have so far, but it returns 0 for all the teams. my SQL syntax : SELECT T.name, count(a.victory) as Wins FROM Teams T, Seasons S LEFT JOIN (SELECT TS.id_team, TS.victory FROM Teams_Stats TS WHERE TS.victory = 1) a ON a.id_team = 'T.id_team' WHERE T.id_season = S.id_season AND S.name = '2015' GROUP BY T.nom ORDER BY T.nom What am I doing wrong ? Thanks :) A: Try modifying your query a bit like SELECT T.name, count(TS.victory) as Wins FROM Teams T JOIN Seasons S ON T.id_season = S.id_season AND S.name = '2015' LEFT JOIN Teams_Stats TS ON TS.id_team = T.id_team AND TS.victory = 1 GROUP BY T.name ORDER BY T.name
{ "pile_set_name": "StackExchange" }
Q: R: ggplot incompatibility between shape and fill aesthetics at plot legend I am trying to create a plot using fill and shape aesthetics. The plot looks wonderful however the legend does not get colored by the fill aesthetics. Could you please help me to sort this out? Here an example code #Example dataset bio_rep = rep(c(1:3), 4) category = rep(c("w", "x", "y", "z"), each = 3) ranking = sample(c("s","a","b","c"), 12, replace = T) score = runif(12) df = data.frame(bio_rep, category, ranking, score) > df bio_rep category ranking score 1 1 w b 0.12496463 2 2 w b 0.82229942 3 3 w b 0.20121351 4 1 x a 0.06352934 5 2 x s 0.57510752 6 3 x a 0.54471793 7 1 y a 0.87203684 8 2 y c 0.32858945 9 3 y a 0.06234144 10 1 z c 0.41124401 11 2 z s 0.62253128 12 3 z a 0.42499771 Now the plot require(ggplot2) ggplot(df, aes(category, score, shape = factor(bio_rep), fill = ranking))+ geom_point(size = 3)+ scale_shape_manual(values = c(21,22,23)) As you can see, ranking does not get colored in the legend Image link here! Do you know how to solve it? Many thanks in advance MP A: The reason is that the default shape used by the "ranking" legend does not have a fill aesthetic (only color). You can change this shape to match the ones in your other legend using override.aes: ggplot(df, aes(category, score, shape = factor(bio_rep), fill = ranking))+ geom_point(size = 3)+ scale_shape_manual(values = c(21,22,23)) + guides(fill = guide_legend( override.aes = list(shape=21) ))
{ "pile_set_name": "StackExchange" }
Q: Workflow Rule to check for null lookup I'm trying to write a very simple workflow where if the Case Contact is NULL do some action. In my Rule Criteria, I've tried: isNull( ContactId ) However, this doesn't seem to trigger the workflow. |WF_FORMULA|Formula:ENCODED:[treatNullAsNull]isNull( {!ID:Contact} )|Values:ContactId=null |WF_CRITERIA_END|false What is the correct way to do this check? A: I tested with ISBLANK(ContactId) and it seems to work:
{ "pile_set_name": "StackExchange" }
Q: Graph Coloring based on neighboring vertices? Cellular Automata I would like to apply a majority rule cellular automata to graphs. Specifically, I would like to take a graph as input, and then define two functions, InitialColoring[graph] and MajorityRule[graph]. Suppose the set of colors is some given finite list. InitialColoring[graph] uses some rule (such as randomly assigning colors to each vertex). MajorityRule[graph] this "updates" the coloring for a given graph by getting the neighbors of each vertex, checking which color has the majority, and then coloring the majority color. For simplicity, let's assume the set of colors only has two colors, and if there is a tie, the vertex keeps its current color. My thoughts: Make a loop ranging over vertices, get neighbors, get colors, count colors, apply. I am very new to Mathematica so I am not sure how to implement this. Any suggestions on this approach or a better method to accomplish the same goal? Also note: I want to apply cellular automata to graphs (specifically CayleyGraphs), not just the integer lattice so the built-in CellularAutomata function doesn't seem to help much. EDIT: EXAMPLE: Suppose we have the graph shown in the upper left corner in the figure below. We want to apply the rule that a vertex's color is determined by the color of the majority of its neighbors (if there is a tie, it keeps its color). Below shows an example of the progression of this automata. This outlines what I want: 1) enter a graph with an initial coloring 2) apply a rule (shown through progression of arrows) that outputs a new graph (or perhaps two functions, one that outputs the graph data, and one that outputs the color data... then these are combined in some way... I'm not sure which would be easier/more efficient to implement). I am lost as to how to implement this, although the algorithm is pretty easy. In fact, focusing to the case where we only have two colors and the majority rule would suffice. EDIT 2: Further Details Updating should be synchronous, i.e., when we go from one time to the next, it should look like we updated every vertex all at once. Otherwise, we could get unwanted colorings due to intermediate updates in sequential updating. For example, in the example above, if we colored the top vertex first, and then proceeded, the rightmost vertex would stay blue the next generation instead of changing to red. Also, when checking for the vertex's color, the vertex itself should only be considered in the event of a tie, i.e., it is not considered one of its neighbors unless there is a loop (we don't assume graphs are implicitly reflexive). A: Update: The original post below computes the commonest color in the NeighborhoodGraph of a vertex v including the vertex v itself. To exclude a vertex in counting the colors in its neighborhood, we can use the following helper function: ClearAll[newClrF]; newClrF = Module[{nc=#, oc=First@#, c1= Commonest[Rest@#][[1]], c2= Quiet@Commonest[Rest@#, 2]}, If[And[Length@c2 > 1, Equal @@ (Count[Rest@nc, #] & /@ c2)], oc, c1]] &; and modify reColorF1 and reColorF2: ClearAll[reColorF1B, reColorF2B]; reColorF1B = Module[{g = #1, vl = VertexList[#1], cl, ncl}, ncl = (neighborColorsF[g, #1] &) /@ vl; cl = newClrF /@ ncl; MapThread[(PropertyValue[{g, #}, VertexStyle] = #2) &, {vl, cl}]; g] &; reColorF2B = Module[{g = #1, vl = VertexList[#1], cl, ncl}, ncl = (neighborColorsF[g, #1] &) /@ vl; cl = newClrF /@ ncl; SetProperty[g, VertexStyle -> Thread[vl -> cl]]] &; Using the same examples as in the previous post: Grid[Most@FixedPointList[reColorF1B, #, 5] & /@ {g1, g2}] Another example: g3 = SetProperty[g, {VertexStyle -> Thread[Range[10] -> {Red, Blue, Green, Orange, Red, Green, Orange, Red, Red, Orange}], VertexSize -> Large, ImageSize -> 100}]; Grid[Most@FixedPointList[#, g3, 9] & /@ {reColorF1, reColorF1B}] Previous post: In the following, color counts in the neighborhood of a vertex v include the color of vertex v. ClearAll[neighborsF, neighborColorsF, commonestColorF, reColorF1, reColorF2]; neighborsF = Function[{g, v}, VertexList[NeighborhoodGraph[g, v]]]; neighborColorsF = Function[{g, v}, PropertyValue[{g, #}, VertexStyle] & /@ neighborsF[g, v]]; commonestColorF = Function[{g, vl}, (Commonest[neighborColorsF[g, #]][[1]]) & /@ vl]; Using the above helper functions, define reColorF1 = Module[{g = #, vl = VertexList @ #, cl = commonestColorF[#, VertexList @ #]}, MapThread[(PropertyValue[{g, #}, VertexStyle] = #2) &, {vl, cl}]; g] &; Alternatively, you can use SetProperty to change the vertex colors: reColorF2 = Module[{g = #, vl = VertexList @ #, cl = commonestColorF[#, VertexList @ #]}, SetProperty[g, VertexStyle -> Thread[vl -> cl]]] &; Examples: g = PetersenGraph[5, 2]; g1 = SetProperty[g, { VertexSize -> Large, ImageSize -> 200, VertexLabels -> Placed["Name", Center], VertexStyle -> Thread[Range[10] -> RandomChoice[{Red, Blue, Green}, {10}]]}]; g2 = SetProperty[g, { VertexSize -> Large, ImageSize -> 200, VertexLabels -> Placed["Name", Center], VertexStyle -> Thread[Range[10] -> RandomChoice[{Red, Blue, Green}, {10}]]}]; Grid[Most@FixedPointList[reColorF1, #, 5] & /@ {g1, g2}] Grid[Most@FixedPointList[reColorF2, #, 5] & /@ {g1, g2}] (* same picture *) Note: Breaking ties in favor of current color: OP's requirement "if there is a tie, the vertex keeps its current color" is satisfied, i.e., both functions above break ties in favor of the current own color, because VertexList[NeighborhoodGraph[g, x]] lists x as the first vertex, and Commonest[list] breaks the ties based on the order the elements appear in list. A: First, let's whip up a random graph: n = RandomInteger[{10, 15}]; m = RandomInteger[{Floor[n^2/20], n (n - 1)/2}]; G = RandomGraph[{n, m}]; For[i = 1, i <= n, i++, chi[0, i] = {Red, Blue}[[RandomInteger[] + 1]] ]; Graph[G, VertexStyle -> Table[i -> chi[0, i], {i, 1, n}]] The coloring at step k will be denoted chi[k,i], where i indicates a vertex. I am going to start now assuming that some graph object G is given, but that it is not necessarily of the above form, so the vertex i might not be an integer: VX = VertexList[G]; n = Length[VX]; EX = EdgeList[G]; m = Length[EX]; Obviously if you generate G as above, some of that is unnecessary. Since the underlying graph is static, it's easiest to just hash out the neighborhoods of each vertex quickly: For[i = 1, i <= n, i++, NBHD[i] = Select[EX, #[[1]] == i || #[[2]] == i &]; NBHD[i] = Complement[Union @@ (List @@ # & /@ NBHD[i]), {i}]; ] From there, we can define kmax steps of this process as: kmax = 10; For[k = 1, k <= kmax, k++, For[i = 1, i <= n, i++, COL = Commonest[chi[k - 1, #] & /@ NBHD[VX[[i]]]]; chi[k, i] = Which[ Length[COL] == 1, COL[[1]], MemberQ[COL, chi[k - 1, i]], chi[k - 1, i], True, COL[[RandomInteger[{1, Length[COL]}]]] ]; ]; ]; I've made the choice that if there is a tie among neighbors, if that tie includes the current color, the vertex says the same color. If some vertex has a tie among neighbors that does not include its current color, it changes randomly to one of those most popular colors. (That's what's happening in the Which conditional.) You can display the results with: Manipulate[ Graph[G, VertexStyle -> Table[i -> chi[k, i], {i, 1, n}]], {k, 0, kmax, 1}] I'm sure there are other/different/better ways to do parts of this, but I think this gets you going the way you want. I hope it is also flexible enough if your G has a non-integer vertex set or some other issue. And so long as you define chi[0,i] for all i using some valid color, you get what you need out. This should be fairly flexible in such regards. You can reproduce the "usual" automata using GridGraph like this: G = GridGraph[{10, 10}]; For[i = 1, i <= n, i++, chi[0, i] = {Red, Blue}[[Mod[i, 2] + 1]] ]; I've used this particular coloring (not random) to get some interesting behavior out of the automaton. Update To achieve the tie-breaking rule where ties result in no color change, just swap out: If[ Length[COL] == 1, COL[[1]], chi[k - 1, i] ]; for the Which conditional above. Note that this will produce possibly counter-intuitive behavior, like a green node with 10 red neighbors and 10 blue neighbors remaining green without any green neighbors. A: More is better, other variation: upDateColor[g_] := Block[{color, vlist, c}, color = Association[PropertyValue[g, VertexStyle]]; vlist = VertexList[g]; SetProperty[g, VertexStyle -> Table[v -> If[Length[c = Commonest[color /@ AdjacencyList[g, v]]] == 1, First[c], color[v]], {v, vlist}]] ] example: g = PetersenGraph[5, 2, {VertexSize -> Large, ImageSize -> 200, VertexLabels -> Placed["Name", Center], VertexStyle -> Thread[Range[10] -> RandomChoice[{Red, Blue, Green}, {10}]]}]; Row@Most[FixedPointList[upDateColor, g]] in case of repeating sequence, you could define a function like below to detect sequence pattern (this one only detect result one above): iFixedPointList[func_, g_, n___] := Block[{i}, i = g; FixedPointList[func, g, n, SameTest -> (SameQ[i, #2] || (i = #1; SameQ[#1, #2]) &)] ] SeedRandom[1]; g = PetersenGraph[5, 2, {VertexSize -> Large, ImageSize -> 200, VertexLabels -> Placed["Name", Center], VertexStyle -> Thread[Range[10] -> RandomChoice[{Red, Blue}, {10}]]}]; iFixedPointList[upDateColor, g] // Length 4 FixedPointList[upDateColor, g, 6] // Length 7
{ "pile_set_name": "StackExchange" }
Q: What is the most common way to refer to a particular note in the chromatic scale without making any implications as regards tonality? It seems to me that in current musical practice, we are often in a 12-TET situation where effectively, we have an (octave repeating) set of 12 notes that make up the chromatic scale, each of which can then have various names - for example, I might point to a particular note on the keyboard and call it 'F♯' in one key; I might call it 'G♭' in another. Calling it one of those names implies you're not playing in any of a certain set of keys in which that wouldn't be the name for the note. However, if I just want to refer to the note in its own right, without implying any sense of key, what do I call it? Obviously pointing to the key on the instrument works, if it's physically in front of you, but that's not much use if it isn't; MIDI note numbers are logically similar to what I'm talking about, except it's rather odd to use them if you're not using MIDI. (If you're wondering why I'm asking, it's because I wanted to write an answer to Is the Western system of notes and intervals essentially two-dimensional?, but in order to write a response clearly, I needed to be able to refer to the idea of 'a note that can be played' without implying a specific tonal context.) A: The standard is to use integers from 0–11 (actually, 0–e or 0–B as I’ll explain in a second) to represent each of the 12 possible pitch classes. “Pitch” refers to a particular note: Gb4 or F#2. “Pitch Class” refers to the family of pitches that are enharmonically and/or octave equivalent to each other. For example F# in any octave is the same family as Gb in any octave. In the unlikely event of an Ex, that too is in the same family. To refer to the entire family generally, we have arbitrarily assigned numbers to each one, starting with the pitch class that includes C as 0. So, any B#s, Cs or Dbbs are members of pitch class 0. Any C#s or Dbs are part of pitch class 1. Any Cxs, Ds or Ebbs are pitch class 2, etc. This means that A#s and Bbs are PC 10 and Bs and Cbs are PC 11, but that can be confusing since it’s often hard to see the difference between 1 0 (meaning, perhaps, a Db followed by a C) and 10 (meaning, perhaps, A#). Instead most analysts refer to 10 and 11 with the symbols t and e, or A and B. EDIT TO ADD: As Tim points out in the comments, this system does NOT specify octave, so if you're looking for a way to specify a particular octave without specifying a particular enharmonic spelling, it's more difficult. For the most part, this isn't an issue because of the way interval is discussed in set theory. I'll provide a quick précis of the four ways that interval is discussed, but will leave details for a different question: 1) If I care about the full size of an interval AND its direction, I will refer to the "ordered pitch interval" or opi using number of semitones and + for up and - for down. The distance from middle C up to Db a minor ninth above is +13. The distance from middle C down to B below is -13. 2) If I care about the full size but I DON'T care about direction (which is another way of saying that I don't care which note came first), then I will refer refer to the "unordered pitch interval" or upi using only number of semitones. Both of the examples I referred to above would be upi 13. 3) If I don't care about octave distances, but I do care about the order of notes, then I use "ordered pitch class intervals" or opci. This is probably the hardest one to envision at first. I will count the number of half steps it would take me to get from the first note up to the next note even if the interval went down in the actual music. Going from any C to any Db (that is to say from 0 to 1) would always be opci 1. Going from any Db to any C (i.e. 1 to 0) would always be 11. Going from D to G (2 to 7) would be 5 and G to D (7 to 2) would be 7. The main benefit of using numbers instead of note names (and, importantly, of starting our numbering system with 0 instead of 1) is that intervals can be easily figured out by simple subtraction. Subtract the first number from the second number (mod 12) and you have the opci. My four examples above: 1-0=1; 0-1=-1 which is 11 mod 12; 7-2=5; 2-7=-5 which is 7 mod 12. The mod 12 part may be unfamiliar to you, but it's something you use every time you say that something happening three hours after 11 AM will happen at 2 PM. 11+3 is actually 14 of course, but we treat time like a circle, and roll back to 2. 4) Finally, and most commonly, we can refer to the interval in the most general way possible: the interval class (sometimes called the "unordered pitch class interval", but IC is pithier and has an obvious similarity to "pitch class." In this situation we just want to know the how to get from one note to the other in semitones in the closest way possible. The closest way to get from a Db (1) to a C (0) if we don't care which comes first is 1. All half steps, major sevenths, minor ninths, etc. will belong to this same family of intervals: interval class 1. Whole steps, minor sevenths, major 9ths, etc. are part of IC 2; minor thirds, major sixths etc. are IC 3; and so on. There are only 6 possible intervals classes (unless you want to count unisons and octaves). A: There is no convention that I have used, except naming them with the way they are used most, in any Western music. Thus, F# wins over Gb, Bb over A# etc. But - it leaves a dead heat with G#/Ab !! A: I know of no standard, but perhaps it's most common to use naturals and sharps: C, C#, D, D#, etc. I don't see any problem in this context in terms of implying any sense of key.
{ "pile_set_name": "StackExchange" }
Q: SSH to jump host, to final host, then tmux In my ssh config, I have Host jumpHostNick HostName jumphost.com User username Host finalHostNick User username ProxyCommand ssh jumpHostNick nc finalHostURL 22 I would like to supplement this by having it run tmux attach -d when it gets to the final host. Is that possible? A: Use -W rather then the netcat: Host jumpHostNick HostName jumphost.com User username Host finalHostNick User username ProxyCommand ssh -W finalHostURL:22 jumpHostNick If you want to run tmux attach -d, you should also add to the finalHostNick: RequestTTY yes and then connect using ssh finalHostNick -t tmux attach -d, or just setup bash alias: alias ssh-final='ssh finalHostNick -t tmux attach -d' in your ~/.bashrc
{ "pile_set_name": "StackExchange" }
Q: which sentence is correct? has left, left or leaves? I am confused with this: "Long after he has left, she finds out that it has been stolen." "Long after he left, she finds out that it has been stolen." "Long after he leaves, she finds out that it has been stolen." I don't really know which one is the correct one. Please help. Thank you :) A: 'after he leaves' = context is present, but describes just a condition that hasn't yet happened. e.g. after he leaves, let's set his bed on fire. 'after he has left' = context is present tense, but describes a condition that happened in the (implied recent) past. e.g. after he has left, he realises that he has left his wallet behind (or he doesn't have his wallet - to make the present tense clearer) 'after he left' = the story context is past. The 'after' has no bearing on the tense change. e.g. After he left the building, he realised he left his wallet behind. He knew he was a dumbass, but he didn't believe he was this dumb. The latter part is present tense - so "Long after he has left..." is the right prefix.
{ "pile_set_name": "StackExchange" }
Q: react-native fetch api arrays I am trying to fetch facebook movie data using axios. In my console, I see the fetched data, but I have trouble getting when I want to access the title text. class BoardScreen extends Component { constructor(props) { super(props); this.state = { movies: [] }; } componentWillMount() { axios.get('https://facebook.github.io/react-native/movies.json') .then(response => this.setState({ movies: response.data })); } renderMovies() { return this.state.movies.movies.map(movies => <Text>{movies.title}</Text>) } render() { if(this.state.movies.length === 0) { return null; } console.log(this.state.movies.title, 'movies') return ( <View> {this.renderMovies()} </View> ) } } The code above only will give me the main title text The Basics - Networking What I really want is to access to each movie title and display. How could I fetch each array title? A: What you need is this looping through it and bind the data. this.state.movies.movies.map(a=>{ return <div key={a.id}>{a.title}</div> }) Ofcourse you need to check if movies is not null, so render should look like this render() { if(this.state.movies.length === 0) { return null; } console.log(this.state.movies.movies, 'movies'); return ( this.state.movies.movies.map(a=>{ return <div key={a.id}>{a.title}</div> }) ) } Demo IMO, would be be very very easy if you just have looked here
{ "pile_set_name": "StackExchange" }
Q: Do pex fittings need to be replaced when installing a new water heater? I have purchased a new water heater to replace the original 11 year unit. I am concerned in attaching the existing fittings to the new unit. I believe the builder used pex directly to the original heater. What is unclear to me is how these will behave when I begin to unscrew them. Should the fitting (B) slide free of the cold side brass fitting (C) or must these pieces be replaced? I believe the black fitting (E) will rotate free, but I have the same concern with the connection to the pressure valve (F) as I do the cold water supply. A: PEX pipe won't slide off the fittings if spun because they are on there through compression and not screwed on. I've spun the crimp style fittings without issues but never spun the style you have before but from what I've read, you can spin them with out issue. If you decide to cut the pipe, remember you'll need a spreading tool to reconnect the pipes or use something like SharkBite fittings. You can reuse the brass fittings by cutting the ring with a knife and then heating up the plastic pipe and then bend it back and forth until it comes off. From what I've read, you can do the same with the plastic fittings but be very careful not to cut or overheat them. I'd just replace the plastic ones instead.
{ "pile_set_name": "StackExchange" }
Q: How do I run a Stored procedure with parameters from Excel VBA string? I am trying to run a stored procedure from Excel using VBA, but I'm getting a "Type Mismatch" error with the following code. Can I execute a Stored procedure with parameters as a string passed to the Command object as shown below? Function Sproc() Dim cnn As New ADODB.Connection Dim rst As New ADODB.Recordset Dim cmd As ADODB.Command Dim ConnectionString As String Dim StrSproc As String ConnectionString = "Provider=SQLOLEDB;Data Source=DBSource;" & _ "Initial Catalog=CurrentDb;" & _ "Integrated Security=SSPI;" 'Opens connection to the database cnn.Open ConnectionString 'Timeout error in seconds for executing the entire query; this will run for 15 minutes 'before VBA times out, but your database might timeout before this value cnn.CommandTimeout = 900 StrSproc = "EXEC StoredProcedure " & _ "@parameter1 = 0," & _ "@parameter2 = 0," & _ "@parameter3 = 0," Application.StatusBar = "Running stored procedure..." Set rst = cmd.Execute(, , StrSproc) End Function A: Try this: Option Explicit Function Sproc() Dim cnn As New ADODB.Connection Dim rst As New ADODB.Recordset Dim cmd As ADODB.Command Dim cnnStr As String Dim Rs As New ADODB.Recordset Dim StrSproc As String cnnStr = "Provider=SQLOLEDB;Data Source=DBSource;" & "Initial Catalog=CurrentDb;" & _ "Integrated Security=SSPI;" With cnn .CommandTimeout = 900 .ConnectionString = cnnStr .Open End With With cmd .ActiveConnection = cnn .CommandType = adCmdStoredProc .CommandText = "[StoredProcedureName]" .Parameters.Append .CreateParameter("@parameter1", adInteger, adParamInput, , 0) .Parameters.Append .CreateParameter("@parameter2", adInteger, adParamInput, , 0) .Parameters.Append .CreateParameter("@parameter2", adInteger, adParamInput, , 0) End With With Rs .CursorType = adOpenStatic .CursorLocation = adUseClient .LockType = adLockOptimistic .Open cmd End With Application.StatusBar = "Running stored procedure..." Set rst = cmd.Execute End Function A: This is my preferred approach: Function Sproc() Dim cnn As ADODB.Connection Dim rst As ADODB.Recordset Dim cmd As ADODB.Command Dim ConnectionString As String Dim StrSproc As String Set cnn = New ADODB.Connection cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=DBSource;" & _ "Initial Catalog=CurrentDb;" & _ "Integrated Security=SSPI;" 'Opens connection to the database On Error GoTo SQL_ConnectionError cnn.Open ConnectionString On Error GoTo 0 'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value cnn.CommandTimeout = 900 Set rst = New ADODB.Connection StrSproc = "set nocount on; " StrSproc = StrSproc & "EXEC StoredProcedure " & _ "@parameter1 = 0," & _ "@parameter2 = 0," & _ "@parameter3 = 0 " rst.ActiveConnection = cnn On Error GoTo SQL_StatementError rst.Open StrSproc On Error GoTo 0 If Not rst.EOF And Not rst.BOF Then Sproc = IIF(IsNull(rst.Fields(0).Value), "(BLANK)", rst.Fields(0).Value) EndIf Exit Function SQL_ConnectionError: Msgbox "Error connecting to the server / database. Please check the connection string." Exit Function SQL_StatementError: Msgbox "Error with the SQL syntax. Please check StrSproc." Debug.Print StrSproc Exit Function End Function Give it a try and let me know what you think.
{ "pile_set_name": "StackExchange" }
Q: Spring message source, getMessage in bean XML? I have set up my resources like this: <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"> <value>locale\\messages</value> </property> </bean> My propertyFile: battle.name=TestBattle I would like to reach the text "TestBattle" when I use a bean: <bean id="battlefield" class="com.mypackage.Battlefield" scope="prototype"> <constructor-arg index="0" value="battle.name" /> <constructor-arg index="1" ref="armies" /> </bean> I want to refeer the message in the propertyFile in this line <constructor-arg index="0" value="battle.name" /> Is there a way to do it without going into java using the getMessage("battle.name",... code in java? A: At least, you could use spel to do it. for example <bean id="messageSourceAccessor" class="org.springframework.context.support.MessageSourceAccessor"> <constructor-arg ref="messageSource" /> </bean> <bean id="battlefield" class="com.mypackage.Battlefield" scope="prototype"> <constructor-arg index="0" value="#{messageSourceAccessor.getMessage('battle.name')}" /> <constructor-arg index="1" ref="armies" /> </bean> However it seems cumbersome if you have to translate many codes. Other option is using a String to String PropertyEditor to do the translation. public class MessageSourcePropertyEditor extends PropertyEditorSupport { private MessageSourceAccessor messageSourceAccessor; public MessageSourcePropertyEditor(MessageSource messageSource) { this.messageSourceAccessor = new MessageSourceAccessor(messageSource); } @Override public void setAsText(String text) throws IllegalArgumentException { String value = text; if (text.startsWith("i18n:")) { value = messageSourceAccessor.getMessage(text.substring(5)); } setValue(value); } } public class MessageEditorRegistrar implements PropertyEditorRegistrar { private MessageSource messageSource; @Override public void registerCustomEditors(PropertyEditorRegistry registry) { registry.registerCustomEditor(String.class, new MessageSourcePropertyEditor(messageSource)); } public MessageSource getMessageSource() { return messageSource; } public void setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } } And use the prefix i18n: to translate codes, ie <bean id="propertyEditorConfigure" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="propertyEditorRegistrars"> <list> <bean class="message.MessageEditorRegistrar"> <property name="messageSource" ref="messageSource" /> </bean> </list> </property> </bean> <bean id="battlefield" class="com.mypackage.Battlefield" scope="prototype"> <constructor-arg index="0" value="i18n:battle.name" /> <constructor-arg index="1" ref="armies" /> </bean>
{ "pile_set_name": "StackExchange" }
Q: Why are HTML elements appending after the I've been trying to append the divs on to the DOM below another div tag but they are all appending after the script tag. HTML: <body> <div class="bg"> </div> <script src = "d3.v4.js"> <script src = "scripts.js"> </body> JavaScript: var dataset = [ 10, 20, 30 ]; d3.select("body").selectAll("div").data(dataset).enter().append("div").attr("class", "bg") CSS: div.bg{ background-color:pink; display: inline-block; height: 100px; width:10px; } It appears this way on DOM now : <body> <div class="bg"> </div> <script src = "scripts.js"> <div class="bg"> </div> <div class="bg"> </div> <div class="bg"> </div> <div class="bg"> </div> </body> A: because your elements are created after your DOM is created (when the script is executed)... so they by default they append at the last. Fix it by appending elements inside a container as below: <body> <div class="container"> </div> <script src = "d3.v4.js"> <script src = "scripts.js"> </body> CODE var dataset = [ 10, 20, 30 ]; d3.select(".container").selectAll("div").data(dataset).enter().append("div").attr("class", "bg") CSS div.bg{ background-color:pink; display: inline-block; height: 100px; width:10px; } OUTPUT <body> <div class="container"> <div class="bg"> </div> <div class="bg"> </div> <div class="bg"> </div> </div> <script src = "scripts.js"> </body>
{ "pile_set_name": "StackExchange" }
Q: Show/Hide div in DataList with Jquery and I made a project with asp, but something is not working...I am trying to show/hide div which is inside of Datalist. But unfortunately is working only in first element, and the others element the div that I want to hide is appear. here is my code: `<script type="text/javascript"> $(function () { $("#hiden").hide(); $("#showddiv").on("click", function () { $("#hiden").toggle(); }); }); </script> <div id="mainReferences"> <asp:DataList ID="DataList1" runat="server" CellPadding="4" ForeColor="#333333"> <AlternatingItemStyle BackColor="#2E2E2E" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <ItemStyle BackColor="#151515" /> <ItemTemplate> <table cellspacing="20"> <tr> <td><a href="#" id="showddiv" class="fontText" title="drop the div down"><img src='<%# Eval("Mainfoto") %>' width="320px" height="290px" /> </a></td> <td width="400px"> <asp:Label ID="Label1" class="FontText" Font-Bold="true" runat="server" Text="Përshkrimi:"></asp:Label><br /> <asp:Label ID="Label2" width="400px" class="FontText" Font-Size="Large" runat="server" Text='<%# Eval("pershkrimi") %>' ></asp:Label></td> </tr> </table> <div id="hiden" class="categorry"> </div> </ItemTemplate> <SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> </asp:DataList>` A: You're re-using id values in your HTML. This is invalid markup and will likely lead to undefined behavior (probably different by browser as well). Notice this element: <div id="hiden" class="categorry"> Since this is essentially inside a loop (repeater, datalist, etc.) it's going to render multiple times to the page. Instead of an id, use a class: <div class="hiden categorry"> Then just change your jQuery selector: $('.hiden') Of course, now you also need to specifically identify which element you want to toggle. You can do this by traversing the DOM a little bit from the clicked element. Something like this: $(this).closest('div').find('.hiden').toggle(); This is an example, since I don't know the rendered markup resulting from your server-side code. Essentially the selector in .closest() should refer to whatever parent element wraps that particular datalist item in the markup. This basically looks for: The element which was clicked -> a common parent between it and the element you want to toggle -> the element you want to toggle. (Naturally, this same fix will need to be applied anywhere else you're duplicating id values, which you do a couple of times in your code.) ids have to be unique in the DOM. classes can be re-used.
{ "pile_set_name": "StackExchange" }
Q: Should I change my misunderstood question to fit a well made answer? I have this question, titled How to Propagate Callback Promise Value on Model.find( obj, callback)?, but the answers for this question have not only fulfilled my final objective but have also changed my understanding of the subject. So, the best answer do not address a propagation of a promise value but, instead, change the subject to a promise-like error and success callbacks. If anyone sees the question title and look to the answer, it will not fit. Should we change title or some important information regarding the initial understanding of the question by the question owner? A: Close or edit question. There are generally several cases for such questions: question was asked in such a way that almost everyone understood it in one particular way which was not at all OP's intention/question (i.e. it could be because of using wrong terms). In such case I'd recommend asking new question and editing original by adding "if you are looking for Xxxx check out other question" at the end and possibly edit title if it clearly wrong/too general. question asked to do particular action (like add DateTime field to SQL) but sample/approach was completely off (i.e. use some strange string formatting to construct SQL statement). In such case edit question with clear goal and keep misguided attempt to solve the problem as it likely lead users trying similar approach to correct question. question asked about one thing but totally changed in comments and such modified version answered with good post. Definitely need to edit question to inline comments and align with answer. I think your question is of second kind (and code you provided is quite plausible approach). I'd recommend replacing first paragraph with actual goal and possibly adjust title.
{ "pile_set_name": "StackExchange" }
Q: Robotic arm ["FAiL"] error display. - Festo / Mitsubishi Melfa RV-2AJ (Controller CR1-571) To avoid wasting your time on this question, you might only want to react on this if you have knowledge of industrial robotic arms specific. Common troubleshooting is unlikely to fix this problem or could take too much time. We've started a project with the Mitsubishi Melfa RV-2AJ robotic arm. Everything went fine until the moment we replaced the batteries. The controller displays: "FAiL" and does not respond to any buttons or commands sent through serial connection. We did replace the batteries of both the robot and the controller. As it took some time to get the batteries delivered, we've left the robot (and controller) withouth power for the weekend. (Which might have caused this problem) Is there anyone with knowledge of Mitsubishi Robotic arms around here? I'm kinda hoping it would be a common problem/mistake and anyone with experience on this subject would know about it? A: After some googling I found that there is an explanation & fix guide, only in German, for this. It'll be of use for others having the same problem. I'll try my very best to translate it a bit, please note that German, not English, is my main language: Concerning "FAIL" in the display of the robotcontroller after voltage drop from back-up batteries (general). - KS00527 When the battery voltage is unsufficient to keep the buffer (which holds the settings of the powered-off robot), the display will show the message: "FAIL". To reset this message/state, a RAM data reset is needed. After this reset, all programs and position data in the robotcontroller will be erased and the parameters will be reverted. The procedure (RAM data reset) is as following: Press STOP and RESET at the same time, while the controller is being activated. The robot controller display would show "|----|". Releave the STOP and RESET buttons. Press RESET untill the display will show "EnG". Press START once. Press RESET until the display shows your Robot type Press Start once. The robot controller display would show "rAMc9". After ~15-25 sec. (depending on the contents of the RAM?) you'll see a countdown from "100-0". The message "ok" will appear on the dispaly. Finally the robot will automatically reboot. (Didn't happen for us though) I believe the procedure might differ a little per controller, but this would get you going. The original text: Anzeige FAIL im Display der Robotersteuerung nach Spannungsverlust der Pufferbatterien (General) - KS00527 Wenn die Batteriespannung die Einstellungen der ausgeschalteten Robotersteuerung nicht mehr puffern kann, zeigt das Display nach dem Einschalten die Anzeige FAIL an. Um diese zu beseitigen hilft nur ein RAM Daten Reset. Nach diesem Reset sind alle Programme, Positionsdaten in der Robotersteuerung gelöscht und die Parameter auf Werkseinstellung zurückgesetzt. Die Prozedur ist wie folgt : - Drücken Sie die STOP und RESET Taste gleichzeitig, während der Controller eingeschaltet wird. - Im Display wird ”I- - - -I” angezeigt. - STOP und RESET Taste loslassen - Die Taste RESET so oft drücken bis ”EnG” im Display angezeigt wird. - Drücken Sie einmal die START Taste. - Drücken Sie die Taste RESET oder STOP so oft bis im Display angezeigt wird. - Drücken Sie einmal die START Taste. - Im Display wird nun ”rAMc9” angezeigt. - Nach ca. 15-25 sec (abhängig vom Inhalt des RAM Speichers) sieht man im Display einen Countdown von ”100-0”. - Es erscheint kurz die Meldung ”ok” im Display. - Abschließend bootet der Controller selbsttätig neu. Source: https://eu3a.mitsubishielectric.com/fa/en/service/knowledgebase?m_culture=de&ks=527 KS00527 of the GERMAN knowledgebase on Mitsubishi (Somehow German people may know things the English aren't allowed to? :D (You can't find it in English))
{ "pile_set_name": "StackExchange" }
Q: Golf Scores Array - Actionscript 3.0 I am making a program which has the user enter a golf score which then stores it in an array. However, the user can only enter up to 18 scores and I have attempted to code a prompt which indicates the number of scores that are in the array/they have entered. The label is called lblPrompt1 and it does not function. I also want to disable the addscore button when the user has entered all 18 scores. The prompt does not function. Please advise. Thanks! // Purpose: To add golf scores to an array // This line makes the button, btnAddScore wait for a mouse click // When the button is clicked, the addName function is called btnAddScore.addEventListener(MouseEvent.CLICK, addScore); // This line makes the button, btnDisplayScores wait for a mouse click // When the button is clicked, the displayScores function is called btnDisplayScores.addEventListener(MouseEvent.CLICK, displayScores); // declare the global variables var scores: Array = new Array(); // array of golf scores // This is the addName function // e:MouseEvent is the click event experienced by the button // void indicates that the function does not return a value function addScore(e: MouseEvent): void { // declare the variables var golfScore: String; // friend's name entered by user // get the name from the user golfScore = txtinScore.text; // append the name to the end of the array scores.push(golfScore); // display the length of the array in the label lblArraySize.text = "Number of Golf Scores Entered: " + scores.length; } // This is the displayNames function // e:MouseEvent is the click event experienced by the button // void indicates that the function does not return a value function displayScores(e: MouseEvent): void { var holeNumber: Number; lblScores.text = ""; for (var x = 0; x < scores.length; x++) { lblScores.text += scores[x] + "\r"; } holeNumber++; if (holeNumber <= 18) { lblPrompt1.text = "Enter the score for hole #" + holeNumber.toString() + ":"; } else { lblPrompt1.text = "All scores are entered."; txtinScore.text = ""; btnAddScore.enabled = false; } } A: While it's not very clear what you are asking, one issue you have is that your holeNumber variable will never have a numeric value - it will always be NaN (Not A Number). Whenever the display scores button is clicked, inside the click handler function (displayScores), you create this variable (holeNumber) and you don't give it a value. Numbers default to NaN, so later when you increment it with holeNumber++, you'll just end up with NaN still (because NaN plus 1 is still NaN). The other part of that issue, is you create the variable in the scope of the click handler, and only increment it once, so even if you changed the var definition to var holeNumber:Number = 0;, it would still have a value of 1 every time you clicked because every click the variable get's recreated and then incremented by 1. What you probably want to do, is forgo the holeNumber var altogether and just reference scores.length as that is essentially the current hole. function displayScores(e: MouseEvent): void { lblScores.text = ""; for (var x = 0; x < scores.length; x++) { lblScores.text += scores[x] + "\r"; } //use scores.length instead of holeNumber if (scores.length < 18) { lblPrompt1.text = "Enter the score for hole #" + String(scores.length + 1) + ":"; //adding 1 to the length because that would be the next hole number } else { lblPrompt1.text = "All scores are entered."; txtinScore.text = ""; btnAddScore.enabled = false; } }
{ "pile_set_name": "StackExchange" }
Q: Login with php an html, user name checking When I type a password just log in, the a name means nothing. You can enter any name and be you log.But I also do not want to, I want that there is a specific name and password to login! PHP: <?php // sha1() encrypted password // the default is "test" $password = '5df04db4e2ae413c40cb20359db92a925d6ff1b4'; // set username $username = 'Marko'; // Start session session_start(); // Initialize wrong password check variable $isWrongPass = false; // Initialize wrong name check variable $isWrongUser = false; if( !isset( $_SESSION['signedIn'] ) ) { $_SESSION['signedIn'] = false; } // If the user clicked "sign out", if( isset( $_GET['signout'] ) ) { $_SESSION['signedIn'] = false; // Change the location to where you want to redirect the user after signing out header("Location: login.php"); } // If the user submitted a password if( isset( $_POST['password'] ) ) { if ( sha1( $_POST['password'] ) == $password ) { $_SESSION['signedIn'] = true; } else { $isWrongPass = true; } } // If the user submitted a name if ( $_POST['username'] == $username ) { $_SESSION['signedIn'] = true; } else { $isWrongUser = true; } if( !$_SESSION['signedIn']): ?> This method only works for a password, I tried to do the same for the name or fails. HTML: <?php if( $isWrongPass . $isWrongUser) { ?> <div class="error">Pogresno ste uneli ime ili lozinku!</div> <?php } ?> <form id="signIn" method="post"> <label for="username">Ime</label> <input style="border-radius: 100px" type="text" id="username" name="username" /> <label for="password">Lozinka</label> <input style="border-radius: 100px" type="password" id="password" name="password" /> <input style="border-radius: 100px" type="submit" name="submit" class="submit" value="Uloguj Se" /> </form> A: This is where your issue is. // If the user submitted a password if( isset( $_POST['password'] ) ) { if ( sha1( $_POST['password'] ) == $password ) { $_SESSION['signedIn'] = true; } else { $isWrongPass = true; } } // If the user submitted a name if ( $_POST['username'] == $username ) { $_SESSION['signedIn'] = true; } else { $isWrongUser = true; } If the password is correct OR the username is correct you are setting signedIn to true. If you want both to be correct, you should try integrating them into the same if statement or setting signedIn to false if isWrongUser or isWrongPass is true. I do not recommend using the above code even with the issue you asked about fixed. You should also keep in mind that sha1 is outdated (an attack on it was published February 2017). You should be using a standardized, secure hashing function. Look here as pointed out in the comment for a guide on how to handle your passwords. Even if you are not working on an application that you are going to release, using the standardized functions is not much more difficult. password_hash and password_verify automatically handle salting the password to prevent rainbow table cracking of password hashes. password_hash takes in a password to hash, and password_verify takes in a plaintext to verify and a hash to verify with.
{ "pile_set_name": "StackExchange" }
Q: Use still stuck around after Def is destroyed: Why it is giving error While deleting: i32 % Use still stuck around after Def is destroyed: %in = alloca [3000 x i32], align 4 opt: Value.cpp:79: virtual llvm::Value::~Value(): Assertion `use_empty() && "Uses remain when a value is destroyed!"' failed. when I am running my LLVM Pass containing these lines . . . Type *t3=dyn_cast<Type>(ArrayType::get(Type::getInt32Ty(context),50)); AllocaInst *al2=new AllocaInst(t3,"ar",ins1); . . . Here I am trying to allocate a new array. A: I assume your pass is doing more than emit an alloca? Your error line above has a 3000 element array while the code snippet below generates a 50 element one. Are you doing possibly an eraseFromParent() on the alloca instruction above? An instruction cannot have any uses when it is being destroyed; You may want to look at replaceAllUsesWith() though I can't say much more without more information as to what your pass is doing.
{ "pile_set_name": "StackExchange" }
Q: Caption Formation for Figure I use the caption package. Somehow I got a period between the type (Figure) and the separator (:) When I wrote listformat=empty, for the Table of Figures, I just got the period and then the caption text. I have no idea, but the period just appeared when I tried to skip the chapter numbering (\counterwithout{figure}{chapter}) One way or the other, I always have the period which looks like: Figure 1.: Description EDIT: I tried it, but I couldn't get it to run. That's everything I have regarding the captions. But somehow I think somewhere is some more. I just can't remember. \documentclass[ 12pt, % Schriftgröße %DIV10, % Teilung der Seite in 10 Teile (Layout bessere Lesbarkeit) ngerman, % für Umlaute, Silbentrennung etc. a4paper, % Papierformat oneside, % einseitiges Dokument (Standard) titlepage, % es wird eine Titelseite verwendet parskip=half, % Abstand zwischen Absätzen (halbe Zeile) headings=normal, % Größe der Überschriften verkleinern listof=totoc, % Verzeichnisse im Inhaltsverzeichnis aufführen bibliography=totoc, % Literaturverzeichnis im Inhaltsverzeichnis aufführen %index=totoc, % Index im Inhaltsverzeichnis aufführen listof=flat, captions=tableheading, % Beschriftung von Tabellen unterhalb ausgeben final % Status des Dokuments (final/draft) ]{scrreprt} \usepackage{chngcntr} \usepackage[ labelfont=bf, % labelsep=none, listformat=simple, % simple ist defaultwert. ]{caption} \counterwithout{figure}{chapter} \usepackage[demo]{graphicx} \begin{document} \listoffigures \begin{figure}[htb] \begin{center} \leavevmode \includegraphics[width=0.8\textwidth]{foo.jpg} \end{center} \caption{Beispiel einer Matrixkombination} \label{fig:Matrixknoten} \end{figure} \end{document} A: In document class scrreprt if you use the Appendix, you automatically get a period after the number. To solve the problem you need to load the class with the option: numbers=noendperiod Thanks for your help!
{ "pile_set_name": "StackExchange" }
Q: Please critique my Engine game Two of my engine's played against Garbo engine. (without a opening Book on my part.) Both lost :( Which played better? I need a comparative analysis. Both shared the same evaluation. frankenstein played much faster :( [Site "Chessrig app"] [White "garbo"] [Black "frankenstein"] [Opening "Mieses-Kotroc Variation, Center Counter"] [Event "Simmulation"] [Date "2017-11-13"] [TimeControl "unlimited"] [Result "1-0"] [Termination "Checkmate by white in 75 moves."] [FEN ""] 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd4 4. Nf3 Qd6 5. d4 Bg4 6. h3 Bh5 7. g4 Bg6 8. Ne5 Qe6 9. Bb5+ c6 10. Bc4 Qd6 11. h4 e6 12. h5 Bxc2 13. Qxc2 Qxd4 14. Qe2 Qd6 15. Bf4 f6 16. Ng6 e5 17. Nxh8 Ne7 18. Bf7+ Kd7 19. Rd1 Nd5 20. Bxd5 exf4 21. Be4 Na6 22. Nf7 Qxd1+ 23. Qxd1+ Ke8 24. Nd6+ Kd8 25. Qb3 Bxd6 26. Qg8+ Kc7 27. Qxa8 Bb4 28. Bxh7 Nc5 29. Qxa7 f3 30. a3 Nd3+ 31. Bxd3 Bd6 32. Ba6 Kd7 33. Qxb7+ Bc7 34. Ne4 Kd8 35. Qc8+ Ke7 36. Qxc7+ Kf8 37. Qd8+ Kf7 38. Bc4# 1-0 game1 analysis using chess.com [Site "Chessrig app"] [White "garbo"] [Black "prospect"] [Opening "Mieses-Kotroc Variation, Center Counter"] [Event "Simmulation"] [Date "2017-11-13"] [TimeControl "unlimited"] [Result "1-0"] [Termination "Checkmate by white in 59 moves."] [FEN ""] 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd4 4. Nf3 Qd6 5. d4 Bg4 6. h3 Bh5 7. g4 Bg6 8. Ne5 Qe6 9. Bb5+ c6 10. Bc4 Qd6 11. h4 e6 12. h5 Bxc2 13. Qxc2 Qxd4 14. Qe2 Qd6 15. Bf4 f6 16. Ng6 e5 17. Nxh8 Ne7 18. Bf7+ Kd7 19. Rd1 Nd5 20. Bxd5 exf4 21. Be4 Na6 22. Nf7 Qxd1+ 23. Qxd1+ Kc7 24. Qf3 Re8 25. Qxf4+ Kc8 26. Kd2 Re6 27. Bf5 Nc7 28. Re1 g5 29. Rxe6 gxf4 30. Re8# 1-0 game2 analysis using chess.com A: I would start by asking why your engine is making horrible tempo loss moves with the queen? 8...Qe6? in game one and 3...Qd4? in game two. You need to consider "developing with tempo" somehow. A: It was obviously a fast game, and your search depth was too low. Your engine liked moving the queen because it didn't see it'd be driven back a few moves later. You need to define better piece square values table. If you do it properly, the engine should aim to control the center with a pawn or a piece, but not moving the queen out.
{ "pile_set_name": "StackExchange" }
Q: Have an error while trying to add a category in Magento 2.0.1 I get the following error while trying to add a new category There has been an error processing your request Notice: Undefined property: Myphone\Override\Controller\Adminhtml\Category\Edit\Interceptor::$storeManager in D:\xampp\htdocs\myphone\app\code\Myphone\Override\Controller\Adminhtml\Category\Edit.php on line 102 So I went Products > categories and I got this error. This is the Edit.php file: <?php /** * * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Myphone\Override\Controller\Adminhtml\Category; class Edit extends \Magento\Catalog\Controller\Adminhtml\Category\Edit { /** * Edit category page * * @return \Magento\Framework\Controller\ResultInterface * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { $storeId = (int)$this->getRequest()->getParam('store'); $store = $this->getStoreManager()->getStore($storeId); $this->getStoreManager()->setCurrentStore($store->getCode()); $categoryId = (int)$this->getRequest()->getParam('id'); if (!$categoryId) { if ($storeId) { $categoryId = (int)$this->getStoreManager()->getStore($storeId)->getRootCategoryId(); } else { $defaultStoreView = $this->getStoreManager()->getDefaultStoreView(); if ($defaultStoreView) { $categoryId = (int)$defaultStoreView->getRootCategoryId(); } else { $stores = $this->getStoreManager()->getStores(); if (count($stores)) { $store = reset($stores); $categoryId = (int)$store->getRootCategoryId(); } } } $this->getRequest()->setParam('id', $categoryId); } $category = $this->_initCategory(true); if (!$category || $categoryId != $category->getId() || !$category->getId()) { /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); return $resultRedirect->setPath('catalog/*/', ['_current' => true, 'id' => null]); } /** * Check if there are data in session (if there was an exception on saving category) */ $categoryData = $this->_getSession()->getCategoryData(true); if (is_array($categoryData)) { if (isset($categoryData['image']['delete'])) { $categoryData['image'] = null; } else { unset($categoryData['image']); } if (isset($categoryData['thumb_nail']['delete'])) { $categoryData['thumb_nail'] = null; } else { unset($categoryData['thumb_nail']); } if (isset($categoryData['thumb_nail_hover']['delete'])) { $categoryData['thumb_nail_hover'] = null; } else { unset($categoryData['thumb_nail_hover']); } $category->addData($categoryData); } /** @var \Magento\Backend\Model\View\Result\Page $resultPage */ $resultPage = $this->resultPageFactory->create(); if ($this->getRequest()->getQuery('isAjax')) { return $this->ajaxRequestResponse($category, $resultPage); } $resultPage->setActiveMenu('Magento_Catalog::catalog_categories'); $resultPage->getConfig()->getTitle()->prepend(__('Categories')); $resultPage->getConfig()->getTitle()->prepend($categoryId ? $category->getName().' (ID: '.$categoryId.')' : __('Categories')); $resultPage->addBreadcrumb(__('Manage Catalog Categories'), __('Manage Categories')); $block = $resultPage->getLayout()->getBlock('catalog.wysiwyg.js'); if ($block) { $block->setStoreId($storeId); } return $resultPage; } /** * @return \Magento\Store\Model\StoreManagerInterface */ private function getStoreManager() { if (null === $this->storeManager) { $this->storeManager = \Magento\Framework\App\ObjectManager::getInstance() ->get('Magento\Store\Model\StoreManagerInterface'); } return $this->storeManager; } } A: Add this before the execute method. protected $storeManager;
{ "pile_set_name": "StackExchange" }
Q: IDE for web development (including PHP and JS) What's the best web development IDE that you've come across, that also handles Core PHP work and JS very well (eg. AngularJS)? Required: Extremely fast -- there's nothing more annoying that a slow/stuttery IDE Excellent at code completion -- very smart at understanding what you're doing Good at HTML/CSS -- no point in only being good at the trickier stuff if you miss the basics Good at PHP/JS (including Angular) too -- as mentioned, this is a necessity Syntax error detection for the above Support for LESS/SASS compiling Overall an enjoyable environment to work in - nice to look at, smart, and helpful and … Windows based Would like: OSX support - it'd be occasionally helpful to be use it in OSX, but not essential Do NOT need: It to be free - I'm a professional and will happily pay for something that makes my daily life easier FTP - I'm happy deploying through FileZilla It's a shame that so many IDEs use Java these days, as it doesn't half seem to make them slow to get going. In terms of "enjoyable environment", I really like Brackets. It's lovely to use, and very quick and clean, but it's a little stuttery at times and is lacking in advanced features out of the box. What IDE do you find to be the best? The one that makes web development less of a chore than others. A: Maybe you could have a look at NetBeans. It is Java based, but it's much, much smoother than Eclipse. works everywhere fast (startup takes a few seconds but no slowdowns after that) HTML/CSS/PHP/JS including Angular, JQuery, RequireJS, Knockout, etc. Support for LESS/SASS compiling nice to look at (light blue) powerful refactoring (e.g. Ctrl+R to safely rename variables) Excellent Git integration (even has its own diff editor) free and Open Source I've used it for HTML5 development since they added official support for it years ago, and it's only been getting better. Its suggestions are spot on and immediate. Things like code completion and refactoring are lightning fast. An alternative would be Aptana Studio, it's Eclipse based, but stronger in the HTML5 department. Maybe you can give it a go. A: I'm sure you have looked into PhpStorm. Even though it's not free, it's still one of the most used IDEs in the world. It's fast (in my experience) It's great at code recognition/completion (based on IntelliJ IDEA you can even manually set chunks of code to a specific language within a file) Good PHP and JS support (including AngularJS and even Meteor -- should you want it) Syntax correction, as requested Support for LESS/SASS compiling Looks nicer than Netbeans (especially in Darcula, IMO) It's also available on OSX. A: PHP Storm is very likely what you will need. (please see the video link at bottom...can't recommend those enough) - Extremely fast -- there's nothing more annoying that a slow/stuttery IDE IMO phpstorm is very fast. It might not start up inside 0.01sec, but once loaded I notice no lag. - Excellent at code completion -- very smart at understanding what you're doing Absolutely. It has very good code completion as long as your code is well laid out and has docblocs etc it will pick them all up. - Good at HTML/CSS -- no point in only being good at the trickier stuff if you miss the basics It has full code quality analysis. PHPStorm Features - Good at PHP/JS (including Angular) too -- as mentioned, this is a necessity Syntax error detection for the above PHP is perfect, angular is coming along. - Support for LESS/SASS compiling There are tutorials showing how to manage this with GULP etc. - Excellent Git support out of the box Git/Mercurial/CVS/Subversion all catered for. - Overall an enjoyable environment to work in - nice to look at, smart, and helpful I can't recommend these short videos enough - they show you how to get the best out of the software.How to Be Awesome in PHP Storm
{ "pile_set_name": "StackExchange" }
Q: How can null reference result in SEH exception with code 0xc0000005? I'm writing some test code using the Google C++ Test Framework and forgot to initialize a certain object myObj. This results in the following error. unknown file: error: SEH exception with code 0xc0000005 thrown in the test body Stepping through the corresponding code it appears that a method call of the form myObj->method() is executed, while myObj is not initialized, i.e. its value is 0x00000000. Then somewhere deep in a third party library this error is thrown. How can this even happen? Why doesn't it throw a null reference exception as soon as the method is called? A: As it was rightfully pointed out in comments, calling a method from the uninitialized class pointer is an undefined behavior, so anything could happen, depending on the compiler implementation. However, it is easy to predict why in your case execution was semi-successful. The only difference between class (__thiscall) members and ordinal functions, is that they receive additional hidden argument, containing a pointer to the class instance (this). Microsoft C++ compiler passes this argument through ecx/rcx register, other compilers may use a different approach. However if your class method is not trying to dereference invalid this pointer, no exception will be thrown, and, depending on the method logic, your program could even continue execution without error. Things would be much different, if you try to call a virtual method. In this case, your program would try to calculate correct method address, using class vtable, dereference an invalid pointer and fail with access violation even if method itself is not using this pointer.
{ "pile_set_name": "StackExchange" }
Q: Creating multiple files in one function but they are overwriting each other. PHP I am in the process of creating a section of a webpage where a user can upload a photo then manipulate the attributes of said picture, title, caption, etc. My questions comes as this: I have an edit picture function that I create a new caption file in by //create new file $file = fopen($newinfofile,"w"); //write to file fwrite($file,$caption); //close the file fclose($file); newinfofile being the files name. I also create a new title file the same way but with different names //create new file for title $file2 = fopen($newinfofile2,"w"); //write to file for title fwrite($file2,$newtitle); //close the file for title fclose($file2); Later I echo the contents of each file but my problem is that they are echoing the same thing, if I reverse the order and create my title file first they both echo caption info instead. So in PHP can you not create and write to two files within the same function? Perhaps I am mis-understanding something but I am unsure as to what. Edit "sharing the entire function" //edit file name, picture title, picture caption function EditRecord($dir, $collection,$picture,$newname,$newtitle,$caption) { //set the picture paths $picpath = $dir . $collection . "/" . $picture; $newpicpath = $dir . $collection . "/" . $newname; //set name of file for caption info by changing out JPG for PHP $infofile = $dir . "Info/" . str_replace("jpg","php", $picture); $newinfofile = $dir . "Info/" . str_replace("jpg","php", $newname); //set name of file for title info by changing out JPG for PHP $infofile2 = $dir . "Info/" . str_replace("jpg","php", $picture); $newinfofile2 = $dir . "Info/" . str_replace("jpg","php", $newname); //replace \r with <br> $caption = str_replace("\r","<br>", $caption); //rename picture JPG file rename($picpath, $newpicpath); //rename info PHP file rename($infofile, $newinfofile); //rename 2nd info php file for title rename($infofile2, $newinfofile2); //create new file $file = fopen($newinfofile,"w"); //write to file fwrite($file,$caption); //close the file fclose($file); //create new file for title $file2 = fopen($newinfofile2,"w"); //write to file for title fwrite($file2,$newtitle); //close the file for title fclose($file2); } A: The two filesnames you create are exactly the same. $newinfofile = $dir . "Info/" . str_replace("jpg","php", $newname); $newinfofile2 = $dir . "Info/" . str_replace("jpg","php", $newname); both variables will contain the same filename and so write to the same file, consequently overwriting.
{ "pile_set_name": "StackExchange" }
Q: Python threading: monitoring threads and executing additional code after threads complete I have the following code: class MyThread(Thread): def __init__(self, command, template, env, build_flavor, logger): Thread.__init__(self) self.command = command self.template = template self.env = env self.build_flavor = build_flavor self.logger = logger def run(self): self.logger.info('Running (%s)...this may take several minutes. Please be patient' % self.build_flavor) run_command(self.command, self.template, self.env) self.logger.info('Complete (%s)' % self.build_flavor) return And then in another class, when I create the actual threads: if self.build_type == 'default': threads = [] for t in self.template: modify_template(t) build_flavor = self.getmatch(t) thread = MyThread(packer, t, self.new_env, build_flavor, self.logger) thread.setName(build_flavor) thread.start() threads.append(thread) for thread in threads: thread.join() vmware_create() openstack_create() Unfortunately, after the threads are .join()'d, I'm calling vmware_create() and openstack_create() in serial. I'd like to be able to execute each of those after their respective threads complete so that I'm not waiting for both threads to finish before starting one of the *_create() functions...and then waiting for the first to complete before executing the 2nd i.e. right now vmware_create() will execute only after BOTH threads are finished, and once vmware_create() is done, only then will openstack_create() begin. I'd like to be able to wait for the respective threads to complete, and then execute the _create() function for whatever thread completed first, all the while waiting for the 2nd thread to finish and then once that's done, immediately executing its _create() function for true parallelization. I haven't been able to figure out how to do this and need a lil help. A: Functions are objects. Just hand them to the thread: class MyThread(Thread): def __init__(self, command, template, env, build_flavor, logger, func=None): Thread.__init__(self) self.command = command self.template = template self.env = env self.build_flavor = build_flavor self.logger = logger self.func = func def run(self): self.logger.info('Running (%s)...this may take several minutes. Please be patient' % self.build_flavor) run_command(self.command, self.template, self.env) self.logger.info('Complete (%s)' % self.build_flavor) # call func if it is there if self.func: self.func() return Now, I supply the first two threads with function to call: if self.build_type == 'default': threads = [] funcs = {0: vmware_create, 1: openstack_create} for i, t in enumerate(self.template): modify_template(t) build_flavor = self.getmatch(t) func = funcs.get(i, None) thread = MyThread(packer, t, self.new_env, build_flavor, self.logger, func=func) thread.setName(build_flavor) thread.start() threads.append(thread) for thread in threads: thread.join() Of course, you can add them to any other threads.
{ "pile_set_name": "StackExchange" }
Q: What are the advantages of using HTTP in Go versus using TCP Sockets for downloading/uploading files to a server? I am setting up multiple servers for a social networking app and have never worked with HTTP before. Is there advantages of using HTTP instead of creating your own protocol for TCP streams? It will be used for both normal text transfer and images/videos. I have started up a general TCP server that can transfer both small organized text packets and also larger image/video streams but I'm unsure if it will be as scalable/efficient/secure as using HTTP/s. I'm not going to post the code as I hope this question is general enough to not require it and I am not looking for code analysis quite yet. The server is working for transferring data but I am not sure of the advantages/disadvantages of using HTTP instead. Do other websites that use Go for their system use HTTP or just straight sockets? A: Raw TCP sockets are theoretically more performant (ignoring several external factors) than HTTP. HTTP libraries are robust and well tested, and constantly updated in the face of new bugs and security threats. So do you optimize for raw performance, or for developer time? A few questions to ask yourself: Is HTTP too slow for my application? (Related question: Have I measured it?) Do I have the time and energy to respond to bugs and vulnerabilities in my connectivity library for the life of my program? If I am wildly successful, can I find, hire, train and retain a qualified workforce? If this is just for your learning, go for it.
{ "pile_set_name": "StackExchange" }
Q: Using $@ for error message passing in module I've been working on a fork of a CPAN module which is now unmaintained (as far as I've been able to tell). In this module, they use $@ to pass error messages up the stack. In other words, they set $@ if anything goes wrong in any call to subroutines, and they check after the call to see if it is set. I had never seen this variable before, but I thought it was useful, so I started using it the same way in the code. Now I recently read up a bit more about it, and found that its purpose is a bit more narrow than this. Reading perlvar (and other SO questions on the matter) doesn't fully answer this for me, but, is it OK to use $@ this way? Some "punctuation" variables I know should definitely not be used in such a general-purpose way (some even with local), is this one of those cases, or am I OK continuing this practice? A: $@ is not normally explicitly set. Rather, it is automatically set for you when an exception is raised. From perldoc die: die LIST die raises an exception. Inside an eval the error message is stuffed into $@ and the eval is terminated with the undefined value. If the exception is outside of all enclosing evals, then the uncaught exception prints LIST to STDERR and exits with a non-zero value. If you need to exit the process with a specific exit code, see exit. For example, #!/usr/bin/perl eval { print "Hi\n"; die "Something went wrong here"; print "Bye\n"; }; print $@; prints Hi Something went wrong here at ./cr22854919 line 5. It is permissible to use $@ to pass error messages up the stack in this way, as a kind of try-catch mechanism. However, since it is a global variable, you should process it as soon as possible after an eval { } block to ensure that no other code interferes with your handling of the exception. The other magic variable commonly used for error handling is $!, which works like errno in C. Example: my $path = "/tmp/no-such-file"; open F, '<', $path or print STDERR "$path: $!\n"; Output: /tmp/no-such-file: No such file or directory A: $@ is a relatively "unspecial" special variable in Perl. Nothing in Perl ever reads from $@, and it's only written to by an eval {} block at the end. This makes it relatively safe to use for your own error-signalling purposes. In particular, the core IO::Socket tree of modules use this to indicate the failure from the constructor: use IO::Socket::IP; my $sock = IO::Socket::IP->new(...) or die "Cannot connect - $@"; The more traditional $! is unsuitable here because $! has magic that wraps the libc-level errno construct; meaning it can only be set to an integer errno value, even though it can be read as either a number or a string. Because sometimes failures can happen that don't directly relate to errno values (in IO::Socket's case, many kinds of resolver failure for example), sometimes $! is inappropriate for this.
{ "pile_set_name": "StackExchange" }
Q: Rails basic index view with haml I'm trying to get a basic index view to work using HAML instead of HTML, but I'm running into problems. Here is my index view %h1 Games %ul - @games.each do |game| %li = game.title = game.summary And I'm getting this error: syntax error, unexpected keyword_ensure, expecting keyword_end But I know haml doesn't require you to have end when you embed ruby on the view, so I'm not sure what the problem is. A: Be very careful with indentation in haml. You need to indent what's inside the each - @games.each do |game| %li = game.title = game.summary I would also suggest sticking to 2 spaces as that is pretty much accepted practice in Ruby/Rails.
{ "pile_set_name": "StackExchange" }
Q: How to access a remote mysql database using java I have already developed a JAVA SWING Application. I want to install this application in several computers which all have access to internet . So where should I place my MYSQL Database ? All these computers should have the ability to access the same database via the internet. A: It's not very common to allow access to a database directly over the internet for security (authentication authorization, encryption) and performance reasons. In most cases, you would create a web-based server application which can perform database operations, enforcing business, domain, and security rules. The client application makes calls over the internet (using REST calls, AJAX calls, or something proprietary), and gets the results back from the server. In your case, since your client software is Java, you may want to research Java Servlets and run something lightweight like Tomcat as a serer. Please see this page and this page for an explanation of client-server relationships.
{ "pile_set_name": "StackExchange" }
Q: Are most Kähler manifolds non-projective? Since now-a-days lots of research activities are happening to prove many results for compact Kähler manifolds which are known for projective varieties, I was wondering are there plenty of non-projective Kähler manifolds? If yes, where can I find some explicit examples? I am aware of the theorem that a generic complex torus $\mathbb{C}^g/\Lambda$ is non-projective. A: See Claire Voisin's amazing results on the subject, or the published version: On the homotopy types of compact kaehler and complex projective manifolds, Inventiones Math. 157 2 (2004), 329 - 343. (ArXiv) Abstract: We show that in every dimension greater than or equal to 4, there exist compact Kaehler manifolds which do not have the homotopy type of projective complex manifolds. Thus they a fortiori are not deformation equivalent to a projective manifold, which solves negatively Kodaira's problem. We give both non simply connected (of dimension at least 4) and simply connected (of dimension at least 6) such examples. A: I agree that in a sense it's harder to get your hands a non algebraic Kähler manifold, because you can't simply write an equation for one, but I would argue that there are plenty of them. You won't find any in complex dimension one, so let's look in dimension two. By classification of surfaces, the non algebraic surfaces would have Kodaira dimensions $\kappa=0$ or $1$. The $\kappa=0$ cases are, I believe, necessarily tori or K3's (there are some other examples, but these are either algebraic or non Kähler). As already noted by you and Francesco, the algebraic surfaces form a proper subset in moduli for these cases. The $\kappa=1$ surfaces are elliptic surfaces, and I expect that there should be plenty of non algebraic examples, although I don't have an example on hand. Added later For my own reasons, I thought about this longer than I normally would. Here's an explicit example. Let $C$ be a smooth projective curve of genus $g>0$, $\Gamma=\pi_1(C)$, and $\tilde C$ the universal cover. Choose an elliptic curve $E$ and a group homomorphism $h:\Gamma\to E$. Define an action of $\Gamma$ on $\tilde C\times E$ by $\gamma(x,y)= (\gamma x, y+h(\gamma))$, and let $S$ be the quotient. $S$ is Kähler. If $h$ has infinite image, then $S$ is not algebraic. Proof. $S$ is Kähler because $\tilde C\times E$ has an invariant Kähler metric. For the second statement, assume that $h$ has infinite image. Projection on the first factor gives a holomorphic map $f:S\to C$. The fibres of $f$ can be identified with $E$. Restricting a meromorphic function $F$ on $S$ to a fibre gives a meromorphic function on $E$ which is constant on the orbits $\{y+h(\gamma)\}$ and therefore constant. Therefore $F$ comes from $C$. This shows that transcendence degree of the field of meromorphic functions on $S$ is 1. Additional remarks: This has $\kappa=1$ when $g>1$. When $g=1$, one can see, with a bit of thought, that $S$ is torus which contains an elliptic curve but it is not isogenous to a product (i.e. Poincar\'e reducibility fails for tori). A: Expanding a bit on Francesco Polizzi's remark, complex K3 surfaces are Kähler [1], the moduli space $M$ of complex K3 surfaces is an irreducible 20-dimensional complex variety, and within $M$, the set of K3 surfaces that are algebraic varieties is a countable union of disjoint subvarieties $F_g$ for integers $g\ge2$. Here $F_g$ has dimension 19, and the K3 surfaces in $F_g$ are those that have a primitive line bundle $\mathcal L$ satisfying $c_1(\mathcal L)^2=2g-2$. So this is the analogue for K3 surfaces of the example you know for complex tori, i.e., in the moduli space of complex tori of a given dimension, the projective ones form a countable union of proper subvarieties. [1] Siu, Y. T. (1983), Every K3 surface is Kähler, Inventiones Mathematicae 73 (1): 139–150
{ "pile_set_name": "StackExchange" }
Q: Do standard white LEDs produce a full spectrum of light? At places like Radioshack, small (and sometimes large) LEDs are available that are labeled to be "white". This is a link to a Radioshack page for such an LED: http://www.radioshack.com/5mm-white-led/2760320.html#q=white%2Bled&start=2 Does a light like this produce a full spectrum of light, such that appropriate light filters could produce any spectrum of visible light? A: @Shamtam have already commented that: (1) the light from a typical while LED doesn't match the spectrum of the sunlight (2) white LEDs are blue LEDs with additional phosphor This is to expand on @Shamtam's comment. Spectrum of a white LED showing blue light directly emitted by the GaN-based LED (peak at about 465 nm) and the more broadband emitted by the phosphor. (source: Wikipedia) Diagram of the spectrum a LED lamp (blue), a CFL (green) and an Incandescent (purple) superimposed the solar spectrum (yellow). Note that the energy used by each lamp is at least the area underneath its curve. (source) A: Quick answer - Shantam to the contrary, yes. But let me explain. Nick Alexeev provided a spectrum from a typical white LED. While it is not a faithful simulation of an incandescent (the big spike in blue is notable), it does contain all visible wavelengths. Your question asked "Does a light like this produce a full spectrum of light, such that appropriate light filters could produce any spectrum of visible light?", and the answer is obviously yes. If you wanted a predominately green light, for instance, it wouldn't (relatively) be very bright, but you could do it. This is not true for RGB LEDs, which would have very narrow spikes of intensity at 3 different wavelengths, with nothing in between. So, while you could easily produce a subjectively yellow light from an RGB LED source (just transmit red and green in the proper intensities), a narrow-band yellow filter would transmit nothing.
{ "pile_set_name": "StackExchange" }
Q: According to Chazal, does Beged Kefet matter? The Hebrew alphabet has 22 written characters (plus 5 specialized characters for the ends of words - ם, ן, ץ ,ף, ך) generally assumed to be each originally associated with distinct sounds. The Masoretes have a tradition (which to our [traditional] ability, we also attempt to follow) regarding a dual pronunciation of six letters in the Alephbet, namely, ב, ג, ד, כ, פ, ת (typically indicated visually by the presence/absence of a dot in the middle of the character) However, the Masoretes were predominantly from a Karaite-heretical sect. Is there any independent basis in traditional halacha, especially in Chazal, for distinct, contextual pronunciations of these letters? What is the view of linguistic scholars regarding the origin and development of Beged Kefet (and how might this be relevant to halacha)? A: Rav Saadiah Gaon writes in Chapter 2 of his commentary to Sefer Yetzirah lays down the correct pronunciation of the Hebrew letters, saying that not only is there בגד־כפת letters, but that even the ר has an alternate pronunciation with a dagesh so more like בגד־כפרת according to him. He basically says that Hebrew and Arabic share all the exact same sounds, except that Hebrew has a בּ ) ב without a dagesh) that Arabic lacks, פ ) פּ with a dagesh) that Arabic lacks, and Arabic has a Jimmal (the normal English J sound) that Hebrew lacks. i don't think anyone is about to call Saadia Gaon a Karaite, so you have a clear Rabbinic Posek speaking of the importance of pronunciation. As for how it may be relevent in Halacha, the Gemara says that one should extend the Daleth from the word Echad until one runs out of breath. This is not possible if you are unable to distinguish between ד and דּ. "All who prolong the word echad will have their days and years prolonged. Rabbi Acha bar Yaakov said that one should prolong the letter daleth. Rabbi Assi added: Provided that he does not slur over the letter cheth." (Berachot 13b) Therefore you have at least one instance of the ד having at least 2 distinct sounds by the time of the Talmud. And while this may not have a direct halakhic significance, it does draw the attention to the proper pronunciation of ו. In modern Hebrew, both ו and ב share the same sound. But according to Saadia, if Arabic doesn't have a ב, then he should have also said ו to go along with it. And he also does not say that Hebrew doesn't have a w sound, that Arabic clearly has. So according to many scholars who read the words of Saadia Gaon, the ו should make the sound of a w. As a bit of a side note, i haven't personally run across any Karaites that distinguished between all the בגד־כפת letters. So i think the idea of attributing the distingishment of these letters as something linked distinctly to Karaism might be a bit misguided.
{ "pile_set_name": "StackExchange" }
Q: Tag Cloud in C# I am making a small C# application and would like to extract a tag cloud from a simple plain text. Is there a function that could do that for me? A: Building a tag cloud is, as I see it, a two part process: First, you need to split and count your tokens. Depending on how the document is structured, as well as the language it is written in, this could be as easy as counting the space-separated words. However, this is a very naive approach, as words like the, of, a, etc... will have the biggest word-count and are not very useful as tags. I would suggest implementing some sort of word black list, in order to exclude the most common and meaningless tags. Once you have the result in a (tag, count) way, you could use something similar to the following code: (Searches is a list of SearchRecordEntity, SearchRecordEntity holds the tag and its count, SearchTagElement is a subclass of SearchRecordEntity that has the TagCategory attribute,and ProcessedTags is a List of SearchTagElements which holds the result) double max = Searches.Max(x => (double)x.Count); List<SearchTagElement> processedTags = new List<SearchTagElement>(); foreach (SearchRecordEntity sd in Searches) { var element = new SearchTagElement(); double count = (double)sd.Count; double percent = (count / max) * 100; if (percent < 20) { element.TagCategory = "smallestTag"; } else if (percent < 40) { element.TagCategory = "smallTag"; } else if (percent < 60) { element.TagCategory = "mediumTag"; } else if (percent < 80) { element.TagCategory = "largeTag"; } else { element.TagCategory = "largestTag"; } processedTags.Add(element); } A: I would really recommend using http://thetagcloud.codeplex.com/. It is a very clean implementation that takes care of grouping, counting and rendering of tags. It also provides filtering capabilities. A: Take a look at http://sourcecodecloud.codeplex.com/
{ "pile_set_name": "StackExchange" }
Q: Actual ramifications of time acceleration For reference, the setting is urban fantasy, with a bit of hard science thrown in. One character can manipulate time; in this setting that means he can speed up his own movement through time. One of the things he's capable of is punching. Now, let's suppose he throws a punch which should take 1 second, but he speeds up the punch to a quarter of a second. The question is, is the force magnified fourfold, or (and this is how I think it works) since he's affecting time directly (and not just moving faster), the force is magnified by 16, because F = M*A, and A is really just m/(s^2)? (Side note: A human punches with 1000 Newtons, so the difference here is between 4,000 (boxer's punch) or 16,000 (shatter your own fist).) A: Given that you're stating that this is a hard-science setting (not a hard-science question) then let's break this down a little to explain the interaction between force and time. Your Premise F=ma, therefore time is a consideration in the amount of force. If a person can throw a punch at normal speed BUT their localised frame of temporal reference is lower than their environment, to an outside observer the punch is faster, therefore delivers more force. My Premise This is just an exotic way of punching faster, delivering more force. One interesting question I get when explaining relativity to others is why the astronaut who's travelling at close to the speed of light ages so much more slowly than his twin back on earth - if relativity is based on the observer, then the speed of both men is close to the speed of light relative to each other, right? Right? Well the problem with this thinking is that relativity is not about relative speed, it's about relative energy. The astronaut has a much higher kinetic energy than the earth, meaning his ageing is slower. Thing is, it's the same with your person's fist. Your person's ability to slow down time is really just a fancy way of saying that he or she can speed up his or her own matabolism to a point where he or she is moving faster. Whether you slow down time or speed your movements up, you're still introducing the same amount of extra energy. That is to say, you're hero is going to have to increase their metabolism to expend the same amount of extra energy either way. If we take relativity into account, speeding one's movements and slowing outside time are basically the same thing. In point of fact, moving faster introduces more energy, which by the astronaut example literally does slow down time. This is because space and time are basically the same thing expressed different ways, hence our 4 dimensional concept of spacetime. In short, if you want it to be hard science, then being able to accelerate time is a confusing distraction for most people - your hero can simply accelerate his or her own movements, which amounts to the same thing. Either way, your hero has to be able to expend massive amounts of energy in a short time which also means he or she is going to get very hungry after doing this for a bit. A: Without violating the conservation of energy, 1,000 Newtons has to be the output. Since distance and force are unchanged... this means that time dilation will need to affect the speedster's mass. So, a if your time moves at a higher speed then your relative mass becomes smaller and acceleration increases maintaining the same force. Logically it would seem that mass would also have to stay the same since you're not gaining or losing any matter, but mass is a quantity that is solely dependent upon the inertia of an object; so, a better way of putting is that as you speed up time, your inertia decreases. There is one advantage here though for performing a speedster punch. While you still only get 1000 Newtons, they will be applied over a shorter period of time. So instead of experiencing a force of 1000 Newtons spread over the course of 1 second you might take it all in .25 seconds. So, your opponent will not go flying back any more than from a normal hit, but you are more likely to create a force over time that is high enough to overcome material strengths and cause injuries. Now, if you assume that your mass stays constant and you can in fact violate the conservation of mass and energy by speeding or slowing time, then force will be a 1-to-1 ratio not exponential gain. In (F = M*A) speeding up time x4 speeds up acceleration by x4 so your outcome would look like (4F = M*4A), but you will also divide your force over 1/4 of the time so you will knock your opponent back with 4x times the force, but cause the structural damage of something with 16x the force.
{ "pile_set_name": "StackExchange" }
Q: how can I clean and sanitize a url submitted by a user for redisplay in java? I want a user to be able to submit a url, and then display that url to other users as a link. If I naively redisplay what the user submitted, I leave myself open to urls like http://somesite.com' ><script>[any javacscript in here]</script> that when I redisplay it to other users will do something nasty, or at least something that makes me look unprofessional for not preventing it. Is there a library, preferably in java, that will clean a url so that it retains all valid urls but weeds out any exploits/tomfoolery? Thanks! A: I think what you are looking for is output encoding. Have a look at OWASP ESAPI which is tried and tested way to perform encoding in Java. Also, just a suggestion, if you want to check if a user is submitting malicious URL, you can check that against Google malware database. You can use SafeBrowing API for that. A: URLs having ' in are perfectly valid. If you are outputting them to an HTML document without escaping, then the problem lies in your lack of HTML-escaping, not in the input checking. You need to ensure that you are calling an HTML encoding method every time you output any variable text (including URLs) into an HTML document. Java does not have a built-in HTML encoder (poor show!) but most web libraries do (take your pick, or write it yourself with a few string replaces). If you use JSTL tags, you get escapeXml to do it for free by default: <a href="<c:out value="${link}"/>">ok</a> Whilst your main problem is HTML-escaping, it is still potentially beneficial to validate that an input URL is valid to catch mistakes - you can do that by parsing it with new URL(...) and seeing if you get a MalformedURLException. You should also check that the URL begins with a known-good protocol such as http:// or https://. This will prevent anyone using dangerous URL protocols like javascript: which can lead to cross-site-scripting as easily as HTML-injection can. A: You can use apache validator URLValidator UrlValidator urlValidator = new UrlValidator(schemes); if (urlValidator.isValid("http://somesite.com")) { //valid }
{ "pile_set_name": "StackExchange" }
Q: How can I get the android device id which I get on dialing " *#*#8255#*#* " How can I get the android device id which I get on dialing *#*#8255#*#* I am using the following code but it does not return the same...what I want String android_id = Secure.getString(getActivity() .getContentResolver(), Secure.ANDROID_ID); A: I think the code you tried probably returns a dynamic ID. Try this. private static final Uri URI = Uri.parse("content://com.google.android.gsf.gservices"); private static final String ID_KEY = "android_id"; String getAndroidId(Context ctx) { String[] params = { ID_KEY }; Cursor c = ctx.getContentResolver() .query(URI, null, null, params, null); try{ if (!c.moveToFirst() || c.getColumnCount() < 2){ return null; } }catch(Exception e){ return null; } try { Toast.makeText(ctx, Long.toHexString(Long.parseLong(c.getString(1))), 500).show(); System.out.println("android id " + Long.toHexString(Long.parseLong(c.getString(1)))); return Long.toHexString(Long.parseLong(c.getString(1))); } catch (NumberFormatException e) { return null; } } In the above code Long.toHexString(Long.parseLong(c.getString(1))), returns the android device id.
{ "pile_set_name": "StackExchange" }
Q: w3c validator invalid error What does it mean when it says: "Error Line 237, Column 6: document type does not allow element "BODY" here " This is the link: http://validator.w3.org/check?uri=http%3A%2F%2Fblog.0arrays.com%2F&charset=%28detect+automatically%29&doctype=Inline&ss=1&outline=1&group=0&No200=1&verbose=1&user-agent=W3C_Validator%2F1.1#line-237 A: That means no body allowed in HTML 4.01 Frameset. Try to correct the DOCTYPE to point to the document type you needed. Choosing a DOCTYPE might help.
{ "pile_set_name": "StackExchange" }
Q: Fuchsian groups and topological isomorphism I have a (finite) presentation of a group and I am wanting to prove that it is not Fuchsian. Because it is given by a presentation, a neat, algebraic description of Fuschian groups would be nice. This exists for Fuchsian groups of the first kind, as Poincaré gave a presentation for these groups. Using this description, I can show that my group is not a Fuchsian group of the first kind. So, I am wondering if such a description exists for Fuschian groups of the second kind. This is the background to my question. According to the "encyclopedia of maths", every finitely-generated Fuchsian group of the second kind is "topologically isomorphic (as a group of the disc) to a finitely-generated Fuchsian group of the first kind". Now, this makes absolutely no sense to me. The disc is referring to viewing Fuchsian groups as transformations of the unit disc onto the complex plane. However, I do not understand what the "topologically isomorphic" means. The groups are discrete and have no topology. No? (And does topologically isomorphic imply algebraically isomorphic? If so, I am happy because then I am done...no?) A: Instead of "topologically isomorphic" people usually say "topologically conjugate" exactly as in the comment by @MartianInvader. In general, given a group presentation it is hard if not impossible to say anything about the group (one cannot even decide if the group is trivial!), since the same group can have two completely different presentations. However, if, by some magic, you can prove that your group is not isomorphic to a Fuchsian group of the 1st kind, then, with few exceptions, it is also not isomorphic to a Fuchsian group of the 2nd kind since, algebraically speaking, there is no difference between the two. The exceptions are groups which are either finite cyclic, or finite dihedral, or infinite cyclic or infinite dihedral. Thus, you should test your magic powers and see if you can prove, say, that your group is not trivial. If you can, then repeat the same for cyclic and dihedral groups. Here are some details on the proof you requested. I will do so under the assumption that the Fuchsian groups are finitely generated and orientation-preserving (it is also true in general but more tedious/hideous). First, some terminology: A discrete subgroup of $PSL(2,R)$ is called elementary if it is either finite or infinite cyclic. I will call finitely generated discrete subgroups of $PSL(2,R)$ "Fuchsian" whether they are elementary or not (it seems that different people use different terminology here). With every Fuchsian subgroup $\Gamma$ one associates the quotient orbifold $O=D/\Gamma$, where $D$ is the open unit disk. The best introduction to orbifolds I know is the article of Peter Scott "Geometries of 3-manifolds". I also found Thurstons treatment of 2-dimensional orbifolds in Chapter 13 of his Princeton Lecture Notes very illuminating. Such orbifolds $O$ always admit a compactification by adding some "boundary circles" so that the result is a compact orbifold with boundary $\overline{O}$. One then defines the Euler characteristic $\chi$ of orbifolds, so that $\chi(O)=\chi(\overline{O})$. This Euler characteristic (like the usual one) is multiplicative under finite coverings. The orbifolds $O$ (and $\overline{O}$) which appear in this context are good and, moreover, they admit finite coverings by surfaces. One further verifies that $F=\Gamma$ is elementary if and only if $\chi(O)=0$; this is easy in the case when $F$ is torsion-free and then proven in general by taking a finite index torsion-free subgroup. The same argument shows that $\chi(O)<0$ once $F$ is nonelementary. The key statement then is that if $O$ is an orbifold without boundary which has negative Euler characteristic and "finite topology" (finitely many singular points and finitely many handles and holes) then $O$ admits a complete hyperbolic metric of finite area, i.e., is isometric to the quotient orbifold $D/F'$, where $F'$ is a Fuchsian group (necessarily of the 1st kind) and with $Area(D/F')<\infty$. You can find proofs in Scott's paper (he treats only compact case, but, considering orbifolds $\overline{O}$, one can repeat his proof in the noncompact case) and by Thurston. Here is the proof in a nutshell: Every boundaryless orbifold (as above) with $\chi(O)<0$ admits a topological "pair of pants" decomposition, along simple loops, where the "pairs of pants" are also allowed to be orbifolds which become pairs of pants after singular points are removed. For every such "pair of pants" $P$ one designates some boundary components to be "cusps" (where the hyperbolic metric is complete and of finite area) or "waists", where the hyperbolic metric completes by a closed geodesic of certain positive length. One then considers various hyperbolic metrics on $P$ and one shows that one can choose such a metric to have prescribed length of "waists" (say, 1 unit). Given this information, one then assembles a hyperbolic metric on $O$ by isometrically gluing "pairs of pants" along "waists", which is possible since they all have the same length. I will denote the new hyperbolic orbifold by $O'$. Then, as in the case of hyperbolic metrics on surfaces, the universal cover of $O'$ is isometric to the hyperbolic plane (unit disk $D$) and the group of covering transformations acts as a Fuchsian group $F'$ on $D$. Finiteness of the area of $O'$ forces $F'$ to be of the first kind. Now given two hyperbolic orbifolds $O=D/F, O'=D/F'$, where $F, F'$ are Fuchsian groups (need not be of 1st kind), if $f: O\to O'$ is a homeomorphism of orbifolds, it lifts to a homeomorphism of the universal covers $\tilde{f}: D\to D$ which topologically conjugates the groups $F$ and $F'$: $$ \tilde{f} F (\tilde{f})^{-1}=F', $$ this is the same as in the case of the usual covering spaces theory. I hope, it helps.
{ "pile_set_name": "StackExchange" }
Q: Can I trust Apple support and share my password? I have problem with iCloud backup on my iPhone. After several calls to the Russian department of Apple support they suggest me to change my AppleID password temporarily to an test password proposed by the support specialist to see what's going on with my account. Also they say that they get access to all my data stored on phone: messages, photo, apps data etc, and I should agree with this terms. Of course they say usually engineers don't read/watch users data, but I think it's weird to grant access to all my data. Should I trust them and share my pretty photos, banking apps and personal chats? I'm pretty sure I have talked with the official Apple support, not scammers. A: In a word, NO. No-one reputable will EVER ask for your password, EVER. Proper support have the tools and such in place to allow them the access they need to do what they need. If they have to actually login as you (Which clearly they can only do from a different device anyway, limiting any usefulness it may even have) then surely there is nothing they need to do that for which they can't simply ask you to replicate for them without handing over credentials. I smell a rat. A: I used to work for Apple support, both iPhone and Mac, both first and second level ("Senior Advisor" to the outside world). Without knowing all the details, here's my reaction: Support operations that Apple runs in other countries than the United States can rarely have some different support procedures, but this one sounds too far out of bounds. Keep in mind that some Apple support centers are actually third party call centers on contract, I have worked at one of those as well, they are not as trustworthy as Apple employees. Not to over generalize but they have less to lose and poor working conditions. As a first-level support person, we never knew customer passwords and I was frustrated when people told me their passwords, I would stop them mid-way through and tell them I don't want to know. There is a process if you get deep into a problem with a senior advisor, where they setup a test account for you. Keyword, they set it up for you, they should never ask you to create a second account yourself or ask for your password to your account. Now if you are dealing with a true Senior Advisor at Apple they are supposed to give you their contact info and the shift they work, so in theory you should be able to verify this. Having said that, if they asked you to change your password on your account, it was a verifiable hack attempt. And as a newb, I can't comment on other answers, but in response to the one comment, everyone can generate a support PIN when they log into appleid.apple.com and I hate the new interface there. A: I've dealt with deep-rooted issues on my iCloud account, and I have been asked by Senior Advisors (in the US) for permission to put my account into Troubleshooting mode, which requires that they provide you with a temporary password so they can access your account and see what's going on with it. Talking with various Senior Advisors over the course of a few weeks that my account was in Troubleshooting mode, everyone knew what I was referring to, including the Corporate Executive Relations Office. This is definitely not a scam, although you are were right to be suspicious. This is a step you should only accept if you are comfortable with granting Apple Support full access to your iCloud account. This is normally a last resort for Apple Support. If you have two-step or two-factor authentication on your account, an Apple Diagnostics device should appear in the list of Trusted Devices shortly thereafter. Point of interest: the second or third time I've had to have my account put into Troubleshooting mode, I asked if I could simply hand them my password (it was already a temporary password, but due to a screwup on their part, my account was out of Troubleshooting mode). The Senior Advisor declined, citing policy that they must provide a randomly-generated password and could not accept a password from a customer. This is a very important point, because I get the impression from the reactions/answers that people think the support technician is asking @Oleg for his password. That is NOT the case. I feel I should also add that yes, I am 100% certain I was talking to Apple employees the entire time. I contacted them through the Apple Support site, they called me back from the same Apple number every time, which I have saved in my Contacts, and every technician I was in touch with emailed me from an @apple.com address, to which I was able to send emails and get responses from (so that takes care of spoofed headers). They're able to Screen Share just by knowing your Apple ID but not your IP address, then ask you to upload diagnostics data to green header address ending in apple.com. It would take a very high degree of sophistication to pull off a scam of this magnitude (not to mention, if all they cared about was accessing your iCloud account, they could just stop once they got your password instead of spending hours upon hours going through troubleshooting steps that don't get them any additional data about you). And obviously, when you get a response from the Corporate Executive Relations Office after emailing Tim Cook directly, you're pretty confident it's an Apple employee talking to you (the response includes your original email). If that person acknowledges that your account is in Troubleshooting mode and understands that you would like to get it out of it, then you're also pretty confident that Troubleshooting mode is a real thing. I am in no way defending Apple's tech support procedures, just saying that yes, when all else fails, the company does ask to set a temporary password on your account. This allows the engineers to go in and troubleshoot themselves. This is definitely a legitimate scenario.
{ "pile_set_name": "StackExchange" }
Q: Edit Firestore collectionGroup query documents I am wondering if it is possible to update the fields of a document from a collectionGroup query. I have set up my query as below and I want to .update() a single field in the document the query returns. Query query = db.collectionGroup("orders").whereEqualTo("restaurantid",fAuth.getUid()).whereEqualTo(docId,getId()); query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { if (!queryDocumentSnapshots.isEmpty()){ Order order = queryDocumentSnapshots.getDocuments().get(0).toObject(Order.class); //can i update the document here? }else { Log.d("STATUS ERROR", "QUERY IS EMPTY"); } } }); A: To write to a document in Firestore you need a DocumentReference to it. Your queryDocumentSnapshots.getDocuments().get(0) gives you a DocumentSnapshot, which has a getReference method. So: Query query = db.collectionGroup("orders").whereEqualTo("restaurantid",fAuth.getUid()).whereEqualTo(docId,getId()); query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { if (!queryDocumentSnapshots.isEmpty()){ DocumentSnapshot snapshot = queryDocumentSnapshots.getDocuments().get(0); // Order order = snapshot.toObject(Order.class); DocumentReference ref = snapshot.getReference(); ref.update("fieldName", "value"); } else { Log.d("STATUS ERROR", "QUERY IS EMPTY"); } } });
{ "pile_set_name": "StackExchange" }
Q: Flex container with divs children not stacking horizontally I'm fairly new to flexbox, and can't figure out how to do what I'm trying. I'd like for the repeated content to stack horizontally to the right. I would like the items to shrink to fit the width of the content (if the title/report id text is longer/shorter). I'm trying to make the red box only as wide as the content and stack to the right. The purple box(container) is flex. It seems like the red div is the culprit that I can't figure out. I've tried converting to inline-block and played with the flex-grow and flex-shrink, but nothing seems to work for me. There might be a style somewhere else in the project that is competing, but not sure what to look for if that's the case... Styles of the purple container div: line-height: 1.5; display: flex; flex-direction: column; max-height: 22.8125rem; padding-bottom: .5rem; margin-bottom: 1rem; background-color: #394b54; flex-basis: 100%; -webkit-box-flex: 1; flex-grow: 1; A: I'd like for the repeated content to stack horizontally to the right Use the default flex-direction: row. I would like the items to shrink to fit the width of the content Use the default flex-grow: 0 and flex-basis: content.
{ "pile_set_name": "StackExchange" }