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
18,215,486
I am executing a python script on one server and needing to read the contents of the passwd file from a remote machine. Does anyone know of a way to do this? Normally I would do: ``` import pwd pwlist = pwd.getpwall() #perform operations ``` This only works for the current system of course, and I'm needing a way to access another machine (like you would via ssh). Any help is appreciated.
2013/08/13
[ "https://Stackoverflow.com/questions/18215486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2336976/" ]
I had the same problem, solved it by using: ``` modal:true, ``` instead of: ``` closeOnContentClick: false, ```
I solved the problem removing HTML and BODY tags in result.php.
7,569,354
I'm having two property file called sample.properties and sample1.properties in src folder at same level. It is having some information like, ``` A1 = please call {sample1:name} ``` Here, sample1 -> property file name name -> key defined in sample1 like [name = abc] I want to call sample1 property file , get value of name from that file and store it into the A1 key in sample.properties. Is there any way to include and fetch value from other property file? Thanks in Advance. Regards, Mayur Patel
2011/09/27
[ "https://Stackoverflow.com/questions/7569354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533326/" ]
Yes. The `<!doctype>` is used as rendering mode switch. This is notable especially in Internet Explorer, because this browser maintains (almost) full backwards compatibility in quirks mode, so there's no `getElementsByClassName`, Element Traversal, `addEventListener`, Selection API, ES5 support and many many other things. ES5 support also means changes in parsing so you might experience differences in things not related to DOM. Always use `<!doctype html>` at the top of your markup, it's simple and provides best cross-browser compatibility.
Not exactly, but there are some differences in DOM support between standards and quirks mode. (e.g. in standards mode the browser does not brokenly support name as id).
37,319,400
I have this jQuery Code: ``` $('#select-adults-room-1').change( function () { og.removeErrorsOcio(); }); $('#select-kids-room-1').change( function () { og.removeErrorsOcio(); }); ``` What is the best way to do it? I know this looks weird, but not sure how to improve it if it's possible. I'm looking for some like this: ``` $('#select-adults-room-1','#select-kids-room-1').change( function () { og.removeErrorsOcio(); }); ``` Thanks
2016/05/19
[ "https://Stackoverflow.com/questions/37319400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3086998/" ]
You don't need to pass separate strings, place the comma between the selectors in a single string, like this: ``` $('#select-adults-room-1, #select-kids-room-1').change(function() { og.removeErrorsOcio(); }); ``` Also note that you can pass the reference of the function directly to the `change()` method, like this: ``` $('#select-adults-room-1, #select-kids-room-1').change(og.removeErrorsOcio); ```
Tried to give common class to each element as ``` $('.your-element').change( function () { og.removeErrorsOcio(); }); ```
58,653,552
Need to check the string has only digits. `any` is the only letter expects to be True Psuedo Code ``` import re test = '''123,456''' bool(re.search('[\d+]', test)) ``` Out ``` True ``` Below is one more string expects to True ``` test = '''123,456,any''' #any is the only string expects as True ``` Below are some sample strings which expect to be False ``` test = '''abc,def,43''' #only digits accept test = '''43,,''' #two #commas which makes illegal test = '''abc,def,43,$'''#dollar makes illegal ``` Expected out ``` False ```
2019/11/01
[ "https://Stackoverflow.com/questions/58653552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There is a re-authenticate method. You just need to obtain the user's password for calling the method. ``` FirebaseUser user = await FirebaseAuth.instance.currentUser(); AuthResult authResult = await user.reauthenticateWithCredential( EmailAuthProvider.getCredential( email: user.email, password: password, ), ); // Then use the newly re-authenticated user authResult.user ```
When you want to change sensitive informations on Firebase you need to re-authenticate first to your account using your current credentials then you can update it. Currently flutter has no reAuthenticate method for Firebase so you need to call **signInWithEmailAndPassword** or any other signIn method.
4,547,570
I'm working on a terminal parser for a calculator written in C. I cannot figure out how to concatenate all of the numbers that are in between operators to put them into an array. For example, if the input (command line argument) was "`4+342`", it would ideally be `input[] = {"4", "+", "342"}`. Here's my code so far. I'm including `<stdio.h>`, `<stdlib.h>`, and `<ctype.h>`. ``` typedef char * string; int main(int argc, char *argv[]) { string inputS = argv[1]; string input[10]; string temp; printf("%s\n", inputS); int i; int len = strlen(inputS); printf("parsed:\n"); for(i = 0; i < len; inputS++, i++) { if(isdigit(*inputS)) { printf("%c",*inputS); } else { printf("\n%c\n",*inputS); } } printf("\n"); return 0; } ``` If it is run with `./calc 4+5-546`, it will output: ``` 4 + 5 - 546 ``` So what's the easiest way to get each line of this into its own array slot?
2010/12/28
[ "https://Stackoverflow.com/questions/4547570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/472974/" ]
strsep is a good choice here - grab the token and then decide what you want to do with it... char \*string = "(3+(5+6)/8)" char *token; while ((token = strsep(&string, "(+/*) "))) { // Store token... if it's not a ( or ) or space } Here - token will be processed similar to a Split() in Java/C#. This does mutilate the string while processing it - however, with the correct delimiters - things will be good :)
Sounds like you want to look at the standard `strtok` function.
205,663
In *Avengers: Infinity War* (2018), Ebony Maw says to Doctor Strange, who wears necklace with Time Stone on it: > > In all the time I've served Thanos...I have never failed him. If I > were to reach our rendezvous on Titan...with the Time Stone still > attached to your vaguely irritating **person**... there would be judgment. > > > What "person" is Ebony Maw referring to?
2019/02/19
[ "https://scifi.stackexchange.com/questions/205663", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/111636/" ]
As per [Oxford dictionary](https://en.oxforddictionaries.com/definition/person), "Person" can refer to: > > A human being regarded as an individual. > > > An individual characterized by a preference or liking for a specified thing. > > > An individual's body. > > > Thus, that is **simply his manner of speech** when talking about Doctor Strange.
**Ebony Maw is an orator. The "person" he is referring to is no less than the body of Doctor Strange. His language is unnecessarily ornate describing Doctor Strange as if he was a non-entity.** The translation would be: "If I were to return to Thanos with the Time Stone still on your body, not available for his immediate use, I would be punished. No one wants this."
269,771
Whats a good word to describe someone who isn't easily fooled or isn't gullible?
2015/08/28
[ "https://english.stackexchange.com/questions/269771", "https://english.stackexchange.com", "https://english.stackexchange.com/users/135719/" ]
Perhaps you can use *[shrewd](http://www.collinsdictionary.com/dictionary/english/shrewd)* or *[astute](http://www.collinsdictionary.com/dictionary/english/astute)*. *[Wary](http://www.collinsdictionary.com/dictionary/english/wary?showCookiePolicy=true)* may be also a good fit.
In the US, we call a person who is quick to "see through" others, ***"street-smart"***. While the expression can be used in other ways, it is often a way to describe someone who is not easily deceived.
26,404,308
How to compare only Date without Time in DateTime types in C#.One of the date will be nullable.How can i do that??
2014/10/16
[ "https://Stackoverflow.com/questions/26404308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1559854/" ]
You can use the `Date` property of `DateTime` object ``` Datetime x; Datetime? y; if (y != null && y.HasValue && x.Date == y.Value.Date) { //DoSomething } ```
You could create a method like the one below, following the similar return values as the .net framework comparisons, giving -1 when the left side is smallest, 0 for equal dates, and +1 for right side smallest: ``` private static int Compare(DateTime? firstDate, DateTime? secondDate) { if(!firstDate.HasValue && !secondDate.HasValue) return 0; if (!firstDate.HasValue) return -1; if (!secondDate.HasValue) return 1; else return DateTime.Compare(firstDate.Value.Date, secondDate.Value.Date); } ``` Of Course a nicer implementation would be to create an extension method for this.
490,608
> > Life is not black and white. There seldom is a definitive right or wrong. We need to learn to **live in the gray**. We need to consider and take aspects from each side in order to make practical life choices. > > > What's another expression or idiom for telling someone to **"live in the gray"**? Preferably one that is also only a few words long.
2019/03/20
[ "https://english.stackexchange.com/questions/490608", "https://english.stackexchange.com", "https://english.stackexchange.com/users/340903/" ]
When people are said to be looking at things in only *black and white* terms, they are also said to be *inflexible*. Therefore, to *live in the grey* is **be flexible**, to **see things from both sides**, and to **have an open mind**. If trying to tell somebody to look at something from somebody else's perspective in a specific situation, a common expression is to [**put yourself in their shoes**](https://idioms.thefreedictionary.com/put+yourself+in+their+shoes): > > [The Free Dictionary] > > > To imagine oneself in the situation or circumstances of another person, so as to understand or empathize with their perspective, opinion, or point of view. *Before being quick to judge someone for their actions, you should always try to put yourself in their shoes. Everyone is human, after all. Put yourself in my shoes and then tell me what you would have done, Dan! It isn't as straightforward as you're making it seem!* > > > So, as a general principle, you could say: > > We need to *put ourselves in other people's shoes*. > > >
As in: *Life is not black and white. We need to learn to **adapt to** the in between.* **adapt to** [TFD](https://idioms.thefreedictionary.com/adapt) idiom > > to change in order to be better suited to something: > > >
3,414,266
It is an exercise in Rotman's "introduction to the theory of groups" to show that if $S \trianglelefteq G$ and $T \leq G$ are solvable, then so is $ST$. I know $ST = S \vee T$ in the lattice of subgroups when $S$ is normal, so I'm curious if $S \vee T$ is solvable more generally (assuming, of course, both $S$ and $T$ are). My proof relied somewhat heavily on the normalcy of $S$, so I'm not sure how to adapt my proof to this more general setting, and a few attempts haven't led to anything. Thanks in advance! ^\_^
2019/10/29
[ "https://math.stackexchange.com/questions/3414266", "https://math.stackexchange.com", "https://math.stackexchange.com/users/655547/" ]
No. Indeed, every finite group can be written as a finite join of solvable subgroups, namely its cyclic subgroups. If a join of two solvable subgroups was always solvable, then by iterating we would conclude that every finite group was solvable. So, every finite non-solvable group must have a counterexample among its subgroups. For a very explicit counterexample, $S\_n$ is generated by the $n$-cycle $(1\ 2\ \dots\ n)$ and the transposition $(1\ 2)$, and so is the join of the cyclic subgroups they generate, but is not solvable for $n>4$.
If you don't assume that $S\trianglelefteq G$, then the product $ST$ need not be solvable. As the product is a subgroup of the join, and solvable groups are closed under taking subgroups, the join need not be solvable either. Below is a simple example. We will take $G=S\_5$ the symmetric group on the set $\{1,2,3,4,5\}$, which is more or less the simplest example of a non-solvable group. Then we take $S=\langle (1 2), (1 2 3)\rangle$ and $T=\langle (4 5), (3 4 5)\rangle$. As each of $S,T$ is contained in a copy of $S\_3$ living inside $S\_5$ and is generated by a transposition and a $3$-cycle, both are isomorphic to $S\_3$, which is solvable. Now $ST$ contains $(1 2 3)(3 4 5)$ which you can easily check is a $5$-cycle. $ST$ also contains a transposition, so $ST=G$, which is not solvable.
63,585,661
So Im trying to use the Google GeolocationAPI. It sends the quest successfully and also authenticates successfully with my api key but it returns me this ``` { "error": { "code": 404, "message": "Requested entity was not found.", "errors": [ { "message": "Requested entity was not found.", "domain": "global", "reason": "notFound" } ], "status": "NOT_FOUND" } } ``` The url Im requesting to is <https://www.googleapis.com/geolocation/v1/geolocate?key=MY_KEY> with post as described in the documentation. Thanks in advance
2020/08/25
[ "https://Stackoverflow.com/questions/63585661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277653/" ]
I recommend you to check out the [documentation](https://developers.google.com/maps/documentation/geolocation/overview): As you can read: > > Before you start developing with the Geolocation API, review the > authentication requirements (you need an API key) and the API usage > and billing information (you need to enable billing on your project). > > > I was getting the exact same error until my billing information was validated. How I realized it, was using the geocoding API, which does return a better error.
You need to create and associate a billing account to your project. It will work immediately.
20,147,671
i got into a problem. I have 3 tables, I join them but cant get the right answer, if anyone could help me, I would appreciate it. So what i want is, for Answer to show me unused Materials. Tables: ![enter image description here](https://i.stack.imgur.com/ot4e8.png) With a lot of help I got all the unused materials with this: ``` SELECT DISTINCT(Materials.Material_Name) AS Unused_materials FROM Materials LEFT JOIN Table2 ON Table2.Material_Number = Materials.Material_Number LEFT JOIN Table1 ON Table1.Procedure_Name = Table2.Procedure_Name WHERE Table1.Procedure_Name IS NULL ``` **UPDATED:** If I may ask one more question in the same post. Maybe anyone would know how to get the above information, just with the Wanted Day. Like: Unused materials in 2012-11-20?
2013/11/22
[ "https://Stackoverflow.com/questions/20147671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2965118/" ]
Edit: Disregard this solution. I'm leaving it up for the sake of having the complete discussion. Or woukd it be customary to remove this answer? After comment-discussion under David Fleeman's solution, I did some profiling and the short answer is: go with David Fleemans solution, using NOT IN. It will be faster than the left join solution. Do use David Fleemans solution Original post The reason you will never get anything but an empty resultset using that query is that you are selecting material\_name and also specify that material\_name should be null… All used materials will have entries in Table2. All unused materials will lack such entries. Therefor, select from Materials, left join with Table2 and add condition that procedure name is null. ``` SELECT Material_Name FROM Materials M LEFT JOIN Table2 T ON M.Material_Number = T.Material_Number WHERE Procedure_Name IS NULL ```
Johan above almost has it (unused materials will still exist in table\_2, since Table2 is just a lookup of Procedure\_Name to Material\_Number (which if it's a 1:1 relationship seems like a silly addition). Still need to join against Table1 to get the null values. so ``` SELECT * FROM Materials c LEFT JOIN Table2 b ON b.Material_Number = c.Material_Number LEFT JOIN Table1 a ON a.Procedure_Name = b.Procedure_Name WHERE a.Procedure_Name is null; ``` All commands for repeat comparison: ``` create table Table1 (Procedure_Name char, date date); create table Table2 (Procedure_Name char, Material_Number int); create table Materials (Material_Name varchar(12), Material_Number int); insert into Table1 values ('A', '2012-11-22'); insert into Table1 values ('B', '2012-11-21'); insert into Table1 values ('C', '2012-11-20'); insert into Table2 values ('A', '101'); insert into Table2 values ('B', '102'); insert into Table2 values ('C', '103'); insert into Table2 values ('D', '104'); insert into Table2 values ('E', '105'); insert into Materials values ('Iron', 101); insert into Materials values ('Steel', 102); insert into Materials values ('Wood', 103); insert into Materials values ('Glass', 104); insert into Materials values ('Sand', 105); -- johan query SELECT Material_Name FROM Materials M LEFT JOIN Table2 T ON M.Material_Number = T.Material_Number WHERE Procedure_Name IS NULL; -- my query select Material_Name from Materials c left join Table2 b on b.Material_Number = c.Material_Number left join Table1 a on a.Procedure_Name = b.Procedure_name where a.Procedure_Name is null; ```
3,719,015
Why does the following line ``` Object[] objects = new Object[10000000]; ``` result in a lot of memory (~40M) being used by the JVM? Is there any way to know the internal workings of the VM when allocating arrays?
2010/09/15
[ "https://Stackoverflow.com/questions/3719015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116388/" ]
It creates an array with 10.000.000 reference pointers, all initialized with `null`. What did you expect, saying this is "a lot"? --- **Further reading** * [Size of object references in Java](https://stackoverflow.com/questions/981073/how-big-is-an-object-reference-in-java-and-precisely-what-information-does-it-con)
I may be behind the times but I understood from the book Practical Java that Vectors are more efficient and faster than Arrays. Is it possible to use a Vector instead of an array?
12,917
My seven year old daughter plays on a soccer team. She loves soccer. She is not the best player and not the worst. She is however, the team crybaby. She finds some reason to cry every single game and practice. She fakes injuries, gets frustrated and cries in front of everyone when she doesn't score a goal, and is the first one to say, "We're never going to beat the other team." Personally, I always HATED that kid on my team, and now I'm that kid's mom. She does love to play and has fun when things are going her way. She's getting too old for this babyish behavior, and quite frankly, it is embarrassing when 10 other girls and their parents are staring at us because she's being a baby about missing a shot, or because she's too hot. I mean, who cries because they are too hot? No one else's kid does. I am not a negative parent. I tell always encourage her and always tell her when I'm proud of her. I don't say anything to her when she is acting like a baby. I just tell her very calmly to take a deep breath, take a look at the situation, and go from there...sometimes this works and she catches herself, most of the time she doesn't. In every other aspect of her life, she is pleasant, a team player, and a leader. Just not on the soccer field....any ideas on how to stop her from being the team crybaby and to stop being the negative Nellie on the field?
2014/06/07
[ "https://parenting.stackexchange.com/questions/12917", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/7976/" ]
> > "We're never going to beat the other team." > > > Never? Absolutely never? Are you sure? Here I'd question the language she uses. The language we use out loud is often the same language we use in our thoughts. And the language we use in our thoughts tends to shape our thoughts and emotions. For advice on how to question/reframe such thoughts, I'd recommend you listen to some of the Audiobooks/videos made by Byron Katie. You should be able to find some samples of Byron Katie's work [on Youtube](http://www.thework.com/watch.php). If you want something more technical, but still interesting, you may want to read books on Cognitive Behaviorial Therapy. Cognitive Behavioral Therapy (CBT) utilizes a very similar questioning strategy to Byron Katie's method. As to the crying, I believe that's an emotional response that's also an outgrowth of our thoughts and beliefs. So the next time you're alone with her after such a game, it might be useful to ask her what she's thinking when she starts crying. But also, I wouldn't make too big deal out of it, because the added pressure from you might inadvertently stress her out even more the next time it happens.
My daughter (also 7) acts the same way with her marching band. She plays the trumpet. I know she's not being bullied (in fact, most of them are very nice) and her coaches are wonderful. I asked her many times if she wants to quit but refuses to do so. She's even excited to go. That's why it was so confusing for me why she keeps insisting on sticking with it if it makes her unhappy. She has a hard time articulating her feelings so took me a while to figure out what was wrong. It turns out she was really insecure about the fact that she's not as good as some of the kids in class. I explained to her that everyone starts out as a beginner. And if she wanted to be as good as her bandmates, all she needed to do was practice more and ask her coach and friends for help if she needs it. It seemed to work. She has stopped crying in class and has started practicing more. And when I shared with her coach about her insecurity, he paired her up with an older kid who also plays the trumpet to be her band "buddy". They practice together and my daughter won't stop talking about how her "big sister" is helping her get better at the trumpet.
10,448,047
I want to include a .c file in another. Is it possible right? It works well if I include a header file in a .c file, but doesn't work as well if I include a .c file in another .c file. I am using Visual Studio and I get the following error: ``` main.obj : error LNK2005: _sayHello already defined in sayHello.obj /* main.c */ #include "sayHello.c" int main() { return 0; } /* sayHello.c */ #include <stdio.h> void sayHello() { printf("Hello World"); } ``` I don't know what this error could mean. Time to ask more advanced C coders. :)
2012/05/04
[ "https://Stackoverflow.com/questions/10448047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/898390/" ]
This is a linker error. After compiling all your .c files to .obj files (done by the compiler) the linker "merges" them together to make your dll/exe. The linker has found that two objects declare the same function (which is obviously not allowed). In this case you would want the linker to only process main.obj and not sayhello.obj as well (as its code is already included in main.obj). This is because in main.obj you will ALSO have the sayHello() function due to the include!
The problem seems to be that `sayHello.c` got compiled into an object file called `sayHello.obj`, and `main.c` (also including all the source text from `sayHello.c`), got compiled into `main.obj`, and so both `.obj` files got a copy of all the external symbols (like non-`static` function definitions) from `sayHello.c`. Then all the object files were supposed to get "linked" together to produce the final executable program file, but the linking breaks when any external symbols appear more than once. If you find yourself in this situation, you need to stop linking `sayHello.obj` to `main.obj` (and then you might not want to compile `sayHello.c` by itself into its own object file at all). If you manually control every step of the build (like you might when using the CLI of your compiler), this is often just a matter of excluding that object file from the invocation of the linker or compiler. Since you are using Visual Studio, it's probably making a bunch of assumptions for you, like "every .c file should be compiled into its own object file, and all those object files should be linked together", and you have to find a way to circumvent or disable this assumption for `sayHello.c`. One easy and somewhat idiomatic solution might be to rename `sayHello.c` into `sayHello.c.inc`.
57,961,964
When setting the scale of a view programmatically, setScaleX() and setScaleY() do not accept decimal values like **"0.1"** and displays the error code **"setScaleX(float) in View cannot be applied to (double)"** when such a value is specified. setScaleX() and setScaleY() only seems to accept integers like **1, -5 or 10**. How do you set this scale value to a decimal amount?
2019/09/16
[ "https://Stackoverflow.com/questions/57961964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12019381/" ]
The best way is to use XSLT-1.0 to transform your input XML to your desired output XML. This can be achieved by using [`XslCompiledTransform`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xsl.xslcompiledtransform?view=netframework-4.8). The following stylesheet (`transform.xslt`) does the job: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- Identity template --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*" /> </xsl:copy> </xsl:template> <xsl:template match="generated-items"> <xsl:copy-of select="*" /> </xsl:template> </xsl:stylesheet> ``` The necessary C# code is identical to the example in the link: ``` // Load the style sheet. XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load("transform.xslt"); // Execute the transform and output the results to a file. xslt.Transform("input.xml", "output.xml"); ``` Then `output.xml` contains the data you want.
Using Xml Linq : ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication1 { class Program { const string FILENAME = @"c:\temp\test.xml"; static void Main(string[] args) { XDocument doc = XDocument.Load(FILENAME); List<XElement> generated_items = doc.Descendants("generated-items").ToList(); foreach (XElement generated_item in generated_items) { generated_item.AddAfterSelf(generated_item.Descendants()); generated_item.Remove(); } } } } ```
4,733,273
I'm working on a (simple) caching solution of sorts, where a service can request a Cache object from a Map of caches. A Cache object works essentially just like a Map, too, with a key and a value and methods to access and store objects. I came up with the following solution, but as you can see, it contains a cast (because get() can't know what the types of the nested object are supposed to be). ``` private final Map<String, Cache<?, ?>> caches = new HashMap<String, Cache<?, ?>>(); public <K, V> Cache<K, V> getOrCreateCache(String identifier) { if (caches.containsKey(identifier)) { return (Cache<K, V>) caches.get(identifier); } else { Cache<K, V> cache = new CacheImpl<K, V>(); caches.put(identifier, cache); return cache; } } private void test() { Cache<String, String> strCache = getOrCreateCache("string cache"); strCache.set("key", "value"); } ``` Now, my questions: * Is this a 'safe' approach, as long as classcastexceptions are handled properly? (probably going to catch those and pack them into a custom exception class) * Is there a 'safe' alternative? One with generics, if at all possible, because I like them and dislike casts. * (not directly related) Is this threadsafe? I assume not, but then, I'm no threading expert. Is it enough to just make the whole method synchronized, or would that (with half a dozen clients) cause too much overhead / locking? Is there a neat solution for that? Edit: Woo, lots of answers, thanks! Editing here to describe an oddity I found while actually testing this: ``` Cache<String, String> someCache = service.getOrCreateCache(cacheIdentifier); someCache.set("asdf", "sdfa"); Cache<String, Integer> someCacheRetrievedAgain = service.getOrCreateCache(cacheIdentifier); System.out.println(someCacheRetrievedAgain.get("asdf")); // prints "sdfa". No errors whatsoever. Odd. ```
2011/01/19
[ "https://Stackoverflow.com/questions/4733273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204840/" ]
On the thread safety question, no it's not thread safe. You should look at [ConcurrentHashMap](http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html) or Google Guava's [MapMaker](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html)
You can just make the whole method synchornized to make it thread safe. Provided its not called often it will be efficient enough. If you want to make the code safer I suggest you try the following add a runtime check for the types. ``` public <K, V> Cache<K, V> getOrCreateCache(String identifier, Class<K> kClass, Class<V> vClass) { Cache<K, V> cache = (Cache<K, V>) caches.get(identifier); if(cache == null) caches.put(identifier, cache = new CacheImpl<K, V>(kClass, vClass)); assert cache.kClass() == kClass; assert cache.vClass() == vClass; return cache; } ```
163,785
Is there a way I can monitor connections that are attempted/made to my linux server? I'm running Debian Lenny.
2010/07/24
[ "https://serverfault.com/questions/163785", "https://serverfault.com", "https://serverfault.com/users/49243/" ]
I find the **iptstate** tool really useful to monitor iptables entries in real time. On Fedora it is a *yum install iptstate* so I imagine in Debian you can install via *apt-get*. As already mentioned, for very detailed analysis, *tcpdump* is awesome (or alternatively *Wireshark*). Not sure about Debian, but on Fedora you need to adjust the settings in **/etc/rsyslog.conf** to configure verbose firewall logs in syslog or a custom log file. For regular reports, Logwatch is also worth checking out.
You could try scheduling command `ss -s` to check number of connections made on your server at some convenient interval using [cron tab](http://v1.corenominal.org/howto-setup-a-crontab-file/). Or there is a free service, [SeaLion](https://sealion.com) which you can use to schedule commands and see output online.
77,180
> > And he shall pass through the sea with affliction, and shall smite the waves in the sea, and all the deeps of the river shall dry up: and the pride of Assyria shall be brought down, and the sceptre of Egypt shall depart away. (Zechariah 10:11) > > > What was the pride of Assyria during the time of Zechariah because he was prophesying towards the end of the 6th century BC and by this time of Zechariah, Assyria was already conquered by the Babylonians and taken over by the Persians? What historical event fulfills the pride of Assyria being brought down during or after the time of Zechariah?
2022/07/02
[ "https://hermeneutics.stackexchange.com/questions/77180", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/40416/" ]
There is a similar "problem" in Ezra 6:22 where "Assyria" is used as the name for the nation that now controls it, ie, Persia. See appendix below. Thus, the simplest way to understand the "pride of Assyria" in Zech 10:11 is to read "pride of Persia" because Persia now controlled and occupied the area once held by Assyria. There is a similar explanation for "king of Babylon" found in Ezra 5:13. **APPENDIX - Comment on Ezra 6:22** In Ezra 6:22 we read: > > For seven days they kept the Feast of Unleavened Bread with joy, > because the LORD had made them joyful and turned the heart of the **king > of Assyria** toward them to strengthen their hands in the work on the > house of the God of Israel. > > > Note that no such literal king of Assyria existed at the time of Ezra, it had been conquered about 200 years earlier. Persia now occupied and controlled the area that Assyria once controlled. Note the comments of Benson: > > **And turned the heart of the king of Assyria** — Of the king of Persia, called the king of Assyria, as now reigning over all the > kingdoms which were formerly under the power of the Assyrians; > > > The Cambridge Commentary is similar: > > **of the king of Assyria** This is a strange expression to be used of a Persian king. For by the context it naturally refers to Darius. > > > (1) It has been said that Darius is so called because the Persian > kings were the successors to the great Assyrian empire. > > > (2) It has been suggested that all Western Asia might be termed > Assyria. > > > (3) It has been supposed that Darius is not personally referred to, > but that the power of Western Asia is symbolized by the name of > Assyria, Israel’s traditional foe. (But to the Jew, after the > Captivity, the symbolical hostile power is Babylon.) > > > Of these views the first is the most probable. See note on Ezra 5:13 > (Cyrus king of Babylon). > > >
When reading the whole passage of Zechariah 10; vv1-3a - The Lord reminded the remnants the days their ancestors' wrong doings that led to the destruction of Jerusalem. vv3b - However the Lord still care of His people vv4 - Implying the coming Messiah vv5 - 10 - Implying the salvation from the Lord eventually reinstated His people and reunited the Israelites. vv11 - now then why it mentioned Assyria's pride and Egypt's scepter? In the prophetic books, it has been frequently seen the prophets warned and condemned the evil deeds of the Israelites followed at the end of the book, a promise of salvation, which give a picture of prosperous and wonderful future of them. Did this promise given unconditional? The temple worship was the core of the covenant between God and the Israelites. It was a main cause that their ancestors worship idols led to the destruction of Jerusalem and the exile of their ancestors. Now the punishment was over, and God will forget their sin. The descendants of them were brought back to Jerusalem, reinstated their covenant by rebuilding the temple. However, since its foundation was laid at 536BC by Zerubbabel, the work had been abandoned for 16 years. God sent Haggai and Zechariah to encourage the Israelites completed the work. Finally the 2nd temple completed in 516BC, exactly 70 years after the 1st temple destruction. The punishment to the kingdoms who oppressed the Israelites had been prophesized by the earlier prophets. The remnants should see these words realized, that only their God is real, all idols were deceitful (vv2). They should "Ask the Lord" for well being (vv1) by putting God as their centre of living, rebuild of the temple and resumed their worship of the Lord. > > Assyria’s pride will be brought down > and Egypt’s scepter will pass away. (Zechariah 10:11b NIV) > > > Who brought down Assyria's pride? Who took away Egypt's scepter? The remnants should know only God was their highest, their shield and only protection.
13,845,020
Using only Javascript, how can I iterate through every span id = "expiredDate"? I would think that this would be quite easy with a for each loop, but it doesn't appear to exist in javascript. My below code only works for the first element. ``` <script type="text/javascript"> window.onload = function() { var definedDate = window.document.getElementById('expiredDate').innerHTML.split("-"); var expiredDate = new Date(definedDate[0], definedDate[1] - 1, definedDate[2]); var graceDate = new Date(definedDate[0], definedDate[1] - 1, definedDate[2] - 30); var currentDate = new Date(); if(currentDate > expiredDate) {document.getElementById('expiredDate').style.color = '#cc6666';} else if(currentDate < expiredDate && currentDate > graceDate) {document.getElementById('expiredDate').style.color = '#f0c674';} else {document.getElementById('expiredDate').style.color = '#b5bd68';} } </script> <span id="expiredDate">2013-01-01</span> <span id="expiredDate">2014-01-01</span> <span id="expiredDate">2015-01-01</span> ```
2012/12/12
[ "https://Stackoverflow.com/questions/13845020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326111/" ]
Switch your IDs to classes and try the following ``` var spans = document.getElementsByTagName('span'); var l = spans.length; for (var i=0;i<l;i++) { var spanClass = spans[i].getAttribute("class"); if ( spanClass === "expiredDate" ) { /*do stuff to current spans[i] here*/ } } ```
Two methods not said yet; for both you should be using the form ``` <span class="expiredDate">...</span> ``` 1. [`.querySelectorAll`](https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll) method: ``` var result = document.querySelectorAll('span.expiredDate'); // NodeList ``` 2. [`.getElementsByClassName`](https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByClassName) combined with [`Array.prototype.filter`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter) ``` var result = Array.prototype.filter.call( document.getElementsByClassName('expiredDate'), function (elm) { return elm.tagName === 'SPAN'; } ); // Array ``` --- Method 1 is faster, but because you're already iterating through them with method 2 you could save yourself a loop later by putting your desired actions inside the filter's function, therefore making it faster overall.
45,296,575
I want two divs next to each other . one contains a button the other some text. i would like the text before the button with som margin. But the keep ending up on the wrong side. My code: ```css .helpButton { display: inline-block; float: right; } .helpText { margin-right: 5em; float: right; display: inline-block; } .help-block { display: inline-block; overflow: auto; float: right; } ``` ```html <div class="help-block"> <div class="helpText">@Resource.FooterHelp</div> <button type="button" data-toggle="modal" data-target="#helpModal" class="btn btn-default helpButton">@Resource.FooterHelpLink</button> </div> ``` I know there are similar questions like this here on this forum, but cant get theme to work for me > > Thank you all for all your suggestions! > > >
2017/07/25
[ "https://Stackoverflow.com/questions/45296575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6804444/" ]
Dont' use floats (right floats reverses therorder of the elements). As you are using `display: inline-block`, a simple tex-align will work ```css .help-block { display: inline-block; text-align: right } .helpButton { display: inline-block; } .helpText { display: inline-block; } ``` ```html <div class="help-block"> <div class="helpText">Some text</div> <button type="button" data-toggle="modal" data-target="#helpModal" class="btn btn-default helpButton">Buttom</button> </div> ```
I would use a flexbox and avoid floats. This way, all elements will follow the document flow (and you need less CSS code). ```css .helpText { margin-right: 5em; } .help-block { display: flex; align-items: center; justify-content: flex-end; } ``` ```html <div class="help-block"> <div class="helpText">@Resource.FooterHelp</div> <button type="button" data-toggle="modal" data-target="#helpModal" class="btn btn-default helpButton">@Resource.FooterHelpLink</button> </div> ```
22,560,130
I have seen many post with a similar issue. My R.java file has been generated but it's missing the elements below 1. Project clean does nothing 2. There's no errors in my res folder It cannot be resolved for the areas e.g. menu, action.edit, action.delete, action.new Example 1: ``` @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } } ``` Example 2: ``` public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_edit: { if (mEditMode) { sendPutRequest(new PutResponseListener()); } setEditMode(!mEditMode); getActivity().invalidateOptionsMenu(); return false; } case R.id.action_delete: { sendDeleteRequest(new DeleteResponseListener()); return false; } } return super.onOptionsItemSelected(item); } ```
2014/03/21
[ "https://Stackoverflow.com/questions/22560130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765446/" ]
If "Control Panel" -> "Regional and Language Options" -> "System Locale" is set correctly but you still suffer from this problem some times then note that **while you're copying** your keyboard layout must be switched to the non-English language. This is applicable to all non-unicode-aware applications not only VBA. **Credit** goes to @parakmiakos
I had a similar problem with Cyrillic characters. Part of the problem is solved when set the System locale correctly. However, The VBA editor still does not recognize cyrillic characters when it has to interpret them from inside itself. For example it can not display characters from the command: ``` Msgbox "Здравей" ``` but if the sheet name is in cyrillic characters it does it well: ``` Msgbox Activesheet.Name ``` Finally, it turned out that these kind of problems were solved when I changed to 32 bits version of MS Office.
20,418
At the end of *Pirates of the Caribbean: Dead Man's Chest*, we see Barbossa reincarnated. Is there any in-movie explanations of how that was possible, since he was shot cleanly through the chest at the end of the first movie? If Tia Dalma was responsible, does that mean she had the power to make anyone come back from dead?
2012/07/12
[ "https://scifi.stackexchange.com/questions/20418", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/1570/" ]
In-movie, there is no specific explanation as to just *how* Barbossa was resurrected. Similarly, as far as I can find, there is no explanation in any of the side-story books that were written. When we first meet her, Tia Dalma is presented as a Voodoo priestess having performed [numerous acts related to the supernatural](http://pirates.wikia.com/wiki/Tia_Dalma) - specifically mentioning providing Jack with his compass. > > In truth, Tia Dalma is really the goddess Calypso bound in a human body, so many of her "Voodoo priestess" powers may actually be powers as a goddess. > > > Whether or not she can "resurrect anybody" is unclear. For instance, Barbossa had been killed, while Jack had been banished to Davy Jones' Locker. Barbossa's soul was not judged by Jones as he had been killed on land. Even with her available powers, she could not retrieve Jack without help. The below quote implies that if they are actually dead and fully crossed over, she would be able to resurrect them. > > **Pintel**: No one said anything about cold. > **Ragetti**: I'm sure there must be a good reason for our suffering. > **Pintel**: Why don't that Obeah woman bring Jack back the same way she brought back Barbossa? > **Tia Dalma**: Because Barbossa was only dead. Jack Sparrow is taken body and soul to a place not of death, but of punishment, the worst fate a person can bring upon himself stretching on forever. That's what awaits at Davy Jones' locker. > **Ragetti**: Well, I knew there was a good reason. > > >
At the end of Pirates of the Carribean: The Curse of the Black Pearl, there is an after-credits scene that shows Barbossa's pet monkey (Jack) take one of the coins from the chest, which then curses the monkey again. Now, perhaps the monkey *gave* the dead or dying Barbossa the coin for him to be cursed again, therefore being able to survive or be resurrected.
21,177,423
I have two images: -loading.gif (which is the loading animation) -scenery.jpeg (which is i what i want to display after the loading process); because scenery.jpeg is a small file, using load() function will only skip the loading.gif so when I click the button how do i display the loading.gif for 3 seconds before it loads scenery.jpeg? advance thanks! :D so i have this html file: ``` <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("#loading , #picture").hide(); $("#button1").click(function(){ /* the loading.gif shows then after 3 seconds scenery.jpeg will use fadeIn() */ }); }); </script> </head> <body> <button id="button1">Click Me!</button> <img id="loading" src="loading.gif"/>> <img id="picture" src="scenery.jpeg"/> </body> </html> ```
2014/01/17
[ "https://Stackoverflow.com/questions/21177423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205046/" ]
You can use [delay()](http://api.jquery.com/delay/) in this case: ``` $("#button1").click(function(){ $("#loading").fadeIn().delay(3000).fadeOut('slow', function() { $(this).next().fadeIn() }); }); ``` [Demo](http://jsfiddle.net/5E2nK/)
One of the ways would be: 1. Replace image `src` with throbber `src`. 2. Create new `Image` object, set it's `src` to one of image. 3. Add `load` event listener on `Image`, and set img src inside `setTimeout` with desired value. The function the does that: ``` function delayLoad (img, throbber, delay) { var src = img.src, hidden = new Image(); img.src = throbber; hidden.addEventListener("load", function (e) { setTimeout(function () { img.src = src; }, delay); }); hidden.src = src; } ``` Use it like this: ``` delayLoad(document.querySelector("img"), "http://www.mfshop.ru/images/throbber.gif", 3000); ``` [JSBin](http://jsbin.com/ENUhUMip/2/edit).
891
There is [an article about this word in Urban Dictionary](http://www.urbandictionary.com/define.php?term=brogrammer). But what is the Russian for this word? "говнокодер" and "быдлокодер" are not suitable here (it means good developer, not bad). An example of using: *I don't write unit tests, interfaces, use IOC or heavy ORMs. Yet I'm not a brogrammer.*
2012/08/27
[ "https://russian.stackexchange.com/questions/891", "https://russian.stackexchange.com", "https://russian.stackexchange.com/users/329/" ]
Есть выражение "погромист", но оно тоже скорее насмешливое, чем серьёзное. Русского аналога "brogrammist" боюсь что нет.
Consider программист-раздолбай
46,450,246
Need to make screenshot of some games. Found this JNA code, but when I try to do screen`s I just get black screen. When I try to do screen of some program, like WordPad ot smth it works well. As well I am bad in JNA, I want ask you about help. Is it possible to accomplish this task ? ``` public class Paint extends JFrame { public BufferedImage capture(HWND hWnd) throws IOException { String gettime = Gettime.screentime(); HDC hdcWindow = User32.INSTANCE.GetDC(hWnd); HDC hdcMemDC = GDI32.INSTANCE.CreateCompatibleDC(hdcWindow); RECT bounds = new RECT(); User32Extra.INSTANCE.GetClientRect(hWnd, bounds); int width = bounds.right - bounds.left; int height = bounds.bottom - bounds.top; HBITMAP hBitmap = GDI32.INSTANCE.CreateCompatibleBitmap(hdcWindow, width, height); HANDLE hOld = GDI32.INSTANCE.SelectObject(hdcMemDC, hBitmap); GDI32Extra.INSTANCE.BitBlt(hdcMemDC, 0, 0, width, height, hdcWindow, 0, 0, WinGDIExtra.SRCCOPY); GDI32.INSTANCE.SelectObject(hdcMemDC, hOld); GDI32.INSTANCE.DeleteDC(hdcMemDC); BITMAPINFO bmi = new BITMAPINFO(); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = -height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = WinGDI.BI_RGB; Memory buffer = new Memory(width * height * 4); GDI32.INSTANCE.GetDIBits(hdcWindow, hBitmap, 0, height, buffer, bmi, WinGDI.DIB_RGB_COLORS); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, width, height, buffer.getIntArray(0, width * height), 0, width); GDI32.INSTANCE.DeleteObject(hBitmap); User32.INSTANCE.ReleaseDC(hWnd, hdcWindow); File outputfile = new File("C:\\image" +gettime+ ".jpg"); ImageIO.write(image, "jpg", outputfile); return image; } public static void main(String[] args) throws IOException { new Paint(); } BufferedImage image; public Paint() throws IOException { HWND hWnd = User32.INSTANCE.FindWindow(null, "some game"); this.image = capture(hWnd); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); setExtendedState(MAXIMIZED_BOTH); setVisible(true); } @Override public void paint(Graphics g) { super.paint(g); g.drawImage(image, 20, 40, null); } } ```
2017/09/27
[ "https://Stackoverflow.com/questions/46450246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8199966/" ]
GDI32Util.getScreenshot(HWND hwnd) Method is already provided in jna. but my case is as the same as you.... the game screen is black... nothing...
Using JNA to take a screenshot sounds utterly complicated, besides not being platform-agnostic. Java has built-in functionality to take screenshots using the `Robot` class: ``` import java.awt.Robot; Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage capture = new Robot().createScreenCapture(screenRect); ImageIO.write(capture, "png", new File("./screenshot.png")); ``` By adjusting the `screenRect` you could also just take a screenshot of a portion of the screen.
59,931,063
Here is my code: ``` import styles from 'styles.css'; // other code render() { return <CSSTransition classNames= {{ enter: 'example-enter', enterActive: 'example-enter-active', exit: 'example-leave', exitActive: 'example-leave-active' }} in={true} timeout={300} onEnter = { () => console.log('mounting') } unmountOnExit > <div className={styles['someclass']}>Will animate</div> </CSSTransition> } ``` How I use the styles array for setting classes on the transition group? I have tried setting the classes as `styles['example-enter'], styles['example-leave']` etc. but no luck. Additionally my onEnter handler doesn't work! Note: It is `classNames` for the transition and `className` for CX, so it is not a typo.
2020/01/27
[ "https://Stackoverflow.com/questions/59931063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/744519/" ]
The `lambda m: '19'+m` is wrong because `m` is a `MatchData` object, not a string. You might have tried `m.group()`, but since you also match any non-digit chars on both ends of a number (as whitespace) you might still get wrong results. You may use ``` df['year'] = df['year'].str.strip().str.replace('^\d{2}$', r'19\g<0>') ``` NOTES: * You need to get rid of leading/trailing whitespace with `str.strip()` * You need to match all strings that consist of just 2 digits with `^\d{2}` * The replacement is a concatenation of `19` and the match value (`\g<0>` is the whole match backreference).
IIUC, count strings that has a length of two and prefix it with 19 ``` df.assign(year = np.where(df.year.str.strip().str.len()==2, '19'+df.year.str.strip(), df.year)) month year 0 2 2001 1 5 1989 2 8 1999 ```
1,901,716
Very strange situation here: I'm using L2S to populate a DataGridView. Code follows: ``` private void RefreshUserGrid() { var UserQuery = from userRecord in this.DataContext.tblUsers orderby userRecord.DisplayName select userRecord; UsersGridView.DataSource = UserQuery; //I have also tried //this.UserBindingSource.DataSource = UserQuery; //UsersGridView.Datasource = UserBindingSource; UsersGridView.Columns[0].Visible = false; } ``` Whenever I use L2S to Add/Delete records from the database, the GridView refreshes perfectly well. However, if someone is editing the grid and makes a mistake, I want them to be able to hit a refresh button and have their mistakes erased by reloading from the datasource. For the life of me, I can't get it to work. The code I am currently using on my refresh button is this: ``` private void button1_Click(object sender, EventArgs e) { this.DataContext.Refresh(RefreshMode.OverwriteCurrentValues); RefreshUserGrid(); } ``` But the damn GridView remains unaffected. All that happens is the selected row becomes unselected. I have tried `.Refresh()`, `.Invalidate()`, I've tried changing the DataSource to NULL and back again (all suggestions from similar posts here)....none of it works. The only time the Grid refreshes is if I restart the app. I must be missing something fundamental, but I'm totally stumped and so are my colleagues. Any ideas? Thanks!
2009/12/14
[ "https://Stackoverflow.com/questions/1901716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/219993/" ]
The easiest would be to use a BindingSource. Create an instance of the BindingSource to the class initialize it to the data query then assign the BindingSource to the UsersGridView. The BindingSource will handle the updates etc. There are several events that can be caught for custom management. [This link gives an example of using a BindingSource](http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx) EDIT: My first post assumed Webforms instead of WinForms.
It seems that this is a bug in LINQ to SQL. I understand from the Janus GridEx folks that the cause of the problem is that LINQ presents a static list to the grid that is not refreshed after Refresh is called on the DataContext. A solution is to simply re-instantiate the DataContext.
19,378,987
I've been trying to create a function that splits a string and return a pointer to the first element of the array. It compiles with no error but when i run the program it crashes. Here is my code. Any help on how to fix this. Thanks. ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #define split_count(a) a int count(char *str, char *sub) { int sublen = strlen(sub); int templen = 0; int count = 0; if (sublen > strlen(str)) return 0; int i, j; for (i = 0; i < strlen(str); i++) { if (*(str + i) == *sub) { templen = 1; for (j = 1; j < sublen; j++) { if (*(str + i + j) == *(sub + j)) { templen += 1; } } if (templen == sublen) { count += 1; } templen = 0; } } return count; } char * split(char *str, char *sep, int maxsplit) { if (!count(str, sep)) return NULL; char *arr[split_count(count(str, sep)) + 1]; int i, j; int templen = 0; int stop = 0; int counter = 0; for (i = 0; i < strlen(str); i++) { if (*(str + i) == *sep) { templen = 1; for (j = 1; j < strlen(sep); j++) { if (*(str + i + j) == *(sep + j)) { templen += 1; } if (templen == strlen(sep)) { arr[counter] = (char*)malloc(sizeof(char) * strlen(str)); strcpy(arr[counter], ""); int k; for (k = stop; k < i; k++) { *(arr[counter] + strlen(arr[counter])) = *(str + k); *(arr[counter] + strlen(arr[counter])) = '\0'; } stop = i + strlen(sep); counter++; } } } } return arr[0]; } int main() { char *before = "This is a house isisis is"; printf("%s\n", split(before, "is", 1)); return 0; } ```
2013/10/15
[ "https://Stackoverflow.com/questions/19378987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2461500/" ]
to save few computations: ``` boolean mod3 = x mod 3 == 0 boolean mod5 = x mod 5 == 0 if (mod3 && mod5) return "ab" if (mod3) return "a" if (mod5) return "b" ```
Alternatively: ``` String result = ""; if (x mod 3 == 0) result += "a"; if (x mod 5 == 0) result += "b"; return result; ``` But it has the overhead of string concatenation
36,435,521
I know this question has been asked before, but my case is different and I have not found a solution yet. This is my problem: I have a checkbox that when you click it, a hidden div becomes visible. However, my page shifts-moves to the left. However, with my case there is no scrollbar that appears. If I click the checkbox again, the div is hidden and the page shifts to the right again. And this only happens in Firefox (so far). Tried it in Chrome and it didn't happen. Here is my code: **HTML** ``` <div class="main"> <div class="modelsdiv"> <form id="models" name="models" method="post" novalidate="novalidate"> <fieldset> <label for="type" id="type" class="title">Artist type: <span class="required">*</span>&nbsp;<span class="small">Can be more then 1</span></label> <input type="checkbox" name="arttype[]" id="modelbox" class="typebox" value="Model" required=""><span class="box">Model</span><br /> <div class="modelinfo"> ..... ``` **JS** ``` $(document).ready(function(){ $('#modelbox').click(function(){ $(".modelinfo").slideToggle('slow'); $(this).toggleClass('divactive'); }); ``` **CSS** ``` body { background: #323132; overflow-y: scroll; } .modelsdiv { display: table; width: 100%; } form { display: table-cell; vertical-align: middle; } form label { display: block; margin-bottom:.2em; font-family:"Inconsolata", sans-serif; font-size:15px; line-height:15px; color:#BDBDBD; text-align: left; font-weight: bold; } form label.error { color:#DF0101; } form label.errorg, label.errort { display: none; color:#DF0101; } form textarea { margin-bottom:5px; font-family:"Inconsolata", sans-serif; font-size:14px; font-size:1.4rem; box-shadow:none; -moz-box-shadow:none; -webkit-box-shadow:none; background:#6E6E6E; border:1px solid #BDBDBD; -moz-border-radius:0.2em 0.2em 0.2em 0.2em; -webkit-border-radius:0.2em 0.2em 0.2em 0.2em; border-radius:0.2em 0.2em 0.2em 0.2em; color: #BDBDBD; width:359px; height:192px; } form input[type="text"], form input[type="tel"], form input[type="email"], form input[type="url"] { margin-bottom:5px; font-family:"Inconsolata", sans-serif; font-size:14px; font-size:1.4rem; box-shadow:none; -moz-box-shadow:none; -webkit-box-shadow:none; background:#6E6E6E; border:1px solid #BDBDBD; -moz-border-radius:0.2em 0.2em 0.2em 0.2em; -webkit-border-radius:0.2em 0.2em 0.2em 0.2em; border-radius:0.2em 0.2em 0.2em 0.2em; color: #BDBDBD; } fieldset { border:0px; margin:0 auto; padding:0; width: 350px; } .required { color:#c0392b; } #success, #error { display:none; } #success span, #error span { display:block; position:fixed; top:40%; left:36%; } #success span p, #error span p { } #success span p { color:#01DF01; } #error span p { color:#DF0101; } input[type="submit"] { border:3px #BDBDBD solid; background-color: #1C1C1C; color: #BDBDBD; -webkit-border-radius:40px; -moz-border-radius:40px; border-radius:40px; width: 100px; height: 40px; } .box { color: #BDBDBD; font-family:"Inconsolata", sans-serif; } .small { font-family:"Inconsolata", sans-serif; font-size:15px; line-height:15px; color:#BDBDBD; text-align: left; text-decoration: none; font-weight: normal; } .modelinfo { display: none; } .divactive { display: inline-block; } ``` I have tried different display types and positions, but it keeps happening. I hope someone can help!
2016/04/05
[ "https://Stackoverflow.com/questions/36435521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5711970/" ]
I had the same issue with the same error message and it was a network issue. My replication instance didn't have access to the database. My database is in a VPC with a subnet x and my replication instance is in the same VPC with the same subnet x. I opened the 3306 port in my Network ACL and in the security group of the database to the Internet (0.0.0.0/0) just to test if it was a network problem. The connection test worked with those settings. After the test, I removed the last setting for security. The solution to my problem was to open the 3306 port in the security group and in the network ACL of the database to all the vpc connection. e.g. 172.0.0.0/16. Hope it helps
You must add the security group from your DMS replication instance to your RDS database associated security group as an authorised inbound traffic. * Go to Database Migration Service dashboard and them to "Replication Instances" * Select your replication instance to get the "VPC Security Group"
27,298
I am translating in my main class `render`. How do I get the mouse position where my mouse actually is after I scroll the screen ``` public void render(GameContainer gc, Graphics g) throws SlickException { float centerX = 800/2; float centerY = 600/2; g.translate(centerX, centerY); g.translate(-player.playerX, -player.playerY); gen.render(g); player.render(g); } playerX = 800 /2 - sprite.getWidth(); playerY = 600 /2 - sprite.getHeight(); ``` ***Image to help with explanation*** ![game world showing selected grid not where the mouse is](https://i.stack.imgur.com/Gfwim.png) I tried implementing a camera but it seems no matter what I can't get the mouse position. I was told to do this `worldX = mouseX + camX;` but it didn't work the mouse was still off. Here is my Camera class if that helps: ``` public class Camera { public float camX; public float camY; Player player; public void init() { player = new Player(); } public void update(GameContainer gc, int delta) { Input input = gc.getInput(); if(input.isKeyDown(Input.KEY_W)) { camY -= player.speed * delta; } if(input.isKeyDown(Input.KEY_S)) { camY += player.speed * delta; } if(input.isKeyDown(Input.KEY_A)) { camX -= player.speed * delta; } if(input.isKeyDown(Input.KEY_D)) { camX += player.speed * delta; } } ``` ***Code used to convert mouse*** ``` worldX = (int) (mouseX + cam.camX); worldY = (int) (mouseY + cam.camY); ``` ***Tile class*** ``` public class TileGen { Block block; public Block[] tiles = new Block[2]; public int width, height; public int[][] index; int mouseX, mouseY; int worldX, worldY; boolean selected; Image dirt, grass, selection; SpriteSheet tileSheet; int startX, startY, stopX, stopY; Camera cam; Player player; public void init() throws SlickException { tileSheet = new SpriteSheet("assets/tiles/tileSheet.png", 64, 64); grass = tileSheet.getSprite(0,0); dirt = tileSheet.getSprite(1,0); selection = tileSheet.getSprite(2,0); tiles[0] = new Block(BlockType.Grass, new Vector2f(0,0), grass, true); tiles[1] = new Block(BlockType.Dirt, new Vector2f(0,0), dirt, true); width = 50; height = 50; index = new int[width][height]; cam = new Camera(); player = new Player(); Random rand = new Random(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { index[x][y] = rand.nextInt(2); } } } public void update(GameContainer gc) { Input input = gc.getInput(); mouseX = input.getMouseX(); mouseY = input.getMouseY(); worldX = (int) (mouseX - player.playerX); worldY = (int) (mouseY - player.playerY); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) { selected = true; } else {selected = false;} for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if(IsMouseInsideTile(x, y) && selected) { if(tiles[index[x][y]]== tiles[0]) index[x][y] = 1; } } } startX = (int) (cam.camX/64); startY = (int) (cam.camY/64); stopX = startX + (gc.getWidth()/64) + 2; stopY = startY + (gc.getHeight()/64) + 2; System.out.println(worldX); } public void render(Graphics g, GameContainer container) { for (int x = startX; x < stopX; x++) { for (int y = startY; y < stopY; y++) { tiles[index[x][y]].texture.draw(x * 64, y *64); if(IsMouseInsideTile(x, y)) { selection.draw(x * 64, y * 64); } } } } public boolean IsMouseInsideTile(int x, int y) { return (worldX >= x * 64 && worldX <= (x + 1) * 64 && worldY >= y * 64 && worldY <= (y + 1) * 64); } ``` }
2012/04/12
[ "https://gamedev.stackexchange.com/questions/27298", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/15290/" ]
Edit: just realised this is pretty old. Anyways, I did something similar to this in a TD game so hopefully the same would apply here. In my `TileMap` class I have a method called `getTileCoord(int mouseX, int mouseY)` and for your game it would be translated to something like this: ``` int tileX = (int) (mouseX - camX) / tileWidth; int tileY = (int) (mouseY - camY) / tileHeight; ...// cap the tile coordinates to 0 and the max width/height if needed tileX *= tileWidth; tileY *= tileHeight; or multiply at at draw of selection selection.draw(tileX * 64, tileY * 64); ``` Calling `selection.draw` should now be done outside the x and y loop. If you can scale your camera the the code would become: ``` int tileX = (int) (((x - camX * scale) / tileWidth) * (1 / scale)); int tileY = (int) (((y - camY * scale) / tileHeight) * (1 / scale)); ``` Contains some unnecessary code at the moment, I'll update it once I find the recent version.
float mouseY = Math.abs(Mouse.getY() - Gamecontainer.getHeight());
24,059,880
I can successfully create composite primary key in sql server management studio 2012 by selecting two columns (OrderId, CompanyId) and right click and set as primary key. But i don't know how to create foreign key on two columns(OrderId, CompanyId) in other table by using sql server management studio 2012.
2014/06/05
[ "https://Stackoverflow.com/questions/24059880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3004110/" ]
If you open the submenu for a table in the table list in Management Studio, there is an item `Keys`. If you right-click this, you get `New Foreign Key` as option. If you select this, the Foreign Key Relationships dialogue opens. In the section (General), you will find `Tables And Columns Specifications`. If i open this, i can select multiple columns.
Add two separate foreign keys for each column.
2,767,913
If $A \in M\_n$, $A \succeq 0$ is positive semidefinite, and $a\_{ii} a\_{jj} = |a\_{ij}|^2$, then why $A$ is a non-invertible matrix? Thank you in advance p.s.: this problem is in "Matrix Analysis" by Horn and Johnson, second edition (please see [7.1.P1] page 434).
2018/05/05
[ "https://math.stackexchange.com/questions/2767913", "https://math.stackexchange.com", "https://math.stackexchange.com/users/550103/" ]
The claim is true for $n=2$ and symmetric $A$, as then $\det A=0$ follows from the conditions on $a\_{ij}$.
This is false for a general (possibly non-symmetric) positive semidefinite matrix: $$\begin{pmatrix}1 & -1 \\ 1 & 1\end{pmatrix}$$ is positive semidefinite (its associated quadratic form is $x^2+y^2$) yet invertible
5,215,781
I'm maintaining a vb6 project(ActiveX DLL). When debugging, the app run into the following function: ``` Public Function HasValue(ByVal vValue) As Boolean On Error GoTo Err If IsMissing(vValue) Then HasValue = False ElseIf IsNull(vValue) Or Len(vValue) = 0 Then HasValue = False ElseIf isEmpty(vValue) Then HasValue = False Else HasValue = True End If Exit Function Err: If IsArray(vValue) Or IsObject(vValue) Then HasValue = True Else HasValue = False End If End Function ``` and it stops at the line ElseIf IsNull(vValue) Or Len(vValue) = 0 Then vValue is a custom object, contains some properties(obviously, not null). Although I didn't put any break point there, the app stopped there and alerted error dialog saying that "Run-time error '438': Object doesn't support this property or method". We had error handling code but the app didn't run to error handling code. It just stopped at the line causing the error and I had to stop the application. Do you have any idea about that? Thank you very much.
2011/03/07
[ "https://Stackoverflow.com/questions/5215781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497033/" ]
As far as getting the popup running in the debugger, it is probably related to your "Error Trapping" settings in the IDE. Go To Tools->Options->General and see what selected under "Error Trapping". At first glance it seems odd that your error handler is testing the vValue in the event of an error. It makes more sense to me based on my limited understanding of this method to move both the IsArray and IsObject conditions up into the main testing logic. Just my 2 cents :)
As far as i know vb6 does not support **boolean short evaluation** in ``` ElseIf IsNull(vValue) Or Len(vValue) = 0 Then ``` so `Len(vValue) = 0` is executed even if `IsNull(vValue)` is true. changing your code to ``` ... ElseIf IsNull(vValue) Then HasValue = False ElseIf Len(vValue) = 0 Then HasValue = False ElseIf ... ``` might solve the problem
277,092
I can't figure out how to set environment variables properly, even though I tried to follow <https://wiki.debian.org/EnvironmentVariables>. I've added this to `~/.bashrc`: ``` if [ -f ~/.bash_profile ]; then . ~/.bash_profile fi ``` It seemed logical to me to comment these lines in `~/.profile` after doing that: ``` # if running bash # if [ -n "$BASH_VERSION" ]; then # # include .bashrc if it exists # if [ -f "$HOME/.bashrc" ]; then # . "$HOME/.bashrc" # fi #fi ``` Now when I open a terminal, variables in `~/.profile` and `~/.bash_profile` are correctly exported. How do I make the variables in `~/.profile` available for applications I launch through XFCE menu? I know it isn't the case because if I launch `gpodder` from a terminal, it does what I want, ie. it detects `$GPODDER_HOME` which is set in my `.profile`, but this doesn't happen when I launch it "graphically".
2016/04/17
[ "https://unix.stackexchange.com/questions/277092", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/165260/" ]
See `man xsession`: > > `/etc/X11/Xsession.d/40x11-common_xsessionrc` > > > Source global environment variables. This script will source anything in `$HOME/.xsessionrc` if the file is present. This allows the user to set global environment variables for their X session, such as locale information. > > >
I finally added a `profile.desktop` file in `~/.config/autostart` that looks like this: ``` ~/.config/autostart$ cat profile.desktop [Desktop Entry] Encoding=UTF-8 Version=0.9.4 Type=Application Name=profile Comment= Exec=/bin/bash /home/nicoco/.profile OnlyShowIn=XFCE; StartupNotify=false Terminal=false Hidden=false ``` This is the only workaround I found that doesn't involve modifying files as root.
192,860
I have this sentence: > > The problem is he is very stingy with his money. > > > But I feel it sounds weird or even wrong with the two *is*es so close. Is the sentence structure grammatical? If it isn't, how to fix it?
2014/08/23
[ "https://english.stackexchange.com/questions/192860", "https://english.stackexchange.com", "https://english.stackexchange.com/users/85010/" ]
If you aren't happy with your (correct) sentence, and still feel it needs "fixing," you could reword to: > > The problem is his (great/considerable) stinginess with money. > > >
> > **[What comes after "the problem is...."?](https://english.stackexchange.com/questions/574726/what-comes-after-the-problem-is)** (This post does not seem to be a duplicate of the linked post as it offers no answer to the question.) > > > A statement of the nature of the problem, which can take several forms: The problem is difficult; The problem is solved; The problem is solved by John; The problem is the error; The problem is to correct the error; The problem is reducing; The problem is reducing the water flow; The problem is the reducing of the water flow; The problem is the reduction of the water flow; The problem is that we have no tools; The problem is not the dependence on his parents
8,938,107
I am trying to post a date to a dateTime column in a SQL Server 2008 R2 database, but I have run into many problems that I don't know what are the causes. First, I used this code but I got the error:cannot convert string to date. ``` ADOOF.SQL.Text:='UPDATE OFTab SET CA='''+ CA.Text + ''', demandeClient=''' + DateTimeToStr(demandeClient.DateTime) + ''' WHERE ID='''+ ADOOF.FieldByName('ID') + ''''; ADOOF.ExecSQL; ``` Second, I have used parameters: ``` ADOOF.SQL.Text:='UPDATE OFTab SET CA='''+ CA.Text + ''', demandeClient=:demande_client WHERE ID='''+ ADOOF.FieldByName('ID') + ''''; ADOOF.Parameters.ParamByName('demande_client').Value:= demandeClient.Date; ADOOF.ExecSQL; ``` But I got the error: Parameter (demande\_client) not found. I googled this problem and I found a suggestion by Embarcadero saying that the parametres sould be created before calling the ADOQuery like this: ``` ADOOF.SQL.Text:='UPDATE OFTab SET CA='''+ CA.Text + ''', demandeClient=:demande_client WHERE ID='''+ ADOOF.FieldByName('ID') + ''''; ADOOF.Parameters.ParseSQL(ADOOF.SQL.Text, True); ADOOF.Parameters.ParamByName('demande_client').Value:= demandeClient.Date; ADOOF.ExecSQL; ``` Finely I removed the connection Persist Security Info but always the same problem. Please, any suggestions. INFO: I am using MICROSOFT OLE DB Provider For SQL Server.
2012/01/20
[ "https://Stackoverflow.com/questions/8938107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989318/" ]
in your first example use ``` FormatDateTime('YYYYMMDD hhmmss',demandeClient.DateTime) ``` instead of ``` DateTimeToStr(demandeClient.DateTime) ``` This is because DateTimeToStr without formatsettings uses your localized machine settings and your database just might or might not like the format. Using FormatDateTime also gets rid of ambiguities: consider 01/02/03, for some people on the world this is january 2nd 2003 but for others 1st of februari 2003 and even some will say 2001, februari 3rd. YYYYMMDD is universal. 20030201 is always 1st of februari 2003.
1. I will strongly suggest to use SQL Native Client 11 when you are working with SQL Server 2008 R2. New SQL Server 2008 data types (including `DATE`, `TIME`, `DATETIME2`, and `DATETIMEOFFSET`) are not supported by the SQL Server 2000 OLEDB provider. 2. Your second code sample should work. Check that you have `TADOQuery`.`ParamCheck` = True.
45,341,206
Below is the code for my action creator: ``` export function fetchPosts() { const request = axios.get(`${ROOT_URL}/posts${API_KEY}`); return { type: FETCH_POSTS; payload: request }; } ``` Next to type: FETCH\_POSTS, if i add , instead of ; i get the error Unexpected token. Is that the syntax for action creators? Then if i replace , with ; upon compile i get the error 'Actions must be plain Javascript Objects. Any idea why?
2017/07/27
[ "https://Stackoverflow.com/questions/45341206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8373663/" ]
GibboK's answer has already pointed out the syntax error. However, I don't think you understand using actions properly. You run: ``` const request = axios.get(`${ROOT_URL}/posts${API_KEY}`); ``` This is creating a promise. You are currently returning this in an action. Reducers are meant to be deterministic & side effect free, hence why actions should be plain JS objects. You should not be submitting a promise. Instead, you should be using some relevant middleware, e.g. [redux-thunk](https://github.com/gaearon/redux-thunk), [redux-saga](https://github.com/redux-saga/redux-saga) or something else. You should send an action when the actual promise has resolved. As a simple contrived example, using `redux-thunk`: ``` export const fetchPosts = () => (dispatch) => { // Send action to notify request started. Reducers often want to // update the state to record that a request is pending, e.g. for // UI purposes. dispatch({type: FETCH_POSTS_START}); // Start request request = axios.get(`${ROOT_URL}/posts${API_KEY}`) .then(res => { // Successfully received posts, submit response data dispatch({type: FETCH_POSTS_COMPLETE, payload: res.data}) }) .catch(err => { // API call failed, submit error dispatch({type: FETCH_POSTS_ERROR, payload: err}) }); }; ``` *Note this code is just an example and not necessarily suitable for use in a production system.*
As per **[redux](http://redux.js.org/docs/basics/Actions.html)** documentation: > > `Actions` are plain JavaScript objects. Actions must have a `type > property` that indicates the type of action being performed. Types > should typically be defined as `string constants`. Once your app is > large enough, you may want to move them into a separate module. > > > And Action Creators > > Action creators are functions that create actions > > > In Redux action creators simply return an action: > > > > ``` > function addTodo(text) { > return { > type: ADD_TODO, > text > } > } > > ``` > > So when you call the `action creator` from your component through `dispatch` your action creator just needs to simply return a plain javascript object. So a normal action creator will be ``` export function fetchPosts() { return { type: FETCH_POSTS; payload: "somevalue" }; } ``` Now if you want to call APIs within your action creators you need to make use of middlewares like `redux-thunk` or `redux-saga` while creating a store like ``` import thunk from 'redux-thunk'; const store = createStore(reducers, applyMiddleware(thunk)); ``` You you configure your store with middleware you can modify your actions to ``` export function fetchPosts() { return (dispatch) => { axios.get(`${ROOT_URL}/posts${API_KEY}`) .then((response)=> { dispatch( { type: FETCH_POSTS, payload: request }) }) } } ``` As per the **[redux-thunk](https://github.com/gaearon/redux-thunk)** documentation > > **Why Do you need redux-thunk?** > > > `Redux Thunk middleware` allows you to write action creators that > return a function instead of an action. The thunk can be used to delay > the `dispatch` of an action, or to `dispatch` only if a certain > condition is met. The inner function receives the store methods > `dispatch and getState` as `parameters`. > > >
22,296,293
In My DataBaseAdapter Class, I write a method getAll like that ``` public List<AllUserInfor> getAllInfor(int id) { List<AllUserInfor> allInfor = new ArrayList<AllUserInfor>(); String selectQuery = "SELECT Name, Gender FROM MY_TABLE where _id = '"+id+"' "; Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { AllUserInfor alluserinfor = new AllUserInfor(); alluserinfor.setName(cursor.getString(1)); alluserinfor.setGender(cursor.getString(2)); allInfor.add(alluserinfor); } while (cursor.moveToNext()); } return allInfor; } ``` and in the second activity, I have ``` @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btShow: // I get id from the first activity Bundle extras = getIntent().getExtras(); id = extras.getInt("Roomid"); List<AllUserInfor> userInfor = mySQLiteAdapter.getAllInfor(id); for (AllUserInfor aui : userInfor){ tvname.setText(aui.getName()); tvgender.setText(aui.getGender()); } break; } } ``` this is the way I get id from first activity ``` lvroom.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> listView, View view, int position, long id) { // TODO Auto-generated method stub cursor = (Cursor) lvroom.getItemAtPosition(position); int item_id = cursor.getInt(cursor.getColumnIndex(SQLiteAdapter.KEY_ID)); Intent i = new Intent(); Bundle bundle = new Bundle(); bundle.putInt("Roomid", item_id); i.putExtras(bundle); i.setClass(FirstActivity.this, SecondActivity.class); startActivityForResult(i, 0); } ``` After I hit the Show button inf second activity, nothing change, its mean that the name and gender are not showed in second layout. Where are my mistakes? Help me this is my logcat ``` 03-10 18:01:20.790: E/AndroidRuntime(1224): FATAL EXCEPTION: main 03-10 18:01:20.790: E/AndroidRuntime(1224): java.lang.NullPointerException 03-10 18:01:20.790: E/AndroidRuntime(1224): at com.superman.medreport.SecondActivity.onClick(SecondActivity.java:127) 03-10 18:01:20.790: E/AndroidRuntime(1224): at android.view.View.performClick(View.java:4204) 03-10 18:01:20.790: E/AndroidRuntime(1224): at android.view.View$PerformClick.run(View.java:17355) 03-10 18:01:20.790: E/AndroidRuntime(1224): at android.os.Handler.handleCallback(Handler.java:725) 03-10 18:01:20.790: E/AndroidRuntime(1224): at android.os.Handler.dispatchMessage(Handler.java:92) 03-10 18:01:20.790: E/AndroidRuntime(1224): at android.os.Looper.loop(Looper.java:137) 03-10 18:01:20.790: E/AndroidRuntime(1224): at android.app.ActivityThread.main(ActivityThread.java:5041) 03-10 18:01:20.790: E/AndroidRuntime(1224): at java.lang.reflect.Method.invokeNative(Native Method) 03-10 18:01:20.790: E/AndroidRuntime(1224): at java.lang.reflect.Method.invoke(Method.java:511) 03-10 18:01:20.790: E/AndroidRuntime(1224): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 03-10 18:01:20.790: E/AndroidRuntime(1224): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 03-10 18:01:20.790: E/AndroidRuntime(1224): at dalvik.system.NativeStart.main(Native Method) 03-10 18:01:24.802: E/Trace(1256): error opening trace file: No such file or directory (2) ```
2014/03/10
[ "https://Stackoverflow.com/questions/22296293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3399020/" ]
Do not cast your `id` value into the `String` as its an `Integer` in your table. Change your criteria as below to get value: ``` "SELECT Name, Gender FROM MY_TABLE where _id = "+id+" "; ``` Just remove the single `" ' "` and write as `"+id+"` not `'"+id+"'`
use this : ``` "SELECT Name, Gender FROM MY_TABLE where _id ="+id+"; ``` instead of ``` "SELECT Name, Gender FROM MY_TABLE where _id = '"+id+"' "; ```
8,693,733
I'm working on a project where I need to make modifications in more then 500 images to **give outerglow on hover** effect. I will need to modify each image to give the outer glow. It will be a very time consuming task. **This is example of one image.** All images are transparent .png ![enter image description here](https://i.imgur.com/HkzvA.jpg) **Is it possible to give this outerglow effect to the bottle image using any tricks of CSS3?** This is just an example of one image other images are in different size and shape.
2012/01/01
[ "https://Stackoverflow.com/questions/8693733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84201/" ]
As easy as pie. You just use the same image twice, one above the other. ```html <div class="container"> <img class="main" src="http://www.pngmart.com/files/2/Mario-PNG-Image.png" /> <img class="glow" src="http://www.pngmart.com/files/2/Mario-PNG-Image.png" /> </div> ``` You just work on the image below, scale it a little, bright it until it's white and then blur it. Then you set your opacity on 0 and set it back to one when the above image is hovered. ```css .container { position:relative; background-color:#444444; width:600px; height:600px; } img { position:absolute; max-height:90%; top:50%; left:50%; transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); transform-origin: 0 0; -webkit-transform-origin: 0 0; } img.main { z-index:2; } img.glow { z-index:1; transform: scale(1.01) translate(-50%, -50%); -webkit-transform: scale(1.01) translate(-50%, -50%); filter: brightness(0) invert(1) blur(5px); -webkit-filter: brightness(0) invert(1) blur(5px); opacity:0; } img.main:hover ~ img.glow { opacity:1; } ``` No Javascript required whatsoever. <https://jsfiddle.net/nkq1uxfb/3/>
I found an easy way if you can work with photoshop. You open the transparent image (example.png) in photoshop and take the blur tool. Then blur the whole image and save as (example-hover.png). ``` <div id="img1"> <img src="images/example.png"> </div> #img1:hover{ background: url('images/example-hover.png') no-repeat 0px 0px;; } ```
68,105
If there is a segmented audience set, comprising of individuals as one segment, and various types of businesses as other segments, is there a good collective term that can be used as a top level navigation item: Currently **Audiences** is the top level nav item, and the audience types are: * Researchers (individual people) * Universities * Engineering companies * Public sector organisations **Audiences** feels a bit like UX jargon, and not very user friendly. **Customers** doesn't feel right either. Is there a better term?
2014/11/28
[ "https://ux.stackexchange.com/questions/68105", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/5900/" ]
Interesting problem to try solve in the general case. I fairly frequently have an accurate, but abstract collective term that is derived from strong analysis of the domain. However as most people actually *in the domain* do not do the abstract analysis, and thus they would not recognise and engage with the term. Equally because the analysis is not widely done, there *is no familiar term*. This example appears to be a specific case of this type of issue. Strategies I have applied when facing this issue include * Immerse yourself in the domain with all aspects users, managers, purchase, trainers and try identify natural language to apply * Use first good concrete term in the hierarchy- even if means more UI elements e.g. Have both "Individuals" "Organisations" * Build a "journey UX". e.g. "If you are a [AAA][BBB][CCC]" take this route
You could try "Clients" if it fits the context
1,876,506
For a list like: ``` Column1 Column2 Column3 DataA 1 1234 DataA 2 4678 DataA 3 8910 DataB 2 1112 DataB 4 1314 DataB 9 1516 ``` How do I get a list like this: ``` Column4 Column5 Column6 DataA 1 1234 DataB 2 1112 ``` The key is to only return the minimum value in column2 and its corresponding column3 value.
2009/12/09
[ "https://Stackoverflow.com/questions/1876506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127776/" ]
This exceptions means that you are trying to autowire `EntityManagerFactory` by type. Do you have any `@Autowired` annotation in your code? Aslo, when using `@PersistenceContext`, set the `unit` attribute correctly. And (I'm not sure if this is a proper thing to do) - try setting the `name` attribute to your respective factory name. Also, check if you haven't copy-pasted incorrectly the REST transaction manager - now there is no such bean `REST`
Ensure all of your @PersistenceContext specify unitName. I haven't figured out how to tell Spring that a particular EMF or PersistenceUnit is the default. I thought specifying primary="true" on the default EMF would work but doesn't appear to
15,955,249
I wrote this css code: ``` body.product.70 div.mydiv { display:none } ``` and the HTML: ``` <body class="product 70"> <div class="mydiv"> content </div> </body> ``` But it doesn't want to hide. thanks
2013/04/11
[ "https://Stackoverflow.com/questions/15955249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2271447/" ]
Well for starters, your `class` attribute is missing a closing quote... EDIT: Aside from that, you're applying two class names, one of which is `70`. This is NOT a valid CSS class name. CSS classes must begin with a hyphen, underscore, or letter.
You don't need to specify too many classes when you call it on css. If you have the class .product for every product, no need to use the class '70' on the css: ``` body.product { display:none; } ``` I recomend you to use something more semantic html like: ``` <body> <div class="product"> <div class="mydiv"> Hello </div> </div> </body> ``` And finally the css code: ``` .product{ display:none; } ``` I recomend to you that not use only numbers on the classes names. Maybe a single letter followed by a number it'd be more explicative for the developer :)
44,278,983
I would like to know if it's possible to match one pattern multiple time (the number of match is not know) and extract each occurences for make a compare? My goal is to find if a vlan is configure on an interface. I have this file sample (I have trunc it) : ``` interface Ethernet1/16 shutdown switchport access vlan 777 spanning-tree bpduguard enable interface Ethernet1/17 switchport mode trunk switchport trunk native vlan 201 switchport trunk allowed vlan 1-69,71-100,110-111,120,153,198,200-366,368-397,400-599,1000-3967,4048-4093 channel-group 2 mode active interface Ethernet1/18 switchport mode trunk switchport trunk native vlan 201 switchport trunk allowed vlan 1-69,71-100,110-111,120,153,198,200-366,368-397,400-599,1000-3967,4048-4093 channel-group 2 mode active interface Ethernet1/19 switchport mode trunk switchport trunk native vlan 201 switchport trunk allowed vlan 1-69,71-100,110-111,120,153,198,368-397,400-599,1000-3967,4048-4093 channel-group 2 mode active ``` I have this code for parsing the file and for each interface, I check if I can find the vlan (provided in argument) in a range. ``` REGEX="^interface (.*)" REGEX_TRUNKRANGEVLAN="^switchport trunk allowed.*(\d+)-(\d+),*" vlan=$2 while read line; do if [[ $line =~ $REGEX ]]; then ifname=${BASH_REMATCH[1]} else if [[ $line =~ $REGEX_TRUNKRANGEVLAN ]]; then #for each pattern match on this line, I need to check if [ ${BASH_REMATCH[1]} -lt $vlan ] && [ ${BASH_REMATCH[2]} -gt $vlan ]; then echo "vlan is included in interface $ifname" fi fi fi done <$1 ``` For example, if I looking for the vlan 250, the output will : > > vlan is included in interface Ethernet1/17 > > vlan is included in interface Ethernet1/18 > > >
2017/05/31
[ "https://Stackoverflow.com/questions/44278983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544062/" ]
I think this will work : ``` REGEX="^interface (.*)" REGEX_TRUNKRANGEVLAN="^[ ]*switchport trunk allowed vlan (.*)" vlan=$2 while read line do if [[ $line =~ $REGEX ]] then ifname=${BASH_REMATCH[1]} fi if [[ $line =~ $REGEX_TRUNKRANGEVLAN ]] then old=$IFS IFS="," for range in ${BASH_REMATCH[1]} do if [[ $vlan -ge ${range%-*} && $vlan -le ${range#*-} ]] then echo "vlan is included in interface $ifname" fi done IFS=$old fi done < $1 ```
Clearly not the prettiest way to do it, certainly not the most efficient way also, but because I put some time writing this command, I'll share it even if your problem is solved : ``` sed -r -e ':a' -e 'N' -e '$!ba' -e 's/\n//g' -e 's/(interface Ethernet)/\n\1/g' |awk '{gsub(",", " ", $15); print "echo "$1"_"$2" "$15}' | sed -r 's#([0-9]*)-([0-9]*)#`seq \1 \2`#ge' ``` What it does is transforming all the interfaces blocks as one line `<interface> <ranges>`and transforming all the ranges on each line on the list of vlans. ie. if the line is : `<interface> 3-5 7 8-10` it will transform into : `<interface> 3 4 5 7 8 9 10` * `-e ':a' -e 'N' -e '$!ba' -e 's/\n//g'` : Removes all the `\n` * `-e 's/(interface Ethernet)/\n\1/g'` : Each `interface Ethernet` will be the start of a new line * `awk '{gsub(",", " ", $15); print "echo "$1"_"$2" "$15}'` : Replaces the `","` by `" "` and print the `interface Ethernet...` and ranges field. The trick here is the `echo` which will be used on the next sed statement * `sed -r 's#([0-9]*)-([0-9]*)#`seq \1 \2`#ge'` : Replaces each pattern `XXX-XXX` of vlan range by : `seq XXX XXX`. The `e` flag will then execute the replacement line. which will be of the form : ``` echo interface `seq 3 5` 7 `seq 8 10` ``` After that you just need to `grep` the lines where the vlan appears. I don't think it will be of much use for you now, but I spent too much time on this one to not share it ;) -- Edit Some awk script a little more refined : ``` awk '/interface Ethernet[0-9]*\/[0-9]*/{iface=$1" "$2}; /switchport trunk allowed vlan/{ gsub(",", " "); print "echo "iface" \\" ; for(i = 5; i<=NF; i++) { if ($i~/[0-9]*-[0-9]*/) { gsub("-", " ", $i); printf (" `seq %s`", $i) } else { printf (" %s",$i) } ; if (i!=NF){print "\\"} else {print""} } }' /tmp/test.vlan | sh |grep ' 250 ' |cut -d" " -f1,2 ```
46,118,361
I have a data frame: ``` df = read.table(text="index Htype 3 AAAABABBAAAAAABBAAHBUUAUAABBAABA 4 AAAABABBAAABABBABBAAHBBBBAABAABB 7 AAAABABBAAAAAABBAAABUBAUAABBAABA 8 BBBABABAAAAAAAABBABBAUAUAABBAAAA 9 BBHABABAAAAAAAABBABBABAUAABBAAAA", header=T, stringsAsFactors=F) ``` I would like to find out the the positions of characters "U" or "H" in the "Htype" column. So the expected result: ``` index Htype pos 3 AAAABABBAAAAAABBAAHBUUAUAABBAABA 19 21 22 24 4 AAAABABBAAABABBABBAAHBBBBAABAABB 21 7 AAAABABBAAAAAABBAAABUBAUAABBAABA 21 24 8 BBBABABAAAAAAAABBABBAUAUAABBAAAA 22 24 9 BBHABABAAAAAAAABBABBABAUAABBAAAA 3 24 ``` I used the script not working, ``` df$pos <- apply(df$Htype,1,function(x) unlist(gregexpr(pattern ='U|H',x))) ``` I need helps thanks.
2017/09/08
[ "https://Stackoverflow.com/questions/46118361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3354212/" ]
I think this is something on the Google's end. My application have been running on production for more than a week. Based on the logs everything was fine till 6 hours ago but since that the users don't get any answer back. If I request on the API.AI the response is okay so it's not the firebase/fullfillment causing the issue. Checked other applications some had the same problem some had no problem at all. Not sure what we can do here.
Errors like this are usually caused by a syntax error or other problem in your Firebase Function after you've updated it. There are a few good approaches to diagnosing problems like this: 1. Check the Firebase function log. If there is an error, it will almost certainly show up here. From the command line you can use `firebase functions:log` to see the most recent logging messages. You can also use the console to view the logs by going to console.firebase.com, selecting the project, selecting Functions, and then the Logs tab. 2. If there isn't an error, it becomes more of a logic problem. Adding your own logs via `console.log()`, `console.info()`, or `console.error()` 3. Many times the logs will indicate the function is timing out after 60 seconds when you think you're returning things by then. Make sure you are completing any callbacks and calling `assistant.ask()` or `assistant.tell()` (or one of their cousins) to make sure they're being called.
10,877,223
I have an interface that I've exposed as a regular SOAP web service. One method of the interface consists for the client to send a file to the server, then the server processes the file and returns a result file. Processing the file may take some time, so I think using asynchronous invocation of this method is a better idea. I thought about the following flow: The client invokes the asynchronous method and sends the file using an attachment (MTOM). When the file is received by the server, a response is sent back to the client indicating that the file has been received and that it will be processed shortly. Once the file is processes, a response is sent back to the client indicating it has been processed and a result file is returned in the response also as an attachment. Is it possible using SOAP with CXF? Thanks
2012/06/04
[ "https://Stackoverflow.com/questions/10877223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1002972/" ]
You can use `Callback` approach of `Asynchronous InvocationModel`. > > Callback approach - in this case, to invoke the remote operation, you > call another special method that takes a reference to a callback > object (of javax.xml.ws.AsyncHandler type) as one of its parameters. > Whenever the response message arrives at the client, the CXF runtime > calls back on the AsyncHandler object to give it the contents of the > response message > > > More information can be had from the following: [Apache CXF](http://cxf.apache.org/docs/developing-a-consumer.html)
If you use some tool like WSDL2Java for client generation, you can even choose to generate an asynchronous client. It will generate for you a callback handler with empty methods for each of the service operations and exceptions of the service. You then can just implement those methods to set the actions to do when the response is received. Remember that when an asynchronous call is done a new thread is started.
37,956
I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me. I've tried to use Direct Show with the SampleGrabber filter (using this sample <http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx>), but I only managed to grab some frames (not every frames!). I'm quite new in video software programming, maybe I'm not using the best library, or I'm doing it wrong. I've pasted a part of my code (mainly a modified copy/paste from the msdn example), unfortunately it doesn't grabb the 25 first frames as expected... ``` [...] hr = pGrabber->SetOneShot(TRUE); hr = pGrabber->SetBufferSamples(TRUE); pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. // Find the required buffer size. long cbBuffer = 0; hr = pGrabber->GetCurrentBuffer(&cbBuffer, NULL); for( int i = 0 ; i < 25 ; ++i ) { pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. char *pBuffer = new char[cbBuffer]; hr = pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer); AM_MEDIA_TYPE mt; hr = pGrabber->GetConnectedMediaType(&mt); VIDEOINFOHEADER *pVih; pVih = (VIDEOINFOHEADER*)mt.pbFormat; [...] } [...] ``` Is there somebody, with video software experience, who can advise me about code or other simpler library? Thanks Edit: Msdn links seems not to work ([see the bug](http://stackoverflow.uservoice.com/pages/general/suggestions/19963))
2008/09/01
[ "https://Stackoverflow.com/questions/37956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1578/" ]
I know it is very tempting in C++ to get a proper breakdown of the video files and just do it yourself. But although the information is out there, it is such a long winded process building classes to hand each file format, and make it easily alterable to take future structure changes into account, that frankly it just is not worth the effort. Instead I recommend ffmpeg. It got a mention above, but says it is difficult, it isn't difficult. There are a lot more options than most people would need which makes it look more difficult than it is. For the majority of operations you can just let ffmpeg work it out for itself. For example a file conversion ffmpeg -i inputFile.mp4 outputFile.avi Decide right from the start that you will have ffmpeg operations run in a thread, or more precisely a thread library. But have your own thread class wrap it so that you can have your own EventAgs and methods of checking the thread is finished. Something like :- ``` ThreadLibManager() { List<MyThreads> listOfActiveThreads; public AddThread(MyThreads); } Your thread class is something like:- class MyThread { public Thread threadForThisInstance { get; set; } public MyFFMpegTools mpegTools { get; set; } } MyFFMpegTools performs many different video operations, so you want your own event args to tell your parent code precisely what type of operation has just raised and event. enum MyFmpegArgs { public int thisThreadID { get; set; } //Set as a new MyThread is added to the List<> public MyFfmpegType operationType {get; set;} //output paths etc that the parent handler will need to find output files } enum MyFfmpegType { FF_CONVERTFILE = 0, FF_CREATETHUMBNAIL, FF_EXTRACTFRAMES ... } ``` Here is a small snippet of my ffmpeg tool class, this part collecting information about a video. I put FFmpeg in a particular location, and at the start of the software running it makes sure that it is there. For this version I have moved it to the Desktop, I am fairly sure I have written the path correctly for you (I really hate MS's special folders system, so I ignore it as much as I can). Anyway, it is an example of using windowless ffmpeg. ``` public string GetVideoInfo(FileInfo fi) { outputBuilder.Clear(); string strCommand = string.Concat(" -i \"", fi.FullName, "\""); string ffPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ffmpeg.exe"; string oStr = ""; try { Process build = new Process(); //build.StartInfo.WorkingDirectory = @"dir"; build.StartInfo.Arguments = strCommand; build.StartInfo.FileName = ffPath; build.StartInfo.UseShellExecute = false; build.StartInfo.RedirectStandardOutput = true; build.StartInfo.RedirectStandardError = true; build.StartInfo.CreateNoWindow = true; build.ErrorDataReceived += build_ErrorDataReceived; build.OutputDataReceived += build_ErrorDataReceived; build.EnableRaisingEvents = true; build.Start(); build.BeginOutputReadLine(); build.BeginErrorReadLine(); build.WaitForExit(); string findThis = "start"; int offset = 0; foreach (string str in outputBuilder) { if (str.Contains("Duration")) { offset = str.IndexOf(findThis); oStr = str.Substring(0, offset); } } } catch { oStr = "Error collecting file information"; } return oStr; } private void build_ErrorDataReceived(object sender, DataReceivedEventArgs e) { string strMessage = e.Data; if (outputBuilder != null && strMessage != null) { outputBuilder.Add(string.Concat(strMessage, "\n")); } } ```
I would recommend FFMPEG or GStreamer. Try and stay away from openCV unless you plan to utilize some other functionality than just streaming video. The library is a beefy build and a pain to install from source to configure FFMPEG/+GStreamer options.
22,505,609
I want to force the user to write in an input values, which have max 2 digits after "." For instance : 24.14 or 5.7 or 0.5 or 8 and NOT 4.321 or 5.133121. How can I do that ?
2014/03/19
[ "https://Stackoverflow.com/questions/22505609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3084005/" ]
I found a solution for this. You can use this api from Jquery: [click here](http://digitalbush.com/projects/masked-input-plugin/)
You can make use of [.toFixed()](http://www.w3schools.com/jsref/jsref_tofixed.asp) method which converts a number into a string, keeping a specified number of decimals. **sample**: ``` var myNum = document.getElementById("textboxID").value; myNum = parseFloat(myNum).toFixed(2); //I fixed my precision to 2 digits after "." ```
3,137,094
I have lines like these, and I want to know how many lines I actually have... ``` 09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00 09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 91.00 09:16:41 AM all 0.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 96.00 09:16:42 AM all 3.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 96.00 09:16:43 AM all 0.00 0.00 1.00 0.00 1.00 0.00 0.00 0.00 98.00 09:16:44 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:16:45 AM all 2.00 0.00 6.00 0.00 0.00 0.00 0.00 0.00 92.00 ``` Is there a way to count them all using linux commands?
2010/06/29
[ "https://Stackoverflow.com/questions/3137094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/368453/" ]
If all you want is the number of lines (and not the number of lines and the stupid file name coming back): ``` wc -l < /filepath/filename.ext ``` As previously mentioned these also work (but are inferior for other reasons): ``` awk 'END{print NR}' file # not on all unixes sed -n '$=' file # (GNU sed) also not on all unixes grep -c ".*" file # overkill and probably also slower ```
I know this is *old* but still: ***Count filtered lines*** My file looks like: ```none Number of files sent Company 1 file: foo.pdf OK Company 1 file: foo.csv OK Company 1 file: foo.msg OK Company 2 file: foo.pdf OK Company 2 file: foo.csv OK Company 2 file: foo.msg Error Company 3 file: foo.pdf OK Company 3 file: foo.csv OK Company 3 file: foo.msg Error Company 4 file: foo.pdf OK Company 4 file: foo.csv OK Company 4 file: foo.msg Error ``` If I want to know how many files are sent OK: ``` grep "OK" <filename> | wc -l ``` OR ``` grep -c "OK" filename ```
477,358
I know that the signal was just tone pulses but why was it when (back in the 90s) when you first connected to the internet you heard a bunch of funny noises. After that if you were to use the internet, it still was using the telephone line, why no funny noises then?
2012/09/20
[ "https://superuser.com/questions/477358", "https://superuser.com", "https://superuser.com/users/137864/" ]
Because the modem speaker was turned on by default, to give the user the feedback that something was happening during the handshake. With the proper setup of the AT commands you could have 3 modes - always on for speaker, totally silent during operation, and the default with speaker turned on during connect. They were ATL and ATM if I remember correctly. But the whole command (Hayes commands) to the modem was: ``` Attention. Loudness level x. AT Lx (where x is 0 to 3) ``` Of course this was usually part of a longer string, and many instructions were set by default (unless specifically over-ridden). Newer modems were able to be set; and stored a default command list.
The first modem I ever used was acoustically coupled--that is, you put the handset into a rubber dingus where transmitted/recieved the *sound* to/from a microphone/speaker on the modem body. This was necessary for a while in the US because AT&T had government granted veto over the attachment of any electronic device to their wires---a rule that was later overturned. On those things you could hear a little leakage if you were running it in a quite room.
3,739,661
I'm trying to create a custom view `GhostSurfaceCameraView` that extends `SurfaceView`. Here's my class definition file `GhostSurfaceCameraView.java`: ``` public class GhostSurfaceCameraView extends SurfaceView implements SurfaceHolder.Callback { SurfaceHolder mHolder; Camera mCamera; GhostSurfaceCameraView(Context context) { super(context); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, acquire the camera and tell it where to draw. mCamera = Camera.open(); try { mCamera.setPreviewDisplay(holder); } catch (IOException exception) { mCamera.release(); mCamera = null; // TODO: add more exception handling logic here } } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. // Because the CameraDevice object is not a shared resource, it's very // important to release it when the activity is paused. mCamera.stopPreview(); mCamera.release(); mCamera = null; } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Now that the size is known, set up the camera parameters and begin // the preview. Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(w, h); parameters.set("orientation", "portrait"); // parameters.setRotation(90); // API 5+ mCamera.setParameters(parameters); mCamera.startPreview(); } } ``` And this is in my ghostviewscreen.xml: ``` <com.alpenglow.androcap.GhostSurfaceCameraView android:id="@+id/ghostview_cameraview" android:layout_width="fill_parent" android:layout_height="fill_parent"/> ``` Now in the activity I made: ``` protected void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.ghostviewscreen); } } ``` When `setContentView()` gets called, an exception is thrown: ``` Binary XML file 09-17 22:47:01.958: ERROR/ERROR(337): ERROR IN CODE: android.view.InflateException: Binary XML file line #14: Error inflating class com.alpenglow.androcap.GhostSurfaceCameraView ``` Can anyone tell me why I get this error? Thanks.
2010/09/17
[ "https://Stackoverflow.com/questions/3739661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451119/" ]
@Tim - Both the constructors are not required, only the `ViewClassName(Context context, AttributeSet attrs )` constructor is necessary. I found this out the painful way, after hours and hours of wasted time. I am very new to Android development, but I am making a wild guess here, that it maybe due to the fact that since we are adding the custom `View` class in the XML file, we are setting several attributes to it in the XML, which needs to be processed at the time of instantiation. Someone far more knowledgeable than me will be able to shed clearer light on this matter though.
Another possible cause of the "Error inflating class" message could be misspelling the full package name where it's specified in XML: ``` <com.alpenglow.androcap.GhostSurfaceCameraView android:id="@+id/ghostview_cameraview" android:layout_width="fill_parent" android:layout_height="fill_parent"/> ``` Opening your layout XML file in the Eclipse XML editor should highlight this problem.
5,402,564
How to Add Not condition in the below select case. Is <> works for single value, and 'To' works for a Range but the value are specific values there are not series of numbers. Is it possible to use select case in this scenario, or do i have to switch to if-else. Ex: i don't want case to execute when value is 0 and 3 ``` Select value case 0,1,2,3 End Select ```
2011/03/23
[ "https://Stackoverflow.com/questions/5402564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116489/" ]
I'm not sure I understand the question... Why can't you just write the example code like so: ``` Select Case value Case 1, 2 DoWork() End Select ``` Nothing gets executed when `value = 0` or `value = 3`. The series of values provided to a `Case` statement doesn't have to be sequential. --- **Update in response to comment:** I would write that like this, taking advantage of the `Case Else` label: ``` Select Case myComboBox.SelectedIndex Case 1, 5, 8 'The suggestion is acceptable, so process it DoWork() Case Else 'The suggestion is invalid, so show an error MessageBox.Show("You cannot select that option. " & _ "Please choose options 1, 5, or 8 instead.", _ "Invalid Selection", _ MessageBoxButtons.OK, MessageBoxIcon.Error) End Select ``` Of course, if you don't actually have any "work" to be done in the case that the user selects the *correct* value, there seems little point in using a `Select Case` statement at all. The cardinal rule should be to **use whichever makes your code the clearest** and easiest to understand. There's little validity to the suspicion that `Select Case` is faster than an `If` statement—the compiler is smart enough to produce virtually equivalent results in almost every case.
Building on what Cody wrote I would go with: ``` Select Case value Case 1, 2 DoWork() Case 0 ,3 'nothing to do, only log if needed Case Else Debug.Fail("Please provide a logical path for all possible values") End Select ``` The extra branches are just to clarify the intent of the code and to guard against future changes.
36,161,805
I need to delete rows where the positive values begin in column H after sorting. I was trying to use the find feature. I know >0 does not work but not sure where to go from here. I can switch the sort to descending and search for "-" if I can figure out how to select upwards and delete. ``` Source_Workbook.Worksheets("Sheet1").Activate Source_Workbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("H:H"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal Cells.Select With ActiveWorkbook.Worksheets("Sheet1").Sort .SetRange Range("A1:R65800") .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With Columns("H:H").Select Selection.Find(What:=">0", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Select Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select Selection.EntireRow.Delete ```
2016/03/22
[ "https://Stackoverflow.com/questions/36161805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6100243/" ]
Change the path in the .ini-file. ``` -vm C:\Program Files\Java\JDK1.8.0_172\bin\javaw.exe ``` if you still see the issue Change it into: ``` -vm C:\Program Files\Java\jdk1.8.0_172\jre\bin\server\jvm.dll ``` Note: The path should be in the new line after -vm.
I installed java 9 JDK 64 bit. The install took care of everything in my case and allowed me to start the Anypoint studio from my existing short cut. In some cases you may need to still manually edit your settings but try just a 64 bit install first
37,113,840
My older database version is 2.3.2. There I created a database and inserted nodes and relationships. Now, I upgraded to 3.0 version and restarted the neo4j server. Changed the `dbms.active_directory = xyz_path` But unable to fetch the data from the db now. Is there any more configurations or any specific changes I need to do to access the database. **Edited** Error while using migrating the config files: ``` [root@enteras02 tools]# java -jar config-migrator.jar path/to/neo4j2.3 path/to/neo4j3.0 ``` Exception in thread "main" java.lang.UnsupportedClassVersionError: org/neo4j/config/ConfigMigrator : Unsupported major.minor version 52.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:803) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)
2016/05/09
[ "https://Stackoverflow.com/questions/37113840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2771169/" ]
The problem was the above js code was not generating array in proper JSON format. I tried and fixed that. here is working code: ``` var fs = require("fs"); var data = fs.readFileSync('India2011.json'); var myData=JSON.parse(data);//contains main array var len=myData.length;//main array length var k=1; var count=0; var displayMe=[]; var canRead=0; var cannotRead=0; for (var i = 0; i <len; i++) { var obj2={};//changes here for (var j = k; j <=35; j++) { var obj={}; var header;//changes here if ((myData[i]["State Code"]==(j))&&(myData[i]["Total/ Rural/ Urban"]=="Total")&&(myData[i]["Age-group"]=="All ages")) { obj["Literate - Persons"]=parseInt(myData[i]["Literate - Persons"]); obj["Illiterate - Persons"]=parseInt(myData[i]["Illiterate - Persons"]); obj["Total - Persons"]=parseInt(myData[i]["Total Persons"]); header= myData[i]["Area Name"];//changes here obj2[header]=obj;//changes here displayMe.push(obj2);//changes here count+=(parseInt(myData[i]["Total Persons"])); canRead+=(parseInt(myData[i]["Literate - Persons"])); cannotRead+=(parseInt(myData[i]["Illiterate - Persons"])); ++k; //console.log("Addesd "+myData[i]["Total Persons"]+" Time j: "+k+" State name"+myData[i]["Area Name"]+" i:"+i+"k:"+k+" count "+count); }; }; }; fs.writeFile( "displayMe.json", JSON.stringify( displayMe ), "utf8"); console.log(displayMe); ``` that was the few changes. It is working now.
The problem is caused by this line: ``` var displayMe = []; ``` You're initializing `displayMe` to be an empty array. However, you are subsequently treating that array as an object: ``` displayMe[myData[i]["Area Name"]] = (obj); ``` This won't stringify to JSON properly, because arrays are supposed to have particular properties (like `length`) that `JSON.stringify()` depends on. Instead, initialize `displayMe` to be an empty object: ``` var displayMe = {}; ```
4,355,355
In a past exam question we prove that the following function is well-defined and holomorphic on $\mathbb{C}$ \ $\mathbb{Z}$, and then we are asked to find the closed form. Let $$ f(z)=\sum\_{n=-\infty}^{\infty}\frac{1}{(z+n)^2}. $$ The mark scheme says: > > We have that $f$ is periodic as $f(z) = f(z+2) \forall z$. See that $f(z)$ has double poles at every integer with residue $(-1)^k$. > > > > > $(\*)$ Note that $f(z) = −g'(z)$, where $g(z)$ has single poles with residue $(−1)^k$ at each integer. > Then by periodicity it follows that $g(z) = \frac{\pi}{sin(\pi z)}$ and we obtain $f$ by differentiating. > > > I honestly have no idea why this argument is right. I can see why $f$ is periodic and its residues are as given but everything from $(\*)$ is not resonating. Any help in understanding this would be great! Thanks
2022/01/12
[ "https://math.stackexchange.com/questions/4355355", "https://math.stackexchange.com", "https://math.stackexchange.com/users/923821/" ]
What you wrote is very odd, it suggests a lot of confusion. First of all this is not a Laurent series, the terminology is "Mittag Leffler expansion". Looking only at the poles and the periodicity is not enough, compare $\frac{\pi^2}{\sin^2(\pi z)}$ with $\frac{\pi^2}{\sin^2(\pi z)}+e^{2i\pi z}-e^{4i\pi z} $ The obvious solution is to say that $$\frac{\pi^2}{\sin^2(\pi z)}-\sum\_n \frac1{(z+n)^2}$$ is a $1$-periodic entire function vanishing as $\Im(z)\to \pm\infty$ on $\Re(z)\in [0,1]$. This implies that it is bounded, constant, and identically zero.
I guess some of the information is not properly copied. This looks to me like the following well known calculation. You start with [Euler's infinite product formula for $\sin$](https://math.stackexchange.com/questions/674769/sinx-infinite-product-formula-how-did-euler-prove-it): $$\frac{\sin(\pi z)}{\pi z} = \prod\_{n = 1}^\infty (1 - \frac{z^2}{n^2})$$ and take $\log$ then $\frac d{dz}$ on both sides to get $$\pi \cot(\pi z) = \frac 1z + \sum\_{n = 1}^\infty\left(\frac1{z - n} + \frac1{z + n}\right).$$ Taking $\frac d{dz}$ again gives $$\frac{\pi^2}{\sin^2(\pi z)} = \sum\_{n = -\infty}^\infty \frac 1{(z + n)^2}.$$ This procedure appears e.g. in GTM 97, *Introduction to Elliptic Curves and Modular Forms*, by Neal Koblitz, in Chapter III, page 110.
685,045
I have a problem with conky. I installed hddtemp and my ssd is shown like this: ``` /dev/sda: Crucial_CT120M500SSD1: 39°C ``` now in conky I wrote: ``` ${alignr 10}${color}SSD M500 Crucial 120GB Temp ${color1}${hddtemp /dev/sda}ºC ``` But desktop shows N/A°C. How can I fix it? Regards
2015/10/13
[ "https://askubuntu.com/questions/685045", "https://askubuntu.com", "https://askubuntu.com/users/423264/" ]
If you don't want to have `hddtemp` running in daemon mode all the time, you could also run `hddtemp` as an external command instead. However, `hddtemp` needs to be run as root: ``` $ hddtemp /dev/sda /dev/sda: open: Permission denied $ sudo hddtemp /dev/sda /dev/sda: ST3500418AS: 35°C ``` So, you will first need to give your user permission to run the command. Run `visudo` and add this line to the `sudoers` file (change `linofex` to your actual username): ``` linofex ALL=NOPASSWD:/usr/sbin/hddtemp ``` That should let you run `sudo hddtemp` without needing to enter a password. Now, replace the line from your `conkyrc` file with: ``` ${alignr 10}${color}SSD M500 Crucial 120GB Temp ${color1}${exec sudo hddtemp /dev/sda | awk '{print $NF}'} ```
You need to first start hddtemp as a background daemon with the commmand: ``` hddtemp -d /dev/sda ``` `${hddtemp ...}` is a conky built-in object. It connects to 127.0.0.1:7634 by default to get the disk temperatures. You therefore need to start, independently, the hddtemp daemon which listens on this port and replies with the information. An alternative is to use `${exec hddtemp /dev/sda}` which runs hddtemp on each window update, and does not need a daemon. --- If you just want the temperature, pipe the output into awk to get the next-to-last field (in my case) ie $(NF-1), or the last field $NF in your case: ``` ${exec hddtemp /dev/sda|awk '{print $NF}'} ```
48,740,658
I am trying to calculate renderRow in listView. actually i need to show index of the row with data. its working fine for subitems but not working for parent. i did like this- ``` render() { return( <ScrollView style={styles.drawer}> <View style={styles.content} key={1}> <ListView dataSource={this.state.dataSource} renderRow={(data) => <View> <Text style={styles.navMenuTop}> {'› '+data.Name} </Text> {data.SubItems.map((b,Index) => <View> <Text style={styles.navMenu} onPress={this.handlePressCatid.bind(this,b.cPath)}> {'» '+b.Name+"=="+Index}</Text> {b.SubItems != undefined && b.SubItems.map((c) => <View> <Text style={styles.navMenu} onPress={this.handlePressCatid.bind(this,c.cPath)}> {'»»»» '+c.Name}</Text> </View> )} </View> )} </View> } /> </View> </ScrollView> ); } } ``` I want to show Index with data.Name . its working properly for b.Name and c.Name. how i can do this?
2018/02/12
[ "https://Stackoverflow.com/questions/48740658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644708/" ]
In my case, I realized that this problem happens with all numbers that has ported from one provider to another. With phone numbers that has never ported Firebase Authentication works like a charm!
1. Update your SHA keys. If your app is in Playstore then you will get new SHA keys from Play Console: release---> app intrigity---> SHAH keys. sometimes they updates their website so it will better to search How to get SHA Keys from play console
106,095
I create a data collection system that has a tree-like structure built on the similarity to the pattern of the factory, and I have the difficulty in working with this structure, more stingrays lot of code to find the element opredelnie. ``` public interface ITag : IRegister { string Name { get; set; } string SystemName { get; } } public interface ISignal : IRegister { } public interface IRegister { Type GetType { get; } } public interface IGroup : IRegister { string Name { get; set; } string SystemName { get; } } public interface IDevice : IRegister { string Name { get; set; } string SystemName { get; } } public interface IServer : IRegister { } public interface INode : IRegister { string Name { get; set; } string SystemName { get; } } [Serializable] public class Server : IServer { public string Name; public string SystemName; public List<INode> Nodes; public Server(string name, List<INode> node) { Name = name; Nodes = node; SystemName = "Server"; } public Type GetType { get { return typeof(Server); } } } [Serializable] public class TCP : INode { public string IPAddress; public int Port; public List<IDevice> Nodes; public string Name { get; set; } public string SystemName { get; } public TCP(string name, string ip, int port, List<IDevice> devices) { Name = name; IPAddress = ip; Port = port; Nodes = devices; SystemName = "Node"; } public TCP() { } public Type GetType { get { return typeof(TCP); } } } [Serializable] public class RTU : INode { public string Name { get; set; } public string SystemName { get; } public string Port; public int SpeedRate; public int DataBits; public int StopBits; public Parity Parity; public List<IDevice> Devices; public RTU(string name, int sr, int db, int sb, Parity par, string port, List<IDevice> devices) { Name = name; Port = port; SpeedRate = sr; StopBits = sb; DataBits = db; Devices = devices; Parity = par; SystemName = "Node"; } public Type GetType { get { return typeof(RTU); } } } [Serializable] public class Device : IDevice { public int Address; public string Name { get; set; } public string SystemName { get; } public List<IGroup> Groups; public Device(int address, string name, List<IGroup> groups) { Address = address; Groups = groups; Name = name; SystemName = "Device"; } public Type GetType { get { return typeof(Device); } } public Type DeviceType(List<IRegister> list ) { return list.GetType(); } } [Serializable] public class Group : IGroup { public List<ITag> Tags; public string Name { get; set; } public string SystemName { get; } public Group(string name, List<ITag> tags) { Tags = tags; Name = name; SystemName = "Group"; } public Type GetType { get { return typeof(Group); ; } } } [Serializable] public class Tag : ITag, IGroup { public ISignal Signal; public TypeData Data; public TypeModbus TypeModbus; //public object Value; //public DateTime Time; public string Name { get; set; } public string SystemName { get; } public Tag(ISignal signal, TypeData data, TypeModbus typeModbus,string n, object value = null) { Signal = signal; Data = data; TypeModbus = typeModbus; //Value = value; //Time = time; Name = n; SystemName = "Tag"; } public Type GetType { get { return typeof(Tag); } } } [Serializable] public class Analog : ISignal { public int Address; public int Address_validaty; public float MinWarning; public float MinEmergency; public float MaxWarning; public float MaxEmergency; public bool Control; public float Coeficient; public float Shift; public bool IsCoeficient; public string MinWText; public string MinEText; public string MaxWText; public string MaxEText; public Type GetType { get { return typeof(Analog); } } } [Serializable] public class Discrete : ISignal { public int Address; public int Address_validaty; public bool IsAutomat; public static ITag Tag = null; public string TrueText; public string FalseText; public Discrete(int ad, int adv, bool isautomat, string ft, string tt, ITag tag = null) { Address = ad; Address_validaty = adv; TrueText = tt; FalseText = ft; IsAutomat = isautomat; if (isautomat) Tag = tag; } public Type GetType { get { return typeof(Discrete); } } } [Serializable] public class Managment : ISignal { public ITag ConnectionRegister; public int Address; public int SecondsReply; public Type GetType { get { return typeof(Managment); } } } ``` In this example I'm using nested loops to find Tag on List which contains the entire structure, and are searching for me to have to use for each node of the structure, and it only renames the item, and there is deletion, search duplicate, overlap, and so on. ``` if(e.Node.Name.Equals("Tag")) { foreach(Server z in List) { foreach(INode node in z.Nodes) { if(node.GetType == typeof(TCP)) { TCP _node = (TCP) node; foreach(Device device in _node.Devices) { IEnumerable<IGroup> d = device.Groups.Where(p => p.GetType == typeof(Group)); foreach(Group group in d) { var n = group.Tags.Where(p => p.Name == e.Node.Text); foreach(ITag tag in n) { tag.Name = newname; } } } } else if(node.GetType == typeof(RTU)) { RTU _node = (RTU) node; foreach(Device device in _node.Devices) { IEnumerable<IGroup> d = device.Groups.Where(p => p.GetType == typeof(Group)); foreach(Group group in d) { var n = group.Tags.Where(p => p.Name == e.Node.Text); foreach(ITag tag in n) { tag.Name = newname; } } } } } } } ``` How can I simplify the search, make it more readable?
2015/09/30
[ "https://codereview.stackexchange.com/questions/106095", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/85693/" ]
I believe the `while()` loops are the best way to accomplish your task with how your code is now, so I'm not sure why you "can't stand" them. You could use a `for()` loop, and `break` out of it using an `if` statement to check the same thing that your `while` loops are doing, but I would prefer the `while` loops myself. --- One other thing I'd like to mention: if your input is always going to be similar to your example you have nothing to worry about, but your code might not work correctly on the following examples: > > Extra line of blank space: > > 1,1,1,1,1,0,0,0,1,1,1,1,1 > > 0,0,0,1,1,0,0,0,1,1,0,0,0 > > 0,0,0,0,0,0,0,0,0,0,0,0,0 > > > > No wall separator before the entrance: > > 1,1,1,1,1,0,0,0,1,1,1,1,1 > > 0,0,0,0,0,0,0,0,1,1,0,0,0 > > > > No wall separator before the entrance #2: > > 0,0,0,1,1,1,1,1,1,1,1,1,1 > > 0,0,0,1,1,1,1,1,1,1,1,1,1 > > > > You'd catch the `ArrayIndexOutOfBounds` exception as an "*unguessable entry*", which I assume is the intentional response - but thought I'd put this here just in case.
I'd go with removing the `try-catch` block. In the `while` conditions you just have to check that `xIndex` is smaller than the array's length. I'd also avoid throwing the `InvalidMazeException` and instead just return a `Point` that cannot exist in any maze, if such a point exists, or `null`, but that's just a preference of mine (I don't like throwing many exceptions and tend to keep them to a minimum, especially if we're talking about checked exceptions, see [here](http://www.ibm.com/developerworks/library/j-jtp05254/) why). ``` public Point guessEntry() throws InvalidMazeException { int openingBorder, closingBorder; int xIndex = 0; final int bottomYIndex = content[0].length-1; try { //Find the wall while (!content[xIndex][bottomYIndex]) xIndex++; //Follow the wall to the entry while (content[xIndex][bottomYIndex]) xIndex++; openingBorder = xIndex; //Follow the entry until the end of it while (!content[xIndex][bottomYIndex]) xIndex++; closingBorder = xIndex; return new Point((closingBorder - openingBorder) / 2, bottomYIndex); } catch(IndexOutOfBoundsException e){ throw new InvalidMazeException("The maze has no guessable entry", e); } } ``` would become something like: ``` public Point guessEntry() { int openingBorder, closingBorder; int xIndex = 0; Point result = null; final int bottomYIndex = content[0].length-1; final int contentLength = content.length; //Find the wall while (xIndex < contentLength && !content[xIndex][bottomYIndex]) xIndex++; //Follow the wall to the entry while (xIndex < contentLength && content[xIndex][bottomYIndex]) xIndex++; openingBorder = xIndex; //Follow the entry until the end of it while (xIndex < contentLength && !content[xIndex][bottomYIndex]) xIndex++; closingBorder = xIndex; if(openingBorder < contentLength && closingBorder < contentLength) result = new Point((closingBorder - openingBorder) / 2, bottomYIndex); return result; } ```
13,270
I would like to write a package offering a number of commands. The package should accept options, and some of these options should be available as command options. Usage should be as follows: ``` ... \usepackage[optA=val1,optB=val2]{mypackage} \begin{document} \mycommand[optB=val3] ... ``` It seems as if the `xkeyval` package can do that, but I am not sure how this should be done exactly.
2011/03/12
[ "https://tex.stackexchange.com/questions/13270", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/3391/" ]
Let me provide a simple (but full) example: ``` \ProvidesPackage{myemph}[2011/03/12 v1.0 a test package] \providecommand\my@emphstyle{\em} % Note that the argument must be expandable, % or use xkvltxp package before \documentclass (see manual of xkeyval) \RequirePackage{xkeyval} \DeclareOptionX{style}{% \def\my@emphstyle{\csname my@style@#1\endcsname}} % predefined styles \providecommand\my@style@default{\em} \providecommand\my@style@bold{\bfseries} \ProcessOptionsX % For simple key-value commands, keyval would suffie \define@key{myemph}{code}{% \def\my@emphstyle{#1}} \define@key{myemph}{style}{% \def\my@emphstyle{\csname my@style@#1\endcsname}} \newcommand\setemph[1]{% \setkeys{myemph}{#1}} \renewcommand\emph[1]{% {\my@emphstyle #1}} \endinput ``` Test file: ``` \documentclass{article} \usepackage[style=default]{myemph} \begin{document} Something \emph{important} \setemph{style=bold} Something \emph{important} \setemph{code=\Large\sffamily} Something \emph{important} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/33nVt.png)
An example with some code from the documentation ``` \NeedsTeXFormat{LaTeX2e} \ProvidesPackage{mypackage}[12/03/2011] \RequirePackage{xkeyval} \DeclareOptionX{parindent}[20pt]{\setlength\parindent{#1}} \ExecuteOptionsX{parindent=0pt} \ProcessOptionsX\relax % etc. \endinput ``` `\DeclareOptionX` is equivalent to (thanks to Ahmed Musa for the correction) ``` \define@key{mypackage.sty}{parindent}[20pt]{\setlength\parindent{#1}} ```
31,014
I have a database of GPS points. There aren't any tracks, only points. I need to calculate some value for every 100 meters, but sometimes GPS gave a wrong coordinates that lies far from real GPS points, and instead of calculating values for a small square, I have to calculate it for a really big rectangular area. What is the best algorithm to filter wrong GPS points? I made a screenshot to help understand: ![![http://content.screencast.com/users/smirnoffs/folders/Jing/media/94624331-db6a-4171-bed9-e2183f953a1d/gps_error.png]](https://i.stack.imgur.com/AoWjW.png)
2012/08/07
[ "https://gis.stackexchange.com/questions/31014", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/9372/" ]
Run Anselin Local Moran's I against the points and throw out anything with a z-score below -1.96. That's a statistical method for locating spatial outliers. You must ensure that all points have a value related to their spatial position to do that. But in checking on the tools in 10.1 after whuber's comment, I realize that if you use ArcGIS 10.1, the grouping analysis tool is available, which is really what you want to do. I -think- you would want to do a grouping analysis with a Delaunay Triangulation spatial constraint. The roadblock here is that you need to have a number of partitioning groups equal to or greater than the number of disconnected groups (if any of the outliers are natural neighbors to each other). Otherwise, outliers with no natural neighbors will come up with no group from the grouping analysis. Based on that, I think Delauney triangulation might be the source of a filter algorithm, but I am not sure yet. Another update: After digging into Partition.py, the script that runs the grouping analysis tool, I think it is possible to use the algorithm in there for disconnected groups combined with the NoNeighbors portion, though I am having trouble digging out that part of the script.
I think you've got junk data. Realistically, if you care about the fact that some of the data is wrong, and you can't reliably identify every wrong point using some other factor, then you're going to have some bad data in your analysis. If that matters, then you should probably consider tossing everything, figuring out the root cause (e.g. the bad GPS points are from multipath), addressing that root cause (e.g. adding a choke antenna, or better type of GPS, or whatever the best fix is), and then redoing the data collection. If the bad data doesn't matter, then just use it and ignore the errors.
9,220,300
I'm new to jquery and am trying to alter an existing page template that uses jquery for a contact form to handle form validation. If the form elements are valid, it submits the data elements to a page that processes it (sends an email). What I'm trying to do is to alter the existing code as I have two additional forms that are on the same page. Essentially, one form is for generating the contact email, a second form contains a couple of elements for submitting a donation request to paypal, and a third form will be similar to the contact email but will contain a few other form elements to provide more info than the standard contact form. There are a couple of pieces to the puzzle. First, there is a file called script.js which contains the following: ``` $(document).ready(function() { // hover $('#menu> li > a strong').css({opacity:0}) $('#menu > li').hover(function(){ $(this).find('> a strong').stop().animate({opacity:1}) }, function(){ if (!$(this).hasClass('active')&&!$(this).hasClass('sfHover')) { $(this).find('> a strong').stop().animate({opacity:0}) } }) $('.list1 .img_act').css({opacity:0, display:'none'}) $('.list1 li').hover(function(){ $(this).find('.img_act').css({display:'block'}).stop().animate({opacity:1}, function(){$(this).css({opacity:'none'})}) }, function(){ $(this).find('.img_act').stop().animate({opacity:0}, function(){$(this).css({display:'none'})}) }) $("a[data-type^='prettyPhoto']").prettyPhoto({animation_speed:'normal',theme:'facebook',slideshow:3000, autoplay_slideshow: false}); $('.lightbox-image').hover(function(){ $(this).find('.play').stop().animate({width:71, height:71, marginTop:-35, marginLeft:-35}) }, function(){ $(this).find('.play').stop().animate({width:51, height:51, marginTop:-25, marginLeft:-25}) }) $('ul#menu').superfish({ delay: 600, animation: {height:'show'}, speed: 600, autoArrows: false, dropShadows: false }); //gallery $("#gallery1").jCarouselLite({ btnNext: ".next", btnPrev: ".prev", mouseWheel: true, visible: 3, vertical: true, speed: 600, easing: 'easeOutCirc' }); $('#gallery1 a').hover(function(){ $(this).find('img').stop().animate({opacity:0.7}) },function(){ $(this).find('img').stop().animate({opacity:1}) }) }); $(window).load(function() { //bg animate $('#bgStretch').bgStretch({ align:'leftTop', navigs:$('#pagination').navigs() }) .sImg({ spinner:$('.spinner').css({opacity:.7}).hide() }) $('#pagination li').eq(0).addClass('active'); // scroll $('.scroll').cScroll({ duration:700, step:63, trackCl:'track', shuttleCl:'shuttle' }) // contact form $('#ContactForm').forms({ ownerEmail:'#' }) // other form $('#OtherForm').forms({ ownerEmail:'#' }) // contact form $('#DonateForm').forms({ ownerEmail:'#' }) // contact form $('#JoinForm').forms({ ownerEmail:'#' }) //content switch var content=$('#content'), nav=$('.menu'); nav.navs({ useHash:true }) nav.navs(function(n, _){ content.cont_sw(n); $('#menu > li').not('.sfHover').find('>a strong').stop().animate({opacity:0}) if (_.n!=-1) { $('#menu > li').eq(_.n).find('>a strong').stop().animate({opacity:1}) } if (_.n==0) { $('#content').stop().animate({height:310}) } else { $('#content').stop().animate({height:510}) } }) content.cont_sw({ showFu:function(){ var _=this $.when(_.li).then(function(){ _.next.css({display:'block', left:-1500}).stop().animate({left:0},600, function(){ }); }); }, hideFu:function(){ var _=this _.li.stop().animate({left:2000},600, function(){ _.li.css({display:'none'}) }) }, preFu:function(){ var _=this _.li.css({position:'absolute', display:'none'}); } }) nav.navs(0); var h_cont=950; function centre() { var h=$(window).height(); if (h>h_cont) { m_top=~~(h-h_cont)/2+12; } else { m_top=12; } $('#content').stop().animate({marginTop:m_top}) } centre(); $(window).resize(centre); }) ``` Then there is a separate file called forms.js which contains the code for the form validation and submission. That's what I'm trying to work with to be able to have my other two forms validated and submitted. Here is the full code for the forms.js (rather than the snippet in the original post): ``` (function($){ $.fn.extend({ forms:function(opt){ if(opt===undefined) opt={} this.each(function(){ var th=$(this), data=th.data('forms'), _={ errorCl:'error', emptyCl:'empty', invalidCl:'invalid', successCl:'success', successShow:'4000', mailHandlerURL:'bin/MailHandler.php', ownerEmail:'support@guardlex.com', stripHTML:true, smtpMailServer:'localhost', targets:'input,textarea', controls:'a[data-type=reset],a[data-type=submit]', validate:true, rx:{ ".employer":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'}, ".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'}, ".state":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'}, ".email":{rx:/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,target:'input'}, ".phone":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'}, ".fax":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'}, ".message":{rx:/.{20}/,target:'textarea'} }, preFu:function(){ _.labels.each(function(){ var label=$(this), inp=$(_.targets,this), defVal=inp.attr('value'), trueVal=(function(){ var tmp=inp.is('input')?(tmp=label.html().match(/value=['"](.+?)['"].+/),!!tmp&&!!tmp[1]&&tmp[1]):inp.html() return tmp })() trueVal!=defVal &&inp.val(defVal=trueVal||defVal) label.data({defVal:defVal}) inp .bind('focus',function(){ inp.val()==defVal &&(inp.val(''),_.hideEmptyFu(label),label.removeClass(_.invalidCl)) }) .bind('blur',function(){ !inp.val() ?inp.val(defVal) :(_.isValid(label) ?_.showErrorFu(label) :_.hideErrorFu(label)), (_.isEmpty(label) ?_.showEmptyFu(label) :_.hideEmptyFu(label)) }) .bind('keyup',function(){ label.hasClass(_.invalidCl) &&_.isValid(label) ?_.showErrorFu(label) :_.hideErrorFu(label) }) label.find('.'+_.errorCl+',.'+_.emptyCl).css({display:'block'}).hide() }) _.success=$('.'+_.successCl,_.form).hide() }, isValid:function(el){ var ret=true, empt=_.isEmpty(el) if(empt) ret=false, el.addClass(_.invalidCl) else $.each(_.rx,function(k,d){ if(el.is(k)) d.rx.test(el.find(d.target).val()) ?(el.removeClass(_.invalidCl),ret=false) :el.addClass(_.invalidCl) }) return ret }, isEmpty:function(el){ var tmp return (tmp=el.find(_.targets).val())==''||tmp==el.data('defVal') }, validateFu:function(){ _.labels.each(function(){ var th=$(this) _.isEmpty(th) ?_.showEmptyFu(th) :_.hideEmptyFu(th) _.isValid(th) ?_.showErrorFu(th) :_.hideErrorFu(th) }) }, submitFu:function(){ _.validateFu() var id=$(this).attr('id'); var action=$(this).attr('action'); if(!_.form.has('.'+_.invalidCl).length) $.ajax({ type: "POST", url:_.mailHandlerURL, data:{ name:$('.name input',_.form).val()||'nope', email:$('.email input',_.form).val()||'nope', phone:$('.phone input',_.form).val()||'nope', fax:$('.fax input',_.form).val()||'nope', state:$('.state input',_.form).val()||'nope', message:$('.message textarea',_.form).val()||'nope', owner_email:_.ownerEmail, stripHTML:_.stripHTML }, success: function(){ _.showFu() } }) }, showFu:function(){ _.success.slideDown(function(){ setTimeout(function(){ _.success.slideUp() _.form.trigger('reset') },_.successShow) }) }, controlsFu:function(){ $(_.controls,_.form).each(function(){ var th=$(this) th .bind('click',function(){ _.form.trigger(th.data('type')) return false }) }) }, showErrorFu:function(label){ label.find('.'+_.errorCl).slideDown() }, hideErrorFu:function(label){ label.find('.'+_.errorCl).slideUp() }, showEmptyFu:function(label){ label.find('.'+_.emptyCl).slideDown() _.hideErrorFu(label) }, hideEmptyFu:function(label){ label.find('.'+_.emptyCl).slideUp() }, init:function(){ _.form=this _.labels=$('label',_.form) _.preFu() _.controlsFu() _.form .bind('submit',function(){ if(_.validate) _.submitFu() else _.form[0].submit() return false }) .bind('reset',function(){ _.labels.removeClass(_.invalidCl) _.labels.each(function(){ var th=$(this) _.hideErrorFu(th) _.hideEmptyFu(th) }) }) _.form.trigger('reset') } } if(!data) (typeof opt=='object'?$.extend(_,opt):_).init.call(th), th.data({cScroll:_}), data=_ else _=typeof opt=='object'?$.extend(data,opt):data }) return this } }) })(jQuery) ``` Most of this was already included in my page template and works fine. I added the following in the script.js file for the two additional forms ``` // Donate form $('#DonateForm').forms({ ownerEmail:'#' }) // join form $('#JoinForm').forms({ ownerEmail:'#' }) ``` I have them working from a validation standpoint. That is to say, they seem to behave properly in the same manner as the original contact form. If you click the button or leave focus of an element you get user feedback indicating the form element is required, for example. But I can't quite figure out how to get them submitted. It seems to me the original code in the forms.js was specifically written to submit the contact form. My first thought was to somehow add an additional evaluation on the form name, with each having it's own url value and set of data values pulled from the form. I just am not sure how to do that being new to jquery. As it stands, my other forms seem to get the validation but nothing happens when I hit the submit button.
2012/02/09
[ "https://Stackoverflow.com/questions/9220300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1200843/" ]
You can use more easily ``` $('form').submit(function(e){ e.preventDefault(); var id=$(this).attr('id'); var action=$(this).attr('action'); if(id=='some_id') { $.ajax({ type: "POST", url:action, data:{...}, success: function(){...} }); } if(id=='something_else') { $.ajax({ type: "POST", url:action, data:{...}, success: function(){...} }); } }); ``` Put this code snippet inside $(document).ready(function(){...}) and give an unique id to each form.
Step one: Name your forms so you can easily retrieve them ``` //example <form id="joebob" name="jimbob" ... // in jquery can be called dynamically as: $("#joebob") //or $("form[name=jimbob]") //or you can create one dnamically var frmJoeBob = $("<form />").attr({ id: "joebob", action: "#smartUrl" }); ``` Step two: I **strongly** suggest you go [here](http://jquery.malsup.com/form/) and add this plugin to your library. * Simply download the js and add it to your header AFTER the jquery script call. * What it does is allow an extremely easy way of *ajaxing* your forms so you can have far more control over what they do and when they do it. > > Example usage > > > ``` // first establish a set of option in object style var formAjaxOptions = { target: $("#SomeOutpuEle"), // this is where return text will be displayed on complete beforeSubmit: function (formData, jqForm, options) { /* Here you can preform work such as form validation before the form is submitted. return false; to stop the form from being submitted. */ }, success: function(responseText, statusText, xhr, $formresponseText, statusText, xhr, $form) { /* Here you can preform work if the ajax call was successful, this doesn't mean the serverside didn't have failures, though. This simply means the ajax call is complete. console.log the vars to get more information on them or see the docs. */ } } // then ajax your form using the plugin with these options as such: $("#joebob").ajaxForm(formAjaxOptions); // then simply grab anything you wanna use as a button and set a click event to submit your form $("span.someButtonAsaSpan").click(function(e) { $("#joebob").submit(); }); ``` See how easy that was? One more note, the options object can also be used (in this plugin) to submit jQuery.ajax options, so once you get more of a hang of what's going on, you can fully customize it however you please!
33,590,402
I'm very new to plsql and am having a bit of trouble with one of my assignments. I've been asked to create a date dimension table and populate it with various date information. I created my table as follows ``` CREATE TABLE date_dimension_table ( v_date DATE NOT NULL, full_date VARCHAR2(50) NOT NULL, day_of_week NUMBER(1,0) NOT NULL, day_in_month NUMBER(2,0) NOT NULL, day_in_year NUMBER(3,0) NOT NULL, last_day_of_week_flag VARCHAR2(1) NOT NULL, last_day_of_month_flag VARCHAR2(1) NOT NULL, end_of_week_date DATE NOT NULL, month_number NUMBER(2,0) NOT NULL, month_name VARCHAR2(32) NOT NULL, year_month CHAR(32) NOT NULL, quarter_number NUMBER(1,0) NOT NULL, year_and_quarter VARCHAR2(32) NOT NULL, v_year NUMBER(4,0) NOT NULL, CONSTRAINT date_dimension_table_PK PRIMARY KEY (v_date) ); ``` I then created the following procedure to populate the table. ``` create or replace PROCEDURE sp_populate_dates( v_first_date_in DATE, v_second_date_in DATE) AS --Declare two variables as DATE datatypes v_current_date DATE; v_end_date DATE; BEGIN --Assign the start date and end date to the variables v_current_date := TO_DATE(v_first_date_in, 'DDMMYYYY'); v_end_date := TO_DATE(v_second_date_in, 'DDMMYYYY'); --Delete whats currently in the table DELETE FROM date_dimension_table; --condition checks if the first date is before the second date WHILE v_current_date <= v_end_date LOOP --insert into table INSERT INTO date_dimension_table ( v_date, full_date, day_of_week, day_in_month, day_in_year, last_day_of_week_flag, last_day_of_month_flag, end_of_week_date, month_number, month_name, year_month, quarter_number, year_and_quarter, v_year ) VALUES ( v_current_date, --date TO_CHAR(v_current_date, 'Day, Month DD, YYYY'), --full date TO_NUMBER(TO_CHAR(v_current_date, 'D')) -1, --day in week TO_CHAR(v_current_date,'DD'), --day in month TO_CHAR(v_current_date,'DDD'), --day in year CASE --last day of week flag WHEN TO_CHAR(v_current_date,'FMDay') = 'Sunday' THEN 'Y' ELSE 'N' END, CASE --last day of month flag WHEN last_day(TO_DATE(v_current_date, 'MM/DD/YYYY')) = TO_DATE(v_current_date, 'MM/DD/YYYY') THEN 'Y' ELSE 'N' END, CASE --date of next sunday WHEN TO_CHAR(v_current_date,'FMDay') = 'Sunday' THEN v_current_date ELSE NEXT_DAY(v_current_date,'SUNDAY') END, TO_CHAR(v_current_date,'MM'), --month number TO_CHAR(v_current_date,'MONTH'), --name of month TO_CHAR(v_current_date,'MONTH YYYY'), --month and year TO_CHAR(v_current_date,'Q'), --number of quarter TO_CHAR(v_current_date,'YYYY Q'), --year and quarter TO_CHAR(v_current_date,'YYYY') --year ); --Increment and assign the current date value to be re-evaluated v_current_date := v_current_date + 1; END LOOP; END; ``` As the program has to insert information from a range of dates, I was using two dates as the input parameters and it was throwing up an error. Example: ``` BEGIN sp_populate_dates(01/01/2005, 01/01/2006); END; ``` I was then getting errors suggesting it was the wrong type of argument to call in the function. I was wondering if anyone could help with this please, and show me where I'm going wrong. Cheers
2015/11/08
[ "https://Stackoverflow.com/questions/33590402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5537908/" ]
First of all, you have procedure that get ``` v_first_date_in DATE, v_second_date_in DATE ``` *DATEs*, but you're trying to pass even not a string. Try something like this ``` BEGIN sp_populate_dates(TO_DATE('01/01/2005', 'dd/mm/yyyy'), TO_DATE('01/01/2005', 'dd/mm/yyyy')); END; ``` another thing is - you process these parameters in the procedure, so you probably wanted to pass varchar2 type variables. That means, ``` create or replace PROCEDURE sp_populate_dates( v_first_date_in IN VARCHAR2, v_second_date_in IN VARCHAR2) ... ``` and call it like ``` BEGIN sp_populate_dates('01/01/2005','01/01/2005'); END; ``` However be careful here: if type of date here is ('dd/mm/yyyy'), your processing date in the procedure ('ddmmyyyy') is not correct. Hope it will help!
You can populate such a table (for the dates between 2000-2030) by using the following query: ``` CREATE TABLE DIM_DATE as ( select TO_NUMBER(TO_CHAR(DATE_D,'j')) as DATE_J, DATE_D, TO_CHAR(DATE_D,'YYYY-MM-DD') as DATE_V, TO_NUMBER(TO_CHAR(DATE_D,'YYYY')) as YEAR_NUM, TO_NUMBER(TO_CHAR(DATE_D,'Q')) as QUARTER_NUM, TO_NUMBER(TO_CHAR(DATE_D,'MM')) as MONTH_NUM, TRIM(TO_CHAR(DATE_D,'Month','nls_date_language=english')) as MONTH_DESC, TO_NUMBER(TO_CHAR(DATE_D,'IW')) as ISO_WEEK_NUM, TO_NUMBER(TO_CHAR(DATE_D,'IYYY')) as ISO_YEAR_NUM, TO_NUMBER(TO_CHAR(DATE_D,'DD')) as DAY_OF_MONTH_NUM, TO_NUMBER(TO_CHAR(DATE_D,'D')) as DAY_OF_WEEK_NUM, TRIM(TO_CHAR(DATE_D,'Day','nls_date_language=english')) as DAY_OF_WEEK_DESC, (CASE WHEN TRIM(TO_CHAR(DATE_D,'Day','nls_date_language=english')) IN ('Saturday','Sunday') THEN 'Weekend' ELSE 'Weekday' END) as DAY_TYPE_DESC from ( select to_date('1999-12-31','YYYY-MM-DD')+ROWNUM as DATE_D from dual connect by level <= to_date('2029-12-31','YYYY-MM-DD')-to_date('1999-12-31','YYYY-MM-DD') ) ); ```
47,547,589
In my application I want use `RecyclerView` and for this I set **multiple layout** in `RecyclerView`. **I changed layouts with button in fragment with below codes:** ``` public class AuctionCurrentFragment extends BaseFragment { @BindView(R.id.recyclerList) RecyclerView recyclerList; private ImageView list_item; private ArrayList countries = new ArrayList<>(); private RecyclerView.Adapter adapter; private Context context; private LinearLayoutManager layoutManager; private boolean clickFlag = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View v = inflater.inflate(R.layout.fragment_auction_current_tab, null); ButterKnife.bind(this, v); context = getActivity(); list_item = getActivity().findViewById(R.id.list_item); recyclerList.setHasFixedSize(true); layoutManager = new LinearLayoutManager(getContext()); recyclerList.setLayoutManager(layoutManager); adapter = new AuctionCurrentRecyclerAdapter(context, countries, 1); initViews(); list_item.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (clickFlag) { adapter = new AuctionCurrentRecyclerAdapter(context, countries, 1); recyclerList.setAdapter(adapter); clickFlag = false; } else { adapter = new AuctionCurrentRecyclerAdapter(context, countries, 2); recyclerList.setAdapter(adapter); clickFlag = true; } } }); return v; } private void initViews() { for (int i = 0; i <= 10; i++) { countries.add("Title " + i); } recyclerList.setAdapter(adapter); } } ``` In one of layouts I use `progressBar` for show **count downer**, but when switch the `layouts` (with button in fragment) when show this layout set start again this count downer! **But I want when switch layouts not start again, continue count downer.** **Adapter codes :** ``` public class AuctionCurrentRecyclerAdapter extends RecyclerView.Adapter { private ArrayList<String> countries; private CountDownTimer countDownTimer; boolean isRunning = false; long timeInMillis; private int timeToEnd; private View view; private int itemLayout = 0; private LayoutInflater mInflater; private Context context; public AuctionCurrentRecyclerAdapter(Context context, ArrayList<String> countries, int itemLayout) { this.context = context; this.countries = countries; this.itemLayout = itemLayout; mInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { switch (itemLayout) { case 1: view = mInflater.inflate(R.layout.list_item_auction_large_new, viewGroup, false); return new LargeViewHolder(view); case 2: view = mInflater.inflate(R.layout.list_item_auction_normal, viewGroup, false); return new NormalViewHolder(view); default: return null; } } @Override public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, int i) { switch (itemLayout) { case 1: ((LargeViewHolder) viewHolder).tv_country.setText(countries.get(i)); break; case 2: ((NormalViewHolder) viewHolder).tv_country.setText(countries.get(i)); break; } } @Override public int getItemViewType(int position) { if (itemLayout == 1) { return 1; } else { return 2; } } @Override public int getItemCount() { return countries.size(); } public class LargeViewHolder extends RecyclerView.ViewHolder { private TextView tv_country, progressTxt; private ProgressBar progressBar; public LargeViewHolder(View view) { super(view); tv_country = (TextView) view.findViewById(R.id.text_view_16962); progressTxt = (TextView) view.findViewById(R.id.progressTxt); progressBar = view.findViewById(R.id.progress); timeToEnd = new Random().nextInt(100); long timeInput = timeToEnd * 1000; timeInMillis = timeInput; progressBar.setMax((int) timeInMillis / 1000); isRunning = true; countDownTimer = new CountDownTimer(timeInMillis, 100) { @Override public void onTick(long millisUntilFinished) { progressTxt.setText("" + String.valueOf(Math.round(millisUntilFinished * 0.001f))); progressBar.setProgress(Math.round(millisUntilFinished * 0.001f)); } @Override public void onFinish() { } }.start(); countDownTimer.start(); } } public class NormalViewHolder extends RecyclerView.ViewHolder { private TextView tv_country; public NormalViewHolder(View view) { super(view); tv_country = (TextView) view.findViewById(R.id.text_view_16962); } } } ``` How can I this ? **But I want when switch layouts not start again, continue count downer.**
2017/11/29
[ "https://Stackoverflow.com/questions/47547589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9024349/" ]
You are creating adapter everytime when you are clicking the listview.Instead Create a method inside you adapter to set the itemlayout ``` public void setItemLayout(int itemLayout){ this.itemLayout = itemLayout; notifyDataSetChanged(); } ``` Inside your onclick method call the setItemLayout method. ``` if(adapter==null){ adapter = new AuctionCurrentRecyclerAdapter(context, countries, 1); recyclerList.setAdapter(adapter); } if (clickFlag) { adapter.setItemLayout(1); clickFlag = false; } else { adapter.setItemLayout(2); clickFlag = true; } ```
``` recyclerView.setHasFixedSize(true); recyclerView.setItemViewCacheSize(50); ``` this worked for me. Recycler view executes only once.
1,685,575
I am aware of [another question](https://stackoverflow.com/questions/1103149/non-greedy-regex-matching-in-sed) that is quite similar, but for some reason I'm still having problems. I have a GC log that I'm trying to *trim out* the Tenured section enclosed in `[]`. ``` 63.544: [GC 63.544: [DefNew: 575K->63K(576K), 0.0017902 secs]63.546: [Tenured: 1416K->1065K(1536K), 0.0492621 secs] 1922K->1065K(2112K), 0.0513331 secs] ``` I apply `s/\[Tenured:.*\]//` And quite expectantly, the result is trimmed *greedily* through the remainder of the line: ``` 63.544: [GC 63.544: [DefNew: 575K->63K(576K), 0.0017902 secs]63.546: ``` So let's try and be non-greedy **not** match a closing right bracket with `s/\[Tenured:[^\]]*\]//` but alas no match is made and sed skips over the line, producing the same original output: ``` 63.544: [GC 63.544: [DefNew: 575K->63K(576K), 0.0017902 secs]63.546: [Tenured: 1416K->1065K(1536K), 0.0492621 secs] 1922K->1065K(2112K), 0.0513331 secs] ``` How do I non-greedily match and replace that section? Thanks,
2009/11/06
[ "https://Stackoverflow.com/questions/1685575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199305/" ]
Almost: s/\[Tenured:[^]]\*\]// The manual says: > > To include a literal ']' in the list, make it the first character > (following a possible '^'). > > > i.e. No backslash is required in this context. * Raz
This worked: ``` echo "63.544: [GC 63.544: [DefNew: 575K->63K(576K), 0.0017902 secs]63.546: [Tenured: 1416K->1065K(1536K), 0.0492621 secs] 1922K->1065K(2112K), 0.0513331 secs]" | sed -e s/\\[Tenured:[^\]]*\\]// ```
3,272,883
The code snippet below works fine, but I'm having a little trouble with the `wait.until()` line: ``` wait.until(new ElementPresent(By.xpath("//a[@title='Go to Google Home']"))); ``` It works but I want to send my `PageFactory` `WebElement` `homePageLink` instead: ``` wait.until(new ElementPresent(homePageLink)); ``` Is there any way to do that? These new fangled Selenium 2 features have got my head in a bit of a spin and I can't find much documentation. Thanks. ``` public class GoogleResultsPage extends TestBase { @FindBy(xpath = "//a[@title='Go to Google Home']") @CacheLookup private WebElement homePageLink; public GoogleResultsPage() { wait.until(new ElementPresent(By.xpath("//a[@title='Go to Google Home']"))); assertThat(driver.getTitle(), containsString("Google Search")); } } public class ElementPresent implements ExpectedCondition<WebElement> { private final By locator; public ElementPresent(By locator) { this.locator = locator; } public WebElement apply(WebDriver driver) { return driver.findElement(locator); } } ```
2010/07/17
[ "https://Stackoverflow.com/questions/3272883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394810/" ]
There was a request for implementation on C#. Here it is: ``` IWebDriver driver = new ChromeDriver(); RetryingElementLocator retry = new RetryingElementLocator(driver, TimeSpan.FromSeconds(5)); IPageObjectMemberDecorator decor = new DefaultPageObjectMemberDecorator(); PageFactory.InitElements(retry.SearchContext, this, decor); ```
AjaxElementLocatorFactory uses SlowLoadableComponent internally. Check the source code [here](http://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/support/pagefactory/AjaxElementLocator.java)
287,507
I just downloaded Electricsheep four days before I updated my Ubuntu software and I fell in love with it. After I upgraded to 13.04, I'm kind of upset in saying that Electricsheep no longer works. I have no idea how to fix it and I feel helpless with Linux. As I said, it was working completely fine in 12.10, but now with the Raring Ringtail update: * I use Xscreensaver to launch Electricsheep. * When I open Xscreensaver, "Electricsheep" is one of the options to choose. * When I "preview" ES or even launch the "xscreensaver-demo" in the terminal, it doesn't work anymore; I get an error message. The error message says: > > "detected another electric sheep process. rendering of sheep is > disabled using read only access." > > > Damnit, can someone please help me? I want my trippy screensaver back, it shouldn't be this hard! EDIT: I contacted the creator of Electricsheep (Scott Draves) via the link to his email address on his personal website and asked for his assistance. Hopefully the Askubuntu community will be able to fix this problem, I'm sure I am not the only one who is having this problem as I have searched and searched.
2013/04/28
[ "https://askubuntu.com/questions/287507", "https://askubuntu.com", "https://askubuntu.com/users/153398/" ]
Here's what I did: 1. Get rid of xscreensaver: apt-get purge xscreensaver 2. Get rid of old electricsheep: apt-get purge electricsheep 3. Reinstall by following these directions precisely: <http://electricsheep.org/node/51> Warning: This install process is why the software center was invented! ;-) It works but it takes quite a few steps. No need for xscreensaver, unless you want to use other modules. Electricsheep installs as a default screen saver with this installation method. Good luck!
I was also unable to get electricsheep to work on 13.04 and 13.10. I tried building the latest version from source using instructions at <http://electricsheep.org/node/51> but this also failed to build due to some wxWidget problems. However, I found a solution which works, but isn't ideal: the windows version works fine under wine. Probably no good for setting it as your screensaver, but if you want to start it manually e.g. along with music in the background, it works fine for me.
6,387,854
I have a table as below; ``` <table> <tr> <td id="prev">prev</td> <td class="content"></td> <td class="content"></td> <td class="content"></td> <td class="content"></td> <td class="content"></td> <td id="next">next</td> </tr> </table> ``` and a PHP file, `ajax.php` for AJAX calls as; ``` <?php $array = array(1,2,3,4,5,6,7,8,9,10); $page = $_POST["page"]; $quantity = 5; $offset = ($page-1)*$quantity; $selectedFiles = array_slice($array, $offset, $quantity); echo $selectedFiles; ?> ``` The PHP function is suppose to return an array with a limited number of elements with respect to `$_POST["page"]` like in pagination. The script will return first 5 elements for `$page = 1`, second 5 elements for `$page = 2`, etc..etc.. When page loads, the `<td>`s having id `content` may display 1,2,3,4 and 5 respectively. When user click `next`, it may display next results and may return to previous result if user click `prev`. How can I do this using JavaScript using jQuery? It will be more helpful if some effect is given when user clicks and data changes, like sliding (transition), so that it will look like sliding some bar.
2011/06/17
[ "https://Stackoverflow.com/questions/6387854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484082/" ]
Save yourself a TON of time. Use a pre-done grid solution like [DataTables](http://www.DataTables.net) that does all this work for you. It allows you to sort, filter, paginate, order, and limit your table results that can be fed via the dom, JSON, or true server-side AJAX. Since DataTables is such a mature project, it has already overcome all the random issues with cross-browser quirks, etc. It also includes a [pre-done PHP example](http://datatables.net/release-datatables/examples/data_sources/server_side.html) with the query done for you. Just change to match your table, and voila!
This should help you get started: ``` <table id="pageLinks"> <tr> <td id="prev">prev</td> <td class="content">1</td> <td class="content">2</td> ... <td id="next">next</td> </tr> </table> var currPage = 1; $("#pageLinks tr td").click(function() { if($(this).hasClass("content")) { var currPage = $(this).text(); } else { if(this.id == "next") { currPage++; } else { if(currPage > 1) currPage--; } } $.post("script.php", {currPage: currPage}, function(html) { $("#someDiv").hide().html(html).slideUp(); }); }); ``` Notes: * IDs should not be duplicated in a document, so I've given those cells the class 'content' instead. * I don't fully understand your question, so I've assumed that the table is for paginated links, and you're loading in the content elsewhere.
7,213,697
good evening, i need to check if the input match my regex or not i use this pattern `'@^[a-zA-Z\@]{3,30}$@is'` ``` <?php if( preg_match('@^[a-zA-Z\@]{3,30}$@is', 'input@input') ){ echo 'matched'; }else{ echo 'no match'; } ?> ``` if i removed the `@` char the regex still return `TRUE` ``` <?php if( preg_match('@^[a-zA-Z\@]{3,30}$@is', 'inputinput') ){ echo 'matched'; }else{ echo 'no match'; } ?> ``` i need to edit the regex so it should contain the `@` char
2011/08/27
[ "https://Stackoverflow.com/questions/7213697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893623/" ]
You can use a look-ahead assertion to assert that: ``` /^(?=[^@]*@)[a-zA-Z@]{3,30}$/is ``` Here the look-ahead assertion `(?=[^@]*@)` ensures that there is at least one `@`.
try this ``` ~^[a-z]?@[a-z@]+$~i ``` If you need only 1 `@` char between a-z blocks you may use ``` ~^[a-z]+@[a-z]+$~i ``` if you want to check full length of string you may use `strlen`, if you want do it for every part separately just replace `+` by `{mincnt,maxcnt}`
7,200,281
> > **Possible Duplicate:** > > [How do you close/hide the Android soft keyboard programmatically?](https://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard) > > > First thing first I already saw [this](https://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard) thread. I tried the accepted methods given there, but nothing worked for me. I have two screens in my app. * First one has 2 EditText - One for username and one for password * Second one have one ListView, and an EditText - to filter the listView **In my first screen, I want username EditText to have focus on startup and the Keyboard should be visible**. This is my implementation (simplified by removing unnecessary/unrelated code). #app\_login.xml ``` <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="20dip" android:paddingRight="20dip"> <EditText android:id="@+id/username" android:singleLine="true" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Username" android:imeOptions="actionDone" android:inputType="text" android:maxLines="1"/> <EditText android:id="@+id/password" android:password="true" android:singleLine="true" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Password" /> </LinearLayout> ``` #AppLogin.java ``` class AppLogin extends Activity{ private EditText mUserNameEdit = null; private EditText mPasswordEdit = null; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.app_login); mUserNameEdit = (EditText) findViewById(R.id.username); mPasswordEdit = (EditText) findViewById(R.id.password); /* code to show keyboard on startup.this code is not working.*/ InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT); }//End of onCreate() } ``` Well, **the keyboard is not showing at startup**. And my design badly requires a keyboard there. Now on to **second page**. As I already mentioned, I have a listView and EditText there. **I want my keyboard to be hidden on startup only to appear when the user touches the editText**. Can you believe it? whatever I tried **soft Keyboard is showing when I load the activity**. I am not able to hide it. #app\_list\_view.xml ``` <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/filter_edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Search" android:inputType="text" android:maxLines="1"/> <ListView android:id="@id/android:list" android:layout_height="fill_parent" android:layout_weight="1.0" android:layout_width="fill_parent" android:focusable="true" android:descendantFocusability="beforeDescendants"/> </LinearLayout> ``` #AppList.java ``` public class MyListActivity extends ListActivity{ private EditText mfilterEditText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.app_list_view); mFilterEditText = (EditText) findViewById(R.id.filter_edittext); InputMethodManager imm = InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mFilterEditText.getWindowToken(), 0); } } ``` To simplify 1. On Login Page (first Page) I want my keyboard to be visible on startup. 2. On SecondPage I want the keyboard to be hidden first, only to appear when the user touches editText **And my problem is I am getting the exact opposite on both occasions**. Hope someone faced this issue before. BTW I am testing on the simulator and HTC Desire phone. #FINAL OUTCOME Well, I got it working, with the help of all my friends here. **1. To Show keyboard on startup** Two answers worked for me. **One provided by @CapDroid, which is to use a handler and post it delayed..** ``` mUserNameEdit.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub InputMethodManager keyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.showSoftInput(mUserNameEdit, 0); } },50); ``` The second answer is provided by @Dyarish, In fact, he linked to another SOF thread, which I haven't seen before. But the funny thing is that this solution is given in the thread which I referenced at the start. And I haven't tried it out because it had zero votes in a thread where all other posts have plenty of votes. Height of foolishness. ``` getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ``` For me, the second solution looked neat, so I decided to stick with it..But the first one certainly works. Also, @Dyarish's answer contains a clever hack of using a ScrollView below EditText to give EditText the focus. But I haven't tried it, but it should work. Not neat though. **2. To hide keyboard at activity start** Only one answer worked for me, which is provided by @Dyarish. And the solution is to use focusableInTouchMode settings in XML for the layout containing the EditTexts. This did the trick ``` <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:focusableInTouchMode="true"> <EditText android:id="@+id/filter_edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Search" android:inputType="text" android:maxLines="1"/> <ListView android:id="@id/android:list" android:layout_height="fill_parent" android:layout_weight="1.0" android:layout_width="fill_parent" android:focusable="true" android:descendantFocusability="beforeDescendants"/> </LinearLayout> ``` Anyway, I end up using Dyarish's answer in both cases. So I am awarding the bounty to him. Thanks to all my other friends who tried to help me.
2011/08/26
[ "https://Stackoverflow.com/questions/7200281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/640731/" ]
Try this code. For showing Softkeyboard: ``` InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if(imm != null){ imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); } ``` For Hiding SoftKeyboard - ``` InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if(imm != null){ imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); } ```
Did you try `InputMethodManager.SHOW_IMPLICIT` in first window. and for hiding in second window use `InputMethodManager.HIDE_IMPLICIT_ONLY` **EDIT :** If its still not working then probably you are putting it at the wrong place. Override `onFinishInflate()` and show/hide there. ``` @override public void onFinishInflate() { /* code to show keyboard on startup */ InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT); } ```
1,793,411
What's the advantage, for someone who is not a theoretical computer scientist, of learning a purely functional language like Haskell or Erlang instead of an "impure" language with a strong functional component, like Python or version 2 of the D programming language? My arguments are as follows: 1. No paradigm is perfect. Languages that are single-paradigm, regardless of what paradigm that is, are very restrictive. 2. Python or D will ease you into functional programming while you get real work done. Haskell or Erlang will force you to learn functional style all at once before you can actually do anything of interest in them. Edit: By "impure" functional languages, what I really mean is strongly multiparadigm languages w/ a functional flavor, not strongly functional languages with some non-functional abilities.
2009/11/24
[ "https://Stackoverflow.com/questions/1793411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23903/" ]
Is Erlang purely functional? I honestly thought it wasn't. I'm not an expert on this, so take my words with a grain of salt. Side-effects prevent (or make more complicated) lots of optimizations, including parallelism. So, in theory, going pure functional should mean better optimization for faster code, although I'm not sure this is true in practice. Even if it does not, it might someday be... it will be fun if a purely functional language comes along which makes using up all the cores easy peasy. Additionally, in a way, programming without side-effects makes for easier to understand programs.
Because [only pure is declarative](https://stackoverflow.com/questions/602444/what-is-functional-declarative-and-imperative-programming/15382180#15382180) at the operational semantics level. Pure functional programming (i.e. eliminating accidental dependencies) is [required for parallelism](http://existentialtype.wordpress.com/2011/03/17/parallelism-is-not-concurrency/). Also, without the immutability restriction, you won't be forced to think about how to do algorithms just [as fast as they can be done in imperative](https://stackoverflow.com/questions/1255018/n-queens-in-haskell-without-list-traversal/7194832#7194832), or how to model interaction with the real world without state spaghetti, using functional reactive programming. Thus you won't be maximizing your skills for writing code that is maximally composable and extensible.
7,213,927
I use rspec, devise and cancan at the moment. To be honest, I find cancan to be very confusing and I am encountering a lot difficulties in picking it up and using it effectively. The docs are not very in depth making this extremely difficult for me to debug (check my past questions). Is there an alternative to CanCan that's also easily integratable in the other tools I am using?
2011/08/27
[ "https://Stackoverflow.com/questions/7213927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140330/" ]
Some guys are continuing the development of cancan. Check it out: <https://github.com/CanCanCommunity/cancancan>
I'd recommend [Action Access](//github.com/matiasgagliano/action_access), it's much simpler and straightforward, has seamless integration with Rails and it's very lightweight. It boils down to this: ``` class ArticlesController < ApplicationController let :admin, :all let :user, [:index, :show] # ... end ``` This will automatically lock the controller, allowing admins to access every action, users only to show or index articles and anyone else will be rejected and redirected with an alert. If you need more control, you can use `not_authorized!` inside actions to check and reject access. This makes controllers to be self contained, everything related to the controller is within the controller. This also makes it very modular and avoids leaving forgotten trash anywhere else when you refactor. It's completely **independent** of the authentication system and it can work without `User` models or predefined roles. All you need is to set the clearance level for the current request: ``` class ApplicationController < ActionController::Base def current_clearance_level session[:role] || :guest end end ``` You may return whatever your app requires, like `current_user.role` for example. It also bundles a set of handy model additions that allow to extend user models and do things like: ``` <% if current_user.can? :edit, :article %> <%= link_to 'Edit article', edit_article_path(@article) %> <% end %> ``` Here `:article` refers to `ArticlesController`, so the link will only be displayed if the current user is authorized to access the `edit` action in `ArticlesController`. It supports **namespaces** too. It allows to lock controllers by default, customize the redirection path and the alert message, etc. Checkout the [documentation](https://github.com/matiasgagliano/action_access#action-access) for more.
54,905,561
I try to make a grep like on a PDL matrix or array of Vector : ``` my @toto; push(@toto, pdl(1,2,3)); push(@toto, pdl(4,5,6)); my $titi=pdl(1,2,3); print("OK") if (grep { $_ eq $titi} @toto); ``` I also tried ``` my @toto; push(@toto, pdl(1,2,3)); push(@toto, pdl(4,5,6)); my $titi=pdl(1,2,3); print("OK") if (grep { $_ eq $titi} PDL::Matrix->pdl(\@toto)); ``` None works. Any help Please
2019/02/27
[ "https://Stackoverflow.com/questions/54905561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3752927/" ]
The way to do this efficiently, in a way that scales, is to use [PDL::VectorValued::Utils](https://metacpan.org/pod/PDL::VectorValued::Utils#vv_intersect), with two ndarrays (the "haystack" being an ndarray, not a Perl array of ndarrays). The little function `vv_in` is not shown copy-pasted into the `perldl` CLI because it would be less copy-pastable from this answer: ``` sub vv_in { require PDL::VectorValued::Utils; my ($needle, $haystack) = @_; die "needle must have 1 dim less than haystack" if $needle->ndims != $haystack->ndims - 1; my $ign = $needle->dummy(1)->zeroes; PDL::_vv_intersect_int($needle->dummy(1), $haystack, $ign, my $nc=PDL->null); $nc; } pdl> p $titi = pdl(1,2,3) [1 2 3] pdl> p $toto = pdl([1,2,3], [4,5,6]) [ [1 2 3] [4 5 6] ] pdl> p $notin = pdl(7,8,9) [7 8 9] pdl> p vv_in($titi, $toto) [1] pdl> p vv_in($notin, $toto) [0] ``` Note that for efficiency, the `$haystack` is required to be sorted already (use `qsortvec`). The `dummy` "inflates" the `$needle` to be a vector-set with one vector, then `vv_intersect` returns two ndarrays: * either the intersecting vector-set (which would always be a single vector here), or a set of zeroes (probably a shortcoming of the routine, it should instead be `vectorlength,0` - an empty ndarray) * the quantity of vectors found (here, either 0 or 1) The "internal" (`_vv_intersect_int`) version is used because as of PDL::VectorValued 1.0.15, it has some wrapping Perl code that does not permit broadcasting (an [issue](https://github.com/moocow-the-bovine/PDL-VectorValued/issues/4) has been filed). Note `vv_in` will "broadcast" (formerly known, confusingly, as "threading") over multiple sets of input-vectors and input-haystacks. This could be used to search for several vectors: ``` sub vv_in_multi { my ($needles, $haystack) = @_; die "needles must have same number of dims as haystack" if $needles->ndims != $haystack->ndims; vv_in($needles, $haystack->dummy(-1)); } pdl> p vv_in_multi(pdl($titi,$notin), $toto) [1 0] ```
You can use [`eq_pdl`](https://metacpan.org/pod/Test::PDL#eq_pdl) from [`Test::PDL`](https://metacpan.org/pod/Test::PDL): ``` use PDL; use Test::PDL qw( eq_pdl ); my @toto; push(@toto, pdl(1,2,3)); push(@toto, pdl(4,5,6)); my $titi = pdl(4,5,6); print("OK\n") if (grep { eq_pdl( $_, $titi) } @toto); ``` **Output**: ``` OK ```
56,618,684
I have a text file named Profile.txt which is in key:value pair form. For ex: ``` Name: ABC Father's Name: XYZ DOB: 11-11-2011 ``` How do I access value ABC by key Name so I could store it in database? Here's the code: ``` <?php $my_file = fopen('../img/uploads/ABC_1/Profile.txt' ,"r"); $content = file_get_contents('../img/uploads/ABC_1/Profile.txt'); echo $content; fclose($my_file); ?> ```
2019/06/16
[ "https://Stackoverflow.com/questions/56618684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9639887/" ]
You could try jQuery `.after()` Instead of : `document.getElementById('output').innerHTML += `<p>${message}</p>`;` try: `$('#typing-indicator').after(`<p>${message}</p>`)` ref: <http://api.jquery.com/after/> ```js function send(){ var message = document.getElementById('input').value; $('#typing-indicator').after(`<p>${message}</p>`); $('#output').scrollTop(); } ``` ```css #output{ overflow: auto; height: 150px; background-color: red; } #typing-indicator{ height: 15px; background-color: green; } ``` ```html <script src="https://code.jquery.com/jquery-3.1.0.js"></script><div id="output"> <div id="typing-indicator"></div> </div> <input id="input"/> <button id="send" onclick="send()">SEND</button> ```
so you send function has to be as following ``` function send(){ var p = document.createElement("p"); // Create a <button> element p.innerHTML = document.getElementById('input').value;; document.getElementById('output').insertBefore(p,document.getElementById('typing-indicator')) ; document.getElementById('output').scrollTop = output.scrollHeight; } ``` in this function you create you `p` element then inject it before `<div id="typing-indicator"></div>` element using `insertBefore` that inject element before another element you can check its documentation from the following [link](https://www.w3schools.com/jsref/met_node_insertbefore.asp)
14,583,761
I have defined a class in a file named `Object.py`. When I try to inherit from this class in another file, calling the constructor throws an exception: ``` TypeError: module.__init__() takes at most 2 arguments (3 given) ``` This is my code: ``` import Object class Visitor(Object): pass instance = Visitor() # this line throws the exception ``` What am I doing wrong?
2013/01/29
[ "https://Stackoverflow.com/questions/14583761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1955240/" ]
Your error is happening because `Object` is a module, not a class. So your inheritance is screwy. Change your import statement to: ``` from Object import ClassName ``` and your class definition to: ``` class Visitor(ClassName): ``` **or** change your class definition to: ``` class Visitor(Object.ClassName): etc ```
In my case where I had the problem I was referring to a module when I tried extending the class. ``` import logging class UserdefinedLogging(logging): ``` If you look at the Documentation Info, you'll see "logging" displayed as module. In this specific case I had to simply inherit the logging module to create an extra class for the logging.
8,825,030
I'm wondering how I can extract (get a copy) of the Default Template of a given control using Visual Studio. I know this can be done with Expression Blend (right click a control, "Edit Template" -> "Edit a Copy...") which then copies the default control template in my Xaml. But can this be done with Visual Studio at all?
2012/01/11
[ "https://Stackoverflow.com/questions/8825030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257558/" ]
One thing to keep in mind: if you already have a style defined somewhere that targets the given control then all of the above described options will be disabled. I had the following bit of code in my App.xaml file: ``` <Application.Resources> <Style TargetType="Button"> <Setter Property="IsTabStop" Value="False"/> </Style> </Application.Resources> ``` I was pulling my hair out trying to figure out why the `edit a copy...` and `convert to new resource...` options described in the other answers were disabled for my Button (which was defined in a completely different file). I commented out the above style code for Button and suddenly both options weren't disabled anymore. Moral of the story: *VS won't generate a style containing a template copy for you if a style already exists for that element anywhere in your code.*
As far as I know it's not possible. However, you can use [Show Me The Template](http://www.sellsbrothers.com/posts/details/2091) to view the default template for a given control.
51,457,921
I'm trying to connect my phone to Android Studio to follow up with some app development. I am currently struggling with connecting my phone to the computer properly, as ADB never seems to connect to the device. When attempting to boot the app on the device, this is what Android Studio tells me in the run console ``` com.android.ddmlib.AdbCommandRejectedException: device still connecting Error while Installing APK ``` Which leads me to think that this is a problem with ADB. So when I run `adb devices` I get this log: ``` List of devices attached 5210a780f48b44c5 connecting ``` It stays in the "connecting" state no matter how long I wait. I accepted USB debugging and file transfer. When in Android studio, the device is listed as [![enter image description here](https://i.stack.imgur.com/ttGM9.png)](https://i.stack.imgur.com/ttGM9.png) I'm out of ideas as to how to fix this. I recently updated my phone (Samsung A5) to Android 8.0. This phone connects and debugs fine on my work computer. I tried updating Android Studio, rebooting my computer, installing Samsung drivers, rebooting my phone, revoking debug access, to no avail. I was able to work on this computer a while back but I don't know what changed. How can I fix this problem so I can debug on my device? [EDIT] `adb version` shows this ``` Android Debug Bridge version 1.0.40 Version 4797878 Installed as C:\Users\Frederic\AppData\Local\Android\sdk\platform-tools\adb.exe ```
2018/07/21
[ "https://Stackoverflow.com/questions/51457921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535257/" ]
A friend told me to try to swap ports to a USB 2.0 instead of USB 3.0. After doing so it worked instantly as expected. [EDIT] It appears that this has more to do with the capabilities of the motherboard than the version of USB the port is. The opposite might be true for you, or just any other port.
I had the same problem and found that the issue was solved by switching off USB debugging on the device, then switching it on again.
13,169,298
I can do this to search the Table for emails. ``` // controller method public function forgot_password() { if ($this->Session->read('Auth.User')) { $this->redirect(array('action' => 'add')); } else { if ($this->request->is('post') || $this->request->is('put')) { $user = $this->User->findByEmail($this->request->data('User.email')); if ($user) { $this->request->data['User']['id'] = $user['User']['id']; $this->request->data['User']['random_string'] = $this->String->random(); unset($this->request->data['User']['email']); $this->User->save($this->request->data); // $this->_sendEmail($user); $this->Session->setFlash(__('Instructions has been sent to your email'), 'flash'); $this->redirect(array('action' => 'forgot_password')); } else { // passed! do stuff } } } } // validate in the model public $validate = array( 'email' => array( 'required' => array( 'rule' => array('notEmpty'), 'message' => 'An Email is required' ), 'email' => array( 'rule' => array('email'), 'message' => 'Email is invalid' ), 'isUnique' => array( 'rule' => array('isUnique'), 'message' => 'Email is already in use' ) ), 'password' => array( 'required' => array( 'rule' => array('notEmpty'), 'message' => 'A password is required' ) ), 'role' => array( 'valid' => array( 'rule' => array('inList', array('admin', 'author')), 'message' => 'Please enter a valid role', 'allowEmpty' => false ) ) ); ``` The above code works fine. I was just thinking to validate if the email is a valid email or empty before even querying the database. I came up with the one below. The problem I have is that setting User with `$this->request->data`. Whenever I validate, it runs through the isUnique rule and fails. ``` public function forgot_password() { if ($this->Session->read('Auth.User')) { $this->redirect(array('action' => 'add')); } else { if ($this->request->is('post') || $this->request->is('put')) { $this->User->set($this->request->data); if ($this->User->validates()) { $user = $this->User->findByEmail($this->request->data('User.email')); if ($user) { $this->request->data['User']['id'] = $user['User']['id']; $this->request->data['User']['random_string'] = $this->String->random(); unset($this->request->data['User']['email']); $this->User->save($this->request->data); // $this->_sendEmail($user); $this->Session->setFlash(__('Instructions has been sent to your email'), 'flash'); $this->redirect(array('action' => 'forgot_password')); } } } } } ``` Has someone done a solution similar to what I want?
2012/11/01
[ "https://Stackoverflow.com/questions/13169298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37532/" ]
You could do this from your controller. ``` App::uses('Validation', 'Utility'); if (Validation::email($this->request->data('User.email'))) { ... } ```
I agree with @Dave that you're not quite clear about what you are trying to do. First your access of the request data should probably be $this->request->data['User']['email']; if you are posting data in the standard form helper format. I'm pretty sure that model validation would fail before querying the database in your save call if the value is empty or the email rule fails. Since notEmpty is the first rule, it would be checked by the validation utility prior to querying the database. If it failed, then the field would be skipped and no db call made (as long as 'last' does not equal false. Same applied to the email rule since cake uses a regex pattern for that rule. You can follow the chain of events by reviewing the save function in Model.php. If not empty and email rules pass, the eventually you would have to query the db to find if the address already exists.
244,957
I want to get a list of products from only pending orders! i have this is code but works only for register customers i need to show product for all orders even for guests and multi store. ``` <?php require_once 'app/Mage.php'; Mage::app(); //Get All Users/Customers $users = mage::getModel('customer/customer')->getCollection() ->addAttributeToSelect('*'); foreach ($users as $user){ $customer_id = $user['entity_id']; //Get the all orders by customer id $order_collection = Mage::getResourceModel('sales/order_collection') ->addFieldToSelect('*') ->addFieldToFilter('customer_id',$customer_id) ->addFieldToFilter('status', array('in' => array('pending'))) ->setOrder('created_at', 'desc'); foreach($order_collection as $orders) { echo $increment_id = $orders['increment_id']."</br>"; $order_id = $orders['entity_id']; //Get all items for the order id $order = Mage::getModel('sales/order')->load($order_id); $items = $order->getAllItems(); foreach($items as $i) { echo $i->getName()."</br>"; } echo "</br>"; } } ?> ```
2018/10/03
[ "https://magento.stackexchange.com/questions/244957", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/65887/" ]
This issue is particularly related to the optional parameter that you are setting in the `public function __construct`. In this particular case the original constructor parameters are like this (which is incorrect and not allowed anymore): ``` public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Model\ResourceModel\AbstractResource $resource= null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection= null, \Sugarcode\Test\Model\Total\FeeFactory $feeFactory, array $data = array() ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_feeFactory = $feeFactory; } ``` The correct way is to include all the optional parameters in the last: ``` public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Sugarcode\Test\Model\Total\FeeFactory $feeFactory, \Magento\Framework\Model\ResourceModel\AbstractResource $resource= null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection= null, array $data = array() ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_feeFactory = $feeFactory; } ``` Let me know if it helps.
Please replace your this "Sugarcode/Test/Model/Total/Fee.php" model file function \_construct. ``` protected function _construct() { $this->_init('Sugarcode\Test\Model\ResourceModel\Fee'); } ``` and check after that.
746,525
I have seen this character a number of times in CSS files but I have no idea how its used. Can anyone explain it to me and show how they are useful in making a page style easier?
2009/04/14
[ "https://Stackoverflow.com/questions/746525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59730/" ]
``` p em ``` will match any `<em>` that is within a `<p>`. For instance, it would match the following `<em>`s: ``` <p><strong><em>foo</em></strong></p> <p>Text <em>foo</em> bar</p> ``` On the other hand, ``` p > em ``` Will match only `<em>`s that are immediate children of `<p>`. So it will match: ``` <p>Text <em>foo</em> bar</p> ``` But not: ``` <p><strong><em>foo</em></strong></p> ```
this is known as a Child Combinator: > > A child combinator selector was added > to be able to style the content of > elements contained within other > specified elements. For example, > suppose one wants to set white as the > color of hyperlinks inside of div tags > for a certain class because they have > a dark background. This can be > accomplished by using a period to > combine div with the class resources > and a greater-than sign as a > combinator to combine the pair with a, > as shown below: > > > ``` div.resources > a{color: white;} ``` (from <http://www.xml.com/pub/a/2003/06/18/css3-selectors.html>)
162,458
$$\ce{MnS + 2HCl -> MnCl2 + H2S}$$ If oxidation and reduction is taken to be the **loss of hydrogen** and the **gain of hydrogen** respectively, then I can see how the aforementioned reaction is redox — $\ce{S}$ gains hydrogen and is therefore reduced while $\ce{Cl}$ loses it, and hence is oxidized. But how can this be explained in terms of **electron transfer?** The oxidation state of every atom seems to be unchanged, which should mean that no reduction or oxidation has taken place: $$\ce{\overset{\color{blue}{(2+)}}{Mn}\overset{\color{red}{(2-)}}{S} + \overset{\color{orange}{(+)}}{2H}\overset{(-)}{Cl} -> \overset{\color{blue}{(2+)}}{Mn}\overset{(-)}{Cl\_2} + \overset{\color{orange}{(+)}}{H\_2}\overset{\color{red}{(2-)}}{S}}$$
2022/01/23
[ "https://chemistry.stackexchange.com/questions/162458", "https://chemistry.stackexchange.com", "https://chemistry.stackexchange.com/users/108921/" ]
> > If oxidation and reduction is taken to be the loss of hydrogen and the gain of hydrogen respectively... > > > The loss of hydrogen is oxidation in cases of homolytic breaking the bond with hydrogen when the electron goes away with the proton. Heterolytic losing hydrogen ion(=hydrated proton), when the electron stays, is not oxidation, but acid dissociation. The former case leads to change in [oxidation number/state](https://en.wikipedia.org/wiki/Oxidation_state), the latter does not. E.g. $\ce{CH4 + O2 -> C + 2H2O}$ **is** oxidation, as carbon is oxidized from the oxidation state -IV to 0. Exchanging an acidic hydrogen and a ion of an electropositive metal between some acid and salt (i.e. the metal keeps its oxidation state) in cases like above: $$\ce{MX\_n + n HA -> n HX + MA\_n}$$ does not change oxidation states of elements in involved compounds. Therefore conversion $$\ce{MnS + 2HCl -> MnCl2 + H2S}$$ is not a redox reaction, as Mn keeps the oxidation state +II, sulphur -II hydrogen +I and chlorine -I.
Oxidation state involves a counting of valence electrons, so you have to look at whether and how electrons are transferred between atoms, not how the atoms themselves are transferred. Follow the definitions given by the IUPAC Gold Book for all species: [Oxidation](https://goldbook.iupac.org/terms/view/R05222): > > 1. The complete, net removal of one or more electrons from a molecular entity (also called 'de-electronation'). > 2. An increase in the oxidation number of any atom within any substrate > 3. Gain of oxygen and/or loss of hydrogen of an organic substrate. > > > (Hydrogen and ixygen are understood to be neutral species, not hydrogen or oxide ions, in the organic chemistry definition.) [Reduction](https://goldbook.iupac.org/terms/view/R05222): > > The complete transfer of one or more electrons to a molecular entity (also called 'electronation'), and, more generally, the reverse of the processes described under oxidation (2) and (3). > > > It is true that the transfer of *neutral* hydrogen atoms (implied in definition 3 for oxidation given above) provides a way to transfer electrons because each hydrogen atom picks up an electron, or perhaps leaves one behind if it is initially bound to an electropositive element, as it gets transferred. But here that mechanism does not apply because the hydrogen is transferred as *ions*, and the ions do not pick up or drop off any electrons as they move from $\ce{HCl}$ (or its dissociated solvated hydrogen ions) into $\ce{H2S}$.
7,589,528
I have two buttons in a row and they are shown in two td's, and its not lined up correctly in IE, I doubt that hidden spaces(&nbsp) in the td's somewhere mayby after the input or before the input button, unfortunately I cant access the html code, its automatically generated. The only way is to control by using jQuery I have a jQuery something like this.. ``` $("td:contains('&nbsp;')").css("display", "none"); ``` Is this a right way to get rid of that &nbsp in the td?
2011/09/28
[ "https://Stackoverflow.com/questions/7589528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/852602/" ]
Rather than answering the OP's specific scenario, if we take the question title ("Is it possible to remove '&nbsp' using JQuery..?") and answer this in a general way (which I think is useful), then any answers using `.html()` have one fundamental flaw: replacing the html this way also removes any data and event handlers associated with the old html - not desirable! It may work for the OP's specific scenario, but I think it's useful to answer the question in a more general way... The better way is to replace the `.textContent` of individual text nodes within the element. So given the following markup: ``` <div class="container"> &nbsp;<a href="www.google.com">Here is a link &nbsp;</a> <p>Here is a paragraph with another link inside: <a href="www.facebook.com">&nbsp;&nbsp;another link&nbsp;</a>&nbsp;</p> And some final text &nbsp;&nbsp;&nbsp;&nbsp; </div> ``` We can remove all `&nbsp;` (which is unicode `\u00A0` - see more about this [here](https://stackoverflow.com/a/27028621/422845)) like so: ``` $('.container, .container *').contents().each(function() { if (this.nodeType === 3) { // text node this.textContent = this.textContent.replace(/\u00A0/g, ''); } }); ``` `$('.container, .container *')` selects the container and all elements inside it, then [`.contents()`](https://api.jquery.com/contents/) selects all the children of those elements, including text nodes. We go through each of those nodes, and for every text node we encounter (`nodeType === 3`), we replace the `&nbsp;` (`\u00A0`) with an empty string.
try this ``` $('#div').text($('#div').text().replace(/&nbsp;/g, ' ')); ```
800,094
I've noticed that various services for this IP 85.222.136.21 returns different AS numbers. For example, <http://bgp.he.net/ip/85.222.136.21#_ipinfo> says `AS14340`, while on the Whois section, there it says `AS15982`. Why is that? I've also asked my friend from different continent to run a traceroute with AS number resolution and he got AS14340, while on my machine it resolve to AS15982.
2016/08/30
[ "https://serverfault.com/questions/800094", "https://serverfault.com", "https://serverfault.com/users/188319/" ]
[`dig`](http://linux.die.net/man/1/dig) (domain information groper) as the manual explains, is a flexible tool **for interrogating DNS name servers**, it does not query or use your local DNS cache (and/or `hosts` file) but directly queries the name server you point it at. By default that will be the one(s) from `/etc/resolv.conf`. To use your systems DNS cache from the command line use `getent hosts [ip-address | hostname]` or in scripts/code use a native version of the `man 3 gethostbyname` system call. Admittedly that does not help your with anything else beyond `A` `AAAA` or `PTR` records. --- In `dig` output the SERVER label is ip-address of the name **server** `dig` uses, which will never have a TTL... ``` dig ANY www.google.com ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.47.rc1.el6 <<>> www.google.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 27695 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 4 ;; QUESTION SECTION: ;www.google.com. IN A ;; ANSWER SECTION: www.google.com. 173 IN A 216.58.212.132 ;; AUTHORITY SECTION: google.com. 146915 IN NS ns2.google.com. google.com. 146915 IN NS ns3.google.com. google.com. 146915 IN NS ns1.google.com. google.com. 146915 IN NS ns4.google.com. ;; ADDITIONAL SECTION: ns2.google.com. 145115 IN A 216.239.34.10 ns1.google.com. 145115 IN A 216.239.32.10 ns3.google.com. 145115 IN A 216.239.36.10 ns4.google.com. 145115 IN A 216.239.38.10 ;; Query time: 0 msec ;; SERVER: 127.0.0.1#53(127.0.0.1) <========== My Name SERVER is localhost ;; WHEN: Tue Aug 30 22:51:26 2016 ;; MSG SIZE rcvd: 184 ``` I run my own caching DNS server locally rather than using an ISP's or Google's public resolver (8.8.8.8) mainly for spamassassin, which has the advantage of being local, but the cache doesn't get pre-seeded/populated by other users either.
This is really an OS resolver question at its heart, but you did not specify the operating system. Since `dig` is mentioned, I'm going to assume that we're working with some flavor of UNIX here. UNIX based operating systems do not implement a DNS cache within the kernel itself. There are a few topics that need to be summarized before we get into how it's actually implemented. NSS --- Calls to the resolver library typically implement their lookups using Name Service Switch (NSS), a modular system for specifying data sources to use and the order in which they are looked up. You can find a list of these module stacks in `/etc/nsswitch.conf`. For reference, the one we're concerned with here is `hosts`. It is not recommended to play with the `hosts` entry in `/etc/nsswitch.conf` unless you really know what you're doing. Reordering these modules can result in funky things like DNS consulted before the `/etc/hosts` file! nscd ---- Prior to consulting the module stack, NSS checks for the presence of a running `nscd` socket and attempts to query it. If `nscd` is configured to maintain a cache for the NSS database in question, it's possible that an entry cached by `nscd` will be returned without the NSS modules being consulted. Most Linux distros that I know of *do not* enable caching of the `hosts` database by default, and `/etc/nscd.conf` must be customized. That said, it should be noted that many administrators consider the "stock" `nscd` daemon to be unreliable, at least under Linux. There is at least one alternate implementation out there. Your mileage may vary. Putting it all together ----------------------- Knowing the above, the lookup order for the hosts database works in this order: * `nscd` (if running, its socket is present, and caching of hosts is enabled) * NSS modules, in the order listed in `/etc/nsswitch.conf` * If not found in a NSS module, it doesn't exist. This brings us to where `dig` falls into this equation. You can pretty much refer to HBrujin's entire answer (`dig` doesn't use NSS, only talks over TCP/IP), but the catch is that there is no cache for NSS at all unless 1) `nscd` is running, and 2) it is configured to cache the `hosts` database. tl;dr ----- The complexity of getting DNS caching to play nicely within NSS is usually why most admins go with the "simpler" solution of running their own recursive DNS server. You don't need to know a darn thing about NSS. Just point `/etc/resolv.conf` at your shiny new DNS cache and let it hide the evils of NSS from you. (at least until you need to learn how LDAP integration works)
26,972,822
I am working on an application in Xcode 6.1, iOS 8.1; the application was working completely fine till 2 days before, but today as I executed it I got an error in the web service & the error is printed below. > > Error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed > out." UserInfo=0x7c6899b0 {NSErrorFailingURLStringKey=, > NSErrorFailingURLKey=, NSLocalizedDescription=The request timed > out., NSUnderlyingError=0x7c688f60 "The request timed out."} > > > I had used AFNetworking 2.x and following code snippet to make network call: ``` AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; manager.responseSerializer.acceptableContentTypes=[manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"]; [manager POST:<URL> parameters:<parameters> success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); NSError *error = nil; NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error]; if (error) { NSLog(@"Error serializing %@", error); } NSLog(@"Dictionary %@", JSON); NSLog(@"Success"); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; } ``` **UPDATE:** I had done quit/relaunched the iOS Simulator.app, reseted content & settings, but nothing worked.
2014/11/17
[ "https://Stackoverflow.com/questions/26972822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3840908/" ]
Ok, I lost a lot of time investigeting similar issue. In my case the problem was strange (bad?) firewall on the server. It was banning device when there was many (not so many) requests in short period of time. I believe you can do easy test if you are facing similar issue. 1. Send a lot of (depends of firewall settings) requests in loop (let's say 50 in 1 second). 2. Close/Kill app (this will close connections to server) 3. (OPTIONAL) Wait a while (lets say 60 seconds) 4. Start app again and try send request If you now got timeout for all next requests, you probably have same issue and you should talk with sever guys. PS: if you don't have access to server you can give user info that he should restart wifi on device to quit that timeout loop. It could be last resort in some cases.
You must close the firewall and it will work. I tried this solution and it worked for me.
48,104,433
In **Chrome 61**, support for modules in JavaScript was added. Right now I am running Chrome 63. I am trying to use `import`/`export` syntax in Chrome extension content script to use modules. In **`manifest.json`**: ``` "content_scripts": [ { "js": [ "content.js" ], } ] ``` In **`my-script.js`** (same directory as **`content.js`**): ``` 'use strict'; const injectFunction = () => window.alert('hello world'); export default injectFunction; ``` In **`content.js`**: ``` 'use strict'; import injectFunction from './my-script.js'; injectFunction(); ``` I receive this error: **`Uncaught SyntaxError: Unexpected identifier`** If I change the import syntax to `import {injectFunction} from './my-script.js';` I get this error: **`Uncaught SyntaxError: Unexpected token {`** Is there some issue with using this syntax in **`content.js`** in Chrome extension (since in HTML you have to use `<script type="module" src="script.js">` syntax), or am I doing something wrong? It seems strange that Google would ignore support for extensions.
2018/01/04
[ "https://Stackoverflow.com/questions/48104433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/444998/" ]
The best way would be to use bundlers like webpack or Rollup. I got away with basic configuration ``` const path = require('path'); module.exports = { entry: { background: './background.js', content: './content.js', }, output: { filename: '[name].js', path: path.resolve(__dirname, '../build') } }; ``` Run the file with the command ``` webpack --config ./ext/webpack-ext.config.js ``` Bundlers combine the related files and we can use modularisation in chrome extensions! :D You will need to keep all other files like manifest and static files in build folder. Play around with it and you will eventually find a way to make it work!
Export the module as a object: ``` 'use strict'; const injectFunction = () => window.alert('hello world'); export {injectFunction}; ``` Then you can import its property: ``` 'use strict'; import {injectFunction} from './my-script.js'; ```
10,335,741
I need to create `generic list` that can act as `List<ClassA>` or `List<ClassB>` because I have following situation. ``` if(e instanceof A) return A; else return B ``` But I want to populate one `List Result` which can act as either `List<ClassA> Result` or `List<ClassB> Result`, am sure we can use generics here but i am not sure how to use it? **Update** All i want to do is that runtime, my List should be populated with proper type, either `class A or class B`, ``` if() { //data is present in List<ClassA> classAList = new ArrayList<ClassA>(); //return classAList } else { //return List<ClassB> classBList = new ArrayList<ClassB>(); } ``` Hope this helps.
2012/04/26
[ "https://Stackoverflow.com/questions/10335741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/164299/" ]
You should use a common interface that both of your classes implement. Say your interface is called `MyInterface`. Both of your classes can implement this interface and your generic list can be of type `List<MyInterface>`. The alternative is that both of your classes have a common base class. **Edit:** Added some examples as requested by OP. Example interface: ``` public interface MyInterface { String getName(); void setName(String name); } ``` Example interface implementation: ``` public class ClassA implements MyInterface { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` Example generic list usage: ``` List<MyInterface> list = new ArrayList<MyInterface>(); list.add(new ClassA()); MyInterface item = list.get(0); item.setName("Bob"); String name = item.getName(); ```
Something like this perhaps: ``` public class Test { static class A {} static class B {} private static List<?> getList() { List<A> aList = new ArrayList<A>(); List<B> bList = new ArrayList<B>(); aList.add(new A()); if (aList.size() > 0) { return aList; } else { return bList; } } public static void main(String[] args) { List<?> cList = getList(); System.out.println(cList); } } ```
30,405,413
I import a dataframe via `read_csv`, but for some reason can't extract the year or month from the series `df['date']`, trying that gives `AttributeError: 'Series' object has no attribute 'year'`: ``` date Count 6/30/2010 525 7/30/2010 136 8/31/2010 125 9/30/2010 84 10/29/2010 4469 df = pd.read_csv('sample_data.csv', parse_dates=True) df['date'] = pd.to_datetime(df['date']) df['year'] = df['date'].year df['month'] = df['date'].month ``` UPDATE: and when I try solutions with `df['date'].dt` on my pandas version 0.14.1, I get "AttributeError: 'Series' object has no attribute 'dt' ": ``` df = pd.read_csv('sample_data.csv',parse_dates=True) df['date'] = pd.to_datetime(df['date']) df['year'] = df['date'].dt.year df['month'] = df['date'].dt.month ``` Sorry for this question that seems repetitive - I expect the answer will make me feel like a bonehead... but I have not had any luck using answers to the similar questions on SO. --- FOLLOWUP: I can't seem to update my pandas 0.14.1 to a newer release in my Anaconda environment, each of the attempts below generates an invalid syntax error. I'm using Python 3.4.1 64bit. ``` conda update pandas conda install pandas==0.15.2 conda install -f pandas ``` Any ideas?
2015/05/22
[ "https://Stackoverflow.com/questions/30405413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4263878/" ]
If you're running a recent-ish version of pandas then you can use the datetime attribute [`dt`](http://pandas.pydata.org/pandas-docs/stable/api.html#datetimelike-properties) to access the datetime components: ``` In [6]: df['date'] = pd.to_datetime(df['date']) df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month df Out[6]: date Count year month 0 2010-06-30 525 2010 6 1 2010-07-30 136 2010 7 2 2010-08-31 125 2010 8 3 2010-09-30 84 2010 9 4 2010-10-29 4469 2010 10 ``` **EDIT** It looks like you're running an older version of pandas in which case the following would work: ``` In [18]: df['date'] = pd.to_datetime(df['date']) df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month) df Out[18]: date Count year month 0 2010-06-30 525 2010 6 1 2010-07-30 136 2010 7 2 2010-08-31 125 2010 8 3 2010-09-30 84 2010 9 4 2010-10-29 4469 2010 10 ``` Regarding why it didn't parse this into a datetime in `read_csv` you need to pass the ordinal position of your column (`[0]`) because when `True` it tries to parse columns `[1,2,3]` see the [docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv) ``` In [20]: t="""date Count 6/30/2010 525 7/30/2010 136 8/31/2010 125 9/30/2010 84 10/29/2010 4469""" df = pd.read_csv(io.StringIO(t), sep='\s+', parse_dates=[0]) df.info() <class 'pandas.core.frame.DataFrame'> Int64Index: 5 entries, 0 to 4 Data columns (total 2 columns): date 5 non-null datetime64[ns] Count 5 non-null int64 dtypes: datetime64[ns](1), int64(1) memory usage: 120.0 bytes ``` So if you pass param `parse_dates=[0]` to `read_csv` there shouldn't be any need to call `to_datetime` on the 'date' column after loading.
Probably already too late to answer but since you have already parse the dates while loading the data, you can just do this to get the day ``` df['date'] = pd.DatetimeIndex(df['date']).year ```
61,139
In quantum mechanics, we think of the Feynman Path Integral $\int{D[x] e^{\frac{i}{\hbar}S}}$ (where $S$ is the classical action) as a probability amplitude (propagator) for getting from $x\_1$ to $x\_2$ in some time $T$. We interpret the expression $\int{D[x] e^{\frac{i}{\hbar}S}}$ as a sum over histories, weighted by $e^{\frac{i}{\hbar}S}$. Is there a physical interpretation for the weight $e^{\frac{i}{\hbar}S}$? It's certainly not a probability amplitude of any sort because it's modulus squared is one. My motivation for asking this question is that I'm trying to physically interpret the expression $\langle T \{ \phi(x\_1)...\phi(x\_n) \} \rangle = \frac{\int{D[x] e^{\frac{i}{\hbar}S}\phi(x\_1)...\phi(x\_n)}}{\int{D[x] e^{\frac{i}{\hbar}S}}}$.
2013/04/15
[ "https://physics.stackexchange.com/questions/61139", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/8163/" ]
Up to a universal normalization factor, $\exp(iS\_{\rm history}/\hbar)$ *is* the probability amplitude for the physical system to evolve along the particular history. All the complex numbers in quantum mechanics are "probability amplitudes of a sort". This is particularly clear if we consider the sum over histories in a short time interval $(t,t+dt)$. In that case, all the intermediate histories may be interpreted as "linear fields" – for example, a uniform motion $x(t)$ – which is why only the straight line contributes and its meaning is nothing else than the matrix elements of the evolution operator. It may be puzzling why all the histories have probability amplitudes with the same absolute value. But it's true – in the sense of Feynman's path integral – and it's how Nature operates. At the end, some histories (e.g. coarse-grained histories in the sense of the consistent history interpretation of quantum mechanics) are more likely or much more likely than others. But within quantum mechanics, all these differences between the likelihood of different coarse-grained histories are explained by constructive or destructive interference of the amplitudes (and/or from different "sizes of the ensemble of histories")! That's just the quantum mechanics' universal explanation for why some histories are more likely than others. Histories that are not coarse-grained are equally likely!
At a time when my hammer was the Dirac's delta distribution, I *conjectured* that the answer was **Feynman Integral is a generalization of a Dirac's delta**, the use of this delta being to find the extreme of the action. Given a function $f(x)$, find a Dirac measure $\delta\_f$ concentrated in the critical points of $f$. The answer is obviously $ \delta(f'(x))$, and using that $\delta(w)=\frac 1{2\pi}\int e^{iwt} dt$ we can write $$ < \delta(f'(x)) | g(x)> = \int \int e^{i z f'(x)} g(x) dz dx = \int \int \lim\_{y\to x} e^{i z {f(y)-f(x)\over y-x} } g(x) dz dx $$ and substuting $\epsilon= {y - x \over z}$ $$ <\delta\_f | g> = \int \int \lim\_{\epsilon\to 0} e^{i {1 \over \epsilon} (f(y) - f(x))} g(x) dx {dy \over \epsilon} $$ And if we know that the extreme is unique, we can work with the "halved" expresion $$<\delta\_f^{1/2} | O> = \lim\_{\epsilon\to 0} {1 \over \epsilon^{1/2}} \int e^{i {1\over\epsilon} f(x)} O(x) dx$$ from which, by taking modulus square, $ <\delta\_f | g> = <\delta\_f^{1/2} | O> <\delta\_f^{1/2} | O>^\* $ But this is only a zero dimensional static argument. It is not even a D=0+1 theory, it is D=0+0. The same argument for Quantum or Classical Mechanics (D=0+1) or for Field Theory (D=3+1, say) should involve to control $$<\delta\_L^{h,\epsilon'} | O[\phi] > = \int ... \int {1\over (h \epsilon')^{n/2}} e^{i {1\over h} L^{\epsilon'}\_n[\phi\_0,x\_1,...x\_n,\phi\_1]} O[\phi] (\Pi dx\_i) $$ with some technique similar to a brownian bridge for a Wiener measure, or at least my note of 1998 says that. The funny thing of this idea was to start from the Lagrangian without any postulate of wuantum mechanics, not even the propagator, which is the cornerstone of the answers in [Why is the contribution of a path in Feynmans path integral formalism $\sim e^{(i/\hbar)S[x(t)]}$](https://physics.stackexchange.com/questions/8663/why-is-the-contribution-of-a-path-in-feynmans-path-integral-formalism-sim-e). I think that pursuing this way I had tripped against the non differentiable paths mentioned in [Once a quantum partition function is in path integral form, does it contain any operators?](https://physics.stackexchange.com/questions/9183/once-a-quantum-partition-function-is-in-path-integral-form-does-it-contain-any/9184#comment431362_9184) and [What type of non-differentiable continuous paths contribute for the path integral in quantum mechanics](https://physics.stackexchange.com/questions/185445/what-type-of-non-differentiable-continuous-paths-contribute-for-the-path-integra/186193#186193). The connection of path integral to classical mechanics is discussed also here [What type of non-differentiable continuous paths contribute for the path integral in quantum mechanics](https://physics.stackexchange.com/questions/185445/what-type-of-non-differentiable-continuous-paths-contribute-for-the-path-integra/186193#186193) and in the paper from Dirac quoted in this answer <https://physics.stackexchange.com/a/134215/1335>
22,243,718
Hey guys I am attempting to save an image in my android applicaiton as a blob in mysql database, as far as the actual code goes. I would love some help as for how to connect to the database in the first place, using the html docs and the actual android code itself.
2014/03/07
[ "https://Stackoverflow.com/questions/22243718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2159030/" ]
Do not save the image itself in DB. Better is it to save the image on your server and only save the path to the image (relative) in DB. Send the needed image to the phone.
You can encode your image in string using base64. & while accessing from mysql sever decode it again
8,169,999
I've gone through the steps detailed in [How do you use https / SSL on localhost?](https://stackoverflow.com/questions/5874390/how-do-you-use-https-ssl-on-localhost) but this sets up a self-signed cert for my machine name, and when browsing it via <https://localhost> I receive the IE warning. Is there a way to create a self-signed cert for "localhost" to avoid this warning?
2011/11/17
[ "https://Stackoverflow.com/questions/8169999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4782/" ]
You can use PowerShell to generate a self-signed certificate with the new-selfsignedcertificate cmdlet: ``` New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" ``` Note: makecert.exe is deprecated. Cmdlet Reference: <https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate>
Here's what I did to get a valid certificate for localhost on Windows: 1. Download mkcert executable (<https://github.com/FiloSottile/mkcert/releases>) and rename it to mkcert.exe 2. Run "mkcert -install" 3. Open Windows certificate manager (certmgr.msc) 4. Right click on "Trusted Root Certification Authorities" -> Import 5. Import Root cert (rootCA.pem) from C:\Users[username]\AppData\Local\mkcert\ 6. Create a \*.p12 certificate for specified domain(s): "mkcert -pkcs12 [name1] [name2]" 7. Rename \*.p12 certificate into \*.pfx 8. In IIS -> Server Certificates -> Import (pfx) in "Personal" group [default password: "changeit"] 9. Assign certificate to Default Web Site (binding -> https (443) -> modify -> SSL certificate)
14,154
I am trying to perform a hashing trick and then a random forest with scala. I have the following code: ``` val documents: RDD[Seq[String]] = sc.textFile("hdfs:///tmp/new_cromosoma12v2.csv").map(_.split(",").toSeq) val hashingTF = new HashingTF() val tf: RDD[Vector] = hashingTF.transform(documents) val splits = tf.randomSplit(Array(0.7, 0.3)) val (trainingData, testData) = (splits(0), splits(1)) val numClasses = 3 val categoricalFeaturesInfo = Map[Int, Int]() val numTrees = 10 val featureSubsetStrategy = "auto" val impurity = "gini" val maxDepth = 8 val maxBins = 32 **val trainingData2=LabeledPoint(1.0,trainingData.collect())** val model = RandomForest.trainClassifier(trainingData2, numClasses, categoricalFeaturesInfo, numTrees, featureSubsetStrategy, impurity, maxDepth, maxBins) ``` But I have the error found : Array[org.apache.spark.mllib.linalg.Vector] required: org.apache.spark.mllib.linalg.Vector in the bold line. Do you know how I can solve it? Thank you, Laia
2016/09/22
[ "https://datascience.stackexchange.com/questions/14154", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/8710/" ]
Let's look at the error message: ``` found : Array[org.apache.spark.mllib.linalg.Vector] required: org.apache.spark.mllib.linalg.Vector ``` "found" is the type of object that it came across, "required" is the type of the object that the function accepts. The types look mostly the same ( org.apache.spark.mllib.linalg.Vector ) but the first is Array[X] and the second is X. Why? Because trainingData.collect() gives you the RDD as an array of objects in the array. What you probably want to do instead is `map`, to turn each vector into a LabeledPoint, instead of trying to turn the whole RDD into a single LabeledPoint.
`LabeledPoint` expects: `LabeledPoint(label: Double, features: Vector)` when you execute `val trainingData2=LabeledPoint(1.0,trainingData.collect())` you're actually getting all the Rows in your trainingData set so you will have `Array(Row(???), Row(???), ???)` but what you need is to apply `def transformToLabeledPoint(vector: Vector) = LabeledPoint(1.0, vector)`, you can either apply a map on your trainingData or create a UDF and apply it to your trainingData, for instance: ``` import org.apache.spark.ml.feature.SQLTransformer import org.apache.spark.mllib.regression.LabeledPoint import org.apache.spark.mllib.linalg.Vectors val df = spark.createDataFrame(Seq((1.0,100.0),(2.0,200.0))).toDF("id", "value") spark.udf.register("setLabel", (label: Double, x: Seq[Double]) => LabeledPoint(label, Vectors.dense(x.toArray))) val labeledTrainingData = new SQLTransformer() .setStatement("SELECT setLabel(1.0, array(*)) AS points FROM __THIS__") .transform(df) val labeledRDD = labeledTrainingData.rdd.map(_(1).asInstanceOf[LabeledPoint]) ```
2,816,285
Let's just I had the following code: **foo.h** ``` class Foo { // ... }; ``` **foo.cpp** ``` #include "foo.h" // Functions for class Foo defined here... ``` Let's say that `Foo` are built into a static library `foo.lib`. Now let's say I have the following: **foo2.h** ``` class Foo { // ... }; ``` **foo2.cpp** ``` #include "foo2.h" // Functions for class Foo defined here... ``` This is built into a separate static library `foo2.lib`. Now, if I re-link `foo.lib` and `foo2.lib` into an executable program `foo.exe`, should it be complaining that `class Foo` has been defined twice? In my experiences, neither the compiler or the linker are complaining. I wouldn't be expecting the compiler to complain, because they have been defined in separate translation units. But why doesn't the linker complain? How does the linker differentiate between the 2 versions of the `Foo` class? Does it work by decorating the symbols?
2010/05/12
[ "https://Stackoverflow.com/questions/2816285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22489/" ]
No, neither compiler nor linker required to complain. They might; but it's not required. See the [One Definition Rule](http://en.wikipedia.org/wiki/One_Definition_Rule).
Part of the issue is that each class is in a static library. Linkers treat static libraries specially and only extract the necessary objects to satisfy missing symbols that have linkage. Whether you get a linking error or not will depend on what symbols each implementation of foo has and how they are packaged up together. Since you have simple packaging (a single .cpp file for each foo that holds all the methods), it's easy to generate a conflict. So, let's create a situation where you will get a conflict. You want to define one foo like this: ``` class foo { public: foo(); int a() const; }; ``` and your second foo like this: ``` class foo { public: foo(); int b() const; }; ``` Now each of those foo's have one identical symbol with linkage for the default constructor and a second different symbol. Now in your application, have one function in one file that does: ``` int lib1() { foo f; return f.a(); } ``` and a second file that does this: ``` int lib2() { foo f; return f.b(); } ``` Now your application will have three symbols that it needs, `foo::foo`, `foo::a` and `foo::b`. Because of `foo::a` and `foo::b`, the linker will try to use both static libraries but will then cause two different copies of `foo::foo` to get pulled in which will cause the linker to have an error.
12,216,720
I have a WCF method: ``` public IQueryable<AmenitySummary> GetAmenities(string searchTerm) ``` Now, `AmenitySummary` is defined thus ``` [DataContract] public class AmenitySummary { [DataMember] public int AmenityId { get; set; } [DataMember] public string Amenity { get; set; } [DataMember] public string LowerCaseAmenity { get; set; } } ``` In my client side solution I have a project in which I call this method. The problem is that the signature in the Reference.cs file is this ``` public object GetAmenities(string searchTerm) { return base.Channel.GetAmenities(searchTerm); } ``` How comes? Why isn't the return type `IQueryable<AmenitySummary>`? What am I missing? Not only that, but when I try to use `AmenitySummary` on the client side I can't do it as it's not recognised. I think this is linked. Thanks, S
2012/08/31
[ "https://Stackoverflow.com/questions/12216720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/991788/" ]
Here you go: ``` SELECT JobName, SUM(CASE CounterName WHEN 'Kilos' THEN ProductionCounter ELSE 0 END) AS SumKilos, SUM(CASE CounterName WHEN 'Bars' THEN ProductionCounter ELSE 0 END) AS SumBars, MIN(StartDate), MAX(COALESCE(EndDate, 'undefined date')), MAX(Stage) FROM vwOeeInterval WHERE CounterName IN ('Kilos', 'Bars') GROUP BY JobName; ``` Not sure if this `MAX(COALESCE(EndDate, 'undefined date'))` works in SQL Server, since datatype's might clash. You just need COALESCE(), when you want to replace the NULL value. If it does not work, just do MAX(EndDate) and you're fine.
``` select jobname, max(bars) as "TotalBars", max(kg) as "Total Kilos", sd as "Start date", ed as "End date" from( SELECT JobName, if(countername="bars",SUM(ProductionCounter),null) as "bars" , if(countername="kilograms",SUM(ProductionCounter),null) as "kg" , min(startdate) as sd, max(enddate) as ed FROM vwOeeInterval GROUP BY JobName , CounterName) t group by jobname ```
181,338
I have two servers: one that runs Apache and another one just for MySQL. I don't have any monitoring tools installed on any of them. Every once in a while it appears that my SQL queries are running very very slow (queries that would normally run in 0.3 seconds now take 20 seconds). I don't know if this is a MySQL issue, a CPU issue, or even a networking one, as it usually happens when no one is around to check, so I am looking for a monitoring solution that would help me pinpoint the source of the problem. Thank you.
2010/09/15
[ "https://serverfault.com/questions/181338", "https://serverfault.com", "https://serverfault.com/users/25543/" ]
Analyzing the slow query log is a good idea. My guts tells me though that you are using MyISAM storage engine for your tables and suddenly there's a spike in delete/update/insert activity combined with some long-running selects ... that leads to all kind of funky stuff with MyISAM, whereas with InnoDB everything stays steady.
I've used [mytop](http://jeremy.zawodny.com/mysql/mytop/) to get slow queries very often. When our webmasters start complaining about the performance of the (virtual) mysql server, I ask them politely to come and watch the output of mytop together. We find the culprit query very easily like this and from there you know what the next step can be.
16,724,869
The function below is breaking at the first `if` statement in IE8. I'm not sure what would cause this since from what I have researched none of this should cause an issue. I also tried adding the `toLowerCase()` method after the `referrer` property as well, still no luck. Any ideas? ``` function returnToLogin() { if (document.referrer.indexOf('attendant_login') > 0) { if (thisevent == null) { window.location = document.referrer; } else { setTimeout(returnToLogin, 1000); } return true; } return false; } ```
2013/05/23
[ "https://Stackoverflow.com/questions/16724869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1211604/" ]
IE doesn't always set the `document.referrer` property. The solution is to check if it is defined before calling methods on it. Change your `if` to: ``` if (document.referrer&&document.referrer.indexOf('attendant_login') > 0) { ``` Now if `document.referrer` doesn't exist, it won't try to call the `indexOf` method on it, so it won't break. Instead it will just behave as though the test failed (which I imagine is a suitable default)
IE has problems with using `Array.indexOf()`. Use `jQuery.inArray()` instead.
11,062,841
How can I start and stop a windows service from a c# Form application?
2012/06/16
[ "https://Stackoverflow.com/questions/11062841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1083913/" ]
Add a reference to `System.ServiceProcess.dll`. Then you can use the [ServiceController](http://msdn.microsoft.com/en-us/library/yb9w7ytd) class. ``` // Check whether the Alerter service is started. ServiceController sc = new ServiceController(); sc.ServiceName = "Alerter"; Console.WriteLine("The Alerter service status is currently set to {0}", sc.Status.ToString()); if (sc.Status == ServiceControllerStatus.Stopped) { // Start the service if the current status is stopped. Console.WriteLine("Starting the Alerter service..."); try { // Start the service, and wait until its status is "Running". sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); // Display the current service status. Console.WriteLine("The Alerter service status is now set to {0}.", sc.Status.ToString()); } catch (InvalidOperationException) { Console.WriteLine("Could not start the Alerter service."); } } ```
You can do it like this, [Details of Service Controller](http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx) ``` ServiceController sc = new ServiceController("your service name"); if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); } ``` Similarly you can stop using stop method ``` sc.Stop(); ```
47,026,578
(I have read other answers on SO, but they do not appear to address the problem at hand.) [Swift 4, Xcode 9] I need to get the path representing the drawn areas following the `stroke()` of a path. i.e. a path that represents the outline of the stroke. Given a `UIBezierPath` with the following attributes: ``` let dotWidth: CGFloat = 3 let spacing: CGFloat = 12 let dashes: [CGFloat] = [0.0, spacing] let lineCapStyle: CGLineCap = .round let lineJoinStyle: CGLineJoin = .miter bezierPath.lineCapStyle = lineCapStyle bezierPath.lineJoinStyle = lineJoinStyle bezierPath.setLineDash(dashes, count: dashes.count, phase: 0) bezierPath.lineWidth = dotWidth ``` Xcode's debugger preview will kindly render the result: [![enter image description here](https://i.stack.imgur.com/NtIUy.png)](https://i.stack.imgur.com/NtIUy.png) **I need those dots as a path.** First attempt, using the modern version of `CGPathCreateCopyByStrokingPath()` ``` let strokedCGPath = bezierPath.cgPath.copy(strokingWithWidth: dotWidth, lineCap: lineCapStyle, lineJoin: lineJoinStyle, miterLimit: 4) ``` [![enter image description here](https://i.stack.imgur.com/2M739.png)](https://i.stack.imgur.com/2M739.png) Second attempt: ``` let dashedCGPath = bezierPath.cgPath.copy(dashingWithPhase: 0, lengths: dashes) ``` [![enter image description here](https://i.stack.imgur.com/SrW47.png)](https://i.stack.imgur.com/SrW47.png) Result: neither `copy(strokingWithWidth:)` or `copy(dashingWithPhase:)` give me the complete path that I need. **Question**: am I missing something obvious here? Is there a way to get the entire path of the stroke? Thanks for any help.
2017/10/31
[ "https://Stackoverflow.com/questions/47026578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1452758/" ]
[EDITED] My previous answer was incorrect. Using CGPath's `copy(dashingWithPhase: phase, lengths: pattern)` will not work in this situation. Despite the method's description, it will not actually produce a *full* outline path of the resulting stroke. A working solution is: * create a temporary `CGContext` * on the context, set all the stroke-related parameters such as `lineCap`, `lineWidth`, `lineJoin` and most importantly, `lineDash` * add your path to the context: `context.addPath(bezierPath.cgPath)` * do NOT call `fill()` or `stroke()`. We are not interested in drawing. * instead, call `context.replacePathWithStrokedPath()` * finally, pull a new cgPath out of the context with `let newCGPath = context.path` This `newCGPath` will be the outline of the stroked path, as if it had been drawn.
Since there are two different algorithms discussed here, let me show the difference: ``` cgPath.copy(dashingWithPhase: phase, lengths: pattern) ``` creates one-dimensional polylines as subpaths that are *not* closed for each dash. They do not contain a `closeSubpath` element. "strokes" on the other hand ``` context.replacePathWithStrokedPath() let newCGPath = context.path ``` creates two-dimensional closed polygons as subpaths for each dash. They do contain a `closeSubpath` element. "shapes" Hope this helps to choose the algorithm they need.
11,656,071
I have four (relevent) tables ``` CAKETABLE CAKE ICING RESERVEDSPRINKLES CAKE SPRINKLE SPRINKLETABLE SPRINKLE CONSUMED ICINGTABLE ICING CONSUMED ``` Each cake has exactly 3 sprinkles and 1 icing. I want to query the database and get all the cakes that have 1 icing and 3 sprinkles where neither icing nor any of the sprinkles have CONSUMED = '1'. So let's psuedo insert data: INSERT INTO ICINGTABLE (vanilla, 0), (chocolate, 0); ``` INSERT INTO SPRINKLETABLE (red, 0), (blue, 0), (green, 0), (orange, 0), (purple, 0),(pink, 0); INSERT INTO CAKETABLE (cake1, vanilla), (cake2, chocolate); INSERT INTO RESERVEDSPRINKLES (cake1, red), (cake1, blue), (cake1, green), (cake2, orange), (cake2, purple), (cake2, pink); ``` So now I have cake1 with vanilla icing and red,blue,green sprinkles and cake2 with chocolate icing and orange, purple, and pink sprinkles. When I run the query, I want it to return ``` CAKES cake1 cake2 ``` ONLY IF there are no consumed parts in the cake, so even if ONE sprinkle is marked consumed I want to omit that whole cake from the query. The following query does exactly that for icing. ``` SELECT CAKE FROM CAKETABLE as c INNER JOIN (SELECT * FROM ICINGTABLE WHERE CONSUMED = '0') as i ON c.ICING = i.ICING; ``` But for the sprinkles, I am having trouble. If I use the same technique as above, my query will return: ``` CAKE cake1 cake1 cake1 cake2 cake2 cake2 ``` I can eliminate that with DISTINCT, but it still isn't correct because if any sprinkle has consumed = '0' it shows that cake in the list when I want the opposite functionality (cake only shown if ALL sprinkles have consumed = '0') If anyone has a better title name for this, it'd be appreciated. I can't think of anything descriptive and short.
2012/07/25
[ "https://Stackoverflow.com/questions/11656071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1065671/" ]
You can use `not exists` to demand that no icing or sprinkle is consumed: ``` select cake from caketable c where not exists ( select * from icingtable i where i.cake = c.cake and i.consumed = '1' ) and not exists ( select * from sprinkletable s where s.cake = c.cake and s.consumed = '1' ) ```
I think the following does what you want: ``` select ct.cake from caketable ct join reservedsprinkle rs on ct.cake = rs.cake join sprinkletable st on rs.sprinkle = st.sprinkle join icingtable it on ct.cake = it.cake where it.consumed = 0 group by ct.cake having count(distinct rs.sprinkle) = 3 and sum(case when st.consumed = 1 then 1 else 0 end) = 0 ``` This is grouping by cake and then putting most of the conditions in the HAVING clause. It looks like a cake can have only one icing, by database design. I am assuming that CAKE is unique in the CAKE table.
34,740,362
I've the following Java program and I don't want "," to be assign after my last element, what to do ? ``` String range = "400-450"; Integer startRange = null; Integer endRange = null; StringTokenizer st = new StringTokenizer(range,"-"); while(st.hasMoreTokens()) { startRange = Integer.parseInt(st.nextToken()); endRange= Integer.parseInt(st.nextToken()); } StringBuilder sb = new StringBuilder(); for (int i = startRange; i <= endRange; i++) { sb.append(i).append(","); } System.out.println(sb); ``` The output should be `400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450` --> without comma at last
2016/01/12
[ "https://Stackoverflow.com/questions/34740362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As @Jan says, use `StringJoiner` if you have Java8. Otherwise you could add a separator before the new entry and treat the first item differently by initialising the separator to blank. ``` String separator = ""; for (int i = startRange; i <= endRange; i++) { sb.append(separator).append(i); separator = ","; } ``` This is the Java8 version ``` StringJoiner sb = new StringJoiner(","); for (int i = startRange; i <= endRange; i++) { sb.add(String.valueOf(i)); } ```
Just let the last loop appending the commas stop before the last element is reached: ``` String range = "400-450"; Integer startRange = null; Integer endRange = null; StringTokenizer st = new StringTokenizer(range,"-"); while(st.hasMoreTokens()) { startRange = Integer.parseInt(st.nextToken()); endRange= Integer.parseInt(st.nextToken()); } StringBuilder sb = new StringBuilder(); // here, the "<=" was changed to "<" for (int i = startRange; i < endRange; i++) { sb.append(i).append(","); } // append last element sb.append(endrange) System.out.println(sb); ```
17,135,109
I am following Scott gu's trick of placing a App\_Offline.htm page at the route of my application to bring it offline - <http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx> It does not seem to be working on one of my sites though. I place the file in IIS7 of one my sites, and all traffic is redirected to it. However in the other site, same server etc, I get a page that contains "The service is unavailable.". Not sure where I am going wrong - any ideas?
2013/06/16
[ "https://Stackoverflow.com/questions/17135109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373674/" ]
I had this issue with a MVC site recently, and I managed to solve it by replacing the web.config I originally had with a clean, minimal one when wanting to use the app\_offline.htm file. ``` <?xml version="1.0"?> <configuration> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> </system.webServer> </configuration> ``` If I had more time I'd go through and find the exact thing in the web.config that was altering the behaviour, but this is worth a shot.
Here's how you do it using the GUI (note the last line - that's the one you should add/edit) [![enter image description here](https://i.stack.imgur.com/7vOB2.png)](https://i.stack.imgur.com/7vOB2.png)
208,959
I'm in the process of creating a class that stores metadata about a particular data source. The metadata is structured in a tree, very similar to how XML is structured. The metadata values can be integer, decimal, or string values. I'm curious if there is a good way in C++ to store variant data for a situation like this. I'd like for the variant to use standard libraries, so I'm avoiding the COM, Ole, and SQL VARIANT types that are available. My current solution looks something like this: ``` enum MetaValueType { MetaChar, MetaString, MetaShort, MetaInt, MetaFloat, MetaDouble }; union MetaUnion { char cValue; short sValue; int iValue; float fValue; double dValue; }; class MetaValue { ... private: MetaValueType ValueType; std::string StringValue; MetaUnion VariantValue; }; ``` The MetaValue class has various Get functions for obtaining the currently stored variant value, but it ends up making every query for a value a big block of if/else if statements to figure out which value I'm looking for. I've also explored storing the value as only a string, and performing conversions to get different variant types out, but as far as I've seen this leads to a bunch of internal string parsing and error handling which isn't pretty, opens up a big old can of precision and data loss issues with floating point values, and still doesn't eliminate the query if/else if issue stated above. Has anybody implemented or seen something that's cleaner to use for a C++ variant data type using standard libraries?
2008/10/16
[ "https://Stackoverflow.com/questions/208959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21254/" ]
As of C++17, there’s [`std::variant`](http://en.cppreference.com/w/cpp/utility/variant). If you can’t use that yet, you might want [Boost.Variant](http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html). A similar, but distinct, type for modelling polymorphism is provided by [`std::any`](http://en.cppreference.com/w/cpp/utility/any) (and, pre-C++17, [Boost.Any](http://www.boost.org/doc/libs/1_36_0/doc/html/any.html)). Just as an additional pointer, you can look for “[type erasure](https://stackoverflow.com/q/5450159/1968)”.
You can also go down to a more C-ish solution, which would have a void\* the size of a double on your system, plus an enum for which type you're using. It's reasonably clean, but definitely a solution for someone who feels wholly comfortable with the raw bytes of the system.