INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Eclipse - how to remove light bulb on warnings Super quick question here that has been bugging me for a very long time - Is there any way to remove the light bulb that appears on the left side of the line when there is a warning in Eclipse (Specifically using Java IDE, if it matters). It is very annoying the way it hides breakpoints, and honestly - I can see the little squiggly yellow line just fine. Thanks.
Go to `Windows > Preferences > General > Editors > Text Editors > Annotations`. Select `Warnings` option in the `Annotation Types` list box, un-select `Vertical Ruler`
stackexchange-stackoverflow
{ "answer_score": 53, "question_score": 51, "tags": "eclipse" }
Having issues with Django dbshell Please i dont know what is wrong, i used south for model migration, my question is, is it perfectly alright to use south or is the django traditional way i.e (`manage.py dbshell`) any better. My second question, i tried using `manage.py dbshell`, but i get the message each time. > 'sqlite3' is not recognized as an internal or external command, operable program or batch file. Thanks.
`sqlite3` is a database that saves the records in a single file, the command `dbshell` is for going into the database shell. It works with MySQL and PostgreSQL, but not with SQLite. BTW, if you are using _south_ , its fine, `dbshell` is when you need to do something with the database but, if _south_ does it for you, is fine.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 4, "tags": "django" }
generating lists from google sheet ![enter image description here]( I have a google sheet looks like the image, how could I create two lists using Python. list_1 = [Country,State,State,State,City,City,City,City] list_2 = [USA,California,Washington ,New York,San Francisco, Los Angeles,Seattle,New York City] Thanks!
This will generate lists based on row values. `NaN` should be excluded while doing the task. import pandas as pd import numpy as np df = pd.read_excel('sample.xlsx') total_no = df.loc[~df['No'].isnull(),'No'].tolist() #adding total No. values (excluding NaN) total_topic = [] list_1= [] list_2 = [] for num,topic in zip(df['No'].tolist(), df['Topic'].tolist()): if num in total_no: total_topic.append(topic) elif type(topic) == float: #excluding NaN for topics continue else: list_1.append(total_topic[-1]) list_2.append(topic) print(list_1) print(list_2)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "python, google sheets" }
Statically and dynamically linking the same library I have a program that's statically linking to a library (`libA.2.0.a`) and also dynamically links to another library (`libB.so`). `libB.so` also dynamically links to an older version of libA (`libA.1.0.so`). Is this configuration possible? And if so, how does the system know to use the symbols from `libA.2.0.a` for my program and the symbols from `libA.1.0.so` for `libB.so`?
Yes, this configuration is possible. In answer to your question as to how the system knows how to use the symbols, remember that all of the links happen at build time. After it's been built, it isn't a question of "symbols", just calls to various functions at various addresses. When building libB.so, it sets up it's links to libA.1.0.so. It does not know or care what other applications that use it will do, it just knows how to map its own function calls. When building the application itself, the application links to libB.so. Whatever libB.so calls is completely unknown to the application. The application also statically links to a library, which libB.so does not care about. One gotcha: if libA uses static variables, there will be one set of statics accessible to libB.so, and a different, independent set of statics accessible to the application.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "c, static libraries, dynamic linking, static linking" }
GUI Window Size C# WPF I want to set the window to an exact size for creating a game, since I will use the X and Y coordinates of the screen to move things. The problem is that when setting the window width and height it includes the border in that size, so your actual size is smaller than what you specify. What can I do about this?
You set the width and height to the panel inside of the window instead. Usually it's a Grid panel unless you have changed it. You can then set your window's SizeToContent property so it can autosize to fit the Grid.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c#, wpf, size" }
print variable's value contain variable is it possible in twig? like php we have used $$ to print variable value? i have user object that contain all user fields. and listFields array that have ["user.id", "user.email","user.gender"]. so variables in string. i want to loop listFields and print it's original value from user object currently user.id user.email print on screen. i want to print it's value in screen. have any solution for this! or it is possible? **Mycode** {% for fieldName in listFields %} <td> {{ fieldName }} </td> {% endfor %}
If you want to print dynamic variables u can make use of the function `attribute`: {% set user_fields = [ 'user.id', 'user.email', 'user.gender', 'alice.email', 'bob.id', 'bob.foo', ] %} {% for field in user_fields %} {{ attribute(attribute(_context, (field|split('.'))[0])|default([]), (field|split('.'))[1])|default(null) }} {% endfor %} demo * * * array:3 [ "user" => array:3 [ "id" => 42 "email" => "[email protected]" "gender" => 0 ] "bob" => array:3 [ "id" => 1 "email" => "[email protected]" "gender" => 0 ] "alice" => array:3 [ "id" => 100 "email" => "[email protected]" "gender" => 1 ] ]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "twig" }
How can I prevent GNU Emacs from splitting windows on startup? Whenever I try to open an existing file with GNU Emacs, the window always split horizontally so as to show two buffers: one buffer containing the file and the _GNU Emacs_ buffer. How can I set up Emacs to not do that and show only the buffer that holds the file's text?
You want the following in your init file: (setq inhibit-startup-screen t) or, equivalently, say M-x customize-variable RET inhibit-startup-screen RET
stackexchange-emacs
{ "answer_score": 11, "question_score": 9, "tags": "window, customize" }
What is the value of epsilon? Is the value of epsilon in java always the same? In my lesson in my online class it says double x = 0.7, y = 1.0 - 0.1 - 0.1 - 0.1; System.out.println("x is " + (x)); System.out.println("y is " + (y)); System.out.println("x == y is " + (x == y)); final double EPSILON = 1.0E-6; System.out.println("Math.abs(x - y) < EPSILON is " + (Math.abs(x - y) < EPSILON)); which yields x is 0.7 y is 0.7000000000000001 x == y is false Math.abs(x - y) < EPSILON is true So I was just wondering is epsilon always 1.0E-6 or can it be anything?
You just defined it as one millionth. It could be anything that (a) is useful to you, and (b) is representable in the chosen format. The magnitude of your chosen epsilon depends on the magnitude of the values you're working with; it represents your view of what 'close enough' means, and close enough for numbers near 1 is not the same as close enough for numbers near 1000000000000000 nor near 0.000000000000001.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, epsilon" }
credentials file for running mysql related jobs via script? Is there a method to point mysql to a credentials file instead of entering account passwords directly in scripts? Example: mysqldump --opt --credfile /etc/mysql_creds mydatabase > output.sql /etc/mysql_creds username=myuser password=ToPsEcReT
It would be better to store the credentials in a config file, and load them as an extra-defaults file: $ mysqldump --defaults-extra-file=mycred.cnf ... The config file is the same format as /etc/my.cnf or ~/.my.cnf $ cat mycred.cnf [mysqldump] user = myuser password = xyzzy MySQL 5.6 also introduces encrypted storage of credentials. You can set up an encrypted file ~/.mylogin.cnf: $ mysql_config_editor set --login-path=dump --host=localhost --user=root --password Enter password: Then you can dump using that login path $ mysqldump --login-path=dump ...
stackexchange-dba
{ "answer_score": 6, "question_score": 4, "tags": "mysql, authentication" }
How do I find the line in a text file beginning with 5678 and replace it with nothing using php? Lets say the text file contains: 56715:Jim:12/22/10:19 5678:Sara:9/04/08:92 53676:Mark:12/19/10:6 56797:Mike:12/04/10:123 5678:Sara:12/09/10:49 56479:Sammy:12/12/10:645 56580:Martha:12/19/10:952 I would like to find the lines beginning with "5678" and replace them with nothing, so the file will now contain only: 56715:Jim:12/22/10:19 53676:Mark:12/19/10:6 56797:Mike:12/04/10:123 56479:Sammy:12/12/10:645 56580:Martha:12/19/10:952 Thanks.
// The filename $filename = 'filename.txt'; // Stores each line into an array item $array = file($filename); // Function to return true when a line does not start with 5678 function filter_start($item) { return !preg_match('/^5678:/', $item); } // Runs the array through the filter function $new_array = array_filter($array, 'filter_start'); // Writes the changes back to the file file_put_contents($filename, implode($new_array));
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, replace" }
getting the text from a TextView from a different activiy I have 2 activities: Activity_A and Activity_B. On Activity_A I have a TextView with the id "MyTextView". How can I get its text from Avtivity_B? I have tried to do this in Activity_B main Java file: txtv = (TextView) findViewById(R.id.MyTextView); txtv.getText().toString() But this didn't work. Is there any way to this without Intents?
The challenge is that when an activity is not visible, it has been paused, and is no longer available. Also the id used in findViewById may refer to an id in the other activities layout file. Using an intent to pass the data when moving between activities is a good solution, or if you really need access to that data from different activities you could store it in shared preferences, in a database, or as a static field on the activity class itself.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android, android activity, textview" }
Ruby: install a yanked gem (e.g. wkpdf on OS X 10.9) I'd like to install wkpdf as per < but, as per < and < the gem "wkpdf" is "yanked", even though it should most likely still be in the working order. % sudo gem install wkpdf ERROR: Could not find a valid gem 'wkpdf' (>= 0) in any repository 11.556u 0.437s 0:29.63 40.4% 0+0k 57+1io 363pf+0w Is there a way to install it nonetheless? I'm running OS X 10.9, `gem -v` returns `2.0`,
The project is still online here: < You can do the following: $ wget $ tar -xf v0.6.11.tar.gz $ cd wkpdf-0.6.11 $ gem build wkpdf.gemspec $ sudo gem install wkpdf-0.6.11-universal-darwin.gem
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby, macos, rubygems, osx mavericks" }
Use Pygame mouse while hidden Is there a way to use the mouse while, pygame.mouse.set_visible(False) is activated. Currently mouse only returns the bottom-right coordinate when tried to be used. Being able to get correct coordinates while mouse is hidden is required. Could not find an answer at their documentation.
I solved the problem by using an invisible cursor. pygame.mouse.set_cursor((8,8),(0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0))
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 2, "tags": "python, pygame, mouse" }
Is there any aug that increase the reserve energy? Even if Biocells are plentyful, and can be made from scraps, I d rather use my scrap for something else, and spare my Biocell for item to power up. Which mean I am on my reserve for the majority of my time, waiting for it to recharge or other. Is there any way to increase the reserve part? Human Revolution had one wich increased it to two "batteries" that I got as soon as possible, I'd like to do the same in Mankind Divided.
If by "reserve energy" you mean the portion of your energy bar that always recharges, then no. It cannot be increased in Mankind Divided. Also, you are misremembering Human Revolution; there is no augmentation in that game that increases the reserve energy either. There are augmentations in both games that 1. increase the total size of the energy bar 2. reduce the time you have to wait before energy begins recharging 3. increase the speed at which energy recharges Note that in Mankind Divided's Breach Mode you can indeed increase your reserve energy from 30 units to 45 units and then 60 units.
stackexchange-gaming
{ "answer_score": 2, "question_score": 4, "tags": "deus ex mankind divided" }
Как сделать чтобы в таблице tr растягивались Здравствуйте, делаю таблицу. В этом коде видно что второй row не растягивается table { width:100%; } table td { height:100px; } table tr { width:100%; } <table border="1"> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </table> Как сделать чтобы `tr` растягивались так![введите сюда описание изображения]( Видно что второй растягивается. Как это сделать и в каком направлении копать
О, придумал хак, не меняющий разметку. Только делать так всё равно не надо! table, tbody { display: block; } tr { display: table; width: 100%; } tr + tr { margin-top: -2px; /* не удваивать cellspacing */ } td { height: 94px; } <table border="1"> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </table>
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "html, css" }
TextView to String I'm trying to convert TextView into a string and I'm not sure if I'm going about it the right way, below is the code I thought would work but I keep getting errors. TextView test1 = (TextView)findViewById(R.id.result1); String testA = test1.getText().toString(); Is this the correct method to do this or is there another way? Any help would be appreciated.
Your code is correct. Beware that it will only work once `onCreate` has been called and your `contentView` has been set.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "java, android, string, textview" }
Refer to parent object from child object without assigning an object literal to a variable I need to refer to a parent object from a child object without using a variable assignment , something like the super keyword but in literal my example would be : { a:1, b:{e:a} } There is a solution which is var obj = { a: 1, b: { get e() { return obj.a } } } But I am asking if it is possible without assigning the object literal to a variable
You can use `this` to refer the same level object but in your case, it's nested so use nested getter to keep the parent context. var obj = { a: 1, get b() { const pctx = this; return { get e() { return pctx.a }, c: 1 } } } console.log(obj.b.e) **Note:** This way the reference of the nested object will be different each time and you can't update the property of the nested object.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "javascript" }
Has any research lab done serious work to engineer new bacteria which assemble graphene wafers? I was thinking about crazy uses for engineered bacteria. Nano-assembly of Graphene seems like a potentially excellent target for the technology. Have any research/full-blown labs worked on this? Any papers on it? What would be some of the difficulties?
Surprisingly, the answer is yes. In 2012 Tanizawa et al published a paper titled Microorganism mediated synthesis of reduced graphene oxide films. The gist of it is that most of the steps (including the structuring of the graphene sheet) were carried out with chemical synthesis, but a final reduction step from graphene oxide to graphene was carried out using bacteria from a local river. Probably not quite what you were thinking of, but I imagine this is the closest you'll get for right now.
stackexchange-biology
{ "answer_score": 5, "question_score": 3, "tags": "recombinant, protein engineering" }
Are “shape” and “size” abstract nouns? “Shape” in “the ball has a spherical shape” “Size” in “the ball has a big size” Are “shape” and “size” abstract nouns?
Abstract nouns are those denoting an idea, quality, or state rather than a concrete object, e.g. truth, danger, happiness. So yes "size" and "shape" are abstract nouns, that is they have abstract meanings. But this is not part of the grammatical structure of English, but could apply equally to any other language. The concept expressed by the English word "size", the French "taille", the Chinese "" or the Zulu "ubukhulu" is an abstract concept, and so these are abstract nouns of their respective language. There is also a considerable grey area between "abstract" and "concrete". "There are three shapes on my desk, made of wood. Please bring them to me" seems to be a fairly concrete sense of "shape". But "I love the shape of chair" seems to referring to an abstract quality.
stackexchange-ell
{ "answer_score": 0, "question_score": 1, "tags": "abstract nouns" }
Initial velocity of an object in the inertial frame and the rotating frame (non-inertial) If I launch an object in a rotating reference frame, say at an angle of 90 degrees (see image) with a velocity of 5 m/s, the initial velocity of this object in the inertial reference frame will be, of course, 3 m/s in the 90 degrees direction. In the non-inertial frame, however, the direction of this initial velocity will inherit the linear velocity omega times the radius of the rotating body. The magnitude of the initial velocity in the non-inertial frame will also change, but I don't know how to calculate that. Or in other words, how do you convert the magnitude of initial velocity from the inertial frame to the non-inertial frame. ![enter image description here]( Right now, I am thinking to do the following calculation - the velocity in the inertial frame plus the cross product of the angular velocity and the position vector. ![enter image description here]( Any advice would be appreciated.
If the initial velocity of 5 m/s is relative to the rotating frame then you have to add the rotational velocity vector (with magnitude $\omega r$) to find the velocity vector relative to the non-rotating frame. On the other hand, if the initial velocity of 5 m/s is relative to the non-rotating frame then you have to subtract the rotational velocity vector to find the velocity vector relative to the rotating frame.
stackexchange-physics
{ "answer_score": 1, "question_score": 0, "tags": "newtonian mechanics, reference frames" }
Is NSTS 08209 "Shuttle Systems Design Criteria" available online? This would be a handy reference, to say the least. There is a paper copy in at least one library in Houston, so it's not inconceivable that it's online somewhere, but my searches to date have failed.
A portion of Volume 1 of "NSTS-08209 Shuttle Systems Design Criteria" is available at < which is a pretty amazing shuttle data dump. The pdf only contains the highlighted sections. ![enter image description here](
stackexchange-space
{ "answer_score": 1, "question_score": 6, "tags": "space shuttle, history, reference request" }
What is the meaning of ~. in R? I would like to understand the meaning of `~.` in R. This is an example from kknn function: library(kknn) data(iris) m <- dim(iris)[1] val <- sample(1:m, size = round(m/3), replace = FALSE, prob = rep(1/m, m)) iris.learn <- iris[-val,] iris.valid <- iris[val,] iris.kknn <- kknn(Species~., iris.learn, iris.valid, distance = 1, kernel = "triangular") summary(iris.kknn) fit <- fitted(iris.kknn) table(iris.valid$Species, fit) It is included on the kknn function above, right beside the Species. Thank you!
As you can see here, you are creating a formula object. The documentation of formula states: > There are two special interpretations of . in a formula. The usual one is in the context of a data argument of model fitting functions and means ‘all columns not otherwise in the formula’ So in your case, you are creating a model that uses all other variables than 'Species' as predictors to predict Species.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "r, knn" }
Django - create object in a specific database To save a model to my `'not_default_db'` I'm using : p = Person(name='James') p.save(using='not_default_db') But using **Model.create()** save the model in the default DB: Person.objects.create(name='James') Is it possible to use **Model.create()** on a specifc Data Base ?
Try to use queryset's `using()` method: Person.objects.using('not_default_db').create(name='James')
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "python, django, django models" }
Authentication and authorization with Gun.js the tradicional way with Social logins? Gun.io How can I set up authentication and authorization layers with Gun.js the tradicional way, for example with social logins with (Google, LinkedIn) or AWS cognito, Auth0,our my own RBAC server?
Centralized login systems give access tokens to a server and session tokens to the user. Unfortunately, this means you cannot do fully p2p logins if you want to support other logins, because the server that receives the access token will need to have a "backdoor" into GUN's cryptographic user accounts. If users are okay with this backdoor... Then, save their keypair (or generate a secret password) privately to their profile on your existing centralized user account system. Now you can automatically log them into GUN by calling `gun.user().auth(keypair)`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "authentication, distributed, gun" }
Cardinality of $\{:\{1, \ldots , \} → \{0,1,2\}\mid ∀ ∈ \{1, \ldots , − 1\}: () + ( + 1) ≠ 4\}$ What is the cardinality of this set? $$\\{:\\{1, … , \\} → \\{0,1,2\\}\mid ∀ ∈ \\{1, … , − 1\\}: () + ( + 1) ≠ 4\\}$$ On a logical level, I understand that it must be the set of all functions for which $f(i+1)\neq f(i) \neq 2$. But there's no formula for the function, so.. How can this be found?
Let $a_n$ be the number of such functions. We have two cases: * If $f(1)\in\\{0,1\\}$ then there is $2\cdot a_{n-1}$ such functions. * If $f(1)=2$ then there is $2\cdot a_{n-2}$ such functions. So, all together $$a_n = 2a_{n-1} + 2a_{n-2}$$ with $a_1 = 3$ and $a_2=8$. This means that $$a_n = a\Big({1+\sqrt{3}}\Big)^n+ b\Big(1-\sqrt{3}\Big)^n$$ for some $a,b$ which you can get from boundary terms. Actually it is $a ={3+2\sqrt{3}\over 6}$ and $b ={3-2\sqrt{3}\over 6}$.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "sequences and series, combinatorics, discrete mathematics, elementary set theory, recurrence relations" }
Calculating the equilibrium constants for parallel reactions So, I am attempting to calculate the equilibrium constant for two separate reactions. $$\ce{A + B<=>C + D}$$ $$\ce{A + B <=> C + E}$$ I have figured out the final pressures at equilibrium for $\ce{A}$, $\ce{B}$, $\ce{C}$, $\ce{D}$, and $\ce{E}$. I was wondering if the equilibrium constant is calculated as normal using just the final pressures and molar ratios in the equations, or if the final pressures have to be adjusted somehow to compensate for the fact that the second reaction is also consuming the same products and producing one of the same reactants.
You can combine the two chemical reactions into a single global reaction scheme by adding them: \begin{align} \ce{A + B&<=>C + D}\tag{1}\\\ \ce{A + B&<=>C + E}\tag{2} \\\ \hline \ce{2A + 2B &<=> 2C + D + E} \tag{Global} \end{align} and the equilibrium constant for this overall reaction scheme is equal to the products of the two equilibrium constants: \begin{align} K_\mathrm{eq,global} &= K_\mathrm{eq,1} K_\mathrm{eq,2} \\\ &= \frac{\ce{[C]^2[D][E]} } {\ce{[A]^2[B]^2}} \end{align} (where $\ce{[i]}$ denotes either molar concentration or partial pressure of component i). You do not need to adjust the final total pressure or mole amounts.
stackexchange-chemistry
{ "answer_score": 2, "question_score": 2, "tags": "physical chemistry, equilibrium, pressure" }
Neo4J - count outermost nodes Given a graph (or subgraph), in this case root Neo... How do I get the nodes which are the furthest depth from the root (i.e not directly connected to nodes of greater depth) which have a specific attribute. eg ... how do I get the green "Get Me" nodes when I'm not interested in the other green ones (they're not the outermost layers) or the orange ones (furthest out on their branch but not green). I don't care about depth .... ![how do I get the green "Get Me" nodes]( Thanks for your help Chris
Another approach to Franks would be to find all the leaf nodes first that match your criteria, and then using those nodes, filter down to those that have a path to the Neo node // find all Green nodes (you can add in a filter / WHERE clause to // just match the ones with specific properties) MATCH (g:Green)--(o) // for each match, calculate the degree of the node (the number of // relationships - undirected in this example) WITH g, count(*) as deg // filter down the results to just the leaf nodes (deg 1) WHERE deg = 1 WITH g // finally only return those that have a path to the Blue (neo) node MATCH (g)-[*]-(b:Blue) // just return the green nodes RETURN g;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "graph, neo4j, cypher" }
Is continuous and integrable function bounded? I have a function $f: \mathbb R \rightarrow \mathbb R$ continuous and integrable on $\mathbb R$. Is $f$ bounded?
No, not even if you require the integral to be finite. Consider a function that is zero except on $[n,n+\frac{1}{n^3}]$ where it is a piecewise linear function connecting $(n,0)$, $(n+\frac{1}{2n^3}, n)$ and $(n+\frac{1}{n^3}, 0)$ for $n\in\mathbb{N}$.
stackexchange-math
{ "answer_score": 7, "question_score": 3, "tags": "real analysis, integration" }
Suzuki GSR600 low idle revs and unstable Just a week ago I noticed in my motorbike unstable rpm, +-300rpm. But today I found that the idle rpm are below 1000rpm, at some points around 500rpm (Normally is 1500rpm). I'm due for the annual maintenance next month and I'm not sure if this problem is because of a sensor, dirty fuel injectors or anything else. Any ideas?
Suzuki garage found the issue. Broken hose going to the engine was the problem, nothing major.
stackexchange-mechanics
{ "answer_score": 2, "question_score": 5, "tags": "motorcycle, suzuki, rpm" }
conditional update_all with join tables in ActiveRecord? The following query returns the collection of AR objects that I want to update: Variant.all(:joins => { :candy_product => :candy }, :conditions => "candies.name = 'Skittles'") I'm trying to do something like the following: Variant.update_all(:price => 5, :joins => { :candy_product => :candy }, :conditions => "candies.name = 'Skittles'") This should only update the price for the variants returned from original query. Is this possible with AR or will I have to write the SQL? This is a pretty large collection, so anything that iterates is out. Using Rails 2.3.4.
As @François Beausoleil pointed correctly we should use `scoped` Variant.scoped(:joins => { :candy_product => :candy }, :conditions => "candies.name = 'Skittles'").update_all(:price => 5)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "sql, ruby on rails, activerecord" }
Which of the following map are constant ?? IIT-kanpur PhD paper Which of the following maps are constant? (a) $f : D → C$ such that $f$ is analytic and $f(D) ⊂ R.$ (b) $f : D → D$ such that $f$ is analytic and $f([−1/2, 1/2])$ = {0}. (c) $f : C → C$ such that $f$ is analytic and $Re(f)$ is bounded. (d) $f : C → C$ such that $f$ is analytic and $f$ is bounded on the real and imaginary axes *My works *: option a),b) and c) will true by _Liouville's theorem_ that is real value and analytics implies constant option d) will be false take $f(z) =e^{iz^2}$ Please verify whether I am right /wrong ? Thanks in advanced.
Yes I'm right, my answer is correct
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "complex analysis, proof verification" }
SQL: How to get array of IDs from most common values in a table? I have the most counts of each value in a column like so: SELECT col, COUNT(col) FROM table GROUP BY col ORDER BY col DESC; But I would like to add another column where the IDs of the records with those values are in an array. For example, if "blueberry" was the most common value, the cell next to it should show the ids of those records, e.g. - [1, 21, 123]
You can get an array for each _col_ : SELECT col, COUNT(*), ARRAY_AGG(id) as ids FROM table GROUP BY col ORDER BY COUNT(*) DESC; You can fetch the first row of the above query: SELECT col, COUNT(*), ARRAY_AGG(id) as ids FROM table GROUP BY col ORDER BY COUNT(*) DESC FETCH FIRST 1 ROW ONLY; Does this do what you want?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, postgresql" }
How do I prove that $\lim_{K\searrow0}\frac{P(K,T)}{K} = \mathbb P(S_T=0)$? I am trying to prove that $$\lim_{K\searrow0}\frac{P(K,T)}{K} = \mathbb P(S_T=0)$$ where $P(K,T)$ denotes the put option price with maturity $T$ and strike $K$ for some stock $S$. Assuming interest rates $r=0$ we write $$\lim_{K\searrow0}\frac{P(K,T)}{K} = \lim_{K\to0}\frac{\int_0^K(K-S)f(S)dS}{K}$$ $$= \lim_{K\searrow0} \left(\int_0^Kf(S)dS - \frac1K\int_0^KSf(S)dS\right)$$ $$= \lim_{K\searrow0} \left(\mathbb P(S_T\le K) - \frac1K\mathbb E[S_T1_{S_T<K}]\right)$$ where $f(S)$ is the density of $S_T$. Now $\lim_{K\searrow0} \mathbb P(S_T\le K) = \mathbb P (S_T=0)$, but I am not sure whether it is "obvious" that $\frac1K\mathbb E[S_T1_{S_T<K}]$ tends to zero as $K$ tends to zero.
$$\lim_{K\searrow0}\frac{P(K,T)}{K} = \lim_{K\to0}\frac{\int_0^K(K-S)f(S)dS}{K}$$ $$= \lim_{K\searrow 0} \left(\int_0^Kf(S)dS - \frac1K\int_0^KSf(S)dS\right)$$ $$= \lim_{K\searrow 0} \big(\mathbb P(S_T\le K)\big) - Sf(S)\big\vert_{S=K=0}$$ $$= \mathbb P(S_T=0),$$ where $f(S)$ is the density of $S_T$.
stackexchange-quant
{ "answer_score": 4, "question_score": 2, "tags": "options, put" }
Firefox won't show page when PHP sends a 408-header There are some times when I'd like my site to trigger a 408-response (for when various pieces aren't responsive). (PHP 5.3.3 and Apache, both Windows and Linux machines) I can use the following code and get the expected result in all browsers except Firefox: <?php // Access forbidden: header('HTTP/1.1 408 Request Timeout',true,408); echo 'hi';exit; But Firefox just immediately sends the "The connection was reset" page, and Firebug shows it got the 408 message. Is this by design in Firefox, or is there some way around this?
The 408 response is the server telling the client that the _client_ didn't send all the details for a request within the time that the server was willing to wait, and that the server has forcefully closed the connection. So, yes, this is by design in Firefox. Edit: Consider using the `503 Service Unavailable` temporary error code instead, possibly with a `Retry-After` header. I've never tested to see if the `Retry-After` works.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, firefox" }
How to run the shell command in the appointed line in vim? I have a file edited in Vim with many lines. There is a specific line that contains a shell command, which I want to run. How can I do this through Vim? ![enter image description here](
try Use :exec '!'.getline('.') This is like to copy the current line and run it. You can also map this command to map <F12> :exec '!'.getline('.') getline receives the number of the line. if you will write 4 it will the line 4. The "." it run the current line. so for run the command in line 4 you can write. :exec '!'.getline(4)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "vim" }
Salesforce Data Loader Cant Upsert Tasks using External Id to link to Account? I'm trying to Upsert Tasks to their Accounts using an ExternalID field but the 2nd step (Step 2b) doesn't appear with a Task Upsert. Does Task not support External IDs for Account-association? Also, to add to the confusion, You can't actually create "Task Fields", but instead, we can Create "Activity Fields" which is used on Task Page Layouts. So the actual External ID field is on the Activity object. But you can't select Activity in Dataloader, instead, you use Task or Events.
If you are trying to associate tasks with Accounts using the external Id. The parentId field on task is polymorphic and can relate to different objects. The linking to Account won't work because of that. Here is an Idea on IdeaExchange to have this implemented but it hasn't seen much traction as of now from Salesforce. An easier way would be to query the accounts and use VLookUp to associate tasks or activities to accounts and then do a data load.
stackexchange-salesforce
{ "answer_score": 2, "question_score": 1, "tags": "data loader, tasks, externalid" }
What is the purpose of .loc in pandas data frame I am basically migrating from R to Python. I wanted to subset my data frame based on a column. While going through stack-overflow answer, I found a solution. But consider the below code: import pandas as pd import numpy as np df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(), 'B': 'one one two three two two one three'.split(), 'C': np.arange(8), 'D': np.arange(8) * 2}) df1 = df[df['A'] == "foo"] df1 df2 = df.loc[df['A'] == "foo"] df2 Both df1 and df2 are same. So my question is : what is the requirement for `loc` function in the first place. Please bear in mind, that I come from R background and in R, we dont have to use `loc` type function for subsetting data-frame.
I am learning pandas myself, so excuse the answer that isnt particular in depth. The .loc is has a 'location' function allowing you to note a place in the dataframe DF[1,3] in R. Or allowing you to put in two grid coordinates, where otherwise you could have only 1 parameter. Now I could be wrong, as its been a while since I've had a look at pandas, and as I mentioned I am also only learning it. It is listed as an indexing function on the website <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, r, pandas, dataframe" }
custom effect with cakephp js helper I am using Js helper class and i have successfully implement this.I am using following code for using ajax. $this->Js->link('test','action',array( 'before'=>$this->Js->get('#loader')->effect('fadeIn'), 'success'=>$this->Js->get('#front_album')->effect('fadeIn'), 'update'=>'#front_album')); Now in this when i try to add animate effect instead of fade In,nothing is happen.I try this in following manner. $this->Js->get('#loader')->effect('animate','opacity: 1.0'); Please tell me where i am wrong and how can i add the animate effect in this.
There are some pre-specified effect names available in JsHelper. Instead of if you want to make `animate` effect while clicking on JsHelper link, then you'll have to make your own helper extend by JsHelper and provide the definition for that effect. This post will help you to create your own helper that will support the feature you want. This is the only way that you can use to obtain the required effect.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "cakephp" }
Cross Stack Exchange Search Inspired by this tweet: < As the new, and awesome, StackExchange.com already aggregates the hot questions from across the system. I was wondering if it would be possible to include a global search function also.
See <
stackexchange-meta
{ "answer_score": 2, "question_score": 6, "tags": "feature request, status completed, stackexchange.com, global search" }
Finding cheapest way to buy items in different shops, but shops have one time fee So I have following problem: There is `k` stores and `n` items. Every store can have these items at different prices (and there are stores that don't have all items). But if you want to buy in a specific store, you must pay one-time fee, which is different for every store. How to find the cheapest way to buy all items? The only solution I have now is to try every possible combination of shops and look for the cheapest. Is there a better way or some heuristic approximation?
There's a pretty simple reduction of 3-SAT to this problem, so it's NP-hard (introduce a store for each variable and for the complement of each variable, one time fee of 1, then have as the items for a store all clauses satisfied by the variable or complement, as well as a special item for each variable which is sold only in the variable and complement store, all of cost 0, and see if you can buy everything for price `k`). So there's not going to be a "better way" in the sense of an algorithm which is guaranteed to produce an optimal result with better complexity than a brute-force search. I think simulated annealing would work well here: In each annealing step either add or remove a store, then find the lowest cost for that store selection.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "algorithm, computer science, computer science theory" }
6502 Assembly convert a 2 digit number to 4 digit I have a random number(from 0 to 31) x stored at address `$00`, and another random number(from 0 to 31) y stored at address `$01`. I want to use these two numbers as coordinates and derive an address `$xy`. For example if x = 2, y = 10, the address would be `$020a`. I'm a beginner, so could someone share an effective way of doing this? I want to store some other value in the derived address `$020a`, so this is why I need it.
You need to use indirect addressing. Indirect addressing takes an address plus the Y register, so make sure you clear the Y register first. LDY #0 LDA ($0),Y To store at that address: LDA #$FF ; or whatever you want to store LDY #0 STA ($0),Y Here is some more info on indirect addressing: < I am rusty but hopefully this steers you in the proper direction.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "assembly, 6502" }
How to insert into html table's specific column I've `.csv` file and trying to display it using flask and html tables. I've already parsed csv file and passed it into flask html template file. this is my html file <table class='content-table'> <thead> <tr> <th>First Name</th> <th>Last Name</th> </tr> </thead> <tbody> {% for firstname in firstnames %} <tr> <td>{{ firstname }}</td> </tr> {% endfor %} {% for lastname in lastnames %} <tr> <td>{{ lastname }}</td> </tr> {% endfor %} </tbody> </table> which results !a busy cat I wanted to fill Last Name column with Doe. How can I do it?
You should zip() the firstname and lastname when you rendering your tempalte. like `name_details = zip(firstnames, lastnames)`. Then you can use it in single for loop <table class='content-table'> <thead> <tr> <th>First Name</th> <th>Last Name</th> </tr> </thead> <tbody> {% for firstname, lastnames in name_details %} <tr> <td>{{ firstname }}</td> <td>{{ lastnames }}</td> </tr> {% endfor %} </tbody> </table>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, html, flask" }
Qt ownership of 'objects' (T* and const T*) Is it correct to assume that a `QObject` with a setter taking a pointer: * Will take ownership and delete the pointer, if the pointer is `T*`? Example: `void QComboBox::setModel(QAbstractItemModel *)` * Will not take ownership and not delete the pointer, if the pointer is `const T*`? Example: `void QLineEdit::setValidator(const QValidator *)`
There's no strict rule to that - in your cases the "receiver objects" don't take ownership of the passed objects. In cases where ownership is transferred, it's documented, see for example QComboBox::setLineEdit(): > Sets the line edit to use instead of the current line edit widget. The combo box takes ownership of the line edit. Should there be cases of ownership transfer where it's not documented, I'd consider that a Qt bug. Passing a parent to the validator or model as suggested by piotrus is always safe.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "c++, qt" }
Manipulate json, remove two items in a group by key value How can I manipulate this chunk of json: { "id": "whatever", "attributes": [ { "key": "this", "value": "A" }, { "key": "that", "value": "B" }, { "key": "other", "value": "C" } ] } So that it matches on "that" and removes the key and value both in that grouping, leaving json like this: { "id": "whatever", "attributes": [ { "key": "this", "value": "A" }, { "key": "other", "value": "C" } ] } I am attempting to use jq on linux.
Try this .attributes |= map(select(.key != "that")) Demo
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "json, jq" }
What is the Seller Registration Number on a Bill of Sale? I am selling a car in Ohio and downloaded the generic Bill of Sale form from this website: < Does anyone know what the Seller Registration Number field is used for? Is it my driver's license number, license plate number, or something else entirely? I went on Ohio's BMV website to check my vehicle registration (< but the only number provided is the license plate number? Any help would be greatly appreciated!
In Ohio unlike other states a bill of sale is not required. The car should have a title and that title is on file at the title bureau. You will fill the title out and take it to a notary to get signed. Exchange the title and car for the money. The new owner will take the title to the title bureau and pay the sales tax on the price filled out on the title to get a new title with their name. The bill of sale you have listed seems to be a generic one. I would put private party under seller registration number field. The bill of sale is most likely for use with dealers or resellers that posses such a number.
stackexchange-mechanics
{ "answer_score": 4, "question_score": 3, "tags": "registration" }
How to achieve dynamic url tree in NextJS From what I understand from nextjs routes - blog->[id].jsx gives "blog/1", "blog/2" etc. But I want to achieve page-subpage-subpage kind of url tree where each page can have subpages & subpages can have further subpages. So url's may look like these - "page/sub-page/sub-sub-page" etc. I'm using django treebeard in backend, so pages & subpages urls are all dynamic & comes from API calls. Currently I tried with the below structure - * pages/ * index.js * [slug].js It only gives me ability to fetch only level one pages. I want to acquire multi-level page access. Anybody ever did it? Please help.
The URL tree is based on the folders and files in your pages-folder, so you can simply add folders and files to make the tree you need. For example, a blog could have a structure of folders and files like this: * pages/ * index.js _(blogsite.com)_ * blog/ * index.js _(blogsite.com/blog)_ * [id]/ * index.js _(blogsite.com/blog/123)_ * comments/ * index.js _(blogsite.com/blog/123/comments)_ * [commentId].js _(blogsite.com/blog/123/comments/321)_ **EDIT BASED ON COMMENTS:** I missed that the asker actually meant that they don't know the depth of their tree beforehand. In this case you can use a catch all route like [...id] and the page will get all of the parameters that exist in the query-object.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "typescript, api, url, react router, next.js" }
How to reuse the `apt up` part of the `apt update` and `apt upgrade` commands to execute both in sequence in just one line For learning purposes, I want to know if its possible and if it is, how to reuse the `apt up` part of the `apt update` and `apt upgrade` commands to execute both in sequence in just one line? i.e.: `sudo apt up{date|grade}`
Print commands on two lines and pipe to xargs: printf "apt up%s\n" date grade | xargs -l sudo printf "up%s\n" date grade | xargs -l sudo apt printf "%s\n" date grade | xargs -i sudo apt up{} Similar with evil `eval`: eval $(printf "sudo apt up%s\n" date grade) Similar design, but more bash expansions: eval $(printf %s\; "sudo apt up"{date,grade}) sudo sh -c "$(printf %s\; apt\ up{date,grade})" Another one, knowing that `xargs` splits on spaces: echo up{date,grade} | xargs -n1 sudo apt But really, just a loop: for i in date grade; do sudo apt up$i; done
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "bash, terminal" }
turtle module error with color() I am trying to write a program to have the user specify the colour of lines but I keep getting an error. Can someone please explain why this is happening import turtle wn = turtle.Screen() alex = turtle.Turtle sides = int(input("Enter the number of sides: ")) angle = 360/ sides length = int(input("Enter the length of sides: ")) line_color = input("Enter the color of the lines: ") alex.color(line_color) fill_color = input("Enter the fill color for the polygon:" ) alex.fillcolor(fill_color) alex.begin_fill() for i in range(sides): alex.forward(lenght) alex.left(angle) alex.end_fill()
this should run: import turtle wn = turtle.Screen() alex = turtle.Turtle() # need parens sides = int(input("Enter the number of sides: ")) angle = 360 / sides length = int(input("Enter the length of sides: ")) line_color = input("Enter the color of the lines: ") # takes input like "red" or "black" etc.. alex.color(line_color) fill_color = input("Enter the fill color for the polygon:" ) alex.fillcolor(fill_color) alex.begin_fill() for i in range(sides): alex.forward(44) # added 44, you had an undefined variable there which is not valid alex.left(angle) alex.end_fill() I added the value `44`, you will have to add whatever you require yourself or initialize the variable `length` to some value.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "python, python 3.x" }
Understanding link pseudo class inheritence I have a simple setup with a:link, a:visited a:hover and a:active all defined at the top of my style sheet. I also have a div where I've defined an a:link color for anchors inside of it. When I do this those links do not inherit the remaining pseudo classes for hover and active.... until I click that div's link and it has thus been "visited", at which point the pseudo classes start working. Why is this? the CSS... a:link { color: blue; } a:visited { color: purple } a:hover { color: red; } a:active { color: pink; } #theDiv a:link { color: green; } the HTML... <a href="#33">The First Link</a> <div id="theDiv"> <a href="#33">The Second Link</a> </div> <
`#theDiv a:link` has a higher specificity than all your other selectors and is overriding them until the link no longer matches the `:link` selector, at which point it matches the `:visited` selector.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "css, css selectors, pseudo class" }
how do I make a python gql query with a hardcoded string? I'd like to create a gql query through my browser dashboard to easily look up specific entries, i.e. something like: SELECT * FROM MyEntity where mString = "SpecificEntity" but I can't quite get the syntax right. I see a lot of examples using parameter binding/substitution (not sure what it is called), but I don't know how to simply just write it directly without getting an error when I try to query. Any help? Update: This was for Python (and answered nicely already).
When in the App Engine dashboard, you have to use single quotes. SELECT * FROM MyEntity where mString = "SpecificEntity" Becomes SELECT * FROM MyEntity where mString = 'SpecificEntity'
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "string, google app engine, gql" }
Looking for low-maintenance URLs to load jQuery-ui I'm working with some legacy code that uses the following two lines in many places: <script src=" <script src=" The first of these two lines seems to me to be always up-to-date (or at least, it does not become dated as new versions of jQuery get released). Hence, I consider this a relatively "low-maintenance" URL. In contrast, the second line is clearly liable to becoming obsolete as new versions of jQuery UI are released. What's the jQuery UI-equivalent of the first line?
For whatever reason, there doesn't seem to be a link quite as low-maintenance as the jQuery one in your question. However, there is one that is _almost_ as nice: < or "//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" in code to be http/https-agnostic. This will give you the latest 1.x version. When version 2 is release, I assume you could simply update the link to use "2" instead of "1" and be good for a good while longer.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, jquery ui" }
ipazzport mouse issue I've recently upgraded my pi3 OS using sudo apt-get dist-upgrade Before I upgraded my ipazzport keyboard and mouse pad were working fine. Post upgrade my ipazzport mouse has changed axis, so inorder to move the cursor up the screen I have to swipe to the left. This isn't ideal. Is there a way to change this? Thanks
My bad, this is a keyboard config that's done on the keyboard itself rather than in code. To change the keyboard aspect click Fn and Esc at the same time. Problem solved.
stackexchange-raspberrypi
{ "answer_score": 0, "question_score": 0, "tags": "mouse" }
Add another object to link_to array Thanks to an earlier answer I have the following code in a view. <%= @miniature.contents.where(miniature_id: @miniature).map { |content| link_to content.miniset.name, content.miniset }.join(", ").html_safe %> That outputs `Minisetname, Minisetname, Minisetname` I want to add `(" x#{content.quantity}")` after the linked `Minisetname`so that it appears as Minisetname (x3), Minisetname (x7), Minisetname (x4) I only want it to append the `(" x#{content.quantity}")` if `content.quantity` is not null. I do this elsewhere in a block but I can't work out how to do it with the above array.
First, assuming that you have set up the relationships in your models normally I don't really see why you should need that `where`. I would then have structured the code something like this: **View** <%= content_miniset_links_with_quantity(@miniature) %> **Helper** def content_miniset_links_with_quantity(miniature) miniature.contents.map{|content| content_miniset_link_with_quantity(content)}.join(', ').html_safe end def content_miniset_link_with_quantity(content) string = link_to content.miniset.name, content.miniset string << "(x#{content.quantity})" if content.quantity.present? return string end
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails" }
image cropping c# I want to do image cropping. I saw following link. Image cropping But what i want to do is as follows. I want to crop the image calculating dimension from its centre. So for example if my image is 100 px and cropping i want result to be 50 px. i want to leave 25 px each on left and right hand side and make the width 50 px. Has anyone done it before?
It should be simple. Say you have `width` and `height` (of your source image), and you need your output to be in `cropped_width` and `cropped_height`. For start, we need to calculate center of the source image: int x_center=width/2; int y_center=height/2; Then, we know that we need output picture to be of defined size, so we take HALF of the size to the left-right: int x_source=x_center-cropped_width/2; int y_source=y_center-cropped_height/2; and finally, you have your rectangle for cropping: Rect r = new Rect(x_source, y_source, cropped_width, cropped_height); use some form of `DrawImage()` to copy that rectangle to the place you need.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "c#, .net, image" }
How to reformat Datetime when retrieving it from database using linq I insert `Datetime` value into a SQL Server database with the following format: `dd-MM-yy HH:mm`. If I insert `01-01-18 15:30` into database and execute command select datetimeColumn from mytable I get back `2018-01-01 15:30:00.000`. But if I retrieve all records of the table which contains the column with datetime type like meetings = meetings.Where(m => m.meeting_name.ToLower().Contains(searchString.ToLower())); `datetime` values become like `01-Jan-18 3:30:00 PM`. How can I keep datetime format the same as the format that I've inserted?
SQL Server stores data as two `intergers`, the first one reserved for the date and the 2nd one for the time. meetings = meetings.Where(m => m.meeting_name.ToLower().Contains(searchString.ToLower())); So by querying you just read `date-time` as is! All you need to do is to format datetime in your desired string format, for example: var dateTime = DateTime.Now; var dateTimeFormmated = dateTime.ToString("yyyy-MM-dd hh:mm:ss.ffff"); // 2018-01-26 05:52:54.3250
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, sql server, linq, datetime" }
Get value from object/array I need to get the token only in a variable in JS. { "user": { "id": "string", "nickName": "string", "score": 0, "rank": 0 }, "token": "string" } This is my response saved in a variable but I only need to get the "String" value from the token
If you have stored this response in a variable E.g.: let response = { "user": { "id": "string", "nickName": "string", "score": 0, "rank": 0 }, "token": "string" } You can extract the value from the "token" property like this let tokenFromObject = response.token or let tokenFromObject = response["token"] or let { token } = response
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "javascript, arrays, object, find, response" }
Let $G$ be a group of order $24$, and $a^{2002}=a^n$, find value of $n$. Let $G$ be a group of order $24$, and $a^{2002}=a^n$, where $a\in G$ and $0\lt n\lt 24$. Then the value of $n$ is which among the following: a) $4$, a) $6$, a) $8$, a) $10$. The order $o(G)=24$, and for any element $a$ in group maximum value of its order ($o_a$) can be $24$, and minimum value =$1$. So, does it state $o_a^{2002}= o_a^{24.k+r}= o_a^n, k,r \in \mathbb {N}$ for which possible value of $n$? If correct, then do we need find for each possible value of $a$, the value of $n$? If yes, then what should be a correct approach rather than just checking for $a=24$, which is shown elsewhere to yield answer $10$ by $24*83+10=2002$. The approach of taking a single value for $o_a$ is not clear at all.
Since $2002=83(24)+10$ is indeed true, you are correct that $$\begin{align} a^{2002}&=a^{83(24)+10}\\\ &=a^{83(24)}a^{10}\\\ &=(a^{24})^{83}a^{10}\\\ &=e^{83}a^{10}\\\ &=ea^{10}\\\ &=a^{10}. \end{align}$$ Therefore, $n=10$. You are correct that $24m+10$ will also do for any $m\in\Bbb Z$, but since none of these is between $0$ and $24$ for $m\neq 83$, we can select $n=10$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "abstract algebra, group theory, finite groups" }
Часть строки не влезает в string Что делать, если не хватает string? Часть строки не пишет Freepascal
У Freepascal большой выбор строковых типов. Вам, возможно, подойдёт `WideString` (`2^32` символов максимально) или `UnicodeString`.
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": -2, "tags": "строки, freepascal" }
ASP.NET-MVC 2 DataAnnotations StringLength Can I use the MVC 2 DataAnnotations to specify a minimum length for a string field? Has anyone done this or have they created custom attributes and if so do you mind sharing the source?
If you're using asp.net 4.0, you can use the StringLength attribute to specify a minimum length. Eg: [StringLength(50, MinimumLength=1)] public string MyText { get; set; }
stackexchange-stackoverflow
{ "answer_score": 73, "question_score": 30, "tags": "asp.net mvc 2, data annotations" }
Redirect in 5 seconds when button is pressed What I want to do is when the submit button is pressed, the user gets redirected after 5 seconds when submitted the form. code: <input type="submit" id="submit" value="Submit" onClick="window.location.reload()"> I tried this and other variants but these redirect instantly.
One possible solution is setTimeout(function(){window.location.reload();}, 5000)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, html, forms" }
Shouldn't the code formatter highlight the word "having" for SQL syntax? In this SQL statement, notice the color of the word "having" versus the words "select", "from", "where", and "group by" select cu.name ,cu.email ,count(*) as books_purchased from customers cu ,purchases pu where cu.customerid = pu.customerid and pu.year = 2003 group by cu.name ,cu.email having count(*) > 1
We just deployed the latest trunk of prettify.js ; revision 83 <
stackexchange-meta
{ "answer_score": 1, "question_score": 4, "tags": "bug, status completed, syntax highlighting" }
Weird characters in GVim's visual mode When I enter visual mode (from normal mode), and when then I press `:` there are these characters: `<,'>` after the `:` They are a feature or a bug? Windows XP SP2 alt text
You have a visual range selected, and when you enter `:` while that is the case, then the _selected range_ specifier `'<,'>` is automatically added to indicate that the command will only be applied to the selection.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "vim, vi" }
how to get conditional column selection in SQL? I'm trying to make a query that will give the appropriate column by user selection. If user select cab: i.e. where `user_choice='cab'` Then it will give `l.price_cab column` If user select seat: i.e. where `user_choice='price'` Then it will give `l.price_seat column` Query: SELECT l.company_name, l.price_seat, l.price_cab from login l JOIN users u
You can use a CASE statement to return different columns based on criteria. Here's how you can do it: SELECT l.company_name, CASE WHEN user_choice = 'cab' THEN l.price_cab WHEN user_choice = 'price' THEN l.price_seat END as price from login l JOIN users u
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "mysql, sql" }
Rails how to get an array parameter single quoted and comma seperated in a query. Rails 2.35 I'm may be wrong but I thought with an array in a paramater, rails was suppose to comman seperate the array when used like below for a query. I know I can break the param out into a single quoted and comma seperated string. I was just curious is this can be automatically done by Rails and how I might go about it if so. Thank You **Parameters being sent:** Parameters: {"method"=>:get, "id"=>["3", "1", "4"]} **The SQL statement in the controller I'm using:** sql = "SELECT user.user_alias from users " + "where user.id in (#{params[:id]}) " + "AND user.user_alias is NOT NULL " aliases = User.find_by_sql(sql) **The SQL string Rails outputs (the query results in the IN statement are just all togather '314):** SELECT User.user_alias from lte_users where user.id in (314) AND user.user_alias is NOT NULL
**NEVER** , never, do string concatenation in a SQL query, as someone might use this to perform an **SQL Injection** attack on your webapp. You should be doing it like this: sql = %Q{SELECT user.user_alias from users where user.id in (?) AND user.user_alias is NOT NULL } aliases = User.find_by_sql([ sql, params[:id] ])
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ruby on rails" }
Exterior powers of standard representation of $\mathfrak{sp}(2d, \mathbb C)$ Let $\mathfrak{sp}(2d, \mathbb C)$ be a symplectic Lie algebra over $\mathbb C$. Let $V$ be the standard representation of $\mathfrak{sp}(2d, \mathbb C).$ I'm looking for a reference in which exterior powers of standard representation $\Lambda^k V$ are decomposed into a sum of irreducible representations of $\mathfrak{sp}(2d, \mathbb C)$.
Let $\varpi_1$, $\ldots$, $\varpi_d$ be the fundamental highest weights (with the usual labeling, $\varpi_d$ corresponding to a simple long root). One can show that the contraction map $\varphi: \wedge^k(V) \rightarrow \wedge^{k-2}(V)$ is surjective and that $\operatorname{Ker} \varphi$ is irreducible of highest weight $\varpi_k$. It follows that the composition factors of $\wedge^k(V)$ have highest weights $\varpi_{k-2i}$ for $0 \leq i \leq k/2$. (Here $\varpi_0 = 0$). For details, see for example §17.2 in the representation theory book by Fulton and Harris.
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "reference request, representation theory, lie algebras" }
How to pad arrays by a variable amount? I am trying to make multiple PNG files the same size. I do not want to alter the image, simply add borders around all of them until they are all the same size as the largest PNG file. The language is Python. It is a large amount of files so I am unable to do this manually. I am using a for loop. I already know what the maximum size is: (100, 441). maxImage represents this. images is the name of my arrays. for n in range(0, len(images - 1)): stat_length = maxImage - len(images[n]) hello = py.pad(images[n], 1, 'constant') print (hello[n].shape) This is my code. I would like to know how to pad by a variable amount.
This works for me import numpy as np a = [[1, 2, 3, 4, 5],[6,7,8,9,10]] p = np.shape(a) max_h = 100 max_w = 441 pad_h = (max_h-p[0])//2 pad_w = (max_w-p[1])//2 print(np.pad(a,((pad_h,pad_h),(pad_w,pad_w)),'constant', constant_values=(0)))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, arrays, padding" }
POLLY Nuget Package WaitAndRetryAsync Method I am using Polly nuget package to utilize its Retry feature for webAPI/WCF calls in my project. I am just curious to know what is maximum duration of wait we can give for `WaitAndRetryAsync` method?
Polly imposes no limit on the wait in wait-and-retry. The maximum duration of wait you can specify is therefore `Timespan.MaxValue` (which is probably more than you need ;~).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "polly" }
Elegant way to log actions? Say you have an application with a series of actions. How would you write it such that actions are logged when they are triggered? 1. Use a Template pattern. 2. Use AOP. 3. Use a Listener and Events. 4. Use a combination of the above. 5. Something else (explain).
I'd vote for AOP for the sake of eliminating redundancy, but only if there's room for AOP in your project. You can have custom logging using a logging library from your methods elsewhere in your project, but in a particular component where you hold many similar classes and want to log similar things for all of them, it can be painful to copy/paste and make sure everyone knows how to log. EDIT: regarding the other enumerated approaches, I think the advantage of AOP would be that it doesn't require you to design your code (template methods or events) specifically for this topic. You usually don't lose any of the code flexibility when spotting cross-cutting concerns and treating them as such, as opposed to redesigning a whole class hierarchy just to make use of consistent logging.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "java, swing, logging, action" }
how to create a grid view with only ONE image from nodes containing multiple images? I have Nodes that have an Image field that can have any number of Image Fields. I want to create a Grid View in which I should only a single IMage field (can be the first one or any one actually). Attached image shows my Views settings that shows multiple images - how do I limit to picking a single image from each node for the grid views display? (I am in DRUPAL 6) !Views Screen Display for Grid View
You can do it easily, by clicking the **"Image Field"** and check the **Group Multiple Values** and set **show values** as **1** and set **starting from** 0 see the image below !enter image description here
stackexchange-drupal
{ "answer_score": 4, "question_score": 0, "tags": "6, views, media" }
How to override an app in Django properly? I'm running Satchmo. There are many apps and I've changed some of the source in the Product app. So my question is how can I override this properly because the change is site specific. Do I have to copy over the whole Satchmo framework and put it into my project or can I just copy one of the apps out and place it in say _Satchmo>App>Products_? (Kinda like with templates) Thanks
What I have done which works is to copy the application that I have changed. In this case **_satchmo\apps\product_**. I copied the app into my project folder Amended my _setting.py_ `INSTALLED_APPS` from `'product',` to `'myproject.product',` This now carries the changes I've made to this app for this project only and leaves the original product app untouched and still able to be read normally from other projects.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "python, django, satchmo" }
Customizing Flex Slider plugin I've looked a looked and looked for the perfect rotating banner for my website I am creating and I found flex slider, of which I love as it gives you the circled just underneath and the left and right arrows as well. The option for face or slide is what I was looking for too, however I need a plugin that allows the user to upload an image to the banner like Useful banner Manager. (I'm not using UBM as I don't what each banner image to fade to white and then to the next image, but that's how it acts). Does anyone know a great rotating banner plugin that is easy to follow for wordpress newbies (as this will be integrated into the websites I create for clients) either free or premium? OR do you know how I might just add the upload option to the flex slider plugin?
If you know the data format that the Flex Slider uses you can simply create a custom post type called 'Banner', restrict the various stock metaboxes, leaving say, only the editor and media upload. Then your clients can simply create new 'banners' by creating a new banner post, and uploading its associated image. This is a nice, simple and easy to understand interface for clients, making it easy for them to add, remove, edit banners. Then simply do a get_posts on your banners and provide the Flex slider with data in a format it expects. This has the advantage of not requiring a plugin to create, which is useful if you are distributing themes. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "wordpress" }
How do I get this value from NSMutableArray? this is a fairly simple question. I am using a web service in my app, and the server returns a JSON string to communitcate with the app. Here is an example response: { repsonse = { message = "Message"; "response_id" = X; }; } Using objective-c I want to be able to get what "response_id" is but I am unsure on how to do this. Here is my code: NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil]; // Get json value NSLog(@"%@", json); if([json[@"response"][@"response_id"] isEqualToString:@"1"]){ return YES; }else{ return NO; } Each time the isStringEqualTo method returns false. Could somebody help me? Thanks, Peter
You have two problems: 1. `json` needs to be declared as an `NSDictionary`, not `NSMutableArray` since the JSON root is a dictionary, not an array. And you get back an immutable dictionary, not a mutable one. 2. The JSON has a key of "repsonse", not "response".
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "objective c, json, nsmutablearray, nsarray" }
Open file has data but reports back length 0 in python I must be missing something very simple here, but I've been hitting my head against the wall for a while and don't understand where the error is. I am trying to open a csv file and read the data. I am detecting the delimiter, then reading in the data with this code: with open(filepath, 'r') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read()) delimiter = repr(dialect.delimiter)[1:-1] csvdata = [line.split(delimiter) for line in csvfile.readlines()] However, my csvfile is being read as having no length. If I run: print(sum(1 for line in csvfile)) The result is zero. If I run: print(sum(1 for line in open(filepath, 'r'))) Then I get five lines, as expected. I've checked for name clashes by changing csvfile to other random names, but this does not change the result. Am I missing a step somewhere?
You need to move the file pointer back to the start of the file after sniffing it. You don't need to read the whole file in to do that, just enough to include a few rows: import csv with open(filepath, 'r') as f_input: dialect = csv.Sniffer().sniff(f_input.read(2048)) f_input.seek(0) csv_input = csv.reader(f_input, dialect) csv_data = list(csv_input) Also, the `csv.reader()` will do the splitting for you.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, csv" }
Adding cells to change in solver I have a range from A1 to J1 that I would like to change using solver to optimize a certain value. Usually, I do the following: SolverOK ByChange:=Range("A1:J1") However, my program randomly fills in some cells in the range A1:J1 with fixed numbers that must remain there. How do I only add the empty cells to the SolverOk ByChange:= argument? A1 B1 C1 D1 E1 F1 G1 H1 I1 J1 0 1 1 0 For example I might have the above setup and I would only want to add cells B1, D1, E1, G1, H1, and I1 to the solver change cells argument. I tried looping through the empty cells and adding them to solver but that didn't work because only the last blank cell would be added and not the other ones. Any help would be really appreciated. Thanks so much.
You can capture any truly blank cells in a range (using `SpecialCells(xlBlanks)`) then feed this address into the Solver VBA (`ByChange:=rng1.Address`), ie sample code below which runs if there are blank cells Sub Macro1() Dim rng1 As Range On Error Resume Next Set rng1 = Range("A1:J1").SpecialCells(xlBlanks) On Error GoTo 0 If Not rng1 Is Nothing Then SolverOk SetCell:="$B$2", MaxMinVal:=1, ValueOf:=0, ByChange:=rng1.Address, Engine:= _ 1, EngineDesc:="GRG Nonlinear" End If End Sub
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "excel, vba" }
Mysql group and sum based on condition Is there a way to group and sum columns based on a condition? id | code | total | to_update 1 | A1001 | 2 | 0 2 | B2001 | 1 | 1 3 | A1001 | 5 | 1 4 | A1001 | 3 | 0 5 | A1001 | 2 | 0 6 | B2001 | 1 | 0 7 | C2001 | 11 | 0 8 | C2001 | 20 | 0 In this example I want to group and sum all rows which share the same `code` where at least one row has an `to_update` value of 1. Group by `code` column and sum by `total`. The example above would result in: code total A1001 12 B2001 2
You need to have a subquery that gives you all codes that have at least 1 record where update=1 and you need to join this back to your table and do the group by and sum: select m.code, sum(total) from mytable m inner join (select distinct code from mytable where `to_update`=1) t on m.code=t.code group by m.code Or you can sum the to_update column as well and filter in having: select m.code, sum(total) from mytable m group by m.code having sum(to_update)> 0
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "mysql, sql" }
Installing windows 10 again on a pre-installed system I have purchased a HP laptop with Windows 10 home single language OEM pre-installed on it,However I've formatted my system without making recovery disks.I've downloaded Windows 10 ISO from Microsoft's site and burn it on a dvd and did a fresh install on my system.It gets activated digitally on my system.Is it legal to use this type of fresh installation or do I have to face problems in updates from HP and Microsoft.I went through superuser post Reinstall Windows 10 using ISO onto new SSD without losing activation status I've not changed the hard disk.It's all about a fresh install.
It's not legal or illegal, as there are no laws involved. The correct question would be, are you acting within in the bounds of the license agreement, and within your rights to install the software on your device? The answer is yes - absolutely. You shouldn't face any problems whatsoever.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "windows 10" }
Why do Ethan and Julia just prefer to see each other from long distance rather than meeting each other? In the last scene of _Mission Impossible: Ghost Protocol_ , after Ethan tells William that Julia is alive, Ethan prefers to have a look of Julia only from the distance. While Julia after finding that Ethan is there and he is looking at her, does not prefer to meet him and they just give a smile to each other and then Julia steps into a shop leaving Ethan behind. Why do they not meet each other?
First Julia waves bye to Ethan before going in to shop. Second, as far as I think, they both have chosen to stay separated for Julia's safety. Also Ethan only tells the secret to William to clear the misunderstanding, not any other member of his team. If they meet, it might have possible that MI agency or someone else might find her.
stackexchange-movies
{ "answer_score": 2, "question_score": 4, "tags": "mission impossible, mission impossible ghost protocol" }
2 divs fill horizontal space I have 2 div's in parent wrapper. I would like to make the following: 1. these 2 divs share 100% space in width, so there is no gap between them, everything is red color. 2. When you scale the wrapper down, div b falls into new line below div a (this behaves as it should), but in this case I want both divs to be 100% width, so they make 2 lines of red color. Is it possible to do this just with css (no tables!) and no additional elements? Making wrapper background color red to compensate for this is not the solution. <div class="wrapper"> <div class="a">left</div> <div class="b">right</div> </div> <
Just change the CSS to `width:50%;` for both `a` and `b`, add a media query to set them to 100% at smaller viewports. .wrapper{ position: relative; max-width: 400px; height:30px; background-color: #fff; } .a{ float: left; background-color: red; text-align: left; width:50%; height:30px; } .b{ float: right; background-color: red; text-align: right; width:50%; height:30px; } @media screen and (max-width: 500px) { .a, .b { width: 100%; } } <div class="wrapper"> <div class="a">left</div> <div class="b">right</div> </div>
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "html, css, responsive design" }
Como sortear elementos (selecionar elementos aleatoriamente) de um vetor? Como posso sortear elementos (selecionar elementos aleatoriamente) de um vetor no `R`? Por exemplo, quero sortear elementos deste vetor: numeros = c(1,2,45,63,29,100,999,23.45,76.1)
Para sortear, por exemplo, dez valores do vector em causa de forma pseudo-aleatória, pode-se fazer o seguinte: numeros <- c(1,2,45,63,29,100,999,23.45,76.1) sample(numeros,size=10, replace=TRUE) Nota: `replace=TRUE` para permitir repetições e `replace=FALSE` caso contrário.
stackexchange-pt_stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "r" }
Rails: How to set the value of dropdown unordered list with data that is returned from database I am using Haml and have a form on the page with several input boxes and dropdowns. I am able to set the value of my input boxes like this: %input#txtBillingAddress(placeholder="Address" value="#{@vendor["billing_address"]}") I have this unordered list that is a dropdown: #ddlVendorPosition.wrapper-dropdown %span.selected Position %ul.dropdown %li Owner %li Manager %li Employee Is there a similar way for me to set the value of this dropdown? The params is: @vendor["position"] Thanks EDIT: I want to set the value with the returned data so that the form can be edited, if necessary.
This is what I have come up with: #ddlVendorPosition.wrapper-dropdown - if @vendor["position"] != "None" %span.selected #{@vendor["position"]} - else %span.selected Position %ul.dropdown %li Owner %li Manager %li Employee If there is not a value (saved as "None", apparently), the "Position" placeholder will show. Thanks.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, haml" }
REST framework for Vert.x using Javascript I recently started to use Node.js to develop a simple REST server for a TODO application using the restify framework. Now I want to rebuild my application using Vert.x with JS. Unfortunately, I could not find a REST framework for vert.x with JS (only one for Scala). Are there any good ones out there or is it generally a bad idea to develop something like that using Javascript or is it just that Vert.x is not that widely spread at the moment?
I don't really know what you really mean by "rest framework". I used Jersey in Java and I replaced it with the vert.x RouteMatcher -- In javascript would be var matcher = new vertx.RouteMatcher(); matcher.get('/uppercase/:name', function(request) { var name = request.params()['name']; request.response.end(name.toUpperCase()); }); vertx.createHttpServer().requestHandler(matcher).listen(80); Regards, Carlo
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, rest, vert.x" }
can't see my picture on the form - asp.net i add Image control to my WebForm. i insert picture to App_Data. i connect the picture to my Image control in the ImageUrl it seen like this: <asp:Image ID="Image1" runat="server" Height="94px" ImageUrl="~/App_Data/Tulips.jpg" Width="209px" /> in the design i see this picture, but when i run the project i dont see the picture. what can be the problem ?
App_Data is a special folder in ASP.NET that only must be used to store data and files that aren't intended to be accessed by end users (ie. via a web browser). Try to put your picture in another folder, ie. Images. See < for more info.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, asp.net" }
jQuery banner and Dropdown menu problem Hi I have a problem with jQuery banner and dropdown menu. The dropdown menu is behind the jQuery banner slider. Look for a sample here I tried z-index and position:absolute but I couldn't fix it.
tested in ie... you do have a problem, but it can be solved with the `z-index` property as shernshiou said. you should put this in a css file : #slider{ z-index : -1; } **UPDATE** In ie <= 8, you have to set the z-index for the submenu too (although it should be 0 by default), so, either add a class to every submenu which sets the `z-index` attribute higher than the slider's `z-index`, or you can do it dynamic with jquery : var newZIndex = ($('#slider').css('z-index') || 0) + 10; $('div[id^=menu_child]').css('z-index',newZIndex);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, css, z index, drop down menu, banner" }
Ambiguity of meaning of for in this sentence > Learning everying at once is too confusing. The post concludes with tips for what to learn next. Last sentence is in trouble. I think for in the sentence could have two meanings. To clearify two mearnings: 1. Tips that recap what you've been learning on the post is provided at the end of the post, so that you are not perplexed with the things you will learn on the next. (organizaing your mind with the tips before the next) 2. Tips about what to learn next is provided at the end of the post. Which meaning is correct? Or Both are not valid?
Number 2 is correct. "tips for what to learn next" are usually not a recap, they simply point you to other areas or subjects that you should learn next. These tips are some sort of a guide that leads you from one part to the next.
stackexchange-english
{ "answer_score": 0, "question_score": 0, "tags": "meaning in context, ambiguity" }
Select all the categories and for each category last 5 post I have 2 table one categories and one posts. How do I select all the categories and last 5 post from each. I have this code so far include("includes/connect.php"); $get_cats = "select * from categories"; $run_cats = mysqli_query($con,$get_cats); while ($cats_row=mysqli_fetch_array($run_cats)) { $cat_id=$cats_row['cat_id']; $cat_title=$cats_row['cat_title']; echo '<div class="col-md-4 col-sm-6 col-xs-12">'; echo '<ul class="list-group ">'; echo '<li class="list-group-item table-header"><strong>'; echo $cat_title; echo '</strong><span class="badge badge-color">12</span></li>'; echo '</ul>'; echo '</div>'; } Structure of table categories cat_id cat_title 1 sports 2 news 3 bla 4 bla In post I have a categ_id.
you can run your second query inside above while loop for getting category post data while ($cats_row=mysqli_fetch_array($run_cats)) { $cat_id=$cats_row['cat_id']; $sql2="select * from post where cat_id=".$cat_id." order by id desc limit 5"; $second2=mysql_query($sql2); while (post_row=mysqli_fetch_array($second2)) { // do your stufff } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, sql" }
detect if views are overlapping I have problem with drawing views on another size screens! I need method which has two parameters of View type. And return true if first view overlapping on second view, and false in another case! !enter image description here and !enter image description here
Berserk thanks you for help! After some experiments I wrote method which detect view is overlapped or not for my case! private boolean isViewOverlapping(View firstView, View secondView) { int[] firstPosition = new int[2]; int[] secondPosition = new int[2]; firstView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); firstView.getLocationOnScreen(firstPosition); secondView.getLocationOnScreen(secondPosition); int r = firstView.getMeasuredWidth() + firstPosition[0]; int l = secondPosition[0]; return r >= l && (r != 0 && l != 0); }
stackexchange-stackoverflow
{ "answer_score": 24, "question_score": 21, "tags": "android, view" }
get the name of the property not the value I am using core data and have been using code like this: [self.form setValue:self.comments.text forKey:@"comments"]; I want to put code like this into a loop, all my coredata names are the same as the property name. How can I say `forKey:self.comments.name` and get the same outcome as above or something like that? EDIT: If this is not possible, is there another way to set a ton of values into coredata from properties? I have 50+ attributes and properties alike that need to be set and would like to avoid using what im doing now.
If you really want it, you may use these functions from objc/runtime.h: objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount) // To get properties declared by a class. const char *property_getName(objc_property_t property) // To get the name of one property Something like this: unsigned int propCount = 0; objc_property_t *properties = class_copyPropertyList([self class], &propCount); for(int idx = 0; idx < propCount; idx++) { objc_property_t prop = *(properties + idx); NSString *key = @(property_getName(prop)); NSLog(@"%@", key); }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ios, core data" }
Underscore contains based on object property I would like to use Underscore.js to determine if an instance of an object is present in an array. An example usage would be: var enrollments = [ { userid: 123, courseid: 456, enrollmentid: 1 }, { userid: 123, courseid: 456, enrollmentid: 2 }, { userid: 921, courseid: 621, enrollmentid: 3 } ] I want to be able to identify unique an enrollment where the userid and courseid are the same. So basically, given a list of enrollments I can remove duplicates based on matches to the userid and courseid, but not the enrollment id.
You can use the `filter` method from Underscore: function contains(arr, userid, courseid){ var matches = _.filter(arr, function(value){ if (value.userid == userid && value.courseid == courseid){ return value; } }); return matches; } contains(enrollments, 123, 456);
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "javascript, underscore.js" }
SQL Server 2008 integrated security Anybody please tell, from where I can download sqljdbc_auth.dll for a 32 bit OS.
Have you tried checking the `installation directory\sqljdbc_version\language\auth\` directory of the machine for the file? As directed here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server, sql server 2008, jdbc" }
Supplies and support on a long-distance walk I've travelled long distances, but I've always had my backpack and used transport, and can get by that way fairly easily in general. I've been reading about long-distance walkers - people who walk across America in 87 days, for example. I'm assuming they can't carry a 15kg pack on their backs this whole way, or food and drink - do they usually have support? Put it this way, if I (or you) were to do it, what would one need to achieve a long-distance walk (aside from being fit and slightly mad :)), and how would you ensure you had enough supplies?
From my experience it is practically infeasible to carry food supplies for more than half a week and water supplies for more than a day. Unless you have porters or mules. Freeze-dried food can furthermore reduce the weight you have to carry. There are a lot of people walking the Way of st. James which takes about one month. The best prepared have less than 5kg backpacks. Everything around 10kg or more is going to spoil your walk. All you carry is a small sleeping bag (100-300g in summer), one change of clothes, flip-flops, toothbrush, raincoat, snack for one day and water. Everything else you either do not need or buy on the way. You can find a lot of gear left somewhere on the way :)
stackexchange-travel
{ "answer_score": 11, "question_score": 13, "tags": "food and drink, gear, clothing, walking, long term" }
Should I test private methods or only public ones? I have read this post about how to test private methods. I usually do not test them, because I always thought it's faster to test only public methods that will be called from outside the object. Do you test private methods? Should I always test them?
I do not unit test private methods. A private method is an implementation detail that should be hidden to the users of the class. Testing private methods breaks encapsulation. If I find that the private method is huge or complex or important enough to require its own tests, I just put it in another class and make it public there (Method Object). Then I can easily test the previously-private-but-now-public method that now lives on its own class.
stackexchange-stackoverflow
{ "answer_score": 383, "question_score": 396, "tags": "unit testing, testing, language agnostic" }
Colon (:) instead of period (.) after author with biblatex, alphabetic With `biblatex`, `alphabetic` style, I have > <author>. <title> But I want to have a colon ":" instead of the period "." after the author: > <author>: <title> What do I have to change?
Put the following in your preamble after having loaded **biblatex** \renewcommand{\labelnamepunct}{\addcolon\space} (This is better than `\renewcommand{\labelnamepunct}{:\addspace}`, as remarked by domwass.) * * * **Update** The `\labelnamepunct` command is currently deprecated and the context dependent \DeclareDelimFormat[bib]{nametitledelim}{\addcolon\space} should be used. However, old styles _may_ still be using `\labelnamepunct`, so the original answer has been kept. (Thanks to moewe for recalling to update.)
stackexchange-tex
{ "answer_score": 22, "question_score": 20, "tags": "biblatex, punctuation" }
Spark merge rows in one row I have the following Dataframe: ![enter image description here]( #+-----------------------------+--------+---------+---------+ #|PROVINCE_STATE|COUNTRY_REGION|2/1/2020|2/10/2020|2/11/2020| #+--------------+--------------+--------+---------+---------+ #| -| Australia| 12| 15 | 15| #+--------------+--------------+--------+---------+---------+ I need to merge all rows in one, and for dates to have sum based on COUNTRY_REGION. The thing is that I have many more columns and no idea how to do it dynamically. Tried groupBy, but still doesn't work. Thanks.
If your first two columns are always province and state and other **n** -columns are dates you can try below (Scala): import org.apache.spark.sql.functions._ val dateCols = df.columns.drop(2).map(c => sum(c).as(c)) // select all columns except first 2 and perform sum on each of them df.groupBy('country_region).agg(dateCols.head,dateCols.tail:_*).show() python version: import pyspark.sql.functions as f dateCols = [f.sum(c) for c in df.columns][2:] # select all columns except first 2 and perform sum on each of them df.groupBy('country_region').agg(*dateCols).show() output: +--------------+--------+---------+---------+ |country_region|2/1/2020|2/10/2020|2/11/2020| +--------------+--------+---------+---------+ | aus| 12| 15| 15| +--------------+--------+---------+---------+
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "sql, scala, apache spark, pyspark, apache spark sql" }
convert list of values in dictionary to key pair value Hi iam having below dictionary with values as list a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']} iam just expecting output like this: a=[{"Name":"ANAND",'Place':'Chennai','Designation':'Developer'},{"Name":"kumar",'Place':'Banglore','Designation':'Sr.Developer'}]
this should do the trick : a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']} ans = [] num_of_dicts = len(list(a.values())[0]) for i in range(num_of_dicts): ans.append({key:val[i] for key,val in a.items() }) print(ans) output: [{'Name': 'ANAND', 'Place': 'Chennai', 'Designation': 'Developer'}, {'Name': 'kumar', 'Place': 'Banglore', 'Designation': 'Sr.Developer'}] if you have any questions feel free to ask me in the commennts :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python" }
how to pass asc desc as params in python psycopg2 raw sql execution? i have a sample query template to accept dynamic parameters to execute: ps_conn = psycopg2.connect(...) ps_cursor = ps_conn.cursor() ps_cursor.execute(''' SELECT * FROM "posts" ) ORDER BY "posts"."rate" %s, "posts"."date_created" ASC LIMIT 1 ''', ["DESC"]) as you can see i wanna pass DESC dynamically to orderby the results , but the above code keep throwing the error InvalidSchemaName > schema "posts" does not exist LINE 11:) ORDER BY "posts"."rate" 'DESC', it passes the DESC as 'DESC' to the sql . any opinion how to perform this functionality so i can pass ordering type dynamically?
ps_conn = psycopg2.connect(...) ps_cursor = ps_conn.cursor() ps_cursor.execute(''' SELECT * FROM "posts" ORDER BY "posts"."rate" {order}, "posts"."date_created" ASC LIMIT %s '''.format(order='desc'),(1,))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, sql, database, postgresql, psycopg2" }
QGIS 3.8 Python merge files For a merge operation I need a list of all my layers in the TOC with path and filename. How can I achieve that? layers = QgsProject.instance().mapLayers() # dictionary myLyrList[] for layer in layers.values(): print(layer.name()) #Here I need a List of the my layers in the toc with the path and the filename processing.run("native:mergevectorlayers", {'LAYERS':['/home/lissiklaus/Downloads/2.shp|layername=2','/home/lissiklaus/Downloads/3.shp'],'CRS':QgsCoordinateReferenceSystem('EPSG:31468'),'OUTPUT':'TEMPORARY_OUTPUT'})
You can do that with following modifications in your script. layers = QgsProject.instance().mapLayers() # dictionary for layer in layers.values(): print(layer.name()) list_layers = list(layers.values()) crs = list_layers[0].crs() #Here I need a List of the my layers in the toc with the path and the filename processing.runAndLoadResults("native:mergevectorlayers", {'LAYERS':list_layers, 'CRS':crs, 'OUTPUT':'TEMPORARY_OUTPUT'}) I tried above script out and it worked as expected.
stackexchange-gis
{ "answer_score": 3, "question_score": 3, "tags": "qgis 3, pyqgis 3, python 3" }
ajax in each time or load everything at once Imagine that you have several links on a page. When you clicked, a div gets updated via AJAX. The updated div includes data from the database. According to this scenario, every time a link is clicked, the date is grabbed from the database and injected into the div. Would you... 1. support this scenario or... 2. would load each link's content in several hidden divs and display relevant div on each link click. This way the ajax call is only called once..
depends... is the content going to change? If so... Ajax every time. If not? Ajax once(or zero times if posible)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery, css, ajax, dom" }
How to exclude the TR that contains the TD with a specific class I have a function in which I take the first TR of my table and then I take all the TD of this TR. Now I need to modify this function: when I take the first TR I need to check that if all the TD of my TR have the class 'HD1' I need to take the second TR of the table. I put my function below. Thanks in advance. function getColumnsIdx(id) { var header = $("table#" + id + " thead tr:eq(1)"); var header_fields = $("td", header); var header_idx = new Object(); header_fields.each(function(idx, val) { var $$ = $(val); var key = $$.text(); header_idx[key] = idx; }); return header_idx; }
You can look for the first `td` without that class, and then take its parent: var header = $("table#" + id + " thead tr td:not(.HD1):eq(0)").parent(); This could, however, result in getting the third/fourth/etc row. If you must always return the second row, even if those cells also all have the HD1 class: var header = $("table#" + id + " thead tr:eq(0)"); var header_fields = $("td", header); if (header_fields.length && header_fields.length == header_fields.filter(".HD1").length) { header = header.next(); header_fields = $("td", header); } Note: `:eq()` uses a zero-based index, so use `eq(0)` to select the first element.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, jquery" }
print SyntaxError: invalid syntax ¡Buenas! Actualmente me encuentro aprendiendo Python y en una aplicación sencilla de práctica me he encontrado el siguiente error: File "ruta_fichero", line 9 print(num2, "es menor que ", str(num1)) ^ SyntaxError: invalid syntax El código que he escrito es el siguiente: num1 = int(input("Escribe un número: ")) num2 = int(input("Escribe un número mayor que ", str(num1), ":")) while num2 > num1: num1 = num2 num2 = int(input("Escribe un número mayor que ", str(num1), ":") print(num2, "es menor que ", str(num1)) ¿Sabéis donde puede estar el error de sintaxis? ¡Muchas gracias!
Muchas veces el punto donde te marca el error no es donde está, sino donde se detecta. num2 = int(input("Escribe un número mayor que ", str(num1), ":") print(num2, "es menor que ", str(num1)) En la línea anterior abres tres paréntesis y cierras dos. Como no sabe que pasa, el compilador sigue procesando el fichero, intentando completar la expresión que usará en el `int()`, hasta que se encuentra con un fragmento de código que no puede encajar en lo que está haciendo (el `print(num2..`) y allí es donde marca el error.
stackexchange-es_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, python 3.x" }
How do I write below code using dictionary comprehension Need help to optimize below python code using dictionary comprehension. How can modify my code in such a way that using python special features container_status = {} active=[] inactive=[] not_found=[] if containers: for container in containers: inspect_dict = cli.inspect_container(container) state = inspect_dict['State'] is_running = state['Status'] == 'running' if is_running: active.append(container) else: inactive.append(container) container_status= {'active':active,'inactive':inactive,'not_found':not_found } print(container_status)```
You can try this container_status = {} active=[] inactive=[] not_found=[] inspect_dict = cli.inspect_container('festive_bell') if containers: ls_to_append = active if inspect_dict['State']['Status'] == 'running' else inactive for container in containers: ls_to_append.append(container) container_status= {'active':active,'inactive':inactive,'not_found':not_found } print(container_status) Note that each time that it's run it will show all the containers as active or inactive since it's depends on `cli.inspect_container('festive_bell')` results all of them have the same results
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, list, dictionary, optimization, dictionary comprehension" }