qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
22,615,976
I have the following angular service. ``` angular.module('myApp') .service('StatusService', function StatusService() { var statusService= { show: 'off', on: function() { this.show = 'on'; }, off: function() { this.show = 'off'; } }; return statusService; }); ``` Which is injected into a controller, and its on function is invoked, like this: ``` angular.module('myApp') .controller('aController', function (StatusService) { StatusService.on(); }) ``` But I get the following error. ``` TypeError: Object #<Object> has no method 'on' ```
2014/03/24
[ "https://Stackoverflow.com/questions/22615976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1323435/" ]
I think this will be faster. It's set-based and doesn't use a cursor. ``` DECLARE @return VARCHAR(255) = '' SELECT @return = @return + CAST(quote_ln_no AS VARCHAR) + ',' FROM dbo.quote_line_bom WHERE quote_no = @quote_no AND component_mat_no = @mat_no AND quote_ln_no IS NOT NULL GROUP BY quote_ln_no ORDER BY quote_ln_no IF LEN(@return) > 0 set @return = SUBSTRING(@return, 1, LEN(@return)-1) SELECT @return --This is for a user defined function, right? --RETURN @return ```
You can just use `COALESCE` instead of a cursor: ``` declare @return varchar (255) = '' select @return = coalesce(@return + ' ', '') + quote_ln_no FROM dbo.quote_line_bom WHERE quote_no = @quote_no AND component_mat_no = @mat_no ORDER BY quote_ln_no ``` You can join to it however you need to, I just used cross apply because I'm lazy. Here's a very crude example: [SQLFiddle](http://sqlfiddle.com/#!6/88fa4/8) EDIT: I wasn't clever enough to work out how to use the coalesce in a subquery, but I did work out how to do it using an XML method. Your query will read something like this: ``` select <some stuff> from <some tables> cross apply (select quote_ln_no + ' ' FROM dbo.quote_line_bom WHERE quote_no = @quote_no AND component_mat_no = @mat_no ) t1 (quote_ln_no) ... ``` Another crude example: [XML example](http://sqlfiddle.com/#!6/a106c/14)
4,192,227
I am asking a very basic question which confused me recently. I want to write a Scala For expression to do something like the following: ``` for (i <- expr1) { if (i.method) { for (j <- i) { if (j.method) { doSomething() } else { doSomethingElseA() } } } else { doSomethingElseB() } } ``` The problem is that, in the multiple generators For expression, I don't know where can I put each for expression body. ``` for {i <- expr1 if(i.method) // where can I write the else logic ? j <- i if (j.method) } doSomething() ``` How can I rewrite the code in Scala Style?
2010/11/16
[ "https://Stackoverflow.com/questions/4192227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241824/" ]
The part ``` for (j <- i) { if (j.method) { doSomething(j) } else { doSomethingElse(j) } } ``` can be rewritten as ``` for(j <- i; e = Either.cond(j.method, j, j)) { e.fold(doSomething _, doSomethingElse _) } ``` (of course you can use a yield instead if your do.. methods return something) Here it is not so terrible useful, but if you have a deeper nested structure, it could...
The conditions specified in a Scala for operation act to filter the elements from the generators. Elements not satisfying the conditions are discarded and are not presented to the yield / code block. What this means is that if you want to perform alternate operations based on a conditional expression, the test needs to be deferred to the yield / code block. Also be aware that the for operation is relatively expensive to compute (currently) so perhaps a simpler iterative approach might be more appropriate, perhaps something like: ``` expr1 foreach {i => if (i.method) { i foreach {j => if (j.method) doSomething() else doSomethingElseA() } } else doSomethingElseB() } ``` Update: If you must use a for comprehension and you can live with some restrictions, this might work: ``` for (i <- expr1; j <- i) { if (i.method) {if (j.method) doSomething() else doSomethingElseA()} else doSomethingElseB() } ```
12,373,148
I am considering to use an enum with a static initializer like this: ``` public enum MyEnum{ ... private static HashMap<X, Y> features; static { features.put(X, new (Y)); } ... } ``` Is the HashMap going to be reinitialized every time I need a value from it?
2012/09/11
[ "https://Stackoverflow.com/questions/12373148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/990616/" ]
No, static block will be executed only once while class initialization. It won't execute on each call to retrieve.
No, just once. BTW: [Guava ImmutableMap](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html) can help: ``` private static Map<X, Y> features = ImmutableMap.of(X1, Y1, X2, Y2...)); ``` Benefit: * No need static block * One line code * ImmutableMap means safer, if you just need an immutable Map
31,870
Let's face it: You are *The ultimate God* You created the universe, including its physical laws. You created the stars and alligned them in specific order. You created the solar system where the planets are in order as you wish. You brought life to one (or more) planet(s) in that solar system and did fiddle with evolution for so long it produced intelligent life. Maybe you even created other Gods and Goddesses for that intelligent species to believe in. Or you let them all be just atheists. But there is one ultimate truth: In Worldbuilding, you are the ultimate God. Well, at least in meaning: The one who created it all, the one who knows everything about the universe and the one who has ultimate power about that universe. In my own case, I am playing with the idea of admitting the idea by having only one God in my world. Myselves. But the thing is, I am benevolent creator. I would like people to have the right to completely disbilieve into me and reject the idea of ultimate creator of All. On the other hand, I would like to keep believers happy and give them signs that I exist (last time I checked, I did exist). How can I achieve this task?
2015/12/20
[ "https://worldbuilding.stackexchange.com/questions/31870", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2071/" ]
**Note: Many theologians, priests, rabbis, imams, and believers in God can argue that your situation mirrors life right now. I feel the Worldbuilding Stack Exchange is not the place for this religious discussion. This answer will attempt to answer your question and nothing more; rephrasing this question and posting on Mi Yodeya, Christianity, or Islam SE may yield more insight into this.** It seems you have several attributes for your deity that you want to enforce. Among which: * Freedom to choose and of belief is granted to intelligent beings * Allow for reasonable deniability of the creator's existence (I should mention that the groups mentioned in the starting note may say things about *why* it is this way, but that's not here nor there for the scope of this answer.) This is actually easy; this deity ought to give believers miracles which is in line with their faith and that god's will. However: * These "miracles" need not be supernatural occurrences, but unexpected or direly needed by your believers. * To retain reasonable deniability, not *everything* should go their way. That is, the more subject believers are to forces and events that occur to everyone, the better. The key here is that the miracles in question can be explained by "scientific" or "rational" thought. If a person can just as easily look at isolated incidents and say "that was chance" or "it just happened to be that way" as say "that was my god," then people can argue for and against the existence of that god. This can result in the same problem posed by the [Bielefeld Conspiracy](https://youtu.be/XvHcZciihJw), except it's a deity and not a town in Germany; how do you prove that something exists without witnessing it? **What About Science?** If this god wants to avoid being exposed by scientific inquiry, you simply need to avoid repeatable responses and bring your miracles about by mundane, natural-law abiding means. My wife is a grade school science teacher, and the public-school approved curriculum teaches that [things which cannot be repeated are not fit for scientific inquiry.](https://en.wikipedia.org/wiki/Reproducibility) (As another side note; lack of repeatability may be why psychologists have [such trouble replicating results](http://www.sciencemag.org/content/349/6251/aac4716).) **Reliance On Deniability** Of course, you shouldn't ever discount people's ability to deny. Some people just don't seem to accept some things even though it stares them in the face. People can by annoyingly or unreasonably skeptical, especially when suffering an [existential crisis](https://en.wikipedia.org/wiki/Existential_crisis). After all, if you're unsure if you exist, how can you determine if something else does? Also, remember the Bielefeld Conspiracy! Non-believers can engage in many of the same type of arguments for the non-existence of deity as well as Bielefeld. Maybe all the believers are in on some big trick against nonbelievers? Perhaps the miracles never happened! Pictures and other evidence can be falsified. The list goes on. (Also consider [Clark's third law](https://en.wikipedia.org/wiki/Clarke%27s_three_laws): "Sufficiently advanced technology is indistinguishable from magic." Maybe the believers or other miracle-workers used technology!) **In Conclusion** A deity must not do much to leave room for doubt; simply giving free will to its creations, working within natural law, and not publicly revealing itself may be enough.
This is perhaps less of an answer, and more, some thoughts to consider when attempting as you propose. The main difference between you, the World Builder, and any traditional idea of a god is the reason you are making the world and its peoples. A deity in your world would likely have in-world reasons to do what they are doing. You can write those in however you like, be they altruistic, malevolent, or benign. But you, the World Builder, despite how you might craft internal reasons for making the world and wanting to make people happy, you are from beyond that world. You are from a world in which you have your own mortal trials and issues. You are likely writing their world to be something enjoyable to read, which means intentionally creating conflicts that the people in that world will not enjoy. You are likely writing their world to appease some internal desires and fears of your own life. Furthermore, you do not know everything in their world like one of their deities supposedly would, you only know of it that which you have thus far created (and even then, you probably should check your notes from time to time to avoid retcon). You do not know a character's thoughts, you create their thoughts. Every character is, to some significant degree, an avatar of the World Builder. Even the atheists are the World Builder themselves, not believing in you because you decided they shouldn't.
1,351
I'm trying to translate a poem from English to German, and the missing line is: > > I've heard some talk, they say you think I'm fine. > > > I've rendered *They say you think I'm fine* as *Man sagt du liebst auch mich.* But I need something for *I've heard some talk*. Could I use a construction using the word *Gerücht*?
2011/06/13
[ "https://german.stackexchange.com/questions/1351", "https://german.stackexchange.com", "https://german.stackexchange.com/users/343/" ]
My proposal: > > Es gibt Gerüchte, ... > > > or > > Ich hab davon gehört, ... > > > An elegant translation for "they say" is "es heißt": > > Es heißt, du glaubst es gehe mir gut. > > >
> > Es heißt,.. > > > I consider a good approach There is also > > Man munkelt... > > > and also one might use > > Sie sagen... > > > for *I've heard some talk, they say..* which implicates the speaker heard it by someone, somehow. `Sie` does not need to be determined more closely.
52,901,324
New to code coverage, would like to have some insights... ``` public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Person other = (Person) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.email == null) ? (other.email != null) : !this.email.equals(other.email)) { return false; } if (this.age != other.age && (this.age == null || !this.age.equals(other.age))) { return false; } return true; } ``` How do I cover this in jcoco code coverage.
2018/10/20
[ "https://Stackoverflow.com/questions/52901324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8383210/" ]
To have this class 100% tested you should create a test for every `if` and `?:` operator. Every part of the code should be tested. For instance, the first `if (this == obj)`, you should have a test where you do ``` @Test public void testEqualsSameObj() { MyClass sut = new MyClass(); // sut == system under test assertTrue (sut.equals(sut)); } ``` And now make the next test for passing null: ``` @Test public void testEqualsNull() { MyClass sut = new MyClass(); // sut == system under test assertFalse (sut.equals(null)); } ``` And continue with the next condition, until you cover all branches in the code. You can take the `sut` from the method and store it in the test class as a member variable.
The equals could have 0% coverage because you might have not included the lombok.config file with with generated annotations as true. Set, config.stopBubbling = true; lombok.addLombokGeneratedAnnotation = true in lombok.config file
55,269,186
I am trying to make a function that takes an equation as input and evaluate it based on the operations, the rule is that I should have the operators(\*,+,-,%,^) **between** correct mathematical expressions, examples: ``` Input: 6**8 Result: Not correct ``` **Reason:** \* has another \* next to it instead of a digit or a mathematical expression ``` Input: -6+2 Result: Not correct ``` **Reason:** "-" was in the beginning and it didn't fall between two numbers. ``` Input: 6*(2+3) Result: Correct ``` **Reason:** "\*" was next to a mathematically correct expression "(2+3)
2019/03/20
[ "https://Stackoverflow.com/questions/55269186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234125/" ]
As mentioned in comments, this is called `parsing` and requires a grammar. See an example with [**`parsimonious`**](https://github.com/erikrose/parsimonious), a `PEG` parser: ``` from parsimonious.grammar import Grammar from parsimonious.nodes import NodeVisitor from parsimonious.exceptions import ParseError grammar = Grammar( r""" expr = (term operator term)+ term = (lpar factor rpar) / number factor = (number operator number) operator = ws? (mod / mult / sub / add) ws? add = "+" sub = "-" mult = "*" mod = "/" number = ~"\d+(?:\.\d+)?" lpar = ws? "(" ws? rpar = ws? ")" ws? ws = ~"\s+" """ ) class SimpleCalculator(NodeVisitor): def generic_visit(self, node, children): return children or node def visit_expr(self, node, children): return self.calc(children[0]) def visit_operator(self, node, children): _, operator, *_ = node return operator def visit_term(self, node, children): child = children[0] if isinstance(child, list): _, factor, *_ = child return factor else: return child def visit_factor(self, node, children): return self.calc(children) def calc(self, params): """ Calculates the actual equation. """ x, op, y = params op = op.text if not isinstance(x, float): x = float(x.text) if not isinstance(y, float): y = float(y.text) if op == "+": return x+y elif op == "-": return x-y elif op == "/": return x/y elif op == "*": return x*y equations = ["6 *(2+3)", "2+2", "4*8", "123-23", "-1+1", "100/10", "6**6"] c = SimpleCalculator() for equation in equations: try: tree = grammar.parse(equation) result = c.visit(tree) print("{} = {}".format(equation, result)) except ParseError: print("The equation {} could not be parsed.".format(equation)) ``` This yields ``` 6 *(2+3) = 30.0 2+2 = 4.0 4*8 = 32.0 123-23 = 100.0 The equation -1+1 could not be parsed. 100/10 = 10.0 The equation 6**6 could not be parsed. ```
Important to first mention that `**` stands for exponentiation, i.e `6**8`: 6 to the power of 8. The logic behind your algorithm is wrong because in your code the response depends only on whether the last digit/sign satisfies your conditions. This is because once the loop is complete, your boolean `correctsigns` defaults to `True` or `False` based on the last digit/sign. You can also use `elif` instead of nested `else` statements for cleaner code. Without changing your core algorithm, your code would like something like this: ``` def checksigns(equation): signs = ["*","/","%","^","+","-"] for i in signs: if i in equation: index = equation.index((i)) if (equation[index] == equation[0]): return "Not correct" elif (equation[index] == equation[len(equation) - 1]): return "Not correct" elif (equation[index + 1].isdigit() and equation[index - 1].isdigit()): return "Correct" else: return "Not correct" ```
61,898,211
I have a following testNg xml file. Can someone please advice how to create this dynamically using java. ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Suite"> <test name="Test"> <groups> <run> <include name="PrometheusHome" /> <include name="AlertMgrHome" /> </run> </groups> <classes> <class name="com.amex.eag.telemetry.testcases.PrometheusTests"/> <class name="com.amex.eag.telemetry.testcases.AlertManagerTests"/> </classes> </test> </suite> ```
2020/05/19
[ "https://Stackoverflow.com/questions/61898211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4284762/" ]
Adjusted core from [here:](https://seleniumtips2017.wordpress.com/2017/12/30/generating-dynamic-testng-xml-programmatically/) ``` public class DynamicTestNG { public void runTestNGTest(Map<String,String> testngParams) { //Create an instance on TestNG TestNG myTestNG = new TestNG(); //Create an instance of XML Suite and assign a name for it. XmlSuite mySuite = new XmlSuite(); mySuite.setName("Suite"); mySuite.setParallel(XmlSuite.ParallelMode.METHODS); //Create an instance of XmlTest and assign a name for it. XmlTest myTest = new XmlTest(mySuite); myTest.setName("Test"); //add groups myTest.addIncludedGroup("PrometheusHome") myTest.addIncludedGroup("AlertMgrHome") //Add any parameters that you want to set to the Test. myTest.setParameters(testngParams); //Create a list which can contain the classes that you want to run. List<XmlClass> myClasses = new ArrayList<XmlClass>(); myClasses.add(new XmlClass("com.amex.eag.telemetry.testcases.PrometheusTests")); myClasses.add(new XmlClass("com.amex.eag.telemetry.testcases.AlertManagerTests")); //Assign that to the XmlTest Object created earlier. myTest.setXmlClasses(myClasses); //Create a list of XmlTests and add the Xmltest you created earlier to it. List<XmlTest> myTests = new ArrayList<XmlTest>(); myTests.add(myTest); //add the list of tests to your Suite. mySuite.setTests(myTests); //Add the suite to the list of suites. List<XmlSuite> mySuites = new ArrayList<XmlSuite>(); mySuites.add(mySuite); //Set the list of Suites to the testNG object you created earlier. myTestNG.setXmlSuites(mySuites); mySuite.setFileName("myTemp.xml"); mySuite.setThreadCount(3); myTestNG.run(); //Create physical XML file based on the virtual XML content for(XmlSuite suite : mySuites) { createXmlFile(suite); } System.out.println("File generated successfully."); //Print the parameter values Map<String,String> params = myTest.getParameters(); for(Map.Entry<String, String> entry : params.entrySet()) { System.out.println(entry.getKey() + " => " + entry.getValue()); } } //This method will create an Xml file based on the XmlSuite data public void createXmlFile(XmlSuite mSuite) { FileWriter writer; try { writer = new FileWriter(new File("myTemp.xml")); writer.write(mSuite.toXml()); writer.flush(); writer.close(); System.out.println(new File("myTemp.xml").getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } //Main Method public static void main (String args[]) { DynamicTestNG dt = new DynamicTestNG(); //This Map can hold your testng Parameters. Map<String,String> testngParams = new HashMap<String,String> (); testngParams.put("device1", "Desktop"); dt.runTestNGTest(testngParams); } } ```
[TestNG Official Documentation on Programattic Execution](https://testng.org/doc/documentation-main.html#running-testng-programmatically) If you are looking to run your tests programmatically, it's best to read an existing testng XML file, do some runtime modifications and run it programmatically. **This would basically avoid the problem of hardcoding class names and test names in the code**. If you are hardcoding test names and class names, then you would need to change the test names and class names every time you need to run a different case. **So please avoid hardcoding.** Please follow the below approach, it would suit your need. ``` List<String> deviceNames = StringUtils.isEmpty(System.getProperty("deviceNames")) ? new ArrayList<>() : Arrays.asList(System.getProperty("deviceNames").split(",")); TestNG tng = new TestNG(); File initialFile = new File("testng.xml"); InputStream inputStream = FileUtils.openInputStream(initialFile); Parser p = new Parser(inputStream); List<XmlSuite> suites = p.parseToList(); List<XmlSuite> modifiedSuites = new ArrayList<>(); for (XmlSuite suite : suites) { XmlSuite modifiedSuite = new XmlSuite(); modifiedSuite.setParallel(suite.getParallel()); modifiedSuite.setThreadCount(deviceNames.size()); modifiedSuite.setName(suite.getName()); modifiedSuite.setListeners(suite.getListeners()); List<XmlTest> tests = suite.getTests(); for (XmlTest test : tests) { for (int i = 0; i < deviceNames.size(); i++) { XmlTest modifedtest = new XmlTest(modifiedSuite); HashMap<String, String> parametersMap = new HashMap<>(); parametersMap.put("deviceName", deviceNames.get(i)); modifedtest.setParameters(parametersMap); modifedtest.setName(test.getName() + "Device - " + deviceNames.get(i) + ", OS Version - " + platformVersions.get(i)); modifedtest.setXmlClasses(test.getXmlClasses()); } } modifiedSuites.add(modifiedSuite); } inputStream.close(); tng.setXmlSuites(modifiedSuites); tng.run(); ``` I am adding runtime parameters to each and every test based on the parameters passed in the maven runtime arguments. You could use the same approach for passing test names or class names as runtime arguments and update your testng XML file as per your need.
62,136
Is either of the following correct? > > X is known difficult to implement. > > X is known to be difficult to implement. > > >
2012/03/24
[ "https://english.stackexchange.com/questions/62136", "https://english.stackexchange.com", "https://english.stackexchange.com/users/19332/" ]
The only one of your choices that is a complete sentence is this: > > X is known to be difficult to implement. > > > And there are verbs which fit the other structure, such as *find*, with which the *to be* is unnecessary: > > X has been found [to be] difficult to implement. > > > *Know* with that usage, when it has ever occurred, has been archaic (*He knew the climb dangerous*).
The first expression is possible with *difficult to implement* as an adjective, that is, a noun follows it: > > X is **a** known *difficult to implement* plan. > > > Note, however, the added article **a**. It is also better to hyphenate the phrase (difficult-to-implement) or find a one-word substitute, except where the phrase is a recognized or defined term, such as in a particular field or within a particular document.
17,599,266
I'm trying to count the rows with a datetime less that 10 minutes ago but the current time its being compared to seems to be 1 hour ahead so Imm getting 0 results, if I go into my table and put some fields forward an hour then I get results. Getting results: ``` $stmt = $db->query('SELECT check_log FROM members WHERE check_log >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)'); $row_count = $stmt->rowCount(); echo $row_count.' Members online.'; ``` The datetime of the field of of typing this is 2013-07-11 16:54:12 and I'm getting no results but if I manually change the date time to 2013-07-11 17:54:12 I get 1 result the datetime was input seconds ago using: ``` $date = date("Y-m-d H:i:s"); ``` The 17:54:12 is my local time and 16:54:12 seem to be my servers time, is my compare trying to look into the future or is it using my local time as a reference?
2013/07/11
[ "https://Stackoverflow.com/questions/17599266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558771/" ]
PHP and MySQL don't agree on the current timezone. Pass the desired time in as a literal from PHP to SQL instead of using `NOW()`.
Always store date times in php's timezone. One function you can particularly make use of is [strtotime](http://php.net/strtotime). ``` $now = strtotime("now"); // current timestamp $hour_later = strtotime("+1 hour"); // hour later $now = date("Y-m-d H:i:s", $now); $hour_later = date("Y-m-d H:i:s", $hour_later); ```
23,845,935
All, I have a map with categories and subcategories as lists like this: ``` Map<String,List<String>> cat = new HashMap<String,List<String>>(); List<String> fruit = new ArrayList<String>(); fruit.add("Apple"); fruit.add("Pear"); fruit.add("Banana"); cat.put("Fruits", fruit); List<String> vegetable = new ArrayList<String>(); vegetable.add("Carrot"); vegetable.add("Leak"); vegetable.add("Parsnip"); cat.put("Vegetables", vegetable); ``` I want to find if "Carrot" is in the map and to which key ("Fruit') it matches, however: ``` if (cat.containsValue("Carrot")) {System.out.println("Cat contains Leak");} ``` gives False as outcome. How can I match "Carrot" and get back the key value "Vegetable" Thx.
2014/05/24
[ "https://Stackoverflow.com/questions/23845935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3671825/" ]
Iterate thought all the keys and check in the value if found then break the loop. ``` for (String key : cat.keySet()) { if (cat.get(key).contains("Carrot")) { System.out.println(key + " contains Carrot"); break; } } ```
You have to search for the value in the entire map: ``` for (Entry<String, List<String>> entry : cat.entrySet()) { for (String s : entry.getValue()) { if (s.equals("Carrot")) System.out.println(entry.getKey()); } } ```
3,654,278
Clearly for the **Pair Axiom** for any $x,y$ there esist a set $X$ such that $X=\{x,y\}$ and so for any $x$ there exist a set $X$ such that $X=\{x,x\}$. Unfortunately how prove that $\{x,x\}=\{x\}$? Indeed clearly if $\{x\}$ is a set the statement is trivially true, but unfortunately I don't know if $\{x\}$ is a set: anyway I'm sure that $x$ is the unique element of $X$! so could I **formally** conclude that $X=\{x\}$? I point out that I use **ZFC** axiomatization and I found this statement in "Introduction to Set Theory" by Karel Hrbacek and Thomas Jech where it is written that $\{x,x\}\pmb{:=}\{x\}$, but unfortunately I doubt about the strictness of this definition respect **ZFC**. So could someone help me? I know that the question could seem trivially; but if we have a carefully inspection then it seems insidious.
2020/05/01
[ "https://math.stackexchange.com/questions/3654278", "https://math.stackexchange.com", "https://math.stackexchange.com/users/736008/" ]
What does $X = \{x\}$ mean? It means that (1) $x$ is an element of $X$, and every element of $X$ is equal to $x$. By the Pair axiom, there exists a set $\{x,x\}$. What does this mean? It means that (2) $x$ is an element of $X$, $x$ is an element of $X$, and every element of $X$ is equal to $x$ or equal to $x$. But (1) and (2) are equivalent, just by basic logic. --- Let me try to clarify what I wrote above. You want to prove that $\{x\} = \{x,x\}$. This is immediate from the axiom of extensionality. To prove that $X = Y$, we just need to prove that every element of $X = \{x\}$ is an element of $Y = \{x,x\}$ and vice versa. Well, let $a\in X$. Than $a = x$. So $a\in Y$. Conversely, let $a\in Y$. Then $a = x$ or $a = x$. In either case, $a\in X$. So we're done. --- Now for a more formal answer. The language of set theory, in which ZFC is axiomatized, does not contain the symbols $\{$ and $\}$. We use these symbols when we talk *informally* about set theory. When we write $\{a\_1,\dots,a\_n\}$, we mean a set which contains the elements $a\_1,\dots,a\_n$ and no others. In ZFC, we can express the *informal* statement $X = \{a\_1,\dots,a\_n\}$ with the following formula: $$\left(\bigwedge\_{i=1}^n a\_i\in X\right) \land \forall y\, \left(y\in x\rightarrow \bigvee\_{i=1}^n y = a\_i\right).$$ This says that each $a\_i$ is an element of $X$, and every element of $X$ is equal to one of the $a\_i$. So the formula defining $\{x\}$ (and corresponding to my condition (1) above) is $\varphi(X):$ $$x\in X\land \forall y\, (y\in X\rightarrow y = x).$$ And the formula defining $\{x,x\}$ (and corresponding to my condition (2) above) is $\psi(X)$: $$x\in X\land x\in X \land \forall y\, (y\in X\rightarrow (y = x\lor y = x)).$$ But these are logically equivalent formulas! That is, $\forall X\, (\varphi(X)\leftrightarrow \psi(X))$. You ask whether we can prove that $\{x\} = \{x,x\}$. This means proving $\forall X\forall Y\, (\varphi(X)\land \psi(Y)\rightarrow X = Y)$. Yes, you can prove this in ZFC using the axiom of extensionality, as I explained above.
I presume your version of axiomatic set theory defines sets implicitly as the objects produced by applying the axioms. So... * The empty set, $\varnothing$, is a set by the empty set axiom. * The powerset of $\varnothing$, which is $\{\varnothing\}$ establishes the existence of a one element set. * For the $x$ in your $X = \{x,x\}$, construct the functional predicate $f\_x$ by the relation $\{\varnothing \mapsto x\}$, then use the axiom of replacement to obtain $\{x\}$. This establishes that $\{x\}$ is a set for any $x$. For the equality $\{x\} = \{x,x\}$, use the axiom of extensionality. Every element of $\{x\}$ is an element of $\{x,x\}$ by an exhaustive check of one element. Every element of $\{x,x\}$ is an element of $\{x\}$ by an exhaustive check of two elements. Therefore, the equality holds.
69,611,827
I used Cloud Foundry a lot previously, when an app is bind with a service, all the service connection info will be injected into app's environment variables. In Kubernetes world, I think this is same for normal service. For me, I try to use headless service to describe an external PostgreSQL using below service yaml. ``` --- kind: "Service" apiVersion: "v1" metadata: name: "postgresql" spec: clusterIP: None ports: - protocol: "TCP" port: 5432 targetPort: 5432 nodePort: 0 --- kind: "Endpoints" apiVersion: "v1" metadata: name: "postgresql" subsets: - addresses: - ip: "10.29.0.123" ports: - port: 5432 ``` After deploy the headless service to cluster, the container does not has any environment variables for that, I guess it is because the ClusterIP = None. The apps can use postgresql:5432 to access by DNS, but I just wonder why Kubernetes does not inject the headless service and its endpoints into the app's environment variable, so the app can get both ip and port from it? Is there any way to do so? Thanks!
2021/10/18
[ "https://Stackoverflow.com/questions/69611827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4821961/" ]
The problem was with "**cert-manager-cainjector**" pod status which was "**CrashLoopBackOff**" due to FailedMount as **secret** was not found for mounting. I have created that secret and after that it start working fine.
if you are using webhook, check if you have injected the ca, if not you could do it using: ``` apiVersion: admissionregistration.k8s.io/v1 kind: MutatingWebhookConfiguration metadata: ... annotations: cert-manager.io/inject-ca-from: "<namespace>/<certificate_name>" ```
42,352,427
I found [**this**](http://codepen.io/ccrch/pen/yyaraz) codepen showcasing a zoom and pan effect for images. As far as I can tell, the code works by assigning a background-image to each div based on its `data-image` attribute. Is there any way that I can do this on a direct `img` tag instead of a div with a background-image? EDIT: This is the kind of mark-up I'm talking about. **A container div with an actual img tag inside of it.**
2017/02/20
[ "https://Stackoverflow.com/questions/42352427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Take a look at the [CodePen](http://codepen.io/anon/pen/ygddoj) now. Think i got it to look kinda like you want it ``` <div class="tiles"> <div data-scale="1.1" class="product-single__photos tile" id="ProductPhoto"> <img class="photo" src="//cdn.shopify.com/s/files/1/1698/6183/products/bluza_dama_39377a_large.jpg?v=1487178925" alt="Last Skirt" id="ProductPhotoImg"> </div> </div> ```
You can play with the margin to adjust the image position ```css div{ width:100%; height:200px; overflow:hidden; } img{ width:100%; margin:0%; transition:0.5s; } img:hover{ width:120%; margin:-10; } ``` ```html <div> <img src="https://cdn.pixabay.com/photo/2015/07/06/13/58/arlberg-pass-833326_960_720.jpg"> </div> ```
42,659,113
I would like to generate equations symbolically, then sub in values with types from libraries like [`uncertainties`](https://pythonhosted.org/uncertainties/) (but could be any library with custom types) however it seems that using `.evalf(subs={...})` method fails with a rather odd error message: ``` >>> from uncertainties import ufloat >>> from sympy.abc import x >>> (x**2).evalf(subs={x: ufloat(5,1)}) Traceback (most recent call last): ... File "<string>", line 1 Float ('5.0' )+/-Float ('1.0' ) ^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#116>", line 1, in <module> (x**2).evalf(subs={x: ufloat(5,1)}) ... sympy.core.sympify.SympifyError: Sympify of expression 'could not parse '5.0+/-1.0'' failed, because of exception being raised: SyntaxError: invalid syntax (<string>, line 1) ``` * I know sympy is converting my value with a string since `str(ufloat(5,1))` gives `'5.0+/-1.0'` so it obviously wants the string representation of my substitute value will look like a symbolic expression. I know that many sympy operations (like differentiation) wouldn't be possible to support this and it would only be possible if all free symbols were substituted since the two types don't play nice: ``` >>> x + ufloat(5,1) Traceback (most recent call last): File "<pyshell#117>", line 1, in <module> x + ufloat(5,1) TypeError: unsupported operand type(s) for +: 'Symbol' and 'Variable' ``` But assuming I leave no symbolic operations/variables is it possible to simply evaluate a sympy expression with the python equivalent operations?
2017/03/07
[ "https://Stackoverflow.com/questions/42659113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827215/" ]
maybe you want more, but you can just create ordinary functions from sympy expressions and then use uncertainties ``` from uncertainties import ufloat from sympy.abc import x from sympy.utilities.lambdify import lambdify expr = x**2 f = lambdify(x, expr) f(ufloat(5,1)) Out[5]: 25.0+/-10.0 ```
My current solution is just using a loose call to `eval` which does not seem like a good idea, especially since Sympy [is fine with `Basic.__str__` method being monkey patched.](http://docs.sympy.org/dev/modules/printing.html#sympy.printing.printer.Printer) ``` import math, operator eval_globals = {"Mod":operator.mod} eval_globals.update(vars(math)) def eval_sympy_expr(expr, **subs): return eval(str(expr), eval_globals, subs) ``` and for `uncertainties` support I'd just do `import uncertainties.umath as math` instead of the default math module.
10,621,582
I use a jQuery animation in my page which adds some CSS properties and I don't understand why the `margin: auto` doesn't work. The HTML code (with style properties added by jQuery) : ``` <body style="overflow: hidden;"> <div id="tuto_wamp" style="width: 7680px; height: 923px; "> <!-- Step 1 --> <div style="height: 549px; width: 1280px; margin-top: 0px; margin-left: 0px; position: absolute; overflow-y: hidden; overflow-x: hidden; "> <div class="content_tuto"> <img src="images/install1.png" alt=""> </div> </div> </div> </body> ``` My CSS code : ``` #tuto_wamp { background: #3a393c; width: 100%; } .content_tuto { width: 100%; margin: auto; display: block; } ``` I don't know which property blocks the `margin: auto` to center the image. Thank you.
2012/05/16
[ "https://Stackoverflow.com/questions/10621582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857728/" ]
it won't work because you've set the width of `.content_tuto` to `100%;`
I have created a fiddle and added a border to visualise and solve <http://jsfiddle.net/meetravi/Y42Pf/> You could also have a good read of center a div in css from here <http://stever.ca/web-design/centering-a-div-in-ie8-using-marginauto/> Hope it helps.
25,855,428
Currently, when you set up tabs in Bootstrap 3, the tabs are not responsive. This: ![enter image description here](https://i.stack.imgur.com/O1F8M.png) Turns into this: ![enter image description here](https://i.stack.imgur.com/Wq0jO.png) **CSS. Fixing how it looks is easy, just removing the float, etc. at the max-width. However, the content is disjointed from the tab, so a stack of tabs will work like tabs but on smaller viewports you may or may not see the change in content.** --- This is the basic html for making a tabbed navigation: ``` <!--begin tabs going in wide content --> <ul class="nav nav-tabs" id="maincontent" role="tablist"> <li class="active"><a href="#home" role="tab" data-toggle="tab">Home</a></li> <li><a href="#profile" role="tab" data-toggle="tab">Profile</a></li> <li class="dropdown"> <a href="#" id="myTabDrop1" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu" role="menu" aria-labelledby="myTabDrop1"> <li><a href="#dropdown1" tabindex="-1" role="tab" data-toggle="tab">@fat</a></li> <li><a href="#dropdown2" tabindex="-1" role="tab" data-toggle="tab">@mdo</a></li> </ul> </li> </ul><!--/.nav-tabs.content-tabs --> <div class="tab-content"> <div class="tab-pane fade in active" id="home"> <p>Home Content : ...</p> </div><!--/.tab-pane --> <div class="tab-pane fade" id="profile"> <p>Profile Content : ...</p> </div><!--/.tab-pane --> <div class="tab-pane fade" id="dropdown1"> <p>Dropdown1 - ...</p> </div><!--/.tab-pane --> <div class="tab-pane fade" id="dropdown2"> <p>Dropdown 2 - ...</p> </div><!--/.tab-pane --> </div><!--/.tab-content --> ``` *How do you turn the Tabs into the Accordion or Collapse so that it's small viewport friendly?*
2014/09/15
[ "https://Stackoverflow.com/questions/25855428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1004312/" ]
Slack has a cool way of making tabs small viewport friendly on some of their admin pages. I made something similar using bootstrap. It's kind of a tabs → dropdown. **Demo: <http://jsbin.com/nowuyi/1>** Here's what it looks like on a big viewport: [![as tabs](https://i.stack.imgur.com/m9DJx.png)](https://i.stack.imgur.com/m9DJx.png) Here's how it looks collapsed on a small viewport: [![collapsed dropdown](https://i.stack.imgur.com/psIvl.png)](https://i.stack.imgur.com/psIvl.png) Here's how it looks expanded on a small viewport: [![open dropdown](https://i.stack.imgur.com/YtPw6.png)](https://i.stack.imgur.com/YtPw6.png) the HTML is exactly the same as default bootstrap tabs. There is a small JS snippet, which requires jquery (and inserts two span elements into the DOM): ``` $.fn.responsiveTabs = function() { this.addClass('responsive-tabs'); this.append($('<span class="glyphicon glyphicon-triangle-bottom"></span>')); this.append($('<span class="glyphicon glyphicon-triangle-top"></span>')); this.on('click', 'li.active > a, span.glyphicon', function() { this.toggleClass('open'); }.bind(this)); this.on('click', 'li:not(.active) > a', function() { this.removeClass('open'); }.bind(this)); }; $('.nav.nav-tabs').responsiveTabs(); ``` And then there is a lot of css (less): ``` @xs: 768px; .responsive-tabs.nav-tabs { position: relative; z-index: 10; height: 42px; overflow: visible; border-bottom: none; @media(min-width: @xs) { border-bottom: 1px solid #ddd; } span.glyphicon { position: absolute; top: 14px; right: 22px; &.glyphicon-triangle-top { display: none; } @media(min-width: @xs) { display: none; } } > li { display: none; float: none; text-align: center; &:last-of-type > a { margin-right: 0; } > a { margin-right: 0; background: #fff; border: 1px solid #DDDDDD; @media(min-width: @xs) { margin-right: 4px; } } &.active { display: block; a { @media(min-width: @xs) { border-bottom-color: transparent; } border: 1px solid #DDDDDD; border-radius: 2px; } } @media(min-width: @xs) { display: block; float: left; } } &.open { span.glyphicon { &.glyphicon-triangle-top { display: block; @media(min-width: @xs) { display: none; } } &.glyphicon-triangle-bottom { display: none; } } > li { display: block; a { border-radius: 0; } &:first-of-type a { border-radius: 2px 2px 0 0; } &:last-of-type a { border-radius: 0 0 2px 2px; } } } } ```
I prefer a css only scheme based on horizontal scroll, like tabs on android. This's my solution, just wrap with a class nav-tabs-responsive: ``` <div class="nav-tabs-responsive"> <ul class="nav nav-tabs" role="tablist"> <li>...</li> </ul> </div> ``` And two css lines: ``` .nav-tabs { min-width: 600px; } .nav-tabs-responsive { overflow: auto; } ``` 600px is the point over you will be responsive (you can set it using bootstrap variables)
2,625,869
I have a segmentation fault in the code below, but after I changed it to pointer to pointer, it is fine. What is the reason? ``` void memory(int * p, int size) { try { p = (int *) malloc(size*sizeof(int)); } catch(exception& e) { cout << e.what() << endl; } } ``` It does not work in the main function as below: ``` int *p = 0; memory(p, 10); for(int i = 0; i < 10; i++) p[i] = i; ``` However, it works like thi . ``` void memory(int ** p, int size) { `//pointer to pointer` try { *p = (int *) malloc(size*sizeof(int)); } catch(exception& e) { cout<<e.what()<<endl; } } int main() { int *p = 0; memory(&p, 10); // Get the address of the pointer for(int i = 0; i < 10; i++) p[i] = i; for(int i = 0; i < 10; i++) cout << *(p+i) << " "; return 0; } ```
2010/04/12
[ "https://Stackoverflow.com/questions/2625869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233254/" ]
Regarding, ``` memory(p, 10); // Get the address of the pointer ``` This just sends the *p* value, not the address of the p. It sends (\*p). if the address of p is 123 and its value is 50, it sends 50 to the function. And at the memory function it makes a new pointer with new address like 124 and it contains 50; and it will allocate the memory and write the start of the allocated memory to 124, not 123, so *p* at the main still contains 50. So you did nothing! You can control this with this code. ``` #include <iostream> #include <conio.h> #include <exception> using namespace std; void memory(int* p, int size) { // *************pointer to pointer` is a must********** try { p = new int[size]; p[0] = 100; } catch(bad_alloc &e) { cout << e.what() << endl; } } int main() { int *p = 0; ******you can do you should do this******* p = new int; /* p = malloc(sizeof(int)); // This just changes the value inside // of p. It is unnecessary. And you will lose a address from memory :) And possibly it will be unsafe if you free p may, you just free one address */ /* Before using a pointer, always allocate its memory, else you'll get frequent system crashes and BSODs */ memory(p, 10); // Get the address of the pointer // You are getting nothing cout << p[0]; // We set p[0] to 100, but it will write a garbage value here. // Because the value inside of p didn't change at the memory // function, we sent just the value inside of p. getch(); return 0; } ```
I corrected the code... read the comments and all will be clear... ``` #include <iostream> #include <conio.h> #include <exception> using namespace std; void memory(int* p, int size) { // Pointer to pointer` not needed try { p = new int[size]; } catch(bad_alloc &e) { cout<<e.what()<<endl; } } int main() { //int *p = 0; Wrong ... no memory is assigned and then // you are passing it to a function int *p; p = new int; // p = malloc(sizeof(int)); /* Before using a pointer, always allocate its memory, else you'll get frequent system crashes and BSODs */ memory(p, 10); // Get the address of the pointer for(int i = 0; i < 10; i++) p[i] = i; for(int i = 0 ; i < 10; i++) cout << *(p+i) << " "; getch(); return 0; } ```
126,613
Challenge ========= Given an integer `n` (where `4<=n<=10**6`) as input create an ASCII art "prison door"\* measuring `n-1` characters wide and `n` characters high, using the symbols from the example below. --- Example ------- ``` ╔╦╗ ╠╬╣ ╠╬╣ ╚╩╝ ``` The characters used are as follows: ``` ┌───────────────┬─────────┬───────┐ │ Position │ Symbol │ Char │ ├───────────────┼─────────┼───────┤ │ Top Left │ ╔ │ 9556 │ ├───────────────┼─────────┼───────┤ │ Top │ ╦ │ 9574 │ ├───────────────┼─────────┼───────┤ │ Top Right │ ╗ │ 9559 │ ├───────────────┼─────────┼───────┤ │ Right │ ╣ │ 9571 │ ├───────────────┼─────────┼───────┤ │ Bottom Right │ ╝ │ 9565 │ ├───────────────┼─────────┼───────┤ │ Bottom │ ╩ │ 9577 │ ├───────────────┼─────────┼───────┤ │ Bottom Left │ ╚ │ 9562 │ ├───────────────┼─────────┼───────┤ │ Left │ ╠ │ 9568 │ ├───────────────┼─────────┼───────┤ │ Inner │ ╬ │ 9580 │ └───────────────┴─────────┴───────┘ ``` --- Rules ----- * You may take input by any reasonable, convenient means as long as it's permitted by [standard I/O rules](https://codegolf.meta.stackexchange.com/q/2447/58974). * For the purposes of this challenge, in languages where the symbols used to build the "door" are multi-byte characters, they may be counted towards your score as a single byte each. * All other characters (single- or multi-byte) should be counted as normal. * Output may not contain any trailing spaces but a trailing newline is permitted if absolutely necessary. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so lowest byte count wins. --- Test Cases ---------- ``` Input: 4 Output: ╔╦╗ ╠╬╣ ╠╬╣ ╚╩╝ Input: 8 Output: ╔╦╦╦╦╦╗ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╚╩╩╩╩╩╝ Input: 20 Output: ╔╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╗ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╚╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╝ ``` \* Yes, I'm aware that the bigger it gets the less it looks like a prison door! :D
2017/06/15
[ "https://codegolf.stackexchange.com/questions/126613", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/58974/" ]
[Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ================================================================================================================================= ``` ÷ÅoB↔╒╢Fm|╦a⌐á5µ┐»♫÷d╕Ñ ``` [Run and debug it](https://staxlang.xyz/#p=f68f6f421dd5b6466d7ccb61a9a035e6bfaf0ef664b8a5&i=4%0A8%0A20&a=1&m=2) Here's the ungolfed version. Amusingly, it's actually smaller for stax *not* to use the literal characters because including them as a literal would prevent source packing. ``` "2Pfj_EQGG]T"! packed representation of the 9 characters 3/ split into groups of 3 GG call into trailing program twice m print each row } trailing program begins here 1|xv\ [1, --x - 1]; x starts as original input :B repeat each element corresponding number of times effectively, this repeats the internal row of the matrix M transpose door; this way it expands the two dimensions ``` [Run this one](https://staxlang.xyz/#c=%222Pfj_EQGG]T%22%21%09packed+representation+of+the+9+characters%0A3%2F++++++++++++%09split+into+groups+of+3%0AGG++++++++++++%09call+into+trailing+program+twice%0Am+++++++++++++%09print+each+row%0A%7D+++++++++++++%09trailing+program+begins+here%0A1%7Cxv%5C+++++++++%09[1,+--x+-+1]%3B+x+starts+as+original+input%0A%3AB++++++++++++%09repeat+each+element+corresponding+number+of+times%0A++++++++++++++%09effectively,+this+repeats+the+internal+row+of+the+matrix%0AM+++++++++++++%09transpose+door%3B+this+way+it+expands+two+different+dimensions&i=4%0A8%0A20&a=1&m=2)
Mathematica, 106 bytes ====================== ``` (T[a_,b_,c_]:=a<>Table[b,#-3]<>c;w=Column;w[{T["╔","╦","╗"],w@Table[T["╠","╬","╣"],#-2],T["╚","╩","╝"]}])& ```
309,682
I'm writing a HTML form that's divided in fieldsets, and I need to get the form fields from a specific fiedset in a function. Currently it's like this: ``` function conta(Fieldset){ var Inputs = Fieldset.getElementsByTagName("input"); var Selects = Fieldset.getElementsByTagName("select"); /* Doing the stuff I need to do in two iterations, one for each field type */ } ``` But who knows what the future may hold, and if the form gets some new field types (radios, checkboxes) this could become awful to mantain. I know that `form` elements have the `elements` attribute that returns all the form fields and I was hoping I could use something like that. (I know I still gotta discriminate the field type in a bunch of conditionals inside the iteration, but I think it would be faster and easier to keep. Unless it isn't and I should not be doing it)
2008/11/21
[ "https://Stackoverflow.com/questions/309682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9835/" ]
@Ryan is on the right track if you want to use jQuery (and I would), but I'd suggest something more along the lines of: ``` $('fieldset#fieldset1 > input[type=text]').each( function() { ... do something for text inputs } ); $('fieldset#fieldset1 > input[type=radio]').each( function() { ... do something for radios } ); $('fieldset#fieldset1 > select').each( function() { ... do something for selects } ); $('fieldset#fieldset1 > textarea').each( function() { ... do something for textareas } ); ``` As an improvement over if-then-else constructs.
Haven't tested this and don't know how it would work, but you could use JQuery here to select all the elements into a JQuery object ``` //$("input select textarea").each(function() { $(":input").each(function() { //even better // do stuff here }); ``` this would at least cleanup the code, although you would still have to add conditional statements based on field type like you mentioned.
21,934,275
I've a problem when access to value for `aaData` in "fnFooterCallback". This is the output of log: > > aaData: [object Object],[object Object],[object Object],[object Object] > > > Really, I've 4 rows to show in datatable, but I can't access these values to show totals in dataset. I try to use this: ``` "fnDrawCallback": function(oSettings) { console.log("aaData: "+oSettings.aoData ); iTotal = [0, 0]; for (var i = 0; i < oSettings.aoData.length; i++) { iTotal[0] += oSettings.aoData[i]._aData.quantity; } //Totales $("#Totales").empty(); $("#Totales").append('<th>sum</th><th>'+iTotal[0]+'</th>'); } ``` i also try with this: ``` "fnFooterCallback" : function(nRow, aaData, iStart, iEnd, aiDisplay) { console.log("aaData: " + aaData); var totalCantidad = 0; for ( var i = 0; i < aaData.length; i++) { totalCantidad = totalCantidad+ parseInt(aaData[i].Cantidad) * 1; } var nCells = nRow.getElementsByTagName('th'); nCells[1].innerHTML = totalCantidad; } ``` This is my definition for the datatable: ``` $("#lineOutletTable").dataTable({ "bInfo" : false, "bPaginate" : false, "bLengthChange" : true, "iDisplayLength" : -1, "bFilter" : false, "bSort" : true, "aaSorting" : [ [ 0, "asc" ] ], "bAutoWidth" : false, "oLanguage" : spanishInfo, "aoColumns" : columnsTableLine, "sPaginationType" : "bootstrap", "iDisplayStart" : 20, "sScrollY" : "60px", "sDom" : "<row-fluid'<'span6 wrapMedidasReales'><'span6 wrapPrecios'>>t<row-fluid'<'span6 'l><'span6'p>>", "fnDrawCallback" : function(oSettings) { console.log("aaData: " + oSettings.aoData); iTotal = [ 0, 0 ]; for ( var i = 0; i < oSettings.aoData.length; i++) { iTotal[0] += oSettings.aoData[i]._aData.quantity; } // Totales $("#Totales").empty(); $("#Totales").append('<th>sum</th><th>' + iTotal[0] + '</th>'); }, "fnFooterCallback" : function(nRow, aaData, iStart, iEnd, aiDisplay) { console.log("aaData: " + aaData); var totalCantidad = 0; for ( var i = 0; i < aaData.length; i++) { totalCantidad = totalCantidad + parseInt(aaData[i].Cantidad) * 1; } var nCells = nRow.getElementsByTagName('th'); nCells[1].innerHTML = totalCantidad; } }); ``` I read the values from `Ajax`, the dataset work correctly except the totals. How I can access to values in aaData?
2014/02/21
[ "https://Stackoverflow.com/questions/21934275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3036384/" ]
You could draw that as a filled UIBezierPath (which is a UIKit wrapper on a CGPath). You'd open a path, draw a sequence of straight lines and cubic or quadratic bezier curves, then close the path. Then you'd draw it as a filled path. Once you have the path created, you could draw it with a single call.
A couple of alternatives, as Duncan seems to have answered this. One option would be to dynamically scale a high resolution image. There is one caveat with this approach: you should not scale anything below 1/2 of the original size, otherwise the interpolation tends to glitch. So you would need to store image at say 64x64, 128x128, 256x256 etc You could pack all of these into a single 256x512, and this is what a lot of games do. Another option is to render a quaver unicode character <http://www.fileformat.info/info/unicode/char/266a/index.htm>
292,101
I just learned something interesting. The add method for the javascript select object in IE 6 takes only one parameter. It throws an error when you pass it two parameters which I believe is the [standard](http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html), even as [documented](http://msdn.microsoft.com/en-us/library/aa768859(VS.85).aspx) on the MSDN site. My question is this. What is your best-practice recommendation for programmatically adding option elements to a select element in javascript? * Call the add method differently based on the value of the user agent? * Wrap the select object in a class that provides the proper method signature? * Use a javascript library which does this for you (specify which library)?
2008/11/15
[ "https://Stackoverflow.com/questions/292101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25191/" ]
You shouldn't be using the Select.add method, as it's broken in IE, and there are better ways to add options dynamically (see <http://msdn.microsoft.com/en-us/library/ms535921(VS.85).aspx>) I have had the same problem, and have found that the best way is to use the Node.insertBefore method. This has the advantage of working in all browsers, and making sorting of the elements easy, because you don't have to add the element as the last element of the select list in IE. For example, adding an option from one select list to another, so that the options in the target list are sorted alphabetically, can be done like this: ``` /* adds an option to select element, alphabetically sorted according to the lower case value of the display element (option.text) */ function insertOptionToList(optionToInsert, targetSelectElement){ for (var i=0;i<targetSelectElement.options.length;i++){ var tempOptionText = targetSelectElement.options[i].text; if(tempOptionText.length>0 && optionToInsert.text.toLowerCase()<tempOptionText.toLowerCase()){ targetSelectElement.insertBefore(optionToInsert,targetSelectElement[i]); return true; } } targetSelectElement.options[targetSelectElement.options.length] = optionToInsert; return true; } ```
I did some research myself using all permutations and combinations of creating an option object and I hope this is the best possible way by which we can add options to select in a browser neutral way: ``` function populateSelectField() { document.frmMain.fldSelect.options.length = 0; document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 1"); document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 2"); document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 3"); document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 4"); } ``` Since the select field object is accessed and manipulated by accessing it's parent object, which is "frmMain" (form) in this code, it doesn't create any problem for any browser to run the code. This is supported by all browsers including IE.
62,762,083
I am using ChromeDriver and I would like it to click every button on the page that contains a specific class name. ```cs using OpenQA.Selenium; using OpenQA.Selenium.Chrome; ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService(); chromeDriverService.HideCommandPromptWindow = true; ChromeOptions options = new ChromeOptions(); options.AddArgument("ignore-certificate-errors"); ChromeDriver driver = new ChromeDriver(chromeDriverService, options); driver.Url = "https://www.some-url.com"; driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(2); ``` I was thinking of something along the lines of: ```cs driver.FindElement(By.ClassName("some-class-name")).Click(); ``` However that only clicks on one button. How could I achieve this to click every button found on the web-page?
2020/07/06
[ "https://Stackoverflow.com/questions/62762083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11229214/" ]
Try with `FindElements` instead of `FindElement` ```cs IList<IWebElement> list= driver.FindELements(By.ClassName("some-class-name"); foreach (IWebElement element in list) { element.Click(); } ```
```cs List<WebElement> elementName = driver.findElementsBy.ClassName("some-class-name")); ``` This will return a list of `WebElements` which you can iterate over in a foreach statement, performing `.click()` on each.
28,640,275
This must be a silly question but with my logic i can't understand why it doesn't exit. This is my loop: ``` Random _random = new Random(); int num; char let; string TempName = "~"; string sTempPath; do { while (TempName.Length < 12) { num = _random.Next(0, 26); let = (char)('a' + num); TempName = TempName + let; } sTempPath = sDirectory + @"\" + TempName + @"." + sExt; //MessageBox.Show(sTempPath); } while (!File.Exists(sTempPath)); ``` So with my logic, when Do loop starts, it directly triggers the while loop Inside it. While loop exists after `TempName.Length` is greater than 12 and then do loop should exit since the file doesn't exists. So where am i wrong?
2015/02/20
[ "https://Stackoverflow.com/questions/28640275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4496821/" ]
Currently your loop runs *as long as* `File` doesn't exist. If you wanna stop when the file doesn't exist then change your condition to `File.Exists` by removing negation operator (!).
Your condition is incorrect. `while(File.Exists(sTempPath))`
200,686
I'm investigating options for a small corporate virtualisation setup. We specialise in scientific computing and would like to consolidate our resources. We are keen on KVM, since it looks like it performs well with multiple vCPU per VM. I'm confused by the RedHat KVM offering. We don't want to virtualise everyone's existing desktops but we do want to have additional virtual desktops, not just ssh access. With "RH Virtualisation for Servers" (much cheaper than the Desktop offering) can we still have the virtual GUI desktops?
2010/11/11
[ "https://serverfault.com/questions/200686", "https://serverfault.com", "https://serverfault.com/users/43873/" ]
Certainly. [LTSP](http://www.ltsp.org/) can be served from a virtual machine running on top of RHEL, and then you can have the virtual desktops connect via XDMCP to another virtual machine running on the server that does the actual hard work.
Your environment seems to be a good match for NX/NoMachine - See here: <http://www.nomachine.com/>
437,108
I have just started studying rotational kinematics.
2018/10/27
[ "https://physics.stackexchange.com/questions/437108", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/210963/" ]
when electrical current flows through a circuit component (easy example: a resistor), the resistor dissipates power; as it does, the voltage decreases steadily from the high-voltage side to the low-voltage side. this decrease in voltage is called the voltage drop. In the case of a resistor of resistance R with a voltage difference across it of V volts, the power dissipated is equal to (V^2)/R.
Voltage is a term which is sometimes confusing because people use it different ways in different contexts. Technically, voltage is the *difference* in electrical potential between two points. Electric potential is a physics concept which describes how much potential energy will be added or removed from a system if a unit charge is added or removed. For example, if the electric potential (I like to use the symbol $\phi$ for electric potential) at a point is 93 V, then adding a 1 coulomb charge at that point will add 93 J of potential energy to the system. Next, if we move that charge to a point where the potential is 100 V, we have effectively added 100 J but removed 93 J, for a net change of 7 J. The voltage, potential difference, ($V=\Delta \phi$) between those points is +7 V. On the other hand, if we started with the charge at $\phi = $100 V potential point and moved it to the $\phi = $93 V potential point, we would have a voltage, $$V=\Delta\phi=\phi\_{final}-\phi\_{initial}=-7\text{ V}$$ and a potential energy decrease of 7 J. That potential energy is converted into some other form of energy, depending on the system. This decrease of potential, or negative voltage, is commonly called a voltage drop. I personally don't like adding the word "drop" to voltage. I simply say voltage, and I always emphasize which end of a circuit element is higher, because if the voltage "drops" going left to right, then it "rises" going right to left. The word voltage by itself is enough to convey a difference of potential.
69,497,078
I want to check if the current `id` equals last `id` +1, (this should work for any number of similar dicts added in the list) ### Code ```sh listing = [ { 'id': 1, 'stuff': "othervalues" }, { 'id': 2, 'stuff': "othervalues" }, { 'id': 3, 'stuff': "othervalues" } ] for item in listing : if item[-1]['id'] == item['id']+1: print(True) ``` ### Output ```sh Traceback (most recent call last): File "C:\Users\samuk\Desktop\Master\DV\t2\tester.py", line 10, in <module> if item[-1]['id'] == item['id']+1: KeyError: -1 ``` ### Desired result ``` True ``` **or, in case of fail,** ``` False ```
2021/10/08
[ "https://Stackoverflow.com/questions/69497078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17107125/" ]
To check if all the `id`s are in a sequence we can use [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) here. ``` def is_sequential(listing): start = listing[0]['id'] for idx, item in enumerate(listing, start): if item['id'] != idx: return False return True ```
When you do `for item in some_list`, `item` is *the actual item* in that list. You can't get the previous item by `item[-1]`. So in your case, `item` is a dictionary that has the keys `'id'` and `'stuff'`. Obviously, no key called `-1`, so you get a `KeyError`. You can iterate over two slices of the list after using `zip()` -- one that starts at the zeroth element, and one that starts on the first element. Using `zip()`, you can get corresponding items of these slices simultaneously. You'll have every item and its subsequent item coming out of `zip()`. Also, you want a result *after* you've checked all pairs of items, not *while* you're checking each pair. To do this, create a variable `is_sequential` with an initial value of `True`. If you find a single pair that doesn't work, change this to `False`, and break out of the loop because one pair being non-sequential makes the entire list so. ``` is_sequential = True for item1, item2 in zip(listing, listing[1:]): if item1['id'] + 1 != item2['id']: is_sequential = False break print(is_sequential) ``` Alternatively, you could use the [`any()`](https://docs.python.org/3/library/functions.html#any) function with the same loop and condition, and then invert the result, or use [`all()`](https://docs.python.org/3/library/functions.html#all) with the opposite condition: ``` # use any() is_sequential = not any( item1['id'] + 1 != item2['id'] for item1, item2 in zip(listing, listing[1:]) ) # or, use all() is_sequential = all( item1['id'] + 1 == item2['id'] for item1, item2 in zip(listing, listing[1:]) ) ```
2,386,718
Ok, I'm trying to use the FaceBox() plugin for jQuery along with the jQuery UI datepicker(). I've got it to bind to the lightbox'd inputs on the first appearance of the lightbox, but it's not working afterwards. I'm doing the following: ```` $(function() { $('.jQueryCalendar').live('click', function () { $(this).datepicker({showOn: 'both'}).focus(); }); }); ```` When the lightbox closes, I'm re-appending it's content to the page (in order to not lose the content div), and this seems to be killing the live() call. [NB the re-appending takes place *after* the original content is destroyed] EDIT Ok, the live() event IS firing (thanks to Nick Craver for that), however the datepicker is no longer being shown. Does anyone have an idea why? EDIT #2 Ok, the use of .html() to re-append causes the events to need rebinding, but the element to bind still has the class hasDatepicker, which messes with the datepicker() initialisation. To fix, simply user ```` $(this).removeClass('hasDatepicker') .datepicker({showOn: 'both'}).focus(); ````
2010/03/05
[ "https://Stackoverflow.com/questions/2386718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70847/" ]
Try this and see what happens: ``` $(function() { $('.jQueryCalendar').live('click', function () { $(this).datepicker('destroy').datepicker({showOn: 'both'}).focus(); }); }); ``` If you're using jQuery UI 1.7.2 with jquery 1.4, some effects destroy widgets, it fading, etc may be causing datepicker issues. jQuery UI 1.8 fixes this, it's at RC3 Status at the moment.
its possible that the datepicker is behind the box... i had also the same problem a time ago. put this in a css file, and that did the trick for me. ``` #ui-datepicker-div { z-index:9999999; } ```
320,666
Every time I try to kill the x-server, ``` sudo service lightdm stop ``` so that I can install the latest Nvidia drivers, I get an error message. ``` stop: Unknown instance: ``` What am I doing wrong?
2013/07/16
[ "https://askubuntu.com/questions/320666", "https://askubuntu.com", "https://askubuntu.com/users/101532/" ]
1. Use `ctrl`+`alt`+`F1` to switch to terminal, 2. login 3. run `sudo service lightdm stop`, lightdm and xserver should be stopped now (check with `ctrl`+`alt`+`F7`, which is your current xorg session, it should not show any desktop now) 4. do your things 5. run `sudo service lightdm start` to start lightdm and xorg again. Good Luck!
Ok had the GTX 970 installation Problem under Ubuntu 14.04 too. Sometime i was able to start Ubuntu with the standart drivers and sometime not. However, this should hopefully fix the Problem: After switching from IGP (I7 4770 with HD4600) to GTX970 in Biosi got an error with some Xorg Gui. However you can not install the Nvidia-Driver while X is running: -> sudo killall Xorg solves the problem Then -> sudo ./NVIDIA-x68xxx.run After the first Driver Install (orig. Nvidia 352.xx) i had a blank screen. Then i run the Nvidia Driver Installer again -> sudo ./NVIDIA-x68xxx.run This second install told me some kind of noveu driver is running and should be disabled. The driver asked me if it should disable noveu -> Yes disable noveu After restart: Et Voila lighdm is running again :)
26,466,334
I am trying to get a list of users from the database that have ALL the tags in a criteria. The User entity has a many-to-many association to a Tag entity. The or version where just one of the tags have to match is working using the following code ``` $tagIds = array(29,30); $this->createQueryBuilder('u') ->select('u','t') ->leftJoin('u.tags','t') ->where("t IN(:tagIds)") ->setParameter("tagIds",$tagIds) ; ``` Can anybody help me with getting it to work so ALL tag ids must match ? Keep in mind this is a query to get a list of users, not just one user , so i guess every user must be checked to see if they match all the supplied tag ids. I have tried a bunch of queries but not having any luck so far...
2014/10/20
[ "https://Stackoverflow.com/questions/26466334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374914/" ]
After `cin>>t`, there is a newline remaining in the stream, then the newline will be assigned to `s`, so `cout<<s` seems to print nothing(Actually, it prints a newline). add `cin.ignore(100, '\n');` before first `getline` to ingore the newline.
The newline from `cin >> t;` after pressing enter is still in std::cin when `getline(cin,s)` is called, resulting in s being empty. The string you enter is actually being stored in p. Try using a different capture method or flushing the cin buffer before using it again.
38,588
Would the above mentioned microphone work with a laptop,to create audio for dubbing and podcasts?if not,then what do you guys suggest?
2016/03/21
[ "https://sound.stackexchange.com/questions/38588", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/-1/" ]
You would create stems Dialogue, Ambience, Foley, SFX for the entire length of the film
You simply bounce it down to either a stereo file or If it's surround you need to run it through a surround sound encoder so the resulting wav will know its multiple panned channels. You only need to do stems if it's required for being redubbed in a foriegn language.
66,418,092
I'm learning javascript and AngularJS. I made this little code for something (we made it in AngularJS format), and we need to make this same logic but using only javascript. The color of a botton changes to other when it's available or unavailable. Can someone help me with this and tell me the logic? ``` $scope.saveButton= function(){ $( "#saveButtonPics" ).removeClass( "attachment-space-available" ).addClass( "attachment-boton-guardado" ); }; ```
2021/03/01
[ "https://Stackoverflow.com/questions/66418092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15305215/" ]
It is not Angular but jQuery apart from the $scope which I guess is part of some Angular scope A plain JS version could be ``` const saveButton = () => { const cl = document.getElementById("saveButtonPics").classList; cl.remove("attachment-space-available") cl.add("attachment-boton-guardado"); }; ``` If you want to chain, have a look at [chaining HTML5 classList API without (Jquery)](https://stackoverflow.com/questions/28653761/chaining-html5-classlist-api-without-jquery) ``` const classList = elt => { const list = elt.classList; return { toggle: function(c) { list.toggle(c); return this; }, add: function(c) { list.add (c); return this; }, remove: function(c) { list.remove(c); return this; } }; }; const saveButton = () { classList(document.getElementById("saveButtonPics")) .remove("attachment-space-available") .add("attachment-boton-guardado"); }; ```
In angularjs we need change model to change view ``` <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl"> <button ng-click="saveButton()" ng-class="savebtnclass">Save Pics</button> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.savebtnclass = "attachment-space-available"; $scope.saveButton=function(){ $scope.savebtnclass = "attachment-boton-guardado"; } }); </script> </body> </html> ```
63,942,280
I'm fetching data out of a mapping API (which returns JSON) and luckily for me as a JSON noob, the object I've been wanting to manipulate in the past has been named with a shortcut. However, today I want to get data from an object which is named with a randomly generated number, which I won't know the name of when I fetch it. So I effectively want to write: An example of the JSON is below. The data I am trying to access is the name of the Scottish Parliament constituency. So I am looking for an object which contains [type\_name] = "Scottish Parliament constituency". I then want to look for the key/value pair within for name (in this example, Glasgow Kelvin). In this case, the object has the randomly generated name of 134955, but if I don't know that beforehand, how I can write the javascript to scope within the find if it has that type\_name, and therefore pull the name out? The objects aren't always the name number and order, so I can't just do it by saying "get the first object". ``` { "wgs84_lat": 55.861509653107056, "coordsyst": "G", "shortcuts": { "WMC": 14425, "ward": 151284, "council": 2579 }, "wgs84_lon": -4.246702245398941, "postcode": "G1 1BX", "easting": 259485, "areas": { "134955": { "parent_area": 148764, "generation_high": 40, "all_names": {}, "id": 134955, "codes": { "gss": "S16000117", "unit_id": "41386" }, "name": "Glasgow Kelvin", "country": "S", "type_name": "Scottish Parliament constituency", "generation_low": 15, "country_name": "Scotland", "type": "SPC" }, "2579": { "parent_area": null, "generation_high": 40, "all_names": {}, "id": 2579, "codes": { "gss": "S12000049", "local-authority-canonical": "GLG", "unit_id": "30631" }, "name": "Glasgow City Council", "country": "S", "type_name": "Unitary Authority", "generation_low": 36, "country_name": "Scotland", "type": "UTA" }, "151284": { "parent_area": 2579, "generation_high": 40, "all_names": {}, "id": 151284, "codes": { "gss": "S13002976", "unit_id": "43375" }, "name": "Anderston/City/Yorkhill", "country": "S", "type_name": "Unitary Authority ward (UTW)", "generation_low": 31, "country_name": "Scotland", "type": "UTW" }, "14425": { "parent_area": null, "generation_high": 40, "all_names": {}, "id": 14425, "codes": { "gss": "S14000029", "unit_id": "33920" }, "name": "Glasgow Central", "country": "S", "type_name": "UK Parliament constituency", "generation_low": 2, "country_name": "Scotland", "type": "WMC" } } } ```
2020/09/17
[ "https://Stackoverflow.com/questions/63942280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8805457/" ]
This should do it: ``` Object.values(data.areas) .filter(a=>a.type_name=="Scottish Parliament constituency") .map (a=>a.name) ``` ```js const data={ "wgs84_lat": 55.861509653107056, "coordsyst": "G", "shortcuts": { "WMC": 14425, "ward": 151284, "council": 2579 }, "wgs84_lon": -4.246702245398941, "postcode": "G1 1BX", "easting": 259485, "areas": { "134955": { "parent_area": 148764, "generation_high": 40, "all_names": {}, "id": 134955, "codes": { "gss": "S16000117", "unit_id": "41386" }, "name": "Glasgow Kelvin", "country": "S", "type_name": "Scottish Parliament constituency", "generation_low": 15, "country_name": "Scotland", "type": "SPC" }, "2579": { "parent_area": null, "generation_high": 40, "all_names": {}, "id": 2579, "codes": { "gss": "S12000049", "local-authority-canonical": "GLG", "unit_id": "30631" }, "name": "Glasgow City Council", "country": "S", "type_name": "Unitary Authority", "generation_low": 36, "country_name": "Scotland", "type": "UTA" }, "151284": { "parent_area": 2579, "generation_high": 40, "all_names": {}, "id": 151284, "codes": { "gss": "S13002976", "unit_id": "43375" }, "name": "Anderston/City/Yorkhill", "country": "S", "type_name": "Unitary Authority ward (UTW)", "generation_low": 31, "country_name": "Scotland", "type": "UTW" }, "14425": { "parent_area": null, "generation_high": 40, "all_names": {}, "id": 14425, "codes": { "gss": "S14000029", "unit_id": "33920" }, "name": "Glasgow Central", "country": "S", "type_name": "UK Parliament constituency", "generation_low": 2, "country_name": "Scotland", "type": "WMC" } } }; console.log(Object.values(data.areas).filter(a=>a.type_name=="Scottish Parliament constituency").map(a=>a.name)) ``` First you `.filter()` through all the `Object.values()` of `data.areas` for the `a.type_name=="Scottish Parliament constituency"` and then you apply a `.map()` to extract the `name` property from the filtered object(s).
In Addition to above [comment](https://stackoverflow.com/a/63942457/10102695), You can use "find" if you want to return once the first match occur! ``` const element = Object.keys(x.areas).find(item => x.areas[item].type_name === "Scottish Parliament constituency"); const obj = x.areas[element]; //Complete Object on matched type_name ```
45,176,273
I need to run command line from a c# program. I want to set the directory of the command line window. To do so, I am using the following code: ```cs Process.Start("cmd", @"cd C:\Users\user1\Desktop"); ``` When I run the c# program, a command line window is opened, but the directory is not set to C:\Users\user1\Desktop, meaning the command was not executed. What am I doing wrong?
2017/07/18
[ "https://Stackoverflow.com/questions/45176273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8260918/" ]
To set the working directory, you can also do it using the [ProcessStartInfo](https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo(v=vs.110).aspx) like this: ``` using System; using System.Diagnostics; namespace so45176273 { internal class Program { private static void Main(string[] args) { var startInfo = new ProcessStartInfo("cmd") { WorkingDirectory = @"c:\Trash", Arguments = "/k" // will leave the process running until you type exit }; Process.Start(startInfo); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } } ```
I believe this is the answer you are looking for. ``` Process.Start("cmd", @"/c cd C:\Users\user1\Desktop"); ```
13,620,267
I'm playing with the add-member cmdlet and found the following three piece of code does not give me the same result. Any anyone explain why? Thanks. ``` ################################################################ $hash = @{"a" = "aa"; "b" = "bb"} $result = new-object psobject $result | Add-Member $hash $result ################################################################ $hash = @{"a" = "aa"; "b" = "bb"} $result = new-object psobject | Add-Member $hash $result ################################################################ $hash = @{"a" = "aa"; "b" = "bb"} $result = (new-object psobject | Add-Member $hash) $result ```
2012/11/29
[ "https://Stackoverflow.com/questions/13620267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/170931/" ]
1st one works because $result psobject creation is performed before the Add-Member. The second 2 do not work because $result is null. Code below ensures the order of statement evaluation. ``` ################################################################ $hash = @{"a" = "aa"; "b" = "bb"} ($result = new-object psobject) | Add-Member $hash $result ```
$hash is probably binding to the wrong parameter. The correct way would be to decide on the member type (NoteProperty in this example), a Name and value: ``` $result | Add-Member -MemberType NoteProperty -Name MyHash -Value $hash ``` If you assign the result to a variable add the -PassThru switch: ``` $result = new-object psobject | Add-Member -MemberType NoteProperty -Name MyHash -Value $hash -PassThru $result.MyHash ```
3,265
So I flagged [this question](https://aviation.stackexchange.com/questions/38709/why-dont-pilots-or-passengers-for-that-matter-yet-seem-to-really-like-auto) as being opinion based and the flag got declined, yet the question is currently [on hold] for being opinion based. Has something gone wrong with the system? Declined flag... [![Flag declined](https://i.stack.imgur.com/aPNPq.png)](https://i.stack.imgur.com/aPNPq.png) Question Closed... [![enter image description here](https://i.stack.imgur.com/lS774.png)](https://i.stack.imgur.com/lS774.png)
2017/06/09
[ "https://aviation.meta.stackexchange.com/questions/3265", "https://aviation.meta.stackexchange.com", "https://aviation.meta.stackexchange.com/users/15982/" ]
Based on [the link to a meta.SO post](https://meta.stackoverflow.com/a/284872/6650102) given by Aurora0001 in the comments, and the fact that [the review](https://aviation.stackexchange.com/review/close/23980) shows that nobody in the queue agreed with you, the system has "declined" automatically this flag. The question then got closed through a second [queue](https://aviation.stackexchange.com/review/close/23993)
Four possible reasons. 1. Declined by mistake. It happens. 2. A mod has a vendetta against you. It also happens. Often. 3. Some mods think flagging for close reasons should not be done and blanket decline. This is wrong. But from the looks of it, 4. it timed out, because the question was closed by user votes, making your pending flag pointless. The system, for whatever reason, marks these as declined, instead of simply unflagging or some other option. If you mouse over the time stamp on your declined flag, and compare it to the close time stamp of the question, they should overlap. Edit: since it wasn't a timed out flag, then: 5. The mod that saw the flag simply didn't agree with the close reason. Notice no mod had casted a close vote on it. The problem is that votes and flags are opinion, and not everyone holds the same opinion on any given question.
374,886
I'm trying to setup Spring using Hibernate and JPA, but when trying to persist an object, nothing seems to be added to the database. Am using the following: ``` <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="persistenceUnitName" value="BankingWeb" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="generateDdl" value="true" /> <property name="showSql" value="true" /> <property name="databasePlatform" value="${hibernate.dialect}" /> </bean> </property> </bean> <tx:annotation-driven/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/> <bean name="accountManager" class="ssel.banking.dao.jpa.AccountManager" /> <bean name="userManager" class="ssel.banking.dao.jpa.UserManager" /> ``` And in AccountManager, I'm doing: ``` @Repository public class AccountManager implements IAccountManager { @PersistenceContext private EntityManager em; /* -- 8< -- Query methods omitted -- 8< -- */ public Account storeAccount(Account ac) { ac = em.merge(ac); em.persist(ac); return ac; } } ``` Where ac comes from: ``` Account ac = new Account(); ac.setId(mostRecent.getId()+1); ac.setUser(user); ac.setName(accName); ac.setDate(new Date()); ac.setValue(0); ac = accountManager.storeAccount(ac); return ac; ``` Is there anyone who can point out what I'm doing wrong? The persist call returns without throwing exceptions. If afterwards I do `em.contains(ac)`, this returns true. In case anyone needed, here's how Account is defined: ``` @SuppressWarnings("serial") @Entity @NamedQueries({ @NamedQuery(name = "Account.AllAccounts", query = "SELECT a FROM Account a"), @NamedQuery(name = "Account.Accounts4User", query = "SELECT a FROM Account a WHERE user=:user"), @NamedQuery(name = "Account.Account4Name", query = "SELECT a FROM Account a WHERE name=:name"), @NamedQuery(name = "Account.MaxId", query = "SELECT MAX(a.id) FROM Account a"), @NamedQuery(name = "Account.Account4Id", query = "SELECT a FROM Account a WHERE id=:id"), }) public class Account extends AbstractNamedDomain { @Temporal(TemporalType.DATE) @Column(name = "xdate") private Date date; private double value; @ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE}) @JoinColumn(name="userid") private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER) @OrderBy("date") private List<AccountActivity> accountActivity = new ArrayList<AccountActivity>(); public List<AccountActivity> getAccountActivity() { return accountActivity; } public void setAccountActivity(List<AccountActivity> accountActivity) { this.accountActivity = accountActivity; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public void addAccountActivity(AccountActivity activity) { // Make sure ordering is maintained, JPA only does this on loading int i = 0; while (i < getAccountActivity().size()) { if (getAccountActivity().get(i).getDate().compareTo(activity.getDate()) <= 0) break; i++; } getAccountActivity().add(i, activity); } } @MappedSuperclass public abstract class AbstractNamedDomain extends AbstractDomain { private String name; public AbstractNamedDomain() { } public AbstractNamedDomain(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @MappedSuperclass public abstract class AbstractDomain implements Serializable { @Id @GeneratedValue private long id = NEW_ID; public static long NEW_ID = -1; public long getId() { return id; } public void setId(long id) { this.id = id; } public boolean isNew() { return id==NEW_ID; } } ```
2008/12/17
[ "https://Stackoverflow.com/questions/374886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32713/" ]
I actually came across another way that this can happen. In an injected EntityManager, no updates will ever occur if you have persistence.xml specified like this: `<persistence-unit name="primary" transaction-type="RESOURCE_LOCAL">` You need to remove the transaction-type attribute and just use the default which is JTA.
Probably you're keeping the transaction active and it is not calling "commit" until other methods running supporting the active transaction end (all "voting" for commit and none for rollback.) If you're sure that the entity you're going to persist is ok you could probably do this: ``` @TransactionManagement(TransactionManagementType.BEAN) public class AccountManager implements IAccountManager { ..} ``` and manage your entity persistance adding: ``` @Resource private SessionContext sessionContext; public Account storeAccount(Account ac) { sessionContext.getUserTransaction().begin(); ac = em.merge(ac); em.persist(ac); sessionContext.getUserTransaction().commit(); return ac; } ```
30,252,911
The following `select` query is to search a keyword 'law' from multiple tables `tbl_books`, `tbl_author` and `tbl_books_subject` ``` SELECT * FROM tbl_books p, tbl_books_author d, tbl_books_subject m WHERE p.title = 'law' OR d.author = 'law' OR m.subject = 'law' LIMIT 0,30 ``` This query is giving error. Please help me with it.
2015/05/15
[ "https://Stackoverflow.com/questions/30252911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4902657/" ]
You need three separate SELECTs (and probably a wildcard search): ``` SELECT * FROM tbl_books WHERE title LIKE '%law%' LIMIT 0,30 SELECT * FROM tbl_books_author WHERE title LIKE '%law%' LIMIT 0,30 SELECT * FROM tbl_books_subject WHERE title LIKE '%law%' LIMIT 0,30 ``` If you return compatible results you might UNION them: ``` SELECT 'book ', title FROM tbl_books WHERE title LIKE '%law%' UNION ALL SELECT 'author ', author FROM tbl_books_author WHERE title LIKE '%law%' UNION ALL SELECT 'subject', subject FROM tbl_books_subject WHERE title LIKE '%law%' LIMIT 0,30 ```
You can achieve that in single query but you need to have some foreign key in other tables. Here check the code below. ``` SELECT b.*, ba.*, bs.* FROM tbl_books as b FULL OUTER JOIN tbl_books_author as ba ON ba.book_id=b.id FULL OUTER JOIN tbl_books_subject as bs ON bs.book_id=b.id WHERE b.title LIKE 'law' OR ba.author LIKE 'law' OR bs.subject LIKE 'law' LIMIT 0, 30; ``` look at the query deeply you can see I have used **tbl\_books.id** to make joins which should be in other tables to identify that particular records. Hope this helped you.
19,962,809
I need help please - here's a little history.. I have a google schedule - <https://docs.google.com/spreadsheet/ccc?key=0ArmKEmhue9OgdEFwMHBldFpGenNVdzJUQThCQU9Qcmc&usp=sharing> Within that schedule there are numerous sheets but the ones that I was hoping to get help with is the Form Responses 1 and PROJECTS sheet I have a google form - <https://docs.google.com/forms/d/1yFy3i5H3abhFjdvchuJq2ARODcfRGo6KNkOAgeRIMMU/viewform> It's linked to the google schedule and with each submission the data goes in the Form Responses 1 sheet - There is a script applied to the spreadsheet - **COPYING TO/FROM SCRIPT** ``` /** * A function named onEdit will be called whenever * a change is made to the spreadsheet. * * @param {object} e The edit event (not used in this case) */ function onFormSubmit(e){ var copyFromRange = 'Form Responses 1!A2:AC999'; var copyToRangeStart = 'PROJECTS!A71:AC999'; copyValuesOnly(copyFromRange, copyToRangeStart); } /** * This function will copy the values from a given range to * a second range, which starts from the given cell reference * * @param {string} copyFromRange Range reference eg: * @param {string} copyToRangeStart Cell reference eg: */ function copyValuesOnly(copyFromRange, copyToRangeStart) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var source = ss.getRange(copyFromRange); source.copyTo(ss.getRange(copyToRangeStart), {contentsOnly: true}); } ``` This is allowing the data to copy over to the PROJECTS sheet so multiple users can edit and update BUT realized that it overrides the data each time a new submission comes in Also just to note within the Form Responses 1 sheet under column C "Project Number" there is a forumula =ArrayFormula("MC"&TEXT(ROW(A2:A)-1 ; "000") ) that I placed to allow for automatically numbering each submission with a project number **I also have a ARCHIVE script -** Once a project is final, under column G "Archive" if you type "DONE" it then moves to the ARCHIVE sheet function onEdit() { ``` // moves a row from a sheet to another when a magic value is entered in a column // adjust the following variables to fit your needs // see https://productforums.google.com/d/topic/docs/ehoCZjFPBao/discussion var sheetNameToWatch1 = "PROJECTS"; var sheetNameToWatch2 = "ADVERTISING"; var columnNumberToWatch = 7; // column A = 1, B = 2, etc. var valueToWatch = "DONE"; var sheetNameToMoveTheRowTo = "ARCHIVE"; var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getActiveCell(); if ( (sheet.getName() == sheetNameToWatch1 || sheet.getName() == sheetNameToWatch2) && range.getColumn() == columnNumberToWatch && range.getValue() == valueToWatch) { var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo); var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1); sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange); sheet.deleteRow(range.getRow()); } } ``` **ISSUES -COPYING** - When a new submission is entered using the form, the data comes in Form Responses 1 sheet and then copies to PROJECTS sheet BUT you cannot edit the data under PROJECTS because each submission overrides any edits and brings in the original form submission data - What I would like to have happen is the data comes in Form Responses 1 sheet then copies to PROJECTS sheet on each submission but then does not override when a new submission comes in and any changes to the data under PROJECTS stays there **ISSUES - PROJECT NUMBER** - the formula setup under Form Responses 1 sheet under column C row 2 - each row has a project number assigned and then it copies to the PROJECTS sheet, when the row is then archived ("DONE) and moves to the ARCHIVE sheet the project number assigned to that row goes with it BUT when you submit a new project the same number can be applied to a new project so then ultimately when you archive all the projects many will have the same project number, is there a way to make each project have a unique project number? \**ISSUES - SUBMIT FORM \** - I am not sure why but when a new submission comes in the data is coming in at row 113 each time, not at the end of the form responses rows? Any help would be greatly appreciated - I thought it was going to work but seems the script isn't the right setup for what I would like it to do Thanks so much, Paola G
2013/11/13
[ "https://Stackoverflow.com/questions/19962809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2540437/" ]
Don't use inline JS to do that. Instead use event delegation: ``` $(document).on('click', '.closeAlerts', function(){ $(this).parent().remove(); }); ```
You can set `this` as parameter in function ``` <div class="closeAlerts" onclick="closeAlert(this)">Dismiss</div> ``` And `this` will be your `div` object. But I'm not reccomend you to use embedded javascript code in html elements. Try to separate js code from html.
16,195
In [a review of an entry level DSLR](http://www.dpreview.com/reviews/nikond3100/page19.asp), I found this: > > [this] is an excellent DSLR but make clear that a DSLR is no longer the only way to gain large sensor image quality at this price [around $500] > > > What are the alternatives the reviewer is alluding to? Would they still have interchangeable lens? To be clear, I'm not after specific models, I'm just interested in understanding the kind of camera the reviewer had in mind.
2011/10/05
[ "https://photo.stackexchange.com/questions/16195", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/534/" ]
To specifically answer your question "What are the alternatives the reviewer is alluding to?" If you go to [this](http://www.dpreview.com/reviews/nikond3100/page16.asp "Page 16 - compared to (JPEG)") page of the review, you will see that dpreview have compared the image quality with the following non-dslr cameras: * Olympus PEN E-PL1 * Sony NEX-5 They are both available (in the UK) for less money than the d3100. Note that I haven't tried any of these cameras so I couldn't advise as to their individual strengths. If you are not sure which of these styles you prefer, try and find some friends with similar cameras, or failing that, try in a local camera store.
what it means is that something has a product to sell that's priced like a DSLR but isn't a DSLR, and is trying to convince people to look for his product rather than a DSLR who are susceptible to "new and improved" as the main reason to buy something different from the established standard.
60,406,254
```cpp #include <iostream> struct A{ A(int){ } }; struct B{ B() = default; B(A){ } B(B const&){} B(B&&){} }; int main(){ B b({0}); } ``` For the given codes, the candidate functions are: ``` #1 B::B(A) #2 B::B(const B&) #3 B::B(B&&) ``` According to the standard, for #1, the object of type A is copy-list-initialized by {0} as `A a = {0}`, `A::A(int)` is considered for the initialization, so only the standard conversion within #1. For #2, it's an initialization of a reference form `braced-init-list` which is the cause of [[dcl.init.list]](https://timsong-cpp.github.io/cppwp/n4659/dcl.init.list#3.9) > > Otherwise, if T is a reference type, a prvalue of the type referenced by T is generated. The prvalue initializes its result object by copy-list-initialization or direct-list-initialization, depending on the kind of initialization for the reference. The prvalue is then used to direct-initialize the reference. [ Note: As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference to a non-const type.  — end note ] > > > So it equates with `const B& = {0}`, in this initialization, the conversion function is `B::B(A)` and the argument is `0`, so `B tmp = {0}` and 'B::B(A)' is considered that parameter is initialized by argument `0`, as `A parameter = 0`. > > Otherwise (i.e., for the remaining copy-initialization cases), **user-defined** conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in [over.match.copy], and the best one is chosen through overload resolution... > > > So there's a user-defined conversion within #2 and the situation of #3 is the same as that of #2 and accroding to the [[over.ics.rank]](https://timsong-cpp.github.io/cppwp/n4659/over.ics.rank#2.1), > > a standard conversion sequence is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and... > > > The standard conversion is better than user-defined conversion, so #1 should be better than #2 and #3, but actually, g++ report the invocation is ambiguous, why? The error message is: ``` main.cpp: In function ‘int main()’: main.cpp:12:10: error: call of overloaded ‘B(<brace-enclosed initializer list>)’ is ambiguous B b({0}); ^ main.cpp:8:3: note: candidate: B::B(A) B(A){ ^ main.cpp:6:8: note: candidate: constexpr B::B(const B&) struct B{ ^ main.cpp:6:8: note: candidate: constexpr B::B(B&&) ```
2020/02/26
[ "https://Stackoverflow.com/questions/60406254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11796722/" ]
pass argument to withInput() $request->all() like this ``` return Redirect::back()->withErrors($Validator)->withInput($request->all()); ```
use **Validator** to handle errors - check this - [LINK](https://laravel.com/docs/6.x/validation) ``` use Validator; $validator = Validator::make($request->all(),[ 'username' => 'required|unique:userlists,username|max:20', 'email' => 'required|email|unique:userlists,email|max:20', 'password' => 'required', 'bod' => 'required', 'comments' => 'required', 'Phone_no' => 'required', 'gender' => 'required', 'agreement' => 'required', ],[ 'username.required' => 'Please Enter Your Username', 'email.required' => 'Please Enter Your Username', 'password.required' => 'Please Enter Your Username', 'bod.required' => 'Please Enter Your Username', 'comments.required' => 'Please Enter Your Username', 'Phone_no.required' => 'Please Enter Your Username', ]); if($validator->fails()){ return Redirect::back()->withErrors($validator)->withInput(); } ``` EDITED ``` if($validator->fails()){ return Redirect::back()->withErrors($validator)->withInput($request->all()); //change order if not work above //return Redirect::back()->withInput($request->all())->withErrors($validator); } ```
37,195
I remember reading somewhere that to evacuate a person is a medical procedure, and not something to be done during an earthquake. (I thought it was in Fowler, but I just looked and couldn't see it). The point is that it is the *building* that is being evacuated, not the people. "Evacuate" comes from the Latin word for "to empty out". If this is so, what is happening to the people that are being helped out of a building that is being evacuated? I was reminded of this question during an episode of CSI: Miami (don't judge me) where someone tells flame-haired Horatio Caine that "You helped evacuate me yesterday". What *should* she have said to him? "You helped evacuate the building I was in" sounds a little circumlocutionary. I should have anticipated answers saying "You can use evacuate like that". As far as I can tell, the [OED](http://oed.com/view/Entry/65161) doesn't allow "evacuate" to be the verb that you do to people when removing them from a burning building. So there isn't quite a consensus that I'm barking up the wrong tree, although the concise OED allows "to remove from a place of danger". Let's say I didn't want to do that for the (perhaps mistaken) reason that it was worth having a distinction between what is being made empty and what it is being emptied *of*. Let's say I'm super-worried about there being some confusion about whether Horatio helped the woman get to the hurricane shelter or whether he helped perform an unlicensed medical procedure on her. Both might be legitimate readings of "He helped her evacuate". I want this to refer to the latter, so how would I unambiguously talk about the former?
2011/08/08
[ "https://english.stackexchange.com/questions/37195", "https://english.stackexchange.com", "https://english.stackexchange.com/users/879/" ]
I'd say that you are [rescuing](http://dictionary.reference.com/browse/rescue) them, or helping them [exit](http://dictionary.reference.com/browse/exit) the building.
As others have noted, it is completely correct to say, "You evacuated me from the building." I just checked two dictionaries and both list "to withdraw inhabitants from a threatened area" (with slightly different wording) as one of the definitions. So when the questioner says that this usage is incorrect and the person should have used different wording, this is simply wrong. Yes, the word has multiple meanings, but this is one of them. Actually in ordinary usage, I think it's the most common meaning. It's certainly possible that in any given case, the meaning could be ambiguous. (This word is hardly unique in that way. Lots of words have multiple definitions that can sometimes result in ambiguity.) If you are talking to a nurse who performs enemas, and who once helped you escape from a burning building, yes, "You evacuated me last month" could be ambiguous. In practice, though, I think the poster has it backwards. If you use the word "evacuate", most English-speaking people think of fleeing a place of danger or helping other to flee a place of danger, not the emptying of body contents. If anything, you'd more likely need to clarify that you meant the medical procedure and not getting out of someplace.
147,621
I want to get the output [![matrix](https://i.stack.imgur.com/ZZNWK.png)](https://i.stack.imgur.com/ZZNWK.png) from the code ``` Do[ Print[ Flatten[Table[j + k + s + l, {j, -1, 1}, {k, -2, 1}]]], {s, -1, 1}, {l, -2, 1}] ```
2017/06/05
[ "https://mathematica.stackexchange.com/questions/147621", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/49153/" ]
Don't use `Do` and `Print`; use `Table` with `Flatten` or maybe `ArrayReshape`. ``` m = Flatten[ Table[ Flatten[Table[j + k + s + l, {j, -1, 1}, {k, -2, 1}]], {s, -1, 1}, {l, -2, 1}], 1] m // MatrixForm ``` [![matrix](https://i.stack.imgur.com/PA31M.png)](https://i.stack.imgur.com/PA31M.png) ``` m = ArrayReshape[ Table[j + k + s + l, {j, -1, 1}, {k, -2, 1}, {s, -1, 1}, {l, -2, 1}], {12, 12}] ``` will give the same result with `MatrixForm` but requires explicitly giving the dimensions of the array to be built.
Equivalent output: ``` Array[Plus, {3, 4, 3, 4}, {-1, -2, -1, -2}] ~Flatten~ {{3, 2}, {1, 4}} ``` Or for the particular case illustrated: ``` Array[Plus, {3, 4, 3, 4}] ~Flatten~ {{3, 2}, {1, 4}} - 10 ``` $\left( \begin{array}{cccccccccccc} -6 & -5 & -4 & -3 & -5 & -4 & -3 & -2 & -4 & -3 & -2 & -1 \\ -5 & -4 & -3 & -2 & -4 & -3 & -2 & -1 & -3 & -2 & -1 & 0 \\ -4 & -3 & -2 & -1 & -3 & -2 & -1 & 0 & -2 & -1 & 0 & 1 \\ -3 & -2 & -1 & 0 & -2 & -1 & 0 & 1 & -1 & 0 & 1 & 2 \\ -5 & -4 & -3 & -2 & -4 & -3 & -2 & -1 & -3 & -2 & -1 & 0 \\ -4 & -3 & -2 & -1 & -3 & -2 & -1 & 0 & -2 & -1 & 0 & 1 \\ -3 & -2 & -1 & 0 & -2 & -1 & 0 & 1 & -1 & 0 & 1 & 2 \\ -2 & -1 & 0 & 1 & -1 & 0 & 1 & 2 & 0 & 1 & 2 & 3 \\ -4 & -3 & -2 & -1 & -3 & -2 & -1 & 0 & -2 & -1 & 0 & 1 \\ -3 & -2 & -1 & 0 & -2 & -1 & 0 & 1 & -1 & 0 & 1 & 2 \\ -2 & -1 & 0 & 1 & -1 & 0 & 1 & 2 & 0 & 1 & 2 & 3 \\ -1 & 0 & 1 & 2 & 0 & 1 & 2 & 3 & 1 & 2 & 3 & 4 \\ \end{array} \right)$
48,872,361
I'm using Sonatype Nexus as a Docker Registry and after a while, it got really big (new image with every CI build and some old projects). I tried using "Purge unused docker manifests and images" task, but it doesn't seem to do anything.
2018/02/19
[ "https://Stackoverflow.com/questions/48872361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6657236/" ]
You will need to setup Cleanup Policy. [![enter image description here](https://i.stack.imgur.com/1VKYh.png)](https://i.stack.imgur.com/1VKYh.png)
Create a cleaning policy (for example: 15 days after modification) - Caveat: `docker push` of the same hash is *not* modification For each your registry (Nexus calls it "repository of type Docker"): * Setup the cleaning policy of your choice * The cleanup task + Create + Run until finish + Check the nexus3.log file * The "remove unused manifests and images" + Create + Run until finish + Check the nexus3.log file * The "compact blob" task + Create + Run until finish + Check the nexus3.log file * The space should be freed now * Don't use Nexus in your next project * ... * Profit
56,764,028
would like to identify the number of firms that start and end each month. The goal is to say by column how much firms start and end. My data looks like this, with many more rows and columns. ``` Firm Return_1990_01 Return_1990_02 Return_1990_03 Return_1990_04 Return_1990_05 #1 fg23 NaN NaN 1.54 2.34 .641 #2 sdf1 1.35 NaN 3.53 NaN .231 #3 sdf1 1.12 2.44 1.51 1.64 NaN ``` One challenge is that a firm can have NaNs in between. For example, Row 2 the firm begins 1990\_01 and ends 1990\_05 despite NaNs in between. I tried the following code ``` library(dplyr) library(tidyr) df %>% gather(month, value, -Firm) %>% filter(!is.nan(value)) %>% arrange(Firm, month) %>% group_by(Firm) %>% summarise(start = first(month), end = last(month)) ``` But get the following error message ``` Error in arrange_impl(.data, dots) : data frame column with incompatible number of rows (465), expecting : 59378 ``` Any help is appreciated.
2019/06/26
[ "https://Stackoverflow.com/questions/56764028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3962801/" ]
Another way to represent this with column names using `tidyverse`. We `gather` the data into long format and select only first and last value for each row. Create a new column (`temp`) which holds `"Start"` and `"End"` for each group and `spread` it to wide format. ``` library(dplyr) library(tidyr) df %>% mutate(row = row_number()) %>% gather(key, value, -Firm, -row, na.rm = TRUE) %>% group_by(row) %>% slice(c(1L, n())) %>% mutate(temp = c("Start", "End")) %>% select(-value) %>% spread(temp, key) %>% ungroup %>% select(-row) %>% select(Firm, Start, End) # Firm Start End # <fct> <chr> <chr> #1 fg23 Return_1990_03 Return_1990_05 #2 sdf1 Return_1990_01 Return_1990_05 #3 sdf1 Return_1990_01 Return_1990_04 ```
With `tidyverse`, we can do this without any reshaping with `pmap`. Find the `names` of the elements that are not NaN with `which`, get the `first` and `last` column names ``` library(tidyverse) df %>% transmute(Firm, start_end = pmap(.[-1], ~ which(!is.nan(c(...))) %>% names %>% range %>% {tibble(start = first(.), end = last(.))})) %>% unnest # Firm start end #1 fg23 Return_1990_03 Return_1990_05 #2 sdf1 Return_1990_01 Return_1990_05 #3 sdf1 Return_1990_01 Return_1990_04 ``` --- In `base R`, we can also do this in a vectorized way with `max.col` ``` m1 <- !is.na(df[-1]) start <- colnames(m1)[max.col(m1, "first")] end <- colnames(m1)[max.col(m1, "last")] cbind(df1['Firm'], start, end) # Firm start end #1 fg23 Return_1990_03 Return_1990_05 #2 sdf1 Return_1990_01 Return_1990_05 #3 sdf1 Return_1990_01 Return_1990_04 ```
15,967,652
I have an apache httpd server, say **server1\* (publicly exposed) that is acting as load balancer for some jboss servers(behind firewall) using mod\_cluster. Now I want to install my static content (images/css/htmls) and probably some cg-scripts on a couple of apache servers, say \*\*server2** and **server3** (behind firewall). Now I want **server1** to act as load balancer for these server2 and server3 as well along with the jboss servers. With this arrangement, any request for applications deployed on jboss need to be routed to jboss and any static content request should go to **server2** or **server3**. Here are the versions I am using Linux Server apache httpd - 2.2.22 JBOSS-EAP-6 What mechanism/configuration do I need to use in **server1** to make it possible? Please see if someone can help with this.
2013/04/12
[ "https://Stackoverflow.com/questions/15967652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2273375/" ]
Well, you just add a ProxyPass setting. mod\_cluster is compatible with ProxyPass, so you can use both. For instance, if I would like gif images to be served by httpd, not by AS7, I can add: ``` ProxyPassMatch ^(/.*\.gif)$ ! ``` Furthermore, if you set ``` CreateBalancers 1 ``` mod\_cluster won't create proxies for you and you have to do it yourself. This gives you an additional control. For instance: ``` ProxyPassMatch ^/static/ ! ProxyPass / balancer://qacluster stickysession=JSESSIONID|jsessionid nofailover=on ProxyPassReverse / balancer://qacluster ProxyPreserveHost on ``` In the aforementioned example, we proxy anything but /static/ content to the workers. * Note:If you encounter any cookies related issues, you might want to play with ProxyPassReverseCookieDomain and ProxyPassReverseCookiePath. * Note **qacluster** in my config. The default is **mycluster**, so for naming my balancer qacluster, I added this to mod\_cluster config (outside VirtualHost): ``` ManagerBalancerName qacluster ``` If it is not clear, just reply and I can try to elaborate further.
I had the same issue where in we were using Apache HTTP server for static content and JBOSS AS 7 server for dynamic contents (the JSF web app). So adding the below property at the end of Load modules tells ``` CreateBalancers 0 ``` Tells to **"0: Create in all VirtualHosts defined in httpd."** More at: <http://docs.jboss.org/mod_cluster/1.2.0/html/native.config.html#d0e485> And the below config solved the issues of images and styel sheets not getting displayed. ``` <VirtualHost *:80> ServerName dev.rama.com DocumentRoot "/var/www/assests" UseAlias 1 ProxyPassMatch ^(.*\.bmp)$ ! ProxyPassMatch ^(.*\.css)$ ! ProxyPassMatch ^(.*\.gif)$ ! ProxyPassMatch ^(.*\.jpg)$ ! ProxyPassMatch ^(.*\.js)$ ! ProxyPassMatch ^(.*\.png)$ ! <Directory /var/www/assests> Options Indexes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> ``` Note: All our assests for the web app was on HTTP server at /var/www/assests and the url I was accessing was dev.rama.com on port 80 So when it sees this **ProxyPassMatch ^(.\*.css)$ !** The webserver knows that the css files are local to the http server and we dont need to go to Jboss App server. More info at <http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass>
8,500,309
How to add a div after all dd tags through jquery ? ``` $(document).ready(function(){ $('dd').xyz('<div class="clear"></div>'); // what will be this xyz function }); ``` I have the following HTML structure - ``` <dl> <dt>A</dt> <dd>AA</dd> <dt>B</dt> <dd>BB</dd> </dl> ```
2011/12/14
[ "https://Stackoverflow.com/questions/8500309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078254/" ]
It should be like - `$('<div class="clear" />').insertAfter('dd');`
``` $(document).ready(function(){ $('dd').after('<div class="clear"></div>'); }); ``` Here is example, I've created jsfiddle <http://jsfiddle.net/VWYf4/>
27,855
I am reading up on the `Carhart Four-Factor` model. Let's say there a regression of stock returns on alpha, `RM-RF`, `SMB` (small minus big stocks returns), `HML` (high minus low value stock returns) and `UMD` (up minus down trend stocks). Let's say my portfolio consists of mostly high value stocks (Apple, Google), yet my `HML` coefficient has a t-value of 5 and is therefore very significant. How would I interpret this and how is this possible? I am trying to do the regression but `RMRF`, `SMB`, `HML` and `UMD` all have very highly significant coefficients whereas alpha's coefficient is always the only one very far from significant at ~0.4 t value. I have trouble how to interpret the other coefficients meaning and therefore help would be much appreciated.
2016/06/29
[ "https://quant.stackexchange.com/questions/27855", "https://quant.stackexchange.com", "https://quant.stackexchange.com/users/22366/" ]
Factor models tell you how the returns of your portfolio are related to the returns of the models' factors. In this case, after controlling for the relation with the size, momentum, and market factors, your portfolio is positively related to the value factor. We often say it *loads on* the value factor (meaning it is exposed to the type of risk that is in the HML portfolio). Why does that surprise you? Is it because you think *ex ante* that you know that your portfolio is made up of growth stocks? If so, bear in mind the following: * There a many definitions of value/growth. You seem to have in mind that value means "cheap." This is one definition, but not the one Fama and French use to construct their HML factor. * Just because a stock qualifies as value, even by the Fama-French definition, that doesn't mean it will necessarily have a positive loading on the HML factor. That's the **fallacy of division**. If you have a lot of stocks in your portfolio and they really are growth stocks, then maybe you made a mistake in your math somehow. Otherwise I think you are making wrong assumptions about the probability of the member of a population (or several members) having traits that differ from those of the population as a whole. Generically, the interpretation of a positive coefficient is that your particular portfolio has a lot of whatever type of risk is in the value portfolio, not that is **is** necessarily a value portfolio. If yours really is a diversified portfolio of growth stocks (as defined by Fama and French), a negative HML coefficient would be likely, but I doubt that is really the case for your portfolio.
your modeling was similar to the original paper? in this case a negative momentum coeficient is telling you that for this timeframe the winners of the last period are not the winners in this period.
13,899,746
I have the following command: ``` find . -type d -mtime 0 -exec mv {} /path/to/target-dir \; ``` This will move the directory founded to another directory. How can I use `xargs` instead of `exec` to do the same thing.
2012/12/16
[ "https://Stackoverflow.com/questions/13899746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203997/" ]
If you've got GNU [`mv`](http://www.gnu.org/software/coreutils/manual/html_node/mv-invocation.html) (and `find` and `xargs`), you can use the `-t` option to `mv` (and `-print0` for `find` and `-0` for `xargs`): ``` find . -type d -mtime -0 -print0 | xargs -0 mv -t /path/to/target-dir ``` --- Note that modern versions of `find` (compatible with POSIX 2008) support `+` in place of `;` and behave roughly the same as `xargs` without using `xargs`: ``` find . -type d -mtime -0 -exec mv -t /path/to/target-dir {} + ``` This makes `find` group convenient numbers of file (directory) names into a single invocation of the program. You don't have the level of control over the numbers of arguments passed to `mv` that `xargs` provides, but you seldom actually need that anyway. This still hinges on the `-t` option to GNU `mv`.
With [BSD xargs](http://www.unix.com/man-page/freebsd/1/xargs/) (for **OS X** and FreeBSD), you can use `-J` which was built for this: ``` find . -name some_pattern -print0 | xargs -0 -J % mv % target_location ``` That would move anything matching `some_pattern` in `.` to `target_location` With [GNU xargs](http://www.unix.com/man-page/linux/1/xargs/) (for **Linux** and Cygwin), use `-I` instead: ``` find . -name some_pattern -print0 | xargs -0 -I % mv % target_location ``` The deprecated `-i` option of GNU xargs implies `-I{}` and can be used as follows: ``` find . -name some_pattern -print0 | xargs -0 -i mv {} target_location ``` Note that BSD xargs also has a `-I` option, but that does something else.
2,792,932
I've got some settings saved in my Settings.bundle, and I try to use them in `application:didFinishLaunchingWithOptions`, but on a first run on the simulator accessing objects by key always returns `nil` (or 0 in the case of ints). Once I go to the settings screen and then exit, they work fine for every run thereafter. What's going on? Isn't the point of using default values in the Settings.bundle to be able to use them without requiring the user to enter them first?
2010/05/08
[ "https://Stackoverflow.com/questions/2792932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
If I got your question right, in your app delegate's - (void)applicationDidFinishLaunching:(UIApplication \*)application, set the default values for your settings by calling registerDefaults:dictionaryWithYourDefaultValues on [NSUserDefaults standardUserDefaults] ``` - (void)applicationDidFinishLaunching:(UIApplication *)application { NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:3], @"SomeSettingKey", @"Some string value", @"SomeOtherSettingKey", nil]; [ud registerDefaults:dict]; } ``` These values will only by used if those settings haven't been set or changed by previous executions of your application.
> > Isn't the point of using default > values in the Settings.bundle to be > able to use them without requiring the > user to enter them first? > > > No. The point of the settings bundle is to give the user a place to edit all 3rd Party app settings in a convenient place. Whether or not this centralization is really a good idea is a User Experience issue that is off topic. To answer your question, you should detect if it is the first load, then store all your defaults initially. And while we are on the subject, I would also check out [In App Settings Kit](http://inappsettingskit.com/) as it provides your app with a simple way to display your app settings in both places (in-app and Settings.app) with minimal code.
456,221
[![enter image description here](https://i.stack.imgur.com/2AL7i.jpg)](https://i.stack.imgur.com/2AL7i.jpg) So I have a bunch of these FFC connectors shown here, and a lot of the middle pins are actually ground pins (highlighted in green). I have a multi-layer board, so I want to route all these grounds to an internal layer. Do I need to run separate tracks from each pin and then use separate vias to go the internal layer? Or I can short them all by running a trace across them and then use a single fat via to go the next layer? Sorry I'm a complete newbie to PCB design, I don't have much idea about proper routing techniques.
2019/09/05
[ "https://electronics.stackexchange.com/questions/456221", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/230289/" ]
Take a look at a randomly chosen old op-amp, for example the [TL081](http://www.ti.com/lit/ds/symlink/tl082.pdf). The single-amp version will often have two pins named "offset null" or similar. This is because they have a fairly large offset voltage that can cause problems if you want to amplify DC levels, and the offset voltage is different for each IC. There are [many ways](http://www.ti.com/lit/an/sloa045/sloa045.pdf) to connect these pins but normally it's just a trimpot connected to the pins, with the wiper connected to the most negative supply rail.
It means adjusting the op amp input offset voltage error towards zero with components external to the op amp, such as trimmer potentiometer or resistors connected to op amp adjustment pins.
5,701,281
is there any way to route a ServiceMix message by operation specified in that message? I've tried googling it but was unable to find any way to complete this simple task, maybe I am doing it wrong in first place? I've got an adapter that dispatches 2 types of messages. 2 other adapters have to catch them and give a response. Both messages have identical bodies (for example let it be some `<product>...</product>`) but the operation differs (for example `update` and `create`). How do I route that messages to different adapters? Thanks in advance.
2011/04/18
[ "https://Stackoverflow.com/questions/5701281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43677/" ]
awk can take a regular expression as field separator, so use either parenthesis as the field separator and just emit the 2nd field: ``` awk -F'[()]' '{print $2}' filename ```
You can remove everything from beginning of line until the first `(` and from (including) the last `)` till the end of line with `sed`: ``` sed -r 's/^[^(]*\(.*)\)[^)]*$/\1/' ```
3,160,866
Given $A,B \in P(N)$ We mark $\overline{\sim}$ as $$A\overline{\sim} B = \{x+y : \langle x,y\rangle\in A\times B\}$$ Now, order R will be as following $ARB$ iff $\exists M\in P(N)$ so $A\overline{\sim} M=B$. The question is R is reflexive? symmetric? anti-symmetric? transitive? I think R is partial order, i.e reflexive, anti-symmetric and transitive. and I need to prove it. I think my proof is correct for reflexive so let`s focus on anti-symmetric and transitive. Just for make it sure - N is Set of Natural numbers, including zero. Here what I done for proving transitive: Let $A,B,C \in P(N)$ and assume ARB and BRC. ARB so exists $T \in P(N)$ so $A\overline{\sim} T=B$ BRC so exists $S \in P(N)$ so $B\overline{\sim} S=C$ Let define M as following set: $\{K+P | k\in T$ and $p\in S\}$ $S,T\in P(N)$ so $M\in P(N)$ we need to show $A\overline{\sim} M=C$ Let $q\in A\overline{\sim} M$ here I got stuck, since I have no idea how to show that $q\in C$. Might this R is not transitive? Anti-Symmetric: Let $A,B\in P(N)$ and assume ARB and BRA we need to show A=B. let $a\in A$ ARB so exists $M\in P(N)$ so $A\overline{\sim} M=B$ and here I got stuck. Can we say that M is a set with just a zero element? we have exists as not as target so we can`t choose it, I think.. Might R is not anti-symmetric? Any help would be appreciated.
2019/03/24
[ "https://math.stackexchange.com/questions/3160866", "https://math.stackexchange.com", "https://math.stackexchange.com/users/536356/" ]
You got off to a great start with your transitivity proof! Note that $M=T\overline{\sim} S.$ Having chosen $q\in A\overline{\sim}M,$ we know that $q=a+m$ for some $a\in A$ and some $m\in M.$ Since $M=T\overline{\sim} S,$ then $m=t+s$ for some $t\in T$ and some $s\in S,$ whence $$q=a+(t+s)=(a+t)+s.$$ Since $a\in A$ and $t\in T,$ then $a+t\in A\overline{\sim} T=B,$ so since $s\in S,$ then $q\in B\overline{\sim} S=C.$ Thus, $A\overline{\sim}M\subseteq C.$ On the other hand, suppose that $q\in C=B\overline{\sim} S,$ so that $q=b+s$ for some $b\in B$ and $s\in S.$ Since $B=A\overline{\sim} T,$ then $b=a+t$ for some $a\in A$ and $t\in T,$ so that $$q=(a+t)+s=a+(t+s),$$ and since $M:=T\overline{\sim}S,$ then $q\in A\overline{\sim}M.$ Thus, $C\subseteq A\overline{\sim}M,$ so $C=A\overline{\sim}M,$ and so $ARM,$ as desired. --- You started the proof of antisymmetry just as I would have, but you didn't follow through. Indeed, $A\overline{\sim}M=B$ for some $M,$ but also $B\overline{\sim}L=A$ for some $L.$ Thus, $a=b+l$ for some $b\in B$ and $l\in L.$ Furthermore, since $b\in B=A\overline{\sim} M,$ then $b=a'+m$ for some $a'\in A$ and $m\in M,$ so that $a=(a'+m)+l=a'+(m+l).$ It follows that $A\subseteq A\overline{\sim}(M\overline{\sim}L).$ On the other hand, take $x$ to be any element of $A\overline{\sim}(M\overline{\sim}L),$ so that $x=a+(m+l)=(a+m)+l$ for some $a\in A,m\in M,l\in L.$ Since $a+m\in A\overline{\sim}M=B,$ then $x\in B\overline{\sim}L=A.$ Thus, $A\overline{\sim}(M\overline{\sim}L)\subseteq A,$ and so $A=A\overline{\sim}(M\overline{\sim}L).$ Now, if $A=\emptyset,$ it's clear that $A\overline{\sim}M=\emptyset$ by the definition of $\overline{\sim},$ so $B=A$ in that case. Suppose that $A$ is not empty, and let $a\_0$ be the least element of $A.$ Since $a\_0\in A=A\overline{\sim}(M\overline{\sim}L),$ then $a\_0=a+(m+l)$ for some $a\in A,m\in M,l\in L.$ Consequently, $a\le a\_0,$ so that $a=a\_0$ by our choice of $a\_0$ as the least element of $A.$ Thus, since $m,l\in\Bbb N,$ we conclude that $m=l=0.$ From this, we know that $0\in M$ and $0\in L.$ Thus, taking any $a\in A,$ we have that $a=a+0\in A\sim M=B,$ so $A\subseteq B.$ Similarly, $B\subseteq A,$ and so $A=B,$ as desired.
The usual notation for $\overline{\sim}$ is +. Show + is associative and communitive. Clearly, A + {0} = A, so ARA. Assume ARB, BRC. Thus exists K,L with A + K = B, B + L = C. As A + (K + L) = (A + K) + L = B + L = C, ARC.
67,831,594
I showed data using below angular functions ``` availableLockers = [ { "lockerCode": "L01", "allocStatus": "alloc" }, { "lockerCode": "L02", "allocStatus": "un-alloc" }, { "lockerCode": "L03", "allocStatus": "un-alloc" }, { "lockerCode": "L04", "allocStatus": "temp-alloc" }, { "lockerCode": "L05", "allocStatus": "alloc" },] ``` I am using bellow html ```html <div *ngFor="let locker of availableLockers let i=index;">{{locker.lockerCode}} </div> ``` The above code is working well. currently I need do display count of each status. Ex: how many lockers with "alloc" status, how many lockers with "temp-alloc" status.
2021/06/04
[ "https://Stackoverflow.com/questions/67831594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14753393/" ]
It's better to create a dictionary for the count of each `allocStatus` using [reduce](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) **and then use it where ever you want with O(1) time complexity** ```js availableLockers = [ { lockerCode: "L01", allocStatus: "alloc", }, { lockerCode: "L02", allocStatus: "un-alloc", }, { lockerCode: "L03", allocStatus: "un-alloc", }, { lockerCode: "L04", allocStatus: "temp-alloc", }, { lockerCode: "L05", allocStatus: "alloc", }, ]; const dict = availableLockers.reduce((acc, { allocStatus }) => { if (acc[allocStatus]) ++acc[allocStatus]; else acc[allocStatus] = 1; return acc; }, {}); console.log(dict["alloc"]); console.log(dict["un-alloc"]); console.log(dict["temp-alloc"]); ```
**In Html File** ``` <div *ngFor="let locker of availableLockers; let i=index;"> {{locker.lockerCode}} </div> <div>{{alloc}}</div> <div>{{unAlloc}}</div> <div>{{tempAlloc}}</div> ``` **In TS file** ``` alloc:number = 0; unAlloc:number = 0; tempAlloc:number = 0; ngOnInit(){ availableLockers.forEach((value)=>{ if (value['allocStatus']=='alloc'){ alloc++} elseif (value['allocStatus']=='un-alloc'){ unAlloc++} elseif (value['allocStatus']=='temp-alloc'){ tempAlloc++} }) } ```
2,843,455
Is there a way to resolve mathematical expressions in strings in javascript? For example, suppose I want to produce the string "Tom has 2 apples, Lucy has 3 apples. Together they have 5 apples" but I want to be able to substitute in the variables. I can do this with a string replacement: ``` string = "Tom has X apples, Lucy has Y apples. Together they have Z apples"; string2 = string.replace(/X/, '2').replace(/Y/, '3').replace(/Z/, '5'); ``` However, it would be better if, instead of having a variable Z, I could use X+Y. Now, I could also do a string replace for X+Y and replace it with the correct value, but that would become messy when trying to deal with all the possible in-string calculations I might want to do. I suppose I'm looking for a way to achieve this: ``` string = "Something [X], something [Y]. Something [(X+Y^2)/(5*X)]"; ``` And for the [\_\_\_] parts to be understood as expressions to be resolved before substituting back into the string. Thanks for your help.
2010/05/16
[ "https://Stackoverflow.com/questions/2843455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104421/" ]
The only way I can think of to achieve this would be a templating engine such as [jTemplates](http://jtemplates.tpython.com/). Also see the answers to [this](https://stackoverflow.com/questions/552934/what-javascript-templating-engine-do-you-recommend) SO question.
In ES6 you can now use [template strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings): var X = 2, Y = 3; string = `Tom has ${X} apples, Lucy has ${Y} apples. Together they have ${X+Y} apples`;
5,262,159
How would I go about using an `IF` statement to determine if more than one parameter has a value then do some work, if only one parameter has a value then do other work. Is this possible with the SQL if? I am just trying to determine if one parameter has a value or if multiple parameters has value, because if so then I need to do something completely different. I have tried making a SQL statement but it didnt work properly. Could anyone point me in the right direction?
2011/03/10
[ "https://Stackoverflow.com/questions/5262159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/595208/" ]
In SQL to check if a parameter has a value, you should compare the value to NULL. Here's a slightly over-engineered example: ``` Declare @Param1 int Declare @param2 int = 3 IF (@Param1 is null AND @param2 is null) BEGIN PRINT 'Both params are null' END ELSE BEGIN IF (@Param1 is null) PRINT 'param1 is null' ELSE IF (@Param2 is null) PRINT 'param2 is null' ELSE PRINT 'Both params are set' END ```
You can check the parameter values for NULL values. But it seems like to me at first blush you should check the parameters BEFORE going to the SQL... Once you know what you need to do then call that SQL or Stored Procedure. If you do it that way you can simplify your SQL because you only pass the parameters you really need to pass. Actually the more I think of this the more important it is to do it this way. You can use the NULL values for other things that way. Easy example: Getting a list of employees. Employees are Active or Inactive - Pass an @IsActive boolean parameter (if true only show active employees, if false show only inactive employees, if NULL then show all the employees)
86,743
I am involved with the development of innovative software. The development is innovative since we don't know how to develop it and what algorithm should we use to implement and nobody else did it before. The process consists of several stages of studying books/papers, suggesting algorithms, writing prototypes and comparing the result with actual data. We hope that after some iteration, we converge to a valid software system. Is there any project management software for these types of projects?
2011/06/24
[ "https://softwareengineering.stackexchange.com/questions/86743", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/28844/" ]
> > Is there any project management software for these types of projects? > > > No. There's no "project" until you have a firmly-defined goal. Exploration and Research aren't really amenable to project management. It's exploration of the unknown. If you don't know where you're going, you can't manage the process of getting there. Once you have a goal, you can also define a project.
"The best agile technique" is a contradiction. The [Agile Manifesto](http://agilemanifesto.org/) clearly says "Individuals and interactions over processes and tools", so if you're going to be agile in any real sense you need to pick processes and tools based on the individuals that will be using them.
11,151,228
I really like Python because I can use its shell to explore things. Is it possible to do the same while developing a django app? I mean, is it possible to do: ``` def process_request(request): ... if(request.FILES != none): __builtins__.debug_request = request showPythonShell(); ... ``` so I can experiment with the request? Thanks :D
2012/06/22
[ "https://Stackoverflow.com/questions/11151228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/269334/" ]
Usage of selenium-webdriver behind proxy has browser related specific. In short, you need to find a way of passing proxy settings to the browser instance created by webdriver. Below is a code that works with Firefox. ``` #Firefox keeps proxy settings in profile. profile = Selenium::WebDriver::Firefox::Profile.new profile.proxy = Selenium::WebDriver::Proxy.new( :http => "192.168.1.1:3128") driver = Selenium::WebDriver.for :firefox, :profile => profile driver.navigate.to "http://google.com" puts driver.title driver.quit ```
``` require 'rubygems' require 'selenium-webdriver' ENV['NO_PROXY']="127.0.0.1" driver = Selenium::WebDriver.for :firefox driver.get "http://google.com" ```
2,822,616
We are given angles A and B (70 and 60 respectively). Also AΓ=ΒΔ. Ζ and E are midpoints of AB and ΓΔ respectively. I also drew some bigger circles with radius AH and ΒΘ, trying to see some pattern but with no luck. Geogebra shows that the required angle is 95 degrees but I don't have any clue on how to prove it :( Obviously all midpoints of the 4th side of the quadrilateral, lie on the same line but I can't find its properties. Geometry is not my strong point! [![enter image description here](https://i.stack.imgur.com/Ot5W3.jpg)](https://i.stack.imgur.com/Ot5W3.jpg) ...and here is the original shape: [![enter image description here](https://i.stack.imgur.com/zm2uS.jpg)](https://i.stack.imgur.com/zm2uS.jpg)
2018/06/17
[ "https://math.stackexchange.com/questions/2822616", "https://math.stackexchange.com", "https://math.stackexchange.com/users/330814/" ]
Let us shift this problem to the Coordinate Plane with $A$ at the origin, $AB$ on the $X$ axis, and $AB=2\alpha$. Thus $A\equiv(0,0)$ and $B\equiv(2\alpha,0)$. Also $A\Gamma=B\Delta=r$. Lastly let $\theta=\angle EZB$ $$$$ The equation of $A\Gamma$ is $y=x\tan70^{\circ}$ and the equation of $B\Delta$ is $y=x\tan120^{\circ}-2\alpha\tan120^{\circ}$. $$$$ Thus $\Gamma\equiv (x\_1,x\_1\tan70^{\circ})$ and $\Delta\equiv (x\_2,x\_2\tan120^{\circ}-2\alpha\tan120^{\circ})$. $$$$ Thus the midpoint $E$ has coordinates $\left(\dfrac{x\_1+x\_2}2, \dfrac{x\_1\tan70^{\circ}+x\_2\tan120^{\circ}-2\alpha\tan120^{\circ}}2\right)$. $$$$ Also $$r=x\_1\sec70^{\circ}\Rightarrow x\_1=r\cos70^{\circ}$$ and $$r=x\_2\sec120^{\circ}-2\alpha\sec120^{\circ}\Rightarrow x\_2=(r+2\alpha\sec120^{\circ})\cos120^{\circ}$$ $$$$ Replacing $x\_1,x\_2$ with their equivalent expressions (this looks messy at first but everything gets simplified), $E$ has the coordinates $$$$ $$\left(\dfrac{r\cos70^{\circ}+(r+2\alpha\sec120^{\circ})\cos120^{\circ}}2,\dfrac{{r\cos70^{\circ}\tan70^{\circ}+(r+2\alpha\sec120^{\circ})\cos120^{\circ}\tan120^{\circ}-2\alpha\tan120^{\circ}}}2\right)$$ $$$$ On simplifying, $$E\equiv \left(\dfrac{r\cos70^{\circ}+r\cos120^{\circ}+2\alpha}2,\dfrac{r\sin70^{\circ}+r\sin120^{\circ}}2\right)$$ $$$$ Lastly since $Z$ is the midpoint of $AB$, $Z$ has the coordinates $(\alpha,0)$. $$$$Thus, the slope of $EZ$ is $$\tan\theta=\left( \dfrac{\dfrac{r\sin70^{\circ}+r\sin120^{\circ}}2-0}{\dfrac{r\cos70^{\circ}+r\cos120^{\circ}+2\alpha}2-\alpha}\right)$$ $$$$ $$\Rightarrow\tan\theta=\left( \dfrac{{r\sin70^{\circ}+r\sin120^{\circ}}}{{r\cos70^{\circ}+r\cos120^{\circ}}}\right)$$ $$$$ $$\Rightarrow\theta=\tan^{-1}\left( \dfrac{{r\sin70^{\circ}+r\sin120^{\circ}}}{{r\cos70^{\circ}+r\cos120^{\circ}}}\right)$$ $$$$ $$=\tan^{-1}\left( \dfrac{{\sin70^{\circ}+\sin120^{\circ}}}{{\cos70^{\circ}+\cos120^{\circ}}}\right)$$ $$$$ $$=\tan^{-1}\left( \dfrac{{2\sin95^{\circ}\cos25^{\circ}}}{{2\cos95^{\circ}\cos25^{\circ}}}\right)=\tan^{-1}(\tan95^{\circ})$$ $$$$ Thus $\theta=95^{\circ}$
Alt. hint:  define a complex plane with $\,Z=0, B=1, A=-1, A\Gamma=B\Delta=\lambda \in \mathbb{R}^+\,$. Let $\,\alpha=70^\circ=\frac{7 \pi}{18}\,$, $\,\beta=60^\circ=\frac{\pi}{3}\,$, then $\,\Gamma = -1 + \lambda e^{i\alpha}\,$ and $\,\Delta = 1 + \lambda e^{i(\pi - \beta)}\,$. The midpoint of $\Gamma\Delta$ is $\require{cancel}\,E=\frac{1}{2}(\Gamma+\Delta)=\frac{\lambda}{2}\left(\cancel{-1}+ e^{i\alpha}+\cancel{1}+e^{i (\pi-\beta)}\right)=\frac{\lambda}{2}\left( e^{i\,7\pi/18}+e^{i \,2 \pi / 3}\right)\,$. Angle $\,\angle EZB = \arg E\,$, then using the [identities for sums of sines/cosines](https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Product-to-sum_and_sum-to-product_identities): $$ \begin{align} \frac{2}{\lambda}\,E &\,=\, \left(\cos 70^\circ+\cos 120^\circ\right) + i \left(\sin 70^\circ+\sin 120^\circ\right) \\ &\,=\, 2 \cos \frac{70^\circ+120^\circ}{2} \cos \frac{120^\circ - 70^\circ}{2} + 2i \sin \frac{70^\circ+120^\circ}{2} \cos \frac{120^\circ - 70^\circ}{2} \\ &\,=\, 2 \cos 25^\circ \left( \cos 95^\circ + i \sin 95^\circ\right) \end{align} $$
5,197,274
I have three domain objects: Child, Classroom and ChildClassroom. Here are lists of each: ``` var childrens = new List<Child>() { new Child() { ChildId = 1, FirstName = "Chris" }, new Child() { ChildId = 2, FirstName = "Jenny" }, new Child() { ChildId = 3, FirstName = "Dave" }, }; var classrooms = new List<Classroom>() { new Classroom() { ClassroomId = 1, FullName = "Kindergarten" }, new Classroom() { ClassroomId = 2, FullName = "Elementary" }, new Classroom() { ClassroomId = 3, FullName = "Secondary" }, }; var childclassrooms = new List<ChildClassroom>() { new ChildClassroom() { ClassroomId = 1, ChildId = 1 }, new ChildClassroom() { ClassroomId = 2, ChildId = 1 }, new ChildClassroom() { ClassroomId = 3, ChildId = 2 }, }; ``` What I want is: ``` var childClassroomRelationships = new object[] { new { childid = 1, classrooms = new object[] { new { classroomId = 1, occupied = true }, new { classroomId = 2, occupied = true }, new { classroomId = 3, occupied = false } }, ... }; ``` What's the way to go about this in Linq?
2011/03/04
[ "https://Stackoverflow.com/questions/5197274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86259/" ]
``` var kidsInClass = ( from kid in childrens from c in classrooms select new { ChildID = kid.ChildId, classrooms = ( from cc in childclassrooms select new { ClassroomID = c.ClassroomId, Occupied = cc.ChildId == kid.ChildId }).ToArray() }).ToArray(); ```
You could do this: ``` var childClassroomRelationships = ( from child in children select { childid = child.ChildId, classrooms = ( from classroom in classrooms select new { classroomId = classroom.ClassroomId, occupied = childclassrooms.Any( cc => cc.ChildId == child.ChildId), // Since you wanted an array. }).ToArray() // Since you wanted an array. }).ToArray(); ``` What's very important here is that a join should *not* be used here, if it was, you would get inner join semantics, which would cause children who are not in any classrooms to not show up (which it seems you *don't* want from the example you gave). Note that this will materialize all sequences because of the calls to `ToArray`. Also, it is slightly inefficient, in that to check the occupancy, it has to reiterate the entire `childclassroms` sequence every time. This can be improved by "indexing" the childclassrooms map for efficient lookup, like so: ``` IDictionary<int, HashSet<int>> classroommap = ( from mapping in childclassrooms group mapping.ClassroomId by mapping.ChildId into g select g).ToDictionary(g => g.Key, g => new HashSet<int>(g)); ``` This will give you a map of `HashSet<int>` instances which you can look up the child in once you know the classroom. With that, the first query becomes: ``` var childClassroomRelationships = ( from child in children select { childid = child.ChildId, classrooms = ( from classroom in classrooms select new { classroomId = classroom.ClassroomId, occupied = classroommap.ContainsKey(child.ChildId) && classroommap[child.ChildId]. Contains(classroom.ClassroomId), // Since you wanted an array. }).ToArray() // Since you wanted an array. }).ToArray(); ```
49,131,536
I have `click` event with jquery and i want to know how is selector clicked... ``` $('#parent').on('click','#child',function(){ //.... }); <div id="parent"> <div id="child"> </div> </div> ``` **$(this)** is `#parent` or `#child` ?
2018/03/06
[ "https://Stackoverflow.com/questions/49131536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3162975/" ]
The context `this` is related to the event target. In your case is `#child`. Further, you don't need event delegation when the `id` is available, so bind that event as follow: ``` $('#child').on('click',function(){ //.... }); ```
This is called `Event delegation` which allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. So, `$(this)` here is always referring to the clicked child element to a parent element, which here is `#child`. A simple dynamically added element demo: ```js // Attach Event // on(events, selector, handler); $('#container').on('click', 'a', function(event) { event.preventDefault(); console.log('Anchor clicked!'); alert('Anchor clicked!'); }); // Create elements dynamically $('#container').append('<a href="#output">Click me!</a>'); ``` ```css body{font:12px Tahoma,Arial,Helvetica,sans-serif;color:#333;margin:20px} h1{font-size:1.4em;margin-bottom:20px} h2{font-size:1.2em} #container{border:1px dashed #aaa;font-size:1em;padding:10px} a{color:green} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2>Dynamically added link:</h2> <div id="container"></div> ```
8,410,749
Basically this following code will check whether two different binary trees have the same members of integer. The way that I'm supposed to do it is to store the integer from tree to array and then compare the array. Here is the code that put the integers to array ``` private static int toarray (btNode t, int[] a, int i) { int num_nodes = 0; if (t != null) { num_nodes = toarray (t.left , a , i); a [num_nodes + i] = t.info; num_nodes = num_nodes + i + toarray (t.right,a,num_nodes + i + 1); } return num_nodes; } ``` Here is the code that check if the two trees are equal or not ``` public boolean equals(Intcoll6 obj) { boolean result = true; if (how_many == obj.how_many) { int[]a = new int [how_many]; int[]b = new int [obj.how_many]; toarray (c,a,0); toarray (obj.c,b,0); for (int j = 0; j < how_many; j++) { if ( a[j] == (b[j])) { result = true; } else result = false; } } else { result = false; } return result; } ``` so far (for obvious reason) it only works if the length of tree are not equal. I can't really figure out what's wrong with the code, so any suggestions will help. Thanks in advance
2011/12/07
[ "https://Stackoverflow.com/questions/8410749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084925/" ]
Hi you can use the recursion for comparing two binaryTrees the concept may like follow ``` int compareTree(tree1, tree2) { //if both are empty the return true if (tree1==NULL && tree2==NULL) return(true); // if both non-empty then compare them else if (tree1!=NULL && tree2!=NULL) { return //compare values and recursive call the function for next data && //compareTree(left node of tree1,left node of tree2) && //compareTree(right node of tree1,right node of tree2) ; } // if one empty, and other not then return false else return(false); } ```
Try using `Arrays.deepEquals(a1, a2)` for the array comparison. It should work. You will however need to create an Integer array instead of int since this function works on Object[].
2,286,245
> > Suppost that $a,b,c,d$ are real numbers such that $$a^2+b^2=1$$ $$c^2+d^2=1$$ $$ac+bd=0$$ > > > I've to show that $$a^2+c^2=1$$ $$b^2+d^2=1$$ $$ab+cd=0$$ Basically,I've no any idea or tactics to tackle this problem. Any methods? Thanks in advance. EDITED. The given hint in the books is $S:=(a^2+c^2-1)^2+(b^2+d^2-1)^2=(ac+bd)^2$
2017/05/18
[ "https://math.stackexchange.com/questions/2286245", "https://math.stackexchange.com", "https://math.stackexchange.com/users/221836/" ]
What if $b=0?$ Else $abcd\ne0,$ we have $\dfrac ab=-\dfrac dc=k$(say) $\implies a=bk,d=-ck$ $$1=a^2+b^2=b^2(1+k^2)\implies b^2=?,a^2=(bk)^2=?$$ $$1=c^2+d^2=c^2(1+k^2)\implies c^2=?,d^2=(-ck)^2=?$$
Just a very basic brute force method, $a^2 + b^2 = 1$ - (1) $c^2 + d^2 = 1$ -(2) $ac+bd=0$ On multiplying the two we get, $a^2c^2+b^2d^2+a^2d^2+b^2c^2=1$ Whereas $a^2c^2+b^2d^2+2abcd=0$ {squaring both sides $ac + bd = 0$} Thus we get $-2abcd+a^2d^2+b^2c^2=1 \Rightarrow (ad-bc)^2=1 \Rightarrow ad-bc=\pm1$ Adding (1) and (2) we get, $a^2+b^2+c^2+d^2=2$ , Which can be re written as $a^2+b^2+c^2+d^2=2ad-2bc$. $\Rightarrow (b+c)^2+(a-d)^2=0$. Thus we get, $b=-c$ and $a =d$. #Q.E.D
49,611,196
I have copied some item manually from web pasted into txt and then stored it into database.Now what I missed is invisible characters. when I'm retrieving first characters of each word using different values in substr($word,0,x) it shows presence of invisible characters. php code- ``` public function getPrefixAttribute() { $str=$this->attributes['Subject_name']; $exclude=array('And', 'of','in'); $ret = ''; foreach (explode(' ', $str) as $word) { if(in_array($word, $exclude)) {continue;} else{ $ret .= strtoupper(substr($word,0,1));} } return $ret; } ``` output- ``` substr($word,0,1) string-'data structures and algorithms' output-'SA' expected-'DSA' string-'Web Development' output-'WD' substr($word,0,2) string-'data structures and algorithms' output-'DSTAL' expected-'DASTAL' string-'Web Development' output-'WEDE' ```
2018/04/02
[ "https://Stackoverflow.com/questions/49611196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7701774/" ]
I suspect it's an issue of interpolation. You can kill two birds with one stone by using *prepared statements*. By using *prepared statements* 1. your data won't be corrupted or need to be manually handled by you, 2. your application will not be subject to security issues a la [SQL injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). This might look like: ``` $sql = "UPDATE `prove750_mrdias`.`stringsMrDias` SET `conteudo` = ? WHERE `stringsMrDias`.`ID` = ?"; $preparedStatement = $pdo_handle->prepare( $sql ); $preparedStatement->execute([$conteudo, $id]); ``` That is, you first tell the database the *form* of the query you want executed, and then -- in a separate call -- you send the arguments to that query.
Try <http://php.net/manual/en/function.nl2br.php> Example, ``` $conteudo = nl2br($conteudo); ``` Then store into database.
9,049,790
*(Using iOS 5 and Xcode 4.2.)* I've followed the instructions here: <http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/LocationAwarenessPG/AnnotatingMaps/AnnotatingMaps.html#//apple_ref/doc/uid/TP40009497-CH6-SW15> and used the [MKCircle](http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKCircle_class/Reference/Reference.html) and [MKCircleView](http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKCircleView_class/Reference/Reference.html#//apple_ref/occ/cl/MKCircleView) classes to add a circle overlay on my [MKMapView](http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html). However what I actually want is an inverted circle overlay, like the left map in the sketch below (currently I have a circle overlay like the one on the right): ![Inverted and not-inverted circle overlay sketches](https://i.stack.imgur.com/OQStG.png) For the inverted circle, the overlay should cover the entire map - apart from the visible circle. Is there an easy way to accomplish this using the MKCircle/MKCircleView classes? Or will I have to go deeper and define a custom overlay object/view? Thank you for your help :)
2012/01/29
[ "https://Stackoverflow.com/questions/9049790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404409/" ]
I had the same task and here is how I solve it: **NOTE: this code will only work starting from iOS7** Add an overlay to the map, somewhere in your view controller: ``` MyMapOverlay *overlay = [[MyMapOverlay alloc] initWithCoordinate:coordinate]; [self.mapView addOverlay:overlay level:MKOverlayLevelAboveLabels]; ``` In the MKMapViewDelegate methods write next: ``` - (MKOverlayRenderer *)mapView:(MKMapView *)map rendererForOverlay:(id<MKOverlay>)overlay { /// we need to draw overlay on the map in a way when everything except the area in radius of 500 should be grayed /// to do that there is special renderer implemented - NearbyMapOverlay if ([overlay isKindOfClass:[NearbyMapOverlay class]]) { MyMapOverlayRenderer *renderer = [[MyMapOverlayRenderer alloc] initWithOverlay:overlay]; renderer.fillColor = [UIColor whateverColor];/// specify color which you want to use for gray out everything out of radius renderer.diameterInMeters = 1000;/// choose whatever diameter you need return renderer; } return nil; } ``` The MyMapOverlay itself should be something like followed: ``` @interface MyMapOverlay : NSObject<MKOverlay> - (instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate; @end @implementation MyMapOverlay @synthesize coordinate = _coordinate; - (instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate { self = [super init]; if (self) { _coordinate = coordinate; } return self; } - (MKMapRect)boundingMapRect { return MKMapRectWorld; } @end ``` And the MyMapOverlayRenderer: ``` @interface MyMapOverlayRenderer : MKOverlayRenderer @property (nonatomic, assign) double diameterInMeters; @property (nonatomic, copy) UIColor *fillColor; @end @implementation MyMapOverlayRenderer /// this method is called as a part of rendering the map, and it draws the overlay polygon by polygon /// which means that it renders overlay by square pieces - (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context { /// main path - whole area UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(mapRect.origin.x, mapRect.origin.y, mapRect.size.width, mapRect.size.height)]; /// converting to the 'world' coordinates double radiusInMapPoints = self.diameterInMeters * MKMapPointsPerMeterAtLatitude(self.overlay.coordinate.latitude); MKMapSize radiusSquared = {radiusInMapPoints, radiusInMapPoints}; MKMapPoint regionOrigin = MKMapPointForCoordinate(self.overlay.coordinate); MKMapRect regionRect = (MKMapRect){regionOrigin, radiusSquared}; //origin is the top-left corner regionRect = MKMapRectOffset(regionRect, -radiusInMapPoints/2, -radiusInMapPoints/2); // clamp the rect to be within the world regionRect = MKMapRectIntersection(regionRect, MKMapRectWorld); /// next path is used for excluding the area within the specific radius from current user location, so it will not be filled by overlay fill color UIBezierPath *excludePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(regionRect.origin.x, regionRect.origin.y, regionRect.size.width, regionRect.size.height) cornerRadius:regionRect.size.width / 2]; [path appendPath:excludePath]; /// setting overlay fill color CGContextSetFillColorWithColor(context, self.fillColor.CGColor); /// adding main path. NOTE that exclusionPath was appended to main path, so we should only add 'path' CGContextAddPath(context, path.CGPath); /// tells the context to fill the path but with regards to even odd rule CGContextEOFillPath(context); } ``` As a result you will have exact same view like on the left image that was posted in the question.
Here a Swift version. Thanks Valerii. <https://github.com/dariopellegrini/MKInvertedCircle>
49,498,922
I've been trying to create a bunch of test users for my test application that will be mocking a case when user signed up to Facebook using his phone number (not his email). Turns out that the tool to create test users (`App -> roles -> test users`) allows to create only users who have email and there's no way (AFAIK) to change the data without logging in to Facebook as this user and changing his account settings. Is it not possible or am I missing something? **EDIT 1:** I'm not actually able to add a phone number without verification
2018/03/26
[ "https://Stackoverflow.com/questions/49498922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/809230/" ]
Unfortunately, there is no way to add testers with their phones. You can add your testers by their fbids or usernames. ![Facebook developers reference](https://i.imgur.com/BxlslpM.png)
As others say there is no way to have test user without email address. What you can do however is to create test user and when logging into your app deny access to email. It will have nearly same effect as logging in with user that has phone number instead of email. You can do it in edit section while logging in(as shown in pictures) [![Step 1](https://i.stack.imgur.com/Tng4K.png)](https://i.stack.imgur.com/Tng4K.png) [![Step 2](https://i.stack.imgur.com/UyBeX.png)](https://i.stack.imgur.com/UyBeX.png)
20,530,388
I have a really big problem with UIScrollView. To make sure it wasn't my actual project, I created a NEW project, iPhone only, for iOS 6 and 7. I **disabled autolayout**. 1. I created a Tab Bar project 2. I created a view controller, embedded it in a navigation controller and connected it as Tab bar item #0 3. I put a UIScrollView in my view. 4. I connected the scrollview in the custom UIViewController created for this view. 5. I synthesized my IBOutlet and set the delegate to self. I also implemented delegate in .h Here is my code (ViewDidLoad): ``` self.scrollView.delegate = self; [self.scrollView setScrollEnabled:YES]; [self.scrollView setContentSize:CGSizeMake(self.view.frame.size.width, 20000)]; NSLog(@"contentSize width %f", self.scrollView.contentSize.width); NSLog(@"contentSize height %f", self.scrollView.contentSize.height); NSLog(@"%@", NSStringFromCGAffineTransform(self.scrollView.transform)); ``` It returns me "contentSize width 20000.000000", "contentSize height 0.000000 " and "[1, 0, 0, 1, 0, 0]". It scrolls left-right where it should scroll up-down Please help!
2013/12/11
[ "https://Stackoverflow.com/questions/20530388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318432/" ]
I had the same issue until I realized I hadn't set the UIScrollView delegate. Also, if you're using auto layout, you need to wait for the layout to be applied to the UIScrollView. This means you should set the Content Size in "viewDidLayoutSubviews".
Use this code. ScrollView setContentSize should be called async in main thread. Swift: ``` override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() DispatchQueue.main.async { var contentRect = CGRect.zero for view in self.scrollView.subviews { contentRect = contentRect.union(view.frame) } self.scrollView.contentSize = contentRect.size } } ``` Objective C: ``` - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; dispatch_async(dispatch_get_main_queue(), ^ { CGRect contentRect = CGRectZero; for(UIView *view in scrollView.subviews) contentRect = CGRectUnion(contentRect,view.frame); scrollView.contentSize = contentRect.size; }); } ```
3,761,237
Ok so i have a variable $phone which contains the string (407)888-9999 and I have this code ``` if($phone != ''){ $phone = "<span id='telephone'>{$phone}</span>";} return $phone; ``` This works fine but now the client wants to have a some padding in between the area code and the next three numbers. So i need the code to be like this ``` <span id='telephone'><span class='spacer'>(407)</span>888-9999</span>"; ```
2010/09/21
[ "https://Stackoverflow.com/questions/3761237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223367/" ]
You can do: ``` $input = "(407)888-9999"; $area_code = ''; $ph_num = $input; if(strpos($input,')') !== false) { // if area-code is present. list($area_code,$ph_num) = explode(')',$input); $area_code .= ')'; } ```
Iff the phone number is always in the same format, you can split it with: ``` list($area,$phone1,$phone2) = sscanf($phone,'(%d)%d-%d'); ``` or ``` sscanf($phone,'(%d)%d-%d',$area,$phone1,$phone2) ```
46,727
I've started working on a script that turns sections with headings into a tabbed interface. The repo is at <https://github.com/derekjohnson/tabs> and a demo at <http://derekjohnson.github.io/tabs/> It works in IE8 up, although I haven't fully tested it on all the devices I have access to. I'm particularly interested in feedback on the tabs.js file, and welcome all comments. As I mentioned in the README I know it could do with a config object, but I've never done one so I'll be learning on this project. Any tips on that gratefully received too. tabs.js: ``` (function(win, doc, undefined) { 'use strict'; // Quick feature test if('querySelector' in doc) { var tabs = function() { /* Helper functions ========================================================================== */ // Cross browser events var add_event = function(el, ev, fn) { 'addEventListener' in win ? el.addEventListener(ev, fn, false) : el.attachEvent('on' + ev, fn); }; // Faster class selectors // http://jsperf.com/queryselector-vs-getelementsbyclassname-0 var get_single_by_class = function(className) { return 'getElementsByClassName' in doc ? doc.getElementsByClassName(className)[0] : doc.querySelector('.' + className); } //http://jsperf.com/byclassname-vs-queryselectorall var get_many_by_class = function(className) { return 'getElementsByClassName' in doc ? doc.getElementsByClassName(className) : doc.querySelectorAll('.' + className); } /* Feature detect for localStorage courtesy of http://mathiasbynens.be/notes/localstorage-pattern ========================================================================== */ var storage, fail, uid; try { uid = new Date; (storage = win.localStorage).setItem(uid, uid); fail = storage.getItem(uid) != uid; storage.removeItem(uid); fail && (storage = false); } catch(e) {} /* DOM nodes we'll need ========================================================================== */ var wrapper = get_single_by_class('js-tab-ui'), panels = get_many_by_class('js-panel'), tab_names = get_many_by_class('js-panel__title'), i, ii = panels.length; /* Show hide the panels, update the tabs' attributes ========================================================================== */ var show_hide = function(x_id) { for(i=0; i<ii; i++) { // display the correct panel, hide the others if(panels[i].getAttribute('aria-labelledby') === x_id) { panels[i].style.display = 'block'; } else { panels[i].style.display = 'none'; } // update the ARIA if(items[i].id === x_id) { items[i].setAttribute('aria-selected', 'true'); } else { items[i].setAttribute('aria-selected', 'false'); } } // put the tab id into localStorage if(storage) { localStorage['tab'] = x_id; } } /* When a tab has been clicked ========================================================================== */ var clicked = function(event) { var x, x_id; typeof event.target !== 'undefined' ? x = event.target : x = event.srcElement; if(x.nodeName.toLowerCase() === 'li') { // get the id of the clicked tab x_id = x.id; } else { return; // stop clicks on the <ul> hiding everything } show_hide(x_id); }; /* Keyboard interaction ========================================================================== */ var kbd = function(event) { var x, x_id, key_code, next, prev; event = event || win.event; key_code = event.keyCode || event.which; typeof event.target !== 'undefined' ? x = event.target : x = event.srcElement; // up or right arrow key moves focus to the next tab if(key_code === 38 || key_code === 39) { next = x.nextSibling; // make sure we're on an element node if(next.nodeType !== 1) { next = next.nextSibling; } next.setAttribute('tabindex', 0); next.focus(); } // left or down arrow key moves focus to the previous tab if(key_code === 37 || key_code === 40) { prev = x.previousSibling; // make sure we're on an element node if(prev.nodeType !== 1) { prev = prev.previousSibling; } prev.setAttribute('tabindex', 0); prev.focus(); } // space bar if(key_code === 32) { show_hide(x.id); } // Prevent space bar moving the page down event.preventDefault ? event.preventDefault() : event.returnValue = false; } /* Create each tab item ========================================================================== */ var build_tab = function(el, text, classification) { el.innerHTML = text; el.className = classification; el.setAttribute('role', 'tab'); return el; }; /* Make an empty list that will hold the tabs ========================================================================== */ var frag = doc.createDocumentFragment(), tabs = doc.createElement('ul'); // Basic attributes for the list tabs.className = 'product-tabs'; tabs.setAttribute('role', 'tablist'); /* Build each tab and add all required attributes to tabs & panels ========================================================================== */ var items = []; for(i=0; i<ii; i++) { var li = build_tab(doc.createElement('li'), tab_names[i].innerHTML, 'product-tabs__item'); // Add unique attributes to each list item li.id = 'tab' + (i + 1); li.setAttribute('aria-controls', panels[i].id); if(i === 0) { li.setAttribute('tabindex', 0); li.setAttribute('aria-selected', 'true'); } else { li.setAttribute('aria-selected', 'false'); } // Stick them into the document fragment frag.appendChild(li); // Stick them into the items array items[i] = li; // Panels panels[i].setAttribute('role', 'tabpanel'); panels[i].setAttribute('aria-labelledby', 'tab' + (i + 1)); } /* Insert the tabs into the DOM ========================================================================== */ tabs.appendChild(frag); wrapper.insertBefore(tabs, get_single_by_class('js-panel')); /* Listen for clicks on the tab list ========================================================================== */ add_event(tabs, 'click', clicked); /* Listen for key presses ========================================================================== */ add_event(tabs, 'keydown', kbd); /* If a tab id is in localStorage open the corresponding panel ========================================================================== */ if(storage && localStorage['tab']) { show_hide(localStorage['tab']); } }; // Make all that happen tabs(); } else { return; } })(this, this.document); ```
2014/04/09
[ "https://codereview.stackexchange.com/questions/46727", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/30509/" ]
You don't actually need the `self` variable in most of your code (the constructor doesn't use it at all). You can just use `this` directly in most cases. The only exception is in the `session.requestServer` callback, where you do need a way to reference the object context - and there it's perfectly fine to use `self`. Alternatively, you can use [`.bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) to derive a function that's bound to the right context (but if you're targeting browsers know that [support for `bind` is spotty](http://kangax.github.io/es5-compat-table/#Function.prototype.bind)). More generally, I'd skip the `initialize` method. It depends on what you intend of course, but having the `initialize` function there means that you can re-initialize a `Child` instance whenever you want, because it'll have a publicly accessible `initialize` function that anyone can call. But initializing an instance should be the responsibility of the constructor function, unless there's some good reason to do otherwise. In this case, however, I don't think there is. In other words, simply put everything in the constructor function, and remove the `initialize` function. I end up with this; the "classic" way to define a class (i.e. construtor+prototype) in javascript. ``` function Child(json) { // equivalent to `var Child = function ...`; just for illustration // properties - with defaults this.id = json.id_child || 0; // null might be a better default for the ID this.firstname = json.firstname || ""; this.moneyDue = parseFloat(json.to_pay) || 0; this.moneyCurrent = parseFloat(json.already_paid) + this.moneyDue - parseFloat(json.spent_money) || 0; this.missionsPlay = json.nb_missions.in_progress || 0; this.missionsWait = json.nb_missions.waiting || 0; this.missionsStop = json.nb_missions.completed || 0; this.missions = []; } Child.prototype = { getMissions: function (type, callback) { var self = this; // I assume `session` is a global or closed-over variable? session.requestServer( "parent_getChildMissionList", { sid: session.sid, id_child: this.id, // we can still use `this` here status: type || "", strict_status: false, page: 0 }, function (data) { var missions = [], mission; $(data.missionList).each(function () { mission = new Mission(this); // easier than having to go through missions[missions.length-1] self.missions.push(mission); // This is where we need to use the `self` var missions.push(mission); }); callback(missions); }); } // removed a stray comma on this line - some JS interpreters choke on them, some don't }; ``` Now, you could conceivably just use the JSON more directly. Perhaps have a factory-like method that takes in the "raw" JSON, and add a few things or builds a new object literal from it. That'd look something like: ``` function buildChild(json) { // note lowercase naming; this isn't a constructor var child = { id: json.id_child || 0, firstname: json.firstname || "", moneyDue: parseFloat(json.to_pay) || 0, moneyCurrent: parseFloat(json.already_paid) + this.moneyDue - parseFloat(json.spent_money) || 0, missionsPlay: json.nb_missions.in_progress || 0, missionsWait: json.nb_missions.waiting || 0, missionsStop: json.nb_missions.completed || 0, missions: [], }; child.getMissions = function (type, callback) { session.requestServer( "parent_getChildMissionList", { sid: session.sid, id_child: child.id, // now we use `child` instead of this status: type || "", strict_status: false, page: 0 }, function (data) { var missions = [], mission; $(data.missionList).each(function () { mission = new Mission(this); child.missions.push(mission); // same here missions.push(mission); }); callback(missions); }); }; return child; } ```
Or if you want to avoid classical style but still use prototypes for performance or manageability... ``` var Child = { // defaults values for inherited properties id: 0, firstname = "", moneyCurrent = 0, moneyDue = 0, missionsPlay = 0, missionsWait = 0, missionsStop = 0, missions = [], // factory method which creates new instances and prototype factories create: function(options) { var obj = Object.create(this), proto = obj, inits = []; // fetch all defined init methods in the prototype chain while (proto && proto !== Object.prototype) { if (proto.hasOwnProperty("init")) inits.push(proto.init); proto = proto.getPrototypeOf(); } // execute inits inits.reverse.forEach(function(init) {init.call(this, options);}); }, // constructor for your "class" init: function(options) { // validate input var money = parseFloat(options.already_paid) + parseFloat(options.to_pay) - parseFloat(options.spent_money), due = parseFloat(options.to_pay), play = parseInt(options.nb_missions.in_progress), wait = parseInt(options.nb_missions.waiting), stop = parseInt(options.nb_missions.completed); // use validated input or fallback to inherited values this.id = options.id_child || this.id; this.firstname = options.firstname || this.firstname; this.moneyCurrent = isNaN(money) ? this.moneyCurrent : money; this.moneyDue = isNaN(due) ? this.moneyDue : due; this.missionsPlay = isNaN(play) ? this.missionsPlay : play; this.missionsWait = isNaN(wait) ? this.missionsWait : wait; this.missionsStop = isNaN(stop) ? this.missionsStop : stop; // ensure we have our own copy of the missions array this.missions = this.missions.slice(0); }, getMissions: function(type, callback) { // ... } }; ``` So now creating a new child with Child.create will setup the appropriate prototype chain. You could then create a manageable inheritance hierarchy. ``` var c, FooChild = Child.create(); c = FooChild.create(); FooChild.foo = "FOO!"; assert(c.foo == "FOO!"); ```
15,153,943
My goal is to only display contacts with phone number to user and let user select few contacts which I want to store locally. I have used various options in place of ContactsContract.Contacts.CONTENT\_URI in below method. But I am getting lot many of the contacts (many are junk with only email ids) displayed. ``` public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.contact_selector); ((Button)findViewById(R.id.btnphonecontactlist)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent contactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(contactIntent, 1); } }); } ``` If I pass ContactsContract.Contacts.CONTENT\_URI as parameter for above method and in case of below handler method, the String[] for the query method as projection parameters (which are shown commented), the method fails with java.lang.IllegalArgumentException. If I pass null in below method, then whatever contact I select, I don't find any column related to phone number or email. ``` @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(data != null) { Uri uri = data.getData(); if(uri != null) { Cursor c = null; try { c = getContentResolver().query(uri, null // new String[] { //ContactsContract.CommonDataKinds.Phone.NUMBER, //ContactsContract.CommonDataKinds.Phone.TYPE}, , null, null, null); if(c != null && c.moveToFirst()) { String number = c.getString(0); String type = c.getString(1); } } finally { if(c != null && !c.isClosed()) c.close(); } } } } ``` Is there any way to display only contacts visible to user usually when user goes to phone book and which has phone numbers available? I tried going through all the threads in stackoverflow and other sites, but could not find any solution which resolve issue around this though many people have posted the issue. I haven't worked much with the Android platform and I might have missed out certain minor details and I believe there must be an easy way to achieve this. Kindly suggest. Appreciate your help. Thanks.
2013/03/01
[ "https://Stackoverflow.com/questions/15153943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/344535/" ]
``` *-> Add a permission to read contacts data to your application manifest. <uses-permission android:name="android.permission.READ_CONTACTS"/> -> Use Intent.ACTION_PICK in your Activity Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI); startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT); -> Then Override the onActivityResult() and retrieve the ID,Phone number and Name in the data. @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // check whether the result is ok if (resultCode == RESULT_OK) { // Check for the request code, we might be usign multiple startActivityForReslut switch (requestCode) { case RESULT_PICK_CONTACT: Cursor cursor = null; try { String phoneNo = null ; String name = null; Uri uri = data.getData(); cursor = getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); phoneNo = cursor.getString(phoneIndex); textView2.setText(phoneNo); } catch (Exception e) { e.printStackTrace(); } break; } } else { Log.e("MainActivity", "Failed to pick contact"); } } This will work check it out* ```
Use this: ``` Intent intent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts/people")); intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); startActivityForResult(intent, 1); ```
78,949
When my students ask questions and participate in discussion, class is more thoughtful, more fun, and more effective. I encourage their participation by checking in with them regularly, and making sure that they have time to speak and that they get a respectful hearing. Still, perhaps half of them never say a word. It seems like being in our mutual interest to get them to speak in class. Because of these positive effects, like other teachers I have tried to encourage participation by making it part of the grading rubric. Some measures assess students' class presence within a particular timeframe, but this is hard to distinguish from attendance. More subtle is to give credit for speech, by filtering and counting contributions, whether online or in person. The speech measure is confounded by the fact that some students are happy to talk all the time while some never even want to. Without rewarding loudmouths or penalizing shy international students, what are best practices in scoring class participation?
2016/10/28
[ "https://academia.stackexchange.com/questions/78949", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/14140/" ]
You want to grade people, in part, on their participation. If a person isn't speaking in class, whether it's because they're shy or because they have nothing to say, they're not participating. If part of the assessment of a class involves an oral presentation, and a student refuses to present because they're shy then it would seem unlikely that we might say "we'll let that person pass the presentation component of the class because it would be unfair to punish them for being shy." Rather, I suspect they might fail that component for not producing material upon which they could be assessed (i.e., not delivering a presentation). You mention online discussions. Obviously that might pose less of a barrier to shy people. Ultimately though, if you believe that participation is something upon which students should be assessed, and students are made aware of this, then shy students just have to accept that all other things being equal their grade may be poorer than their more outspoken peers. Perhaps this will encourage them to (take steps to) speak up. Perhaps they'll benefit, both in terms of their grade and in their lives, as a result. As for dealing with loudmouths, I think the answer here is relatively straightforward: You don't assess them on the quantity that they produce, but rather the quality. You decide whether what they're saying reflects meaningful participation and thoughtful contributions, or simply blabbering. **tl;dr** Grading people on the basis of their informal participation adds a few wrinkles (i.e. punishing shy students, and increasing the subjectivity of grading everyone else) but if a teacher decides that this is something they consider important then these wrinkles may just have to be accepted.
What you can do is tell those students that notoriously always answer (in my experience there always are some) to give some others a chance as well. If the few that always contribute also have the best contributions, you should tell them to just wait a little bit for the others to speak up and still hear them out afterwards. If the most frequent contributors have contributions of mixed quality, you should tell them to favor quality over quantity and also adjust your participation grade accordingly. Other than that, I don't think you can force people to speak up. This is a well known issue in the context of MBAs. Women typically have lower grades in those classes that heavily use participation grades.
7,813
There are a number of new developers and testers in our team. When the testers are testing the new features the developers built, they are finding a number of issues, which is not strictly in the scope of the feature. As a result the developers tend to deny responsibility and the bugs are going to the production bug tracking system. These bugs are worked by another set of developers and the fix rate is very slow. As a result, we are not really improving quality sprint by sprint, but just accumulating technical debt. How is this situation normally tackled? **Edit:** My question is not really how a tester will handle the situation so that it wont affect him/her. The question is more like how can we tackle the situation at the process level so that the quality of the software can be improved sprint by sprint.
2014/02/19
[ "https://sqa.stackexchange.com/questions/7813", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/7025/" ]
The first thing you want to do here is perform some bug triage. Problems your team finds during feature testing will be one of: * something introduced by the changes * something that was there before and doesn't have much if any impact on the changes * something that was there before and has a major negative impact on the changes The developers in the team need to fix the items that were there beforehand and negatively impact their work, as well as the problems they accidentally introduce. That's the easy part. Now for the more difficult side - realistically, most of the pre-existing bugs your test team finds won't have a major impact on the feature, and it really isn't the feature developers' role to fix them. In this case, they absolutely need to go into the main issue tracking system with whatever bug advocacy you're able to provide. Some strategies you might try: * **Note any major customers who could be impacted**. In my experience, existing bugs surfaced by new development are usually the kind of thing that isn't terribly severe - but if something that had little or no impact before the feature is likely to upset your biggest customer and you know that customer is planning to use the new feature, you can legitimately increase the priority of the issue - just make sure to note that this customer will be affected. Even if the issue is not fixed, the fact that it's in the issue tracking system will boost your team's credibility when the customer demands to know why this wasn't found in testing. * **Evaluate priority and severity fairly**. By this I mean don't just rank it highly because your team wants it fixed. This will harm your team's credibility. * **Look for possible reasons why the issue hasn't been caught until now**. If it has a workaround, there's a strong possibility your customers know about it and just haven't said anything. In my experience you might get 1 in 10 customers complaining about a problem (if you're lucky - it's more like 1 in 100 or more for a lot of places). Unhappy customers often don't say anything, they just look elsewhere. Your goal is to give the team that prioritizes bug fixes reasons to fix *your* bugs (and if everyone is doing this, all the bugs will have sound reasons for why they should be fixed and the priority level they have). Ultimately, you're not actually increasing technical debt, you're *exposing* it. This is better than not exposing it.
If the test team is finding *that* many then it is possible their focus is not entirely on the new functionality. A common strategy is to focus the test team on the new functionality and look at reporting only issues which arise from interactions between old functionality and new functionality, or issues which will impact the new functionality you are delivering. If you are unwilling to take that responsibility yourself then negotiate it with the next level of management. With something like ie; "The testers are finding a lot of medium level issues which have nothing to do with our current delivery schedule. To meet the schedule I plan to focus our testers on our current priorities and in the short term this may mean some lower priority issues related to [legacy] will go unreported." The fact is that logging and reporting low and medium priority issues accurately and then assessing them has a cost. Since you cannot (in many senses) charge that cost to another project you really have to focus in on what is important to your delivery. You may find the next level is unwilling to commit to any decision or accept any responsibility or has a very limited understanding of the reality of the situation. If that is the case you will have to make the call independently.
31,258,598
I am supposed to write a program with check buttons that allow the user to select any or all of these services. When the user clicks a button the total charges should be displayed. I already have the first portion done and finished but I need help with the second part. I can't find a calculation that works when the user clicks the buttons and the total charges are calculated and displayed within the same box. What is the correct calculation to add the selected? Here's what I have so far: ``` #Create the checkbutton widgets in top frame. self.cb1 = tkinter.Checkbutton(self.top_frame, \ text = 'Oil Change-$30.00', variable = self.cb_var1) self.cb2 = tkinter.Checkbutton(self.top_frame, \ text = 'Lube Job-$20.00', variable = self.cb_var2) self.cb3 = tkinter.Checkbutton(self.top_frame, \ text = 'Radiator Flush-$40.00', variable = self.cb_var3) self.cb4 = tkinter.Checkbutton(self.top_frame, \ text = 'Transmission Flush-$100.00', variable = self.cb_var4) self.cb5 = tkinter.Checkbutton(self.top_frame, \ text = 'Inspection-$35.00', variable = self.cb_var5) self.cb6 = tkinter.Checkbutton(self.top_frame, \ text = 'Muffler Replacement-$200.00', variable = self.cb_var6) self.cb7 = tkinter.Checkbutton(self.top_frame, \ text = 'Tire Rotation-$20.00', variable = self.cb_var7) #Pack the checkbuttons. self.cb1.pack() self.cb2.pack() self.cb3.pack() self.cb4.pack() self.cb5.pack() self.cb6.pack() self.cb7.pack() #Create an OK button and Quit button. self.ok_button = tkinter.Button(self.bottom_frame, \ text = 'OK', command = self.show_choice) self.quit_button = tkinter.Button(self.bottom_frame, \ text = 'Quit', command = self.main_window.destroy) #Pack the buttons. self.ok_button.pack(side = 'left') self.quit_button.pack(side = 'left') #Pack frame. self.top_frame.pack() self.bottom_frame.pack() ```
2015/07/07
[ "https://Stackoverflow.com/questions/31258598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5009501/" ]
``` import os os.path.basename(os.path.dirname(os.path.realpath(__file__))) ``` Broken down: ``` currentFile = __file__ # May be 'my_script', or './my_script' or # '/home/user/test/my_script.py' depending on exactly how # the script was run/loaded. realPath = os.path.realpath(currentFile) # /home/user/test/my_script.py dirPath = os.path.dirname(realPath) # /home/user/test dirName = os.path.basename(dirPath) # test ```
Just write ``` import os import os.path print( os.path.basename(os.getcwd()) ) ``` Hope this helps...
36,986,192
For my work I have done some tests for time chart. I have come to something that surprised me and need help understanding it. I used few data structures as queue and wanted to know how deleting is fast according to number of items. And arraylist with 10 items, deleting from front and not set initial capacity is much slower than the same with set initial capacity (to 15). Why? And why it's same at 100 items. Here's the chart: [![enter image description here](https://i.stack.imgur.com/sSBWx.png)](https://i.stack.imgur.com/sSBWx.png) Data Structures: L - implements List, C - set initial capacity, B - removing from back, Q - implements Queue EDIT: Appending relevant piece of code ``` new Thread(new Runnable() { @Override public void run() { long time; final int[] arr = {10, 100, 1000, 10000, 100000, 1000000}; for (int anArr : arr) { final List<Word> temp = new ArrayList<>(); while (temp.size() < anArr) temp.add(new Item()); final int top = (int) Math.sqrt(anArr); final List<Word> first = new ArrayList<>(); final List<Word> second = new ArrayList<>(anArr); ... first.addAll(temp); second.addAll(temp); ... SystemClock.sleep(5000); time = System.nanoTime(); for (int i = 0; i < top; ++i) first.remove(0); Log.d("al_l", "rem: " + (System.nanoTime() - time)); time = System.nanoTime(); for (int i = 0; i < top; ++i) second.remove(0); Log.d("al_lc", "rem: " + (System.nanoTime() - time)); ... } } }).start(); ```
2016/05/02
[ "https://Stackoverflow.com/questions/36986192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558231/" ]
Read this article about [Avoiding Benchmarking Pitfalls on the JVM](http://www.oracle.com/technetwork/articles/java/architect-benchmarking-2266277.html). It explains the impact of the Hotspot VM on the test results. If you don't take care about it, your measurement isn't right. As you have found out with your own test. If you want to do reliable benchamrking use [JMH](http://openjdk.java.net/projects/code-tools/jmh/).
I too was able to replicate it by creating the code below. However, I noticed that whatever is run first (the set capacity vs non-set capacity) is the one that will take the longest. I assume this is some kind of optimization, maybe the JVM, or some kind of Caching? ``` public class Test { public static void main(String[] args) { measure(-1, 10); // switch with line below measure(15, 10); // switch with line above measure(-1, 100); measure(15, 100); } public static void measure(int capacity, long numItems) { ArrayList<String> arr = new ArrayList<>(); if (capacity >= 1) { arr.ensureCapacity(capacity); } for (int i = 0; i <= numItems; i++) { arr.add("T"); } long start = System.nanoTime(); for (int i = 0; i <= numItems; i++) { arr.remove(0); } long end = System.nanoTime(); System.out.println("Capacity: " + capacity + ", " + "Runtime: " + (end - start)); } } ```
73,784
I'm working on getting my first server up and running and my dad is trying to convince me that Gentoo is the way to go. Is it worth the compile? I was just planning on using Ubuntu.
2009/10/12
[ "https://serverfault.com/questions/73784", "https://serverfault.com", "https://serverfault.com/users/22778/" ]
The answer really depends on your objective. gentoo is not worth the effort if you want to get a server up quickly and easily or think that you will get noticeably better performance. Other distributions (ubuntu, RHEL, CentOS) are easier to set up and operate. I do not believe the typical user will notice much of a performance benefit from controlling the compile flags. gentoo is worth the effort if you want to learn how Linux works below the surface. I learned more from using gentoo for a couple of years than all the many years of using other distros. There are many things to configure and tinker with when using gentoo that make it a lot of fun to use and a good learning experience.
I would suggest Ubuntu for now for it's simplicity... however in the future I **fully recommend** trying Gentoo out just for the experience you'll receive in installing, configuring, troubleshooting linux. It's a great OS and you'll learn a ton.
207,240
I need to draw this kind of simple sequency diagram, but I'm not very good with Ti*k*Z: ![sample](https://i.stack.imgur.com/9npAg.png) ``` \begin{figure}[!ht] \begin{center} \begin{tikzpicture}[node distance=2cm,auto,>=stealth'] \node[] (server) {server}; \node[left = of server] (client) {client}; \node[below of=server, node distance=5cm] (server_ground) {}; \node[below of=client, node distance=5cm] (client_ground) {}; % \draw (client) -- (client_ground); \draw (server) -- (server_ground); \draw[->] ([yshift=-1cm]client.south) -- ([yshift=-1cm]server.south); \draw[->] ([yshift=-1.5cm]server.south) -- ([yshift=-1.5cm]client.south); \end{tikzpicture} ``` I also want the lines to be straight and have text over them.
2014/10/15
[ "https://tex.stackexchange.com/questions/207240", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/64319/" ]
Next time please provide a [minimal working example (MWE)](http://goo.gl/dtPzv). This should be the starting point. ``` \documentclass[tikz]{standalone} \usetikzlibrary{calc} \begin{document} \begin{tikzpicture} \coordinate (a) at (0,0); \coordinate (b) at (0,1); \coordinate (c) at (1,0); \coordinate (d) at (1,1); \draw (a) -- (b)node[pos=1.1,scale=0.25]{Client} (c) -- (d)node[pos=1.1,scale=0.25]{Server}; \draw[-stealth] ($(a)!0.75!(b)$) -- node[above,scale=0.25,midway]{Text}($(c)!0.75!(d)$); \draw[stealth-] ($(a)!0.65!(b)$) -- node[below,scale=0.25,midway]{Hey} ($(c)!0.65!(d)$); \end{tikzpicture} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/NKFrF.png) And this is how your snippet can be modified: ``` \documentclass[tikz]{standalone} \usetikzlibrary{calc,positioning,arrows} \begin{document} \begin{tikzpicture}[node distance=2cm,auto,>=stealth'] \node[] (server) {server}; \node[left = of server] (client) {client}; \node[below of=server, node distance=5cm] (server_ground) {}; \node[below of=client, node distance=5cm] (client_ground) {}; % \draw (client) -- (client_ground); \draw (server) -- (server_ground); \draw[->] ($(client)!0.25!(client_ground)$) -- node[above,scale=1,midway]{Text} ($(server)!0.25!(server_ground)$); \draw[<-] ($(client)!0.35!(client_ground)$) -- node[below,scale=1,midway]{Hey} ($(server)!0.35!(server_ground)$); \end{tikzpicture} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/mduqd.png)
``` \documentclass{article} \usepackage{pgf-umlsd} \usepackage{tikz} \usetikzlibrary{shapes,arrows} \begin{document} \begin{figure} \centering \scalebox{1} { \begin{sequencediagram} \newthread{A}{\shortstack{Cliente\\ \\\begin{tikzpicture} \node [copy shadow,fill=gray!20,draw=black,thick ,align=center] {Aplicaciones \\ Cliente}; \end{tikzpicture}}}{} \newinst[1]{B}{\shortstack{Servidor de \\ aplicaciones \\ \\ \begin{tikzpicture} \node [fill=gray!20,draw=black,thick ,align=center] {Procesos}; \end{tikzpicture}}}{} \newinst[1]{C}{\shortstack{Servidor de \\ de Datos \\ \\\begin{tikzpicture}[shape aspect=.5] \tikzset{every node/.style={cylinder, shape border rotate=90, draw,fill=gray!25}} \node at (1.5,0) {BD}; \end{tikzpicture}}}{} \begin{call}{A}{}{B}{} \end{call} \begin{call}{B}{}{C}{} \end{call} \end{sequencediagram} } \caption{Arquitectura en 3 capas} \end{figure} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/TBBK5.png)](https://i.stack.imgur.com/TBBK5.png)
328,749
I'm working on a Spring-based REST api that has v1 and v2 variants: ``` /api/v1/dates /api/v2/dates ``` Correspondingly, there are v1 and v2 packages in the code base: ``` com.company.api.v1 com.company.api.v2 ``` Is it a good practice to postfix class names with version number like below: * DatesControllerV1.java (in v1 package) * DatesControllerV2.java (in v2 package) I prefer ***not*** postfixing version in the class name as: * their package names should tell you about the version already, redundant; * I simply don't like numeric character in class name. However, not postfixing version(ie. same class name but in different packages) will increase the probability of using the wrong class accidentally due to IDE auto-complete/auto-import by careless developers. I tried looking for a github repo that has similar code base structure and see how they deal with it. But could not find one unfortunately. I'm wondering which approach do you think is better and the reason. I'm also wondering if there is a better approach(for the current code base setup) than these two? **UPDATE** With the help from Azuaron and CormacMulhall, I realized that I really don't have other options to improve my current situation, given that both the v1 and v2 APIs reside in the same code base and I cannot change this setup. For those who are seeking for the proper way of doing this(having different versions of APIs), please see [Azuaron's answer](https://softwareengineering.stackexchange.com/a/328751/76266) below.
2016/08/19
[ "https://softwareengineering.stackexchange.com/questions/328749", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/76266/" ]
I must admit, my heart contracted in stress when I read "...there are v1 and v2 packages in the code base..." Typically, versioned APIs are, well, *versions* of your code, and don't live side-by-side in your codebase. How I've done it before is forking the repo. V1 sticks around for bug fixes until we can get everyone onto V2, and V2 is where all the new features go. Then in production, you deploy *both* codebases (either on different servers, or side-by-side), and your URL routing points to the appropriate instance. This gives you the following benefits: 1. The only way someone writes code against the wrong API is if they're in the wrong repo (at which point, there's not much else you can do for that programmer). 2. You don't have to worry about backward compatibility in "shared" non-API classes (utility, service, DAO, what have you). 3. A deploy of one API does not impact the other. 4. Honestly? It provides a demonstrable business reason to abandon v1 as soon as possible (you can shut down the old server) that can clearly be explained to non-developers. The downside is that the codebase is not shared, so changes in one that are "necessary" in the other must be ported. I don't see this as a big deal. It shouldn't happen that much (new features go into v2, not v1, by design), and any changes that truly need to be shared can be extracted into libraries or other services.
I guess it depends on "Do you see them as two versions of essentially same concept OR do you see them as two different concepts"? If you see two different concepts, it would definitely be better to name them separately (such as SavingsAccount versus CheckingAccount). --- I hated the versions. But, in reality, I had to bite it and do versions in my c++ libraries, to better help my users. I used namespaces. I used to ask my users (show them with sample code) to use appropriate "using namespace proj\_lib\_v1" declaration. The evolution of code gets a bit tough though at times. You would be putting all your packages into a different namespaces (as many times as versions). I used to take out all the helper classes and put them into a different namespace (not exposed to the users). ---
621,042
I have a TP4056 module (datasheet: <https://dlnmh9ip6v2uc.cloudfront.net/datasheets/Prototyping/TP4056.pdf>). It charges a 18650 cell. According to the datasheet : (Pin6): Open Drain Charge Status Output When the battery Charge Termination, the pin is pulled low by an internal switch, otherwise STDBY pin is in high impedance state. (Pin7): Open Drain Charge Status Output When the battery is being charged, the CHRG pin is pulled low by an internal switch, otherwise CHRG pin is in high impedance state. [![enter image description here](https://i.stack.imgur.com/spPeR.jpg)](https://i.stack.imgur.com/spPeR.jpg) As expect, LED1 lights up when it is charging, because I can measure 0V at pin 7. And I can measure about 2.8V at pin 6, which is why LED2 does not light up. So far so good. Since I do not need visual cues, I removed R1, R2, LED1, LED2. I soldered 2 wires at pin 6 and 7 because I want to read high/low states on a microcontroller and display the infos on an OLED screen instead. [![enter image description here](https://i.stack.imgur.com/vNTMy.png)](https://i.stack.imgur.com/vNTMy.png) This did not work as expected because now, while charging the battery cell, pin 6 reads about 0.5V (instead of about 2.8V before I desoldered what I deemed unnecessary components). So I cannot read the HIGH state on my microcontroller. Pin 7 still reds LOW, which is good. What did I do wrong? As far as I can understand from the datasheet, pin 6 should be internally pulled up at 5V, but I read 0.5V (or 2.8V before I altered it). What do I need to do to get rid of the LEDs and still be able to read the HIGH/LOW states of pin 6 and pin 7. I tried the following without any success : [![enter image description here](https://i.stack.imgur.com/7gqY4.png)](https://i.stack.imgur.com/7gqY4.png)
2022/05/25
[ "https://electronics.stackexchange.com/questions/621042", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/294744/" ]
Meters were invented two decades later (Oerstead's compass.) So, how did Volta discover that something was going on here? Wet fingers! With hands well soaked in water (or seawater, or vinegar,) touching a ~10V battery produces a detectable shock-feeling. In figure one, the "measurement instrument" is Volta himself, dipping one finger from each hand into the two final teacups. (Find Volta's first paper, see if he was using salt water, vinegar, weak lye, etc.) A public demonstration common at the time was to use your fingers to compress the stack, since the stack had poor conductivity otherwise. And, the harder you pushed, the worse the electrical-pain! So, in figure two, you'd put one hand in the teacup (bucket,) then use wet fingers to push downwards on the top of the stack, until the shock-feel became apparent. No frogs' legs needed ...especially if you had any tiny cuts on your fingers. Zat givz a zing! The four posts in figure 2 are wood insulators (or glass, for Zamboni or DuLuc dry-piles,) and were used to clamp the pile down under pressure, using an end-disk not shown. With a clamped disk, the output wouldn't be changing all the time, no longer depending on hand-strength. Figure three can zap the experimenter in the same way as figure one, but only using two teacups, without the experimenter touching the stack. (THe two stacks need to be clamped down. Or, have a third party pushing down on the heavy shorting-bar.) Figure four should be WAY more that twice as painful, when you stick your fingers in those two teacups. Yeesh. [![1801 Bulletin des Sciences #3 ](https://i.stack.imgur.com/mlyip.png)](https://i.stack.imgur.com/mlyip.png) above from "Bulletin des Sciences #3, 1801" see [ISIS V89, No2, p310 (6/1998)](https://www.jstor.org/stable/237757) Those flower-thingies appear to be part of a pile-compressing fixture, with an inverted cylindrical cup on top of the stack. This could possibly serve as an early on/off switch, since the max output current is nearly zero when the electrolyte sponge-layers aren't being compressed. > > Do the two buckets signify electrons > > > Note that electrons are mostly a metals thing. Electrons never flow in salt water, or in human bodies, or in acids/bases, or in the dirt, or when leaking across contaminated insulators or through ionized air. Metals (wires) involve electrons. Battery electrolytes don't, and neither do human bodies. In chem class, and in engineering school, we learn that electricity is NOT electrons like we were taught in grade school. (That was a lie-to-children, a "for dummies" concept aimed at youngsters who can understand flows of physical particles, but not abstract concepts such as "Electric Current.") Inside salt water, positives and negatives both flow (in opposite directions, both at the same time!) In acids, protons are flowing, in alkaline, it's OH- ions as charge-carriers. Inside humans, electric currents are flows of Na+, K+, Mg+ H+, OH-, Cl-, and a few other ions. No electrons at all. (And those H+ positive ions have another name: protons.) Science-misconceptions taught in grade-school: atoms look just like tiny solar systems. Above Earth's atmosphere there's zero gravity. Ben Franklin's kite was struck by a lightning-bolt. Electrons zoom through wires at lightspeed. Airfoils work because the top surface is longer. ELECTRIC CURRENT IS A FLOW OF ELECTRONS! (all these are wrong, of course!)
Holding the structure of heavy metal disks was done possibly by wooden poles. The A stood for Ag = Silver, and Z for Zn = Zinc. He focused only on this galvanic electro-potential of bimetals and completely ignored the massive electrochemical energy of an insulated acid or alkaline cell. I guess coal wasn't clean enough or ceramic plates with metallic compounds like used in 2V cells or lead plates didn't exist (?) it took Volta decades to be successful with his pile battery and I'm sure he had hydrogen explosions at times. (4% H2 and 0.0001% O2 is sufficient to detonate with a spark.) After all, batteries are just high-density versions of super big caps or "ultracaps" with a minimum metallic electro potential voltage at a low state of charge with a double-layer effect. A tiny 18650 Li-Ion cell is 10,000 Farads compared to a massive 100F superlarge Ultracap. But the low corrosive effects the Ultracap has on conductive activated-carbon electrodes and insulation, make it good for 1k more cycles than a Li-Ion. All the energy is stored above Vmin in the electrolyte of the capacitive acidic or alkaline dielectric-metallic interface. By the time he was awarded his due prize in London, wars and Eu country power struggles diverted his legacy of research to other countries. He did use saltwater for a wet electrode-interface material but then the corrosion was a problem, so clean water was mostly used. It took Daniell to make a useful primary acid cell with Zinc-sulphate in sulphuric acid. The plate material was too thin to be rechargeable. I wonder if this could be a symbol of "flower power" ;) [![enter image description here](https://i.stack.imgur.com/8afYi.png)](https://i.stack.imgur.com/8afYi.png) The cell bilayers and buckets were just a series accumulation of voltage and series resistance, so the power was pretty puny. It would take another century before [Nernst](https://knowledge.electrochem.org/encycl/art-n02-nernst.htm) would properly explain how a battery works and then someone else (?) a couple decades later to theorize the overpotential theory. Amps \* Ohms = Nernsts . ha ;) Volta was first so he gets the credit. Similar to Marconi's invention was done by Graham Bell earlier in PEI and Boston and credit changed hands. I don't think I've ever seen Volta make a *fish battery* even though the Torpedo fish was always his role model for a battery. (like an e-eel)
36,308,224
I have a requirement, where I need to delete thousands of files efficiently. At present, files are deleted in a sequential manner. I want to speed up the deletions, by calling delete in an asynchronous manner, using std::async(). Current Flow: 1. Get the list of files 2. For each file call delete() Desired Flow: 1. Get the list of files 2. For each file: 1. Call AsyncDelete() using std::async() 2. Store the future object in a vector 3. Wait for each of the deletes to be completed and then return I will launch each of the async tasks using `std::launch::async`, so that it runs on a separate thread. I have following questions: 1. Is async() suited for workloads involving multiple tasks? Or is it better to use threads for such tasks? I read a chapter (Item 35: Prefer task-based programming to thread-based) in Scott Myer's book "Effective Modern C++", where he recommends using task based programming instead of thread-based. 2. How costly is each "async()" call? Does it have any overhead like a thread creation overhead? I am planning to control the number of async tasks called per cycle. For e.g. if 10,000 files are to be deleted, I will call just 100 deletes per cycle, instead of spawning 10,000 async() tasks in one go. I hope the standard library implementation efficiently handles multiple async calls (for e.g. using a thread pool). 3. future() object returned by async() exposes both get() and wait() methods. I read that, get() internally calls wait(). Is it enough to call get() on each of the futures stored in a vector? 4. What if a get() never returns? Is it advisable to use wait\_for() with a time out?
2016/03/30
[ "https://Stackoverflow.com/questions/36308224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2256902/" ]
You may find this doesn't actually help as much as you would like. The file system is likely to have kernel level locks (to ensure consistency), and having many threads hitting these locks it likely to cause trouble. I suggest 1. Get the list of files. 2. Divide the list into (say) ten equal chunks (represented by iterator pairs). 3. Launch ten threads which each delete their own chunk of the list. 4. Wait for the ten threads to finish. 5. Experiment with different values of ten.
As a *completely* different approach, have you considered moving everything into a database? Deleting thousands of persistent things quickly is just the sort of stuff databases are good at.
6,735,549
I've got a FrameLayout with TextView children and I'd like to change the position of the TextViews at runtime (in onSensorChanged(), so several time per seconds). There is no setPosition(...), so how can I do that? Thanks
2011/07/18
[ "https://Stackoverflow.com/questions/6735549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326849/" ]
I would suggest you two ways, and none of them is text-indent(which is obsolete method). First way is to remove text, and instead it ad a title to your anchor, like this: ``` <a href="index.php" id="logo" title"My Website"></a> ``` Second way, is to add an image in this anchor tag: ``` <a href="index.php" id="logo"><img src="path/to/image" alt="My Website"/></a> ``` These two ways are much better then text-indent, especially because few months ago Google announced that it has radically changed the way of indexing sites to prevent bite links and other forms of fraud, meaning that the text-indent will not look favorably, perhaps not from the start, but will try to wean people from it. See this video: <http://www.youtube.com/watch?v=fBLvn_WkDJ4&feature=player_embedded>
Here is a trick that I use a lot. It shouldn't heart seo at all ``` <a href="">&nbsp;</a> - now is visible but without showing any chars. ```
48,712,194
How to get **only** the returned value from a function, in the below example, I want to get only `foorbar` and not `this is a test` in the bash shell. ``` $ cat foo.py print "this is a test" def bar(): return "foobar" $ output=$(python -c 'import foo;print foo.bar()') $ echo $output this is a test foobar ```
2018/02/09
[ "https://Stackoverflow.com/questions/48712194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748513/" ]
I'd recommend if you require for whatever reason the `print "this is a test"` section, you check if the file is being run itself, such as by checking the `__name__` property as follows: **foo.py:** ``` def bar(): return "foobar" if __name__ == "__main__": print("this is a test") ``` This should mean that the only time "*this is a test*" is printed is when you call `python foo.py`, and not when foo is imported as a module. Hope this helps!
If you want to keep the module as-is and get what you want, you need to suppress the module level string being printed by temporarily redirecting the STDOUT to someplace else (e.g. `None`, `/dev/null` or any other file descriptor as a dumping zone), and duplicate again to the original STDOUT once the `import` is done. ``` % cat spam.py print("this is a test") def bar(): return "foobar" % python3 -c 'import sys;sys.stdout=None;import spam;sys.stdout=sys.__stdout__;print(spam.bar())' foobar % out=$(python3 -c 'import sys;sys.stdout=None;import spam;sys.stdout=sys.__stdout__;print(spam.bar())') % echo "$out" foobar ``` Expanded form: ``` import sys sys.stdout = None import spam sys.stdout = sys.__stdout__ print(spam.bar()) ```
25,125,560
When I scroll to the bottom of the child `div`, the `body` element starts scrolling. How can I prevent this? I only want the `body` to scroll when the cursor is over it. Example: [JsFiddle](http://jsfiddle.net/5mmay/)
2014/08/04
[ "https://Stackoverflow.com/questions/25125560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3675747/" ]
By adding some javascript of course! **[FIDDLE](http://jsfiddle.net/5mmay/1/)** ``` $( '.area' ).on( 'mousewheel', function ( e ) { var event = e.originalEvent, d = event.wheelDelta || -event.detail; this.scrollTop += ( d < 0 ? 1 : -1 ) * 30; e.preventDefault(); }); ```
Use this plugin <http://mohammadyounes.github.io/jquery-scrollLock/> It fully addresses the issue of locking mouse wheel scroll inside a given container, preventing it from propagating to parent element. It does not change wheel scrolling speed, user experience will not be affected. and you get the same behavior regardless of the OS mouse wheel vertical scrolling speed (On Windows it can be set to one screen or one line up to 100 lines per notch). Demo: <http://mohammadyounes.github.io/jquery-scrollLock/example/> Source: <https://github.com/MohammadYounes/jquery-scrollLock>
11,495,851
I get tired of the dotted box that appears when you click a tags...so that I started replacing them with p tags...and adding an event listener for click events. I can't help but notice that other popular sites don't do this ( for example when you click Post Your Question on SO the annoying dotted box appears ) Is there any good reason not to replace a tags by p tags. I don't need any of the special a tag properties...in fact I have to use preventDefault() in my JavaScript to stop them from linking some times. Is it O.K to pretty much eliminate the A tag? This is a question regarding major modern browsers. I'm about to rid myself of them...and am paranoid I'm missing something as I see them still in use pretty much everywhere.
2012/07/15
[ "https://Stackoverflow.com/questions/11495851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
No, this is **not** okay. Anchor tags are needed for browsers that don't support your styling, and I'm just talking about old versions of IE. Remember that screen readers, text-only users, and browser plugins all expect to find your anchor tags. As Dash has pointed out, bots such as search engine crawlers also need your anchor tags to be able to follow them and index your pages. HTML is for document structure. CSS is for styling. It is important to keep this principal. A note regarding that dotted box... that is there to show focus on an element. Not everyone uses a mouse you know. Some prefer to tab through the document with a keyboard, and that focus box helps with that. Even if you succeed in removing it with CSS... please don't.
I disagree with the other two commenters a little. While it is true that it will break screen readers and not be backward compatible in general..... IF you have a specific use case where you don't care about any of the above, well...it is your project. :) And you COULD also mostly achieve this and keep the anchor tags by add the following to your CSS: ``` a { text-decoration: none; } ```
2,523,391
Is there an open source project that can serve as a good example on how to use the [maven site plugin](http://maven.apache.org/plugins/maven-site-plugin/) to generate reports? I would prefer it to * consist of many modules, possibly hierarchically structured * use as many plugins as possible (surefire, jxr, pmd, findbugs, javadoc, checkstyle, you name it) * the reports should be aggregated: if some tests fail you want to have a single page that shows all modules with failing tests, not only a gazillion individual pages to check * include enterprisey stuff (WAR, EAR etc), but this is not so important. The idea is to have something where you can gather ideas on how it is done and what is possible.
2010/03/26
[ "https://Stackoverflow.com/questions/2523391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21499/" ]
I don't think there is such a project, if there is I want to know it as well. In order to find things in maven you have to know what you're looking for(which is not exactly the same with what you want to accomplish). If its any help I'm building 13 module project with MAVEN, use cobertura maven plugin, surefire, javadoc, etc .. it works as charm, why are you asking this question, you want to determine the capabilities of maven or ?
You can use [Violations Maven Plugin](https://github.com/tomasbjerre/violations-maven-plugin) to aggregate Findbugs (and many other static code analysis) reports. It needs to run after the analysis. It will parse their report-files and present them in one unified report. It can, optionally, fail the build depending on number of violations found.
2,552,453
Is there a way to give CSS syntax highlighting to any `<textarea>` using any bookmarklets or favlets? I work on a CMS where I write and manage CSS in a plain `<textarea>` like Notepad. Is there a boomarklet to enable CSS syntax highlight in specific `<textarea>` temporarily? Should work in IE.
2010/03/31
[ "https://Stackoverflow.com/questions/2552453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84201/" ]
If you know how to write a bookmarklet, you may be able to adapt [Code Mirror](http://marijn.haverbeke.nl/codemirror/).
I don't know about mookmarklets or Favlets, but you could write a userscript to do that. Not sure if IE supports anything like that, but Firefox, Chrome and Opera all support userscripts. (Use [Greasemonkey](https://addons.mozilla.org/en-US/firefox/addon/748) for Firefox) For example, I wrote [this script](http://atli.advefir.com/greasemonkey/bytes_highlight/) for myself, to highlight code on the Bytes forums, which I can use in all three browsers. (Feel free to use that if you want.) **Edit**. It seems the [IE7pro](http://www.ie7pro.com/) addon for IE supports Greasemonkey-like userscripts.
1,660,856
The rules for promotion is "when operands are of different types, automatic binary numeric promotion occurs with the smaller operand type being converted to the larger". But the operands are of same type for example, ``` byte=byte+byte // Compile time error... found int.. ``` So why is it so?
2009/11/02
[ "https://Stackoverflow.com/questions/1660856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167114/" ]
To understand this you should refer the 2 things: Implicit Casting: byte (8 bit) -> short (16 bit) -> int (32 bit) -> float (32 bit) -> double (64 bit) char (16 bit) -> int (32 bit) Arithmetic Operator Rules 1. Operator Precedence Rule : This rule states that Group of (\*,/, %) will be evaluated first. Then Group of (+,-) operator will be evaluated. From a same Group of Operators, calculate from the left. 2. Operand Promotion Rule : This rule states that Operands having data type smaller than int will be promoted to int. order of promotion (byte->short->int, char->int) 3. Same Type Operand Rule: This rule states that if both operands are int,long,float,double then the same type is carried to the result type. i.e. long+long => long , float + float => float, int+int => int 4. Mix Type Operand Rule : Follow the order of Promotion (int->long->float->double) if any of the operand is from the above order then the smaller will be promoted to the bigger one and result will be calculated in bigger type. i.e. long + double => double , int + long => long
From [this SO question](https://stackoverflow.com/q/13100019/1686291), and above answers due to `+` arithmetic operator, both operands are converted to type `int`. ``` byte b1 = 1; byte b2 = 2; byte b3 = b1 + b2; // compile time error ``` In above code, value of `b1` and `b2` will be resolved at runtime, so compiler will convert both to `int` before resolving the value. But if we consider the following code, ``` final byte b1 = 1; final byte b2 = 2; int b3 = b1 + b2; // constant expression, value resolved at compile time ``` `b1` and `b2` are final variables and values will be resolved at compile time so compilation won't fail.
41,357,643
I am creating a form where user can select a country from a drop-down list, then based on selected country, all related states filled in a multi-select list-box. Now a user can select multiple states and based on selected states another multi-select list-box (assigned for cities) should be filled accordingly. How can achieve this? [![enter image description here](https://i.stack.imgur.com/yVIa7.png)](https://i.stack.imgur.com/yVIa7.png) Html:- ``` <asp:DropDownList ID="ddlCountry" runat="server" CssClass="form-control" AutoPostBack="true OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">/asp:DropDownList> <asp:ListBox ID="ddlState" runat="server" SelectionMode="Multiple" CssClass="form-control multiselectmulticolumnddl" OnSelectedIndexChanged="ddlState_SelectedIndexChanged"></asp:ListBox> <asp:ListBox ID="ddlCity" runat="server" SelectionMode="Multiple" CssClass="form-control multiselectmulticolumnddl"></asp:ListBox> ```
2016/12/28
[ "https://Stackoverflow.com/questions/41357643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6869675/" ]
I solved by doing this: ``` $scope.changeStudentStatus = function(){ if($scope.ctrl.newStudentStatus) { //some logic } }; ```
Change ``` ng-change="changeStudentStatus();" ``` to ``` ng-change="ctrl.changeStudentStatus();" ``` The difference is that in your code, you call a method that is called `changeStudentStatus()`. This method isn't available on the controller. I assumed that you alliased your controller as `ctrl` since your other methods/properties are being called with `ctrl.*` When you call the method `ctrl.changeStudentStatus()` you actually call the method that is set on your controller.
73,120
I am a newbie in comics. Although I'm well aware with all the DC characters and have seen all the movies, I think it's time for me start diving into comics as they're the real deal and I've always wanted to read comics. I like the Batman (who doesn't!) and the Flash (because he's cool). Superman is pretty cool as well. So where do I start reading their comics, if I want to get to know about their history, how they originated and their present *without* missing anything. I don't want to miss stories where they fought together and stuff as well. A friend suggested DC's New 52 saying "it was a complete reboot of the entire DC universe.". So would you guys recommend it as well? Also, I prefer comics with good artwork rather than some lame looking Batman. Looking forward to hearing your thoughts! Thanks.
2014/11/20
[ "https://scifi.stackexchange.com/questions/73120", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/36290/" ]
I've found that there are two big dampers on reading comic books **cost** and **finding complete stories**. When I started reading DC comics I went to a used bookstore and looked for consecutive issues of individual titles. I wound up with a 5 issues of Teen Titans from 1995 and the first 3 issues of Young Justice for around $10. That said I was able to read large plot arcs without getting too lost. I often still use this tactic to find new (always used) comics for my collection. I look for titles from a specific year and fill in runs of an individual title. Sometime special editions are a great place to go to. For 99 cents I was able to get a single part issue of the Atom which was pretty complete and easy to follow (And like 4 times as big as a normal comic book). Also graphic novels and/or volumes containing multiple issues of a story arch can be a great and budget friendly option as well. You mentioned liking 3 of the biggies in the DC universe so while you are familiar with the big names, some of the most fun characters are a bit lesser known. You might want to look around and find out what other titles might interest you. A good way to find that out is watching cartoons and seeing which "guest" characters make an appearance and finding out via the internet what titles and issues that particular character makes an appearance in. I'm not much of a fan of the new 52 as so many of the characters I really like got dumped or had their origin story butchered by the reboot, but you might like it and have an easy time acquiring consecutive issues with it though. Also, wiki pages tend to have good records of issues pertaining to various character arcs, so if you want to find out the origins of a particular character (as it may not be shown in issue #1...probably won't be shown in issue #1) the source materials are usually linked to that bio. The best advise I can give you is find the titles you truly find interesting and have fun.
The latest issue of Batgirl is a good jumping-on point, and Gotham Academy just started up. You might also want to check out older books like Batman Year One, The Dark Knight Returns, The Killing Joke, etc. Other than that, just go into your local comic shop and ask them the question. They'll be able to point you to some books, and you can check out the art to see if it's something you're into.
63,687,810
``` var d = new Date(); var month = d.getMonth(); var monthday = d.getDate(); var hours = d.getHours(); var minute = d.getMinutes(); var date = document.getElementsByClassName("date"); date[0].innerHTML = [month + 1] + "." + monthday + " " + hours + ":" + minute; ``` This is printing the current date like this: `9.1 3:31` ... and I want to format like this: `09.01 03:31` Any idea how can I do that in the shortest code?
2020/09/01
[ "https://Stackoverflow.com/questions/63687810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14128494/" ]
`Add` for every value before the string `"0"` and get with `slice(-2)` the last 2 chars. ```js var d = new Date(); var month = d.getMonth(); var monthday = d.getDate(); var hours = d.getHours(); var minute = d.getMinutes(); var date = document.getElementsByClassName("date"); let res = '0'+[month + 1].slice(-2) + "." + ('0'+monthday).slice(-2) + ". " + ('0'+hours).slice(-2) + ":" + ('0'+minute).slice(-2) ; console.log(res); ```
Try this ``` var d = new Date(); var month = d.getMonth(); var monthday = d.getDate(); var hours = d.getHours(); var minute = d.getMinutes(); var date = document.getElementsByClassName("date"); function pad(s) { return (s < 10) ? '0' + s : s; } date[0].innerHTML = pad([month + 1]) + "." + pad(monthday) + " " + pad(hour) + ":" + pad(minute); ```
7,027,513
Where could I find JavaSpaces tutorials? Points of interests for me: * What can I do with it? * How do I use it? * How does it work?
2011/08/11
[ "https://Stackoverflow.com/questions/7027513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505714/" ]
In addition to what cs94njw mentioned, I would also recommend [JavaSpaces](http://docstore.mik.ua/orelly/java-ent/dist/appc_01.htm) as well as [The Nature Of JavaSpaces](http://www.dancres.org/cottage/javaspaces.html).
Quick google search: <http://java.sun.com/developer/technicalArticles/tools/JavaSpaces/> http://www.gigaspaces.com/wiki/display/XAP7/Plain+JavaSpaces+Tutorial
33,986,143
I have a `listView` in Activity A , which the value are returned from Activity B.When the list is clicked, it will intent to Activity B for edit. **Activity B** ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_details_information); addItemsOnSpinner(); if(getIntent().getExtras()!=null) // if has value pass from A { final String Project1=getIntent().getStringExtra("ReceiveProject"); final String Description1=getIntent().getStringExtra("ReceiveDescription"); final String Progress1=getIntent().getStringExtra("ReceiveProgress"); final String TimeIn1=getIntent().getStringExtra("ReceiveTimeIn"); final String TimeOut1=getIntent().getStringExtra("ReceiveTimeOut"); //project.setText(Project1); description.setText(Description1); //progressText.setText("Covered:") timeIn.setText(TimeIn1); timeOut.setText(TimeOut1); } save.setOnClickListener(new View.OnClickListener() { // return to A @Override public void onClick(View v) { Intent returnIntent=new Intent(); Project=project.getSelectedItem().toString(); // Spinner Value Description=description.getText().toString(); //from editText progress=seekBar.getProgress(); // From SeekBar returnIntent.putExtra("Project",Project); returnIntent.putExtra("Description", Description); returnIntent.putExtra("progress", progress); Toast.makeText(getApplicationContext(), progress+"", Toast.LENGTH_LONG).show(); returnIntent.putExtra("TimeIn", TimeIn); returnIntent.putExtra("TimeOut",TimeOut); setResult(Activity.RESULT_OK,returnIntent); finish(); } }); public void addItemsOnSpinner() { project=(Spinner)findViewById(R.id.SpinnerProject); List<String> list = new ArrayList<String>(); list.add("TRN-XXX-XXX"); list.add("Pro-XXX-XXX); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.spinner_item, list); //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); project.setAdapter(adapter); } ``` **Activity A** ``` listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked @Override public void onItemClick(AdapterView<?> a, View v, int position, long id) { mClickedPosition = position; Intent i = new Intent(getApplication(), Add_Details_Information.class); i.putExtra("ReceiveProject", ReceiveProject); i.putExtra("ReceiveDescription", ReceiveDescription); i.putExtra("ReceiveProgress", ReceiveProgress); i.putExtra("ReceiveTimeIn", ReceiveTimeIn); i.putExtra("ReceiveTimeOut", ReceiveTimeOut); startActivityForResult(i,PROJECT_REQUEST_CODE); } }); } ``` I know that we can use `setText` to display the passed value from A to B for `editText`, but how about the `spinner` and `seekBar` value ? This is the listView in Activity A. Value are returned from Activity B. [![enter image description here](https://i.stack.imgur.com/M4tMl.png)](https://i.stack.imgur.com/M4tMl.png) When listView is clicked, it will goes to B again to edit. [![enter image description here](https://i.stack.imgur.com/ihGPv.png)](https://i.stack.imgur.com/ihGPv.png) So how can I make the spinner in B display Pro-XXX-XXX and the seekBar goes to 48 ? Any idea or suggestion ? Thanks a lot **Edited** After used the answer from @Clairvoyant, now I get this (for spinner value). **Activity A** [![enter image description here](https://i.stack.imgur.com/XgV6Z.png)](https://i.stack.imgur.com/XgV6Z.png) There are 4 list in Activity A. Assume first list is clicked. [![enter image description here](https://i.stack.imgur.com/jpVPb.png)](https://i.stack.imgur.com/jpVPb.png) Everything works fine just the spinner(Project/Service/Training) display wrong value. It display the spinner value from last list(PRO-SKM-D5) instead of itself(Pro-XXX-XXX)
2015/11/29
[ "https://Stackoverflow.com/questions/33986143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5398173/" ]
**First Step:** Make your **addItemsOnSpinner** like as below: ``` public void addItemsOnSpinner(String value) { int position = 0; project=(Spinner)findViewById(R.id.SpinnerProject); List<String> list = new ArrayList<String>(); list.add(position,"TRN-XXX-XXX"); list.add("Pro-XXX-XXX"); for(int i=0; i<list.size() ; i++){ if(list.get(i).equalsIgnoreCase(value)){ position = i; break; } } ArrayAdapter<String> adapter = new ArrayAdapter<String> (getApplicationContext(),R.layout.spinner_item, list); //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); project.setAdapter(adapter); project.setSelection(position); } ``` **Second Step:** call the above method when you are assigning value to the variable you have to show in spinner here for eg: `project1` is the string value which you want to show in spinner then call the method as follows: ``` final String Project1=getIntent().getStringExtra("ReceiveProject"); addItemsOnSpinner(Project1); ```
Use `SharedPreferences`. Next time, [googling helps](https://stackoverflow.com/a/33962422/1390727). **Get `SharedPreferences`** ``` SharedPreferences prefs = getDefaultSharedPreferences(context); ``` **Read preferences:** ``` String key = "test1_string_pref"; String default = "returned_if_not_defined"; String test1 = prefs.getString(key, default); ``` **To edit and save preferences** ``` SharedPreferences.Edtior editor = prefs.edit(); //Get SharedPref Editor editor.putString(key, "My String"); editor.commit(); ``` **Shorter way to write** ``` prefs.edit().putString(key, "Value").commit(); ``` Additional info for SharedPreferences: [JavaDoc](http://developer.android.com/reference/android/content/SharedPreferences.html) and [Android Developers Article](http://developer.android.com/training/basics/data-storage/shared-preferences.html)
35,323,144
Currently my query looks like so: ``` SELECT start_date, from_id, to_id, from_amount, to_amount FROM sample_table WHERE from_id = '123' OR to_id = '123'; ``` However, what I'm really aiming for is one `amount` column in my results which shows `from_amount` WHERE `from_id = 123` and `to_amount` WHERE `to_id = 123`. So instead of: ``` start_date / from_id / to_id / from_amount / to_amount 2016-01-01 / '123' / '456' / 100 / 20 2016-01-07 / '789' / '123' / 50 / 75 ``` I'd like to return: ``` start_date / amount 2016-01-01 / 100 2016-01-07 / 75 ``` I'm assuming I need to use some sort of nested WHERE, but not sure how to set it up.
2016/02/10
[ "https://Stackoverflow.com/questions/35323144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3084511/" ]
They are *some kind* of **colored margin** (used in Android Wear). They are used to create a padding from the main content to the actual border: There are a few examples [here](http://developer.android.com/training/wearables/ui/layouts.html). --- This is an image with 2 insets: Circle/Squared. [![enter image description here](https://i.stack.imgur.com/kzIrE.png)](https://i.stack.imgur.com/kzIrE.png) --- They can also be used in other views to handle especial rendering requirements, like in a [ScrollView](http://developer.android.com/reference/android/widget/ScrollView.html): where to put the actual scroll can be defined with an insideInset as mentioned in [this question](https://stackoverflow.com/questions/3103132/android-listview-scrollbarstyle). ``` <ScrollView android:id="@+id/view2" android:layout_width="100dip" android:layout_height="120dip" android:padding="8dip" android:scrollbarStyle="insideInset" android:background="@android:color/white" android:overScrollMode="never"> ```
You may use [onApplyWindowInsets](http://developer.android.com/reference/android/view/View.OnApplyWindowInsetsListener.html): ``` @Override public void onApplyWindowInsets(WindowInsets insets) { super.onApplyWindowInsets(insets); mRound = insets.isRound(); } ``` to detect if wearable android device is round or square, then using that information draw appropriate application interface (with round or square background)
41,594,631
I wrote a python script to output lines and cells of a csv file. The file I read has been exported from the address-book of a shipment company utility. It appears, that this file is somehow "corrupted". The co-workers who registered the addresses did some wrong copy-paste and inserted many quotation marks often without closing them. And this messes up the csv-file which looks approx. like this when I read it with *less* or *cat*: (I numbered the lines) ``` 1 ;name1;address1;"phone number1;; 2 ;name2;address2;phone number2;; 3 ;name3;address3;"phone number3;; ``` The contents of 'line 1, cell 4' until 'line 3, cell 3;' end up in the line 1 cell 4 altogether... when I output it with my script I see: ``` 1 ;name1;address1;phone number1;;;name2;address2;phone number2;;;name3;address3; 2 phone number3;; ``` The thing is, my file is 30000 lines long and this mistake is repeated over hundreds of lines. The solution is obvious: replace all quotation marks with nothing. The question is: what is the best solution to let python read the file correctly? Or: Is there a way to open the file in python and make the script **ignore** the quotation marks? which would be very nice, I think. Should I find/replace with python first? Should I correct the encoding/re-encode the file? I've no idea how the file is encoded: ``` $ file -i myfile.csv myfile.csv: text/plain; charset=unknown-8bit ``` -- Here is the code of my script in case it would help. Please don't mind the unpythonicnesses. This only is the second script I ever wrote... ``` import sys, csv file = sys.argv[1] x = int(sys.argv[2]) - 1 if len (sys.argv) == 4: y = int(sys.argv[3]) - 1 f = open(file, 'rb') cr = csv.reader(f, delimiter=';') lst = [] linecount = 0 for row in cr: lst.append(row) linecount += 1 if 'y' in locals(): line = lst[x][y] print line print '-'*len(line), '\n', 'line number', x + 1, '|', 'cell number', y + 1 print len(lst[x]), 'cells' else: print lst[x] print '\n', file, linecount, 'lines' ``` *I maybe should use csv.next() instead of putting everything in a list.*
2017/01/11
[ "https://Stackoverflow.com/questions/41594631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5497403/" ]
Using `GNU grep` with `-P` for perl-style `regEx` match, and `-o` flag to return only the matching pattern. ``` grep -oP 'Program Version \K[^ ]*' file 1.3.1 ``` To save it in a variable ``` versionNo="$(grep -oP 'Program Version \K[^ ]*' file)" printf "%s\n" "$versionNo" 1.3.1 ``` Use `perl` `regEx` itself, ``` perl -lne 'print "$1" if /^Program Version (\d.+)/' file 1.3.1 ``` in variable, ``` versionNo="$(perl -lne 'print "$1" if /^Program Version (\d.+)/' file)" file printf "%s\n" "$versionNo" 1.3.1 ``` Using `GNU sed` ``` sed -r 's/Program Version ([[:digit:]].+).*/\1/' file 1.3.1 ``` and ``` versionNo="$(sed -r 's/Program Version ([[:digit:]].+).*/\1/' file)" file printf "%s\n" "$versionNo" 1.3.1 ```
I guess you obtain that `Program Version 1.3.1` for example launching some kind of command. Well, try this: ``` #!/bin/bash version=$(yourCommandWhichShowsVersion 2> /dev/null | egrep "^Program Version [0-9]" | awk '{print $3}') ``` Explanation: * You need to launch the command which show the version * You redirect the output to egrep which search through all lines matching only which starts `^` <- this is to start string, with the desired text `Program Version`, and this `[0-9]` is to match one number. If you don't know if the version can be 1.3 or 1.3.1 or 1 that's all you need. * awk is going to "select" the second column (first is "Program version" and second is the version number) Good luck!
19,086,409
Hello `sackoverflow` I'm trying to develop an application which can backup and restore contacts, my code is as follows ``` public class MainActivity extends Activity { Cursor cursor; ArrayList<String> vCard ; String vfile; FileOutputStream mFileOutputStream = null; Button btnRestorects = null; Button btnBackupCts = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnRestorects = (Button) findViewById(R.id.buttonRstCts); btnBackupCts = (Button) findViewById(R.id.buttonBackCts); vfile = "contacts.vcf"; final String storage_path = Environment.getExternalStorageDirectory().toString() +"/"+ vfile; final File f = new File(storage_path); btnBackupCts.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { if (!f.exists()) f.createNewFile(); mFileOutputStream = new FileOutputStream(storage_path, false); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } getVcardString(); } }); btnRestorects.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent intent = new Intent(); final MimeTypeMap mime = MimeTypeMap.getSingleton(); String tmptype = mime.getMimeTypeFromExtension("vcf"); final File file = new File(Environment.getExternalStorageDirectory().toString() +"/contacts.vcf"); intent.setDataAndType(Uri.fromFile(file),tmptype); startActivity(intent); } }); } private void getVcardString() { // TODO Auto-generated method stub vCard = new ArrayList<String>(); cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); if(cursor!=null&&cursor.getCount()>0) { cursor.moveToFirst(); for(int i =0;i<cursor.getCount();i++) { get(cursor); Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i)); cursor.moveToNext(); } } else { Log.d("TAG", "No Contacts in Your Phone"); } try { mFileOutputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void get(Cursor cursor) { //cursor.moveToFirst(); String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); AssetFileDescriptor fd; try { fd = this.getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); byte[] buf = new byte[(int) fd.getDeclaredLength()]; fis.read(buf); String vcardstring= new String(buf); vCard.add(vcardstring); mFileOutputStream.write(vcardstring.toString().getBytes()); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } ``` Permissions in manifest ``` <uses-permission android:name="android.permission.READ_CONTACTS"/> <uses-permission android:name="android.permission.WRITE_CONTACTS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> ``` So far my code was backing up the contact but only name and contact number, but not retrieving the information like whether the contact is starred or not. Please help me in solving this riddle. Thanks in advance.
2013/09/30
[ "https://Stackoverflow.com/questions/19086409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2503661/" ]
Use this to restore: ``` final MimeTypeMap mime = MimeTypeMap.getSingleton(); String tmptype = mime.getMimeTypeFromExtension("vcf"); final File file = new File(Environment.getExternalStorageDirectory().toString() + "/contacts.vcf"); Intent i = new Intent(); i.setAction(android.content.Intent.ACTION_VIEW); i.setDataAndType(Uri.fromFile(file), "text/x-vcard"); startActivity(i); ```
```java Intent mIntent = new Intent(Intent.ACTION_VIEW); mIntent.setDataAndType(Uri.fromFile(new File(filePath)), MimeTypeMap.getSingleton().getMimeTypeFromExtension("vcf")); startActivity(Intent.createChooser(mIntent, "Select App")); ```
1,120,132
How can I get SMTP to work on a Windows 7 development box? I used to just be able to turn on the IIS SMTP server on Windows XP. Is SMTP not included with Windows 7? If so, what can I use instead as a free relay mechanism?
2009/07/13
[ "https://Stackoverflow.com/questions/1120132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137506/" ]
According to [this post](http://thisthattechnology.blogspot.com/2009/09/smtp-service-on-windows-7.html), the issue an SMTP server was included in IIS6, but has been removed in IIS7. This [thread suggests](http://social.technet.microsoft.com/Forums/en-US/w7itproinstall/thread/7cef5da9-5b31-4b98-9bd9-9f7777dd7b37/) the [Remote Server Administration Tools](http://support.microsoft.com/kb/974877/en-us) (which include a SMTP server), as long as you don't have the Home edition of Windows.
I use "Free SMTP Server" from Softstack. <http://www.softstack.com/freesmtp.html> HTH
59,423,504
I'm having a two columns say Value column is having records like `'abc|comp|science|raja'` and I want to split this records like `abc,comp,science,raja` and I need to compare it with another column say `CHECKER` which is having record as science Value ===== ``` abc|comp|science|raja ``` Checkers ======== ``` science ```
2019/12/20
[ "https://Stackoverflow.com/questions/59423504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10492921/" ]
You don't need to split the string and you don't even need a regular expression; just check whether the `checker` string (with leading a trailing delimiters) is a sub-string of `value` (with leading and trailing delimiters): **Oracle Setup**: ```sql CREATE TABLE your_table ( value, checker ) as SELECT 'abc|comp|science|raja', 'science' FROM DUAL UNION ALL SELECT 'abc|def|ghi', 'xyz' FROM DUAL UNION ALL SELECT 'abc', 'abc' FROM DUAL UNION ALL SELECT 'abcdef', 'abc' FROM DUAL ``` **Query**: ```sql SELECT * FROM your_table WHERE '|' || value || '|' LIKE '%|' || checker || '|%'; ``` **Output**: > > > ``` > > VALUE | CHECKER > :-------------------- | :------ > abc|comp|science|raja | science > abc | abc > > ``` > > *db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=d6fa7b290a28476c5ca483d67c35ebd9)*
It sounds like you just want to check whether the checker is in the value, in that case you can do this: ``` with mytable as ( select 'abc|comp|science|raja' value , 'science' as checker from dual union all select 'science|abc|comp|raja' , 'science' from dual union all select 'abc|comp|raja|science' , 'science' from dual ) select x.value from mytable x where regexp_like(value, '(^|\|)' || checker || '($|\|)') ``` The regex\_like is searching inside the value for the checker with either a pipe or the end of the string, so it will match the keyword at the beginning, in the middle or at the end of the string. But it would not match "sciences". Alternatively if you want to see all the rows and check whether they passed the "check" you could do: ``` with mytable as ( select 'abc|comp|science|raja' value , 'science' as checker from dual union all select 'science|abc|comp|raja' , 'science' from dual union all select 'abc|comp|raja|science' , 'science' from dual union all select 'abc|comp|raja|sciences' , 'science' from dual ) select x.value , x.checker , case when regexp_substr(value, '(^|\|)' || checker || '($|\|)') is not null then 'Y' end as passed from mytable x ```
197,708
I'd like to use Rich Text Editing in place on forms in order to let admins change instructions. What are the best options for doing this? [To be more clear - the admins are non-technical but may want to control some formatting without using markup or with as little markup as possible. What I'd like is for them to be able to edit inline all AJAXy with an RTE featuring some formatting controls and then submit and be able to see what the instructions will look like to the end user without changing pages. With Regards to plugins specifically, what I'd like to know is which Rich Test Editing plugins are the best for use in Rails. Easiest to implement, clearest API, easiest to use inline, etc... ]
2008/10/13
[ "https://Stackoverflow.com/questions/197708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6805/" ]
I'm not sure if I fully understand the question, but if you just ask about which editor to use, there are many options and none of them is a matter of Rails - you can use any of them just by adding a little piece of javascript into your markup. Nice and up to date overview can be found here: [http://bulletproofbox.com/web-based-rich-text-editors-compared/](https://web.archive.org/web/20081012054026/http://bulletproofbox.com:80/web-based-rich-text-editors-compared/).
I know this threat is pretty old but I came across looking for a few good options the a few weeks back, so in case someone else is facing the same issue like I did I give a more resent response. So my favourite editor is [Froala](https://www.froala.com/) ([wysiwyg-editor](https://github.com/froala/wysiwyg-rails) if you are using rails)which looks clean, is easy to handle and supports embedded videos, picture upload, file upload and is fully customisable to a point where you can even make it simple for backend users without any knowledge of responsive developing to place the items correctly on the page to make them fully responsive. We have used this editor for a number projects now and clients love it. The documentation is satisfying but it could be better if you are using it with frameworks such as Rails and Django (as we do). But I think it is improving on a monthly basis. Another very promising editor is [Quill](http://quilljs.com/) ([quill-rails](https://github.com/the-robear/quill-rails) if you are using rails). We haven't used it for projects yet but experimenting. Once we have more experience we are going to post a few notes on here and [SSC](https://sciencesupercrew.com/en). Lastly, if you would like to do or offer responsive front-end editing you might want to take a look at [x-editable](https://github.com/bootstrap-ruby/bootstrap-editable-rails). Check out the demo - it is pretty neat !
2,269,672
Let $A=\{(x,y)\in\mathbb{R}^ 2|x\in\mathbb{Q}\text{ or }y=0\}$. > > 1. How do I show that $A$ is path connected? > 2. How do I show that $A$ is NOT locally path connected? > > > What I thought: 1. So we need a continous map $f:[0,1]\rightarrow X$ from $(x\_1,y\_1)$ to $(x\_2,y\_2)$. I was thinking $$f(t)=t(x\_2,y\_2)+(1-t)(x\_1,y\_1).$$ But how can I show that this is in $X$ for all $t\in[0,1]$? 2. I need to find a $(x,y)\in X$ that does not have a path connected neighborhood. Which one could this be?
2017/05/07
[ "https://math.stackexchange.com/questions/2269672", "https://math.stackexchange.com", "https://math.stackexchange.com/users/427455/" ]
Use [this inequality](https://math.stackexchange.com/questions/184029/inequality-frac116abcd3-geq-abcbcdcdadab?rq=1): $\frac{1}{16}(a+b+c+d)^3 \geq abc+bcd+cda+dab$ equivalent $\frac{1}{4}(a+b+c+d) \geq \sqrt[3]{\frac{abc+abd+acd+bcd}{4}}$ Now just prove$\sqrt{\frac{a^2+b^2+c^2+d^2}{4}}\geq \frac{1}{4}(a+b+c+d)$ equivalent $4(a^2+b^2+c^2+d^2)\geq (a+b+c+d)^2$ equivalent $3(a^2+b^2+c^2+d^2)\geq 2(ab+ac+ad+ bc + bd + cd)$ equivalent $(a-b)^2 + (a-c)^2 + (a-d)^2 + (b-c)^2 + (b-d)^2 + (c-d)^2 \ge 0$
Since $$\frac{a^2+b^2+c^2+d^2}{4}\geq\frac{ab+ac+bc+ad+bd+cd}{6}$$ it's just $$(a-b)^2+(a-c)^2+(a-d)^2+(b-c)^2+(b-d)^2+(c-d)^2\geq0,$$ it's enough to prove that $$\sqrt{\frac{ab+ac+bc+ad+bd+cd}{6}}\geq\sqrt[3]{\frac{abc+abd+acd+bcd}{4}},$$ which I proved here: [How to prove this inequality $\sqrt{\frac{ab+bc+cd+da+ac+bd}{6}}\geq \sqrt[3]{{\frac{abc+bcd+cda+dab}{4}}}$](https://math.stackexchange.com/questions/197955)
18,092,354
Is there a way to split a string without splitting escaped character? For example, I have a string and want to split by ':' and not by '\:' ``` http\://www.example.url:ftp\://www.example.url ``` The result should be the following: ``` ['http\://www.example.url' , 'ftp\://www.example.url'] ```
2013/08/06
[ "https://Stackoverflow.com/questions/18092354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1200615/" ]
There is a much easier way using a regex with a *negative lookbehind assertion*: ``` re.split(r'(?<!\\):', str) ```
As Ignacio says, **yes**, but not trivially in one go. The issue is that you need lookback to determine if you're at an escaped delimiter or not, and the basic `string.split` doesn't provide that functionality. If this isn't inside a tight loop so performance isn't a significant issue, you can do it by first splitting on the escaped delimiters, then performing the split, and then merging. Ugly demo code follows: ``` # Bear in mind this is not rigorously tested! def escaped_split(s, delim): # split by escaped, then by not-escaped escaped_delim = '\\'+delim sections = [p.split(delim) for p in s.split(escaped_delim)] ret = [] prev = None for parts in sections: # for each list of "real" splits if prev is None: if len(parts) > 1: # Add first item, unless it's also the last in its section ret.append(parts[0]) else: # Add the previous last item joined to the first item ret.append(escaped_delim.join([prev, parts[0]])) for part in parts[1:-1]: # Add all the items in the middle ret.append(part) prev = parts[-1] return ret s = r'http\://www.example.url:ftp\://www.example.url' print (escaped_split(s, ':')) # >>> ['http\\://www.example.url', 'ftp\\://www.example.url'] ``` Alternately, it might be easier to follow the logic if you just split the string by hand. ``` def escaped_split(s, delim): ret = [] current = [] itr = iter(s) for ch in itr: if ch == '\\': try: # skip the next character; it has been escaped! current.append('\\') current.append(next(itr)) except StopIteration: pass elif ch == delim: # split! (add current to the list and reset it) ret.append(''.join(current)) current = [] else: current.append(ch) ret.append(''.join(current)) return ret ``` Note that this second version behaves slightly differently when it encounters double-escapes followed by a delimiter: this function allows escaped escape characters, so that `escaped_split(r'a\\:b', ':')` returns `['a\\\\', 'b']`, because the first `\` escapes the second one, leaving the `:` to be interpreted as a real delimiter. So that's something to watch out for.
33,237,731
( F.Y.I. I already searched out many documents in Internet. I'm using storm-0.10.0-beta1. Configuration file of log4j2 in Storm is worker.xml ) Now, I try to use log4j2. I'm searching out way of deleting old logs but I cannot find out. Part of configuration is like below. ```xml <RollingFile name="SERVICE_APPENDER" fileName="${sys:storm.home}/logs/${sys:logfile.name}.service" filePattern="${sys:storm.home}/logs/${sys:logfile.name}.service.%d{yyyyMMdd}"> <PatternLayout> <pattern>${pattern}</pattern> </PatternLayout> <Policies> <TimeBasedTriggeringPolicy interval="1" modulate="true"/> </Policies> <DefaultRolloverStrategy max="9"/> </RollingFile> ``` At first, I expected that log files which are older than 3 days are removed. But, actually, it doesn't. So, I wonder whether there is a way to remove old logs or not. If there is a way which I didn't catch yet, please notify me.
2015/10/20
[ "https://Stackoverflow.com/questions/33237731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2552915/" ]
Since 2.5, Log4j supports a [custom Delete action](http://logging.apache.org/log4j/2.x/manual/appenders.html#CustomDeleteOnRollover) that is executed on every rollover. You can control which files are deleted by any combination of: 1. Name (matching a [glob](https://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String)) or a [regex](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)) 2. [Age](http://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/appender/rolling/action/Duration.html#parseCharSequence) ("delete if 14 days old or older") 3. Count ("keep only the most recent 3") 4. Size ("keep only the most recent files up to 500MB") Users who need even more fine-grained control over which files to delete can specify a script condition using any supported JSR-223 scripting language. Please check out the [documentation](http://logging.apache.org/log4j/2.x/manual/appenders.html#CustomDeleteOnRollover), it has three full examples that may be useful. For your question, this snippet should work: ``` <RollingFile name="rollingFile" fileName="/path/app.log" filePattern="/path/app.%d{yyyy-MM-dd}.log" ignoreExceptions="false"> . . . <DefaultRolloverStrategy> <!-- * only files in the log folder, no sub folders * only rolled over log files (name match) * only files that are 4 days old or older --> <Delete basePath="${sys:storm.home}/logs/" maxDepth="1"> <IfFileName glob="*.service.????????" /> <IfLastModified age="4d" /> </Delete> </DefaultRolloverStrategy> . . . <RollingFile> ``` Finally, be careful! There is no way to recover files deleted this way. :-)
You can find more background information in this JIRA entry for log4j: <https://issues.apache.org/jira/browse/LOG4J2-524> It seems to be the case that auto deleting old log files does not work when you only use a `TimeBasedTriggeringPolicy`