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
1,496,657
I have some JQuery that pops up a JQuery Dialog (<http://docs.jquery.com/UI/Dialog>) box when you hover over an image like so: ``` $(document).ready(function() { $("img").hover(function() { $("#dialog").dialog(); }); }); ``` I have 2 questions 1. When i close the dialog and then hover over an image again the dialog dosn't reappear, how can i fix that 1. How can i pop up the box only if the user hovers over the image for a couple of seconds
2009/09/30
[ "https://Stackoverflow.com/questions/1496657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181659/" ]
1 - you need to initialize the dialog first. [Code here](http://jsbin.com/ijagi/edit) ``` $(document).ready( function() { $("#dialog").dialog({ autoOpen: false }); // init without showing $("img").bind("mouseover", function() { $("#dialog").dialog('open'); // open the dialog }); }); ``` 2 - just use a counter ``` var _counter = 0; var _seconds = 0; $("img").hover(function() { // mouseover _counter = setInterval(openDialogNow(), 1000); }, function() { // mouseout clearInterval(_counter); }); function openDialogNow() { // this function will run every second while the user does not mouseout the image _seconds++; // add 1 to the global variable if(_seconds == 3) { // will open in 3 seconds, 3 * 1000 miliseconds _seconds = 0; // reset, so we can reuse later $("#dialog").dialog('open'); // open the dialog } } ```
use jQuery .delay() method. <http://api.jquery.com/delay/>
1,624,803
I found that this C++ code: ``` vector<int> a; a.push_back(1); a.push_back(2); vector<int>::iterator it = a.begin(); a.push_back(4); cout << *it; ``` print some big random number; but if you add `a.push_back(3)` between 3rd and 4th lines, it will print 1. Can you explain it to me?
2009/10/26
[ "https://Stackoverflow.com/questions/1624803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196634/" ]
Yes, any action that might change the size of the vector can invalidate iterators. Edit: That includes operations (e.g. `erase()`, `resize()`) that reduce the size of the container. `erase()` doesn't invalidate *all* iterators, but it does invalidate any iterators referring to any point after the erased element(s). `resize()` is defined in terms of `insert()` and `erase()`, so it has the same potential.
For future reference, all of the STL sorts of tidbits like this are on SGI's website: <http://www.sgi.com/tech/stl/Vector.html> If you need iterators to stay valid after you add or delete to a collection, take a look at another kind of collection, like a list. The best thing to do though is to identify out of the matrix of features you want from a collection (random access, etc.) then pick the right container. See the wikipedia article on Standard\_Template\_Library Containers for a starting point. If you have the cash, I highly recommend Scott Meyer's "Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library". Apologies for lack of supporting links, I'm a newbie here and lack the reputation to post this with more than one.
1,950,039
Throughout school we are taught that when something is multiplied by 1, it equals itself. But as I am learning about higher level mathematics, I am understanding that not everything is as black and white as that (like how infinity multiplied by zero isn't as simple as it seems). Is there anything in higher-level, more advanced, mathematics that when multiplied by one does not equal itself?
2016/10/02
[ "https://math.stackexchange.com/questions/1950039", "https://math.stackexchange.com", "https://math.stackexchange.com/users/373433/" ]
Usually, if there is an operation called multiplication, it is defined as having an identity element. We call that element $1$. When we do that, we define $1\times x = x \times 1 = x$. Sometimes we only define one of the equalities because we have the power to derive the other one. If we don't have a $1$, we don't have a multiplicative identity.
Outside of the usual integers / rational numbers / real numbers that we learn about in grade school, the symbol "$1$" is often used as a placeholder for the multiplicative identity in a given [algebraic structure](https://en.wikipedia.org/wiki/Algebraic_structure), such as a [ring](https://en.wikipedia.org/wiki/Ring_(mathematics)) or [field](https://en.wikipedia.org/wiki/Field_(mathematics)). To build such a structure, we start with some set, which we'll call $S$. Next, we define "operations" on this set, which are functions that input any two elements of $S$ and output a single element in $S$. Typically, we call these operations "addition" and "multiplication" and use the standard $\times$ and $+$ symbols (though these can be defined quite differently from grade school addition/multiplication). Finally, the mathematician will specify a list of axioms that this set and the operations should satisfy, such as associativity, commutativity, and so forth. Among these axioms will often be a statement along the lines of "There exists a special element in $S$, which we will call the multiplicative identity and denote by the symbol "$1$" which has the property that $y \times 1 = 1 \times y = y$ for any element $y \in S$.
7,726
As answerers noted in [my other question](https://meta.stackexchange.com/questions/7105/time-of-day-day-of-week-and-question-popularity), time-of-day and day-of-week does affect your question's chances, independently of question quality. At the same time, there are probably bandwagon effects: popular questions become popular because they're popular. `<opinion>`To maintain quality of SO ratings in the long-term, questions should be rated on quality (defined by the community, of course). The site should be structured to promote quality over luck.`</opinion>` How might SO be changed -- I'm talking about general ideas here, not the SQL queries that support them -- so that time-of-day/day-of-week effects be mitigated?
2009/07/21
[ "https://meta.stackexchange.com/questions/7726", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/131669/" ]
We already have multiple ways of viewing the lists of questions (Newest, Recently Active, Hot, Featured). It is not the site's fault that most people prefer to watch the Newest Question list and ignore the rest. No matter what type of system checks and mechanisms you put in place, you are not going to stop people from using the site the way they want to use it. If you try to put too many roadblocks in the way of that, they are going to end up leaving. The fact that the time of day and other factors might define whether or not a question gets views is more to do with human psychology/sociology than some inherent flaw in the system. And your idea of rating questions by the community seems redundant. We already upvote questions we consider interesting or thoughtful (or just a generally good question). I don't understand how tacking on some other type of rating system would be beneficial at all.
I have my RSS reader to check for new / newly edited questions. So it doesn't matter what time you ask your question. If it's tagged with one of the tags I'm following, I will see it eventually.
44,949,256
I have this parent class ``` public abstract class Parent { public string Id { get; set; } public static T Find<T>(string id) where T : class, new() { /* logic here ..*/ } } ``` and this child ``` public class Child : Parent { public string Name { get; set; } } ``` Right now, the `Find()` method can be called from child class like this `Child.Find<Child>(myId);` What I need to change so it doesnt have to include class type like this `Child.Find(myId);` **EDIT** I want to make this method as extension, and get it directly without defining the class into variable. the generic class`T` should be it's child type.
2017/07/06
[ "https://Stackoverflow.com/questions/44949256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987018/" ]
I am new to Veracode and was facing CWE-117. I understood this error is raised by Veracode when your logger statement has the potential to get attacked via malicious request's parameter values passed in. So we need to removed /r and /n (CRLF) from variables that are getting used in the logger statement. Most of the newbie will wonder what method should be used to remove CRLF from variable passed in logger statement. Also sometime replaceAll() will not work as it is not an approved method by Veracode. Therefore, here is the link to approved methods by Veracode to handles CWE problems. [Link Expired @22.11.2022] <https://help.veracode.com/reader/4EKhlLSMHm5jC8P8j3XccQ/IiF_rOE79ANbwnZwreSPGA> In my case I have used org.springframework.web.util.HtmlUtils.htmlEscape mentioned in the above link and it resolved the problem. ``` private static final Logger LOG = LoggerFactory.getLogger(MemberController.class); //problematic logger statement LOG.info("brand {}, country {}",brand,country); //Correct logger statement LOG.info("brand {}, country {}",org.springframework.web.util.HtmlUtils.htmlEscape(brand),org.springframework.web.util.HtmlUtils.htmlEscape(country)); ``` **Edit-1:** Veracode has stopped suggesting any particular function/method for sanitization of the logger variable. However still above solution will work. Find out the below link suggested by Veracode which explains what to do and how to do it to fix CWE-117 for some languages. <https://community.veracode.com/s/article/How-to-Fix-CWE-117-Improper-Output-Neutralization-for-Logs> **JAVA:** Using ESAPI library from OWASP for the logger. Checkout more details in link <https://www.veracode.com/security/java/cwe-117>
Though I am a bit late but I think it would help those who do not want to use ESAPI library and facing issue only for exception handler class Use apache commons library ``` import org.apache.commons.lang3.exception.ExceptionUtils; LOG.error(ExceptionUtils.getStackTrace(ex)); ```
58,567,845
I came across the following example of creating an Internet Checksum: > > Take the example IP header `45 00 00 54 41 e0 40 00 40 01 00 00 0a 00 00 04 0a 00 00 05`: > > > 1. Adding the fields together yields the two’s complement sum `01 1b 3e`. > 2. Then, to convert it to one’s complement, the carry-over bits are added to the first 16-bits: `1b 3e + 01 = 1b 3f`. > 3. Finally, the one’s complement of the sum is taken, resulting to the checksum value `e4c0`. > > > I was wondering how the IP header is added together to get `01 1b 3e`?
2019/10/26
[ "https://Stackoverflow.com/questions/58567845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/651174/" ]
It seems like you are looking for libraries functionality in Google App Script. [Documentation](https://developers.google.com/apps-script/guides/libraries) You can save a version of the script that you have the functions in it, and import the functions on to a second script file through menu>resources>libraries. You need to use script id for importing libraries, which you can find from menu>File>Project properties>Script ID You can then execute the function using the script file name as the reference.
You can use the Apps Script API, you may find this helpful [Executing Functions using the Apps Script API](https://developers.google.com/apps-script/api/how-tos/execute) "The Apps Script API provides a scripts.run method that remotely executes a specified Apps Script function"
101,060
The PHB states that when using combat expertise "the changes to attack rolls and Armor Class last until your next action." So when you attack with combat expertise and then use a move action that means you lose your AC bonus. Is that correct?
2017/06/06
[ "https://rpg.stackexchange.com/questions/101060", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/36404/" ]
The creature keeps the bonuses and penalties from the feat [Combat Expertise](http://dndsrd.net/featsAll.html#combat-expertise) until the creature's next turn ============================================================================================================================================================== When the feat Combat Expertise says, "The changes to attack rolls and Armor Class last until your next action" (*Player's Handbook* 92), that's legacy text from when the game—largely prior to the *3.5* revision—equated *action* with *turn*. That the feat Combat Expertise was never updated to more accurate language—even in the premium edition *Player's Handbook* (2012)—is a sad editorial oversight. This issue of *action*-as-*turn* persists in pockets throughout *3.5e*, but folks tend to ignore the absolutely literal readings in favor of common sense ones, recognizing that the game is, in parts, flawed. For example, a strict reading makes the duration of the effect of the feat [Stunning Fist](http://dndsrd.net/featsAll.html#stunning-fist) baffling: "A defender who fails this saving throw [against a Stunning Fist attempt] is stunned for 1 round (until just before your next action)" (*PH* 101), a contradiction that *possibly* could see a monk stunning his foe and, on the same turn, fleeing from that foe so as to render his foe *un*stunned! Likewise, making a shield bash would lead to odd battlefield behavior, as making a shield bash usually means "you lose [the shield's] AC bonus until your next action (usually until the next round)" (*PH* 125)—so a strict reading enables a creature to, for example, make a shield bash then take a free action on its turn to drop prone and regain its shield's bonus to AC! While such readings are *possible*, such readings are not the norm. More egregiously, the *Player's Handbook* Combat chapter is *rife* with *action* being used as a synonym for *turn*. For example, Combat Basics on Initiative says, "A character is flat-footed until he or she takes an action" (135), and taking a free action to [speak](http://dndsrd.net/actionsInCombat.html#speak) can typically be done even if it's *not* a creature's turn! However, I've never heard of a DM saying that a flat-footed creature that yells *Hey, rube!* off-turn is no longer flat-footed. In sum, a creature that uses the feat Combat Expertise continues experiencing that feat's bonuses and penalties *while* it takes the action that yielded the bonuses or penalties and *after having taken* the action that yielded the bonuses or penalties *until the creature's next turn*—even if, for example, the creature subsequently takes other *actions* during *this* turn or an immediate action or an appropriate free action like speaking *after* its turn yet *before* its next. ***Note:*** Many spells that date to before the 3.5 *revision have the* Casting Time: 1 action *entry in their headers—short for 1 standard action. Just one more reason* action *and* turn *should* never *have meant the same thing!*
No, it is not. Unfortunately, early on the rules used this “your action” terminology to refer to *your turn*. You retain Combat Expertise bonuses until your next turn, e.g. you keep them while moving and then also during other people’s turns. The feat would be even more useless than it already is if it only gave you an AC bonus *while attacking* (it is very rare to be attacked in the middle of your own attack).
22,471,402
``` Page code: --------- <html:select property="projectId" styleClass="ctrlwidthfirstpair"> <html:options collection="projects" property="value" labelProperty="label" /> </html:select> ``` JavaScript: ----------- ``` function isProjectSelected() { var selIndex = document.getElementById("projectId").selectedIndex; if (selIndex == 0) { alert("Please Select Project"); return false; } return true; } ``` `document.getElementById("projectId")` returns `null` value. How to get index of selected option of `<html:select>` component?
2014/03/18
[ "https://Stackoverflow.com/questions/22471402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3386628/" ]
The attribute you're looking for is `styleId`. Next time, try [reading the fine manual](http://struts.apache.org/development/1.x/struts-taglib/tlddoc/html/select.html). ``` <html:select styleId="projectId" ... ```
All html tags in Struts **styleId** property will be rendered as id attribute. Try like that.. ``` <html:select property="projectId" styleId="projectId" styleClass="ctrlwidthfirstpair"> <html:options collection="projects" property="value" labelProperty="label" /> ```
54,545,468
How do I convert this sql query to linq equivalent? I have included my models. I am using EF code first from database. I am new to c# programming so I may not know what to include in my questions. Thank you ``` SELECT RestaurantFranchiseeEmail.Email FROM RestaurantVersions INNER JOIN RestaurantFranchiseeEmail ON RestaurantVersions.RestaurantId = RestaurantFranchiseeEmail.RestaurantId WHERE (RestaurantVersions.VersionId = N'M1') GROUP BY RestaurantFranchiseeEmail.Email, RestaurantVersions.VersionId ``` Models ``` namespace { using System.ComponentModel.DataAnnotations; public class RestaurantVersion { public int Id { get; set; } [StringLength(50)] public string RestaurantId { get; set; } [StringLength(150)] public string Franchisee { get; set; } [StringLength(150)] public string VersionId { get; set; } } } namespace { using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; [Table("RestaurantFranchiseeEmail")] public class RestaurantFranchiseeEmail { public int Id { get; set; } [StringLength(50)] public string RestaurantId { get; set; } [StringLength(150)] public string Franchisee { get; set; } [StringLength(150)] public string Email { get; set; } } } ```
2019/02/06
[ "https://Stackoverflow.com/questions/54545468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1959428/" ]
Are you doing this in debug mode or release mode? Debug mode sometimes demonstrates odd artifacts that go away in the final build.
If you are dealing with static data of very low number of list items, you can speed the list up using ``` ListView( addAutomaticKeepAlives: true, ... ) ```
24,080,438
I have a file like this: > > a sth1 > > a sth2 > > b sth3 > > b sth4 > > c sth5 > > c sth6 > > c sth6 > > d sth8 > > d sth9 > > d sth10 > > X sth10 > > X sth11 > > > > and I woul'd like to recive all lines between first line starting with `b` and last line starting with `d`: > > b sth3 > > b sth4 > > c sth5 > > c sth6 > > c sth6 > > d sth8 > > d sth9 > > d sth10 > > > > I have a sed command `sed -n /"b"/,/"d"/p final.txt` but the output is: > > b sth3 > > b sth4 > > c sth5 > > c sth6 > > c sth6 > > d sth8 > > > > My question is how to modify sed command to get expected result ? **Im sorry for beeing not precise. I should ask about this:** I have a file like this: > > 127.0.0.1 - - [04/Jun/2014:11:21:01 +0200] STH1 > > > > and I want extract content between first line containing `$startDate="04/Jun/2014:12:21:01"` and last line containing `$endDate="04/Jun/2014:13:21:01"`. The result should be: > > 127.0.0.1 - - [04/Jun/2014:12:21:01 +0200] STH4 > > > > `$startDate` and `$endDate` are variables in BASH script. I really apologise for my last post where I asked not precise question...
2014/06/06
[ "https://Stackoverflow.com/questions/24080438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3714326/" ]
If your file is unsorted, then it is necessary to loop twice: first to know the lines to print and then to print them: ``` $ awk 'FNR==NR {if (/^b/ && !b) {b=NR} if (/^d/) {d=NR}; next} (FNR>=b && FNR<=d)' file file b sth3 b sth4 c sth5 c sth6 c sth6 d sth8 d sth9 d sth10 ``` As per comments, if you want to define the `b` and `d` as a parameter you can use: ``` -v start="your_start_date" -v end="your_end_date" ``` See an example with current data: ``` $ awk -v start="b" -v end="d" 'FNR==NR {if ($1 == start && !b) {b=NR} if ($1 == end) {d=NR}; next} (FNR>=b && FNR<=d)' file file b sth3 b sth4 c sth5 c sth6 c sth6 d sth8 d sth9 d sth10 ``` --- Based on your last update: ``` $ startDate="04/Jun/2014:12:21:01" $ endDate="04/Jun/2014:13:21:01" $ awk -v start="$startDate" -v end="$endDate" 'FNR==NR {if ($0 ~ start && !b) {b=NR} if ($0 ~ end) {d=NR}; next} (FNR>=b && FNR<=d)' file file 127.0.0.1 - - [04/Jun/2014:12:21:01 +0200] STH4 127.0.0.1 - - [04/Jun/2014:12:21:01 +0200] STH5 127.0.0.1 - - [04/Jun/2014:12:21:01 +0200] STH6 127.0.0.1 - - [04/Jun/2014:12:21:01 +0200] STH7 127.0.0.1 - - [04/Jun/2014:13:21:01 +0200] STH8 127.0.0.1 - - [04/Jun/2014:13:21:01 +0200] STH9 127.0.0.1 - - [04/Jun/2014:13:21:01 +0200] STH10 ```
If you don't mind `grep`: ``` grep "^[b-d]" file ```
61,850,923
I need to return documents from ES that satisfy these 2 conditions: at least one of conditionIds in the `should` clause should match the `conditionId` property of documents AND at least one of the categoryIds should match. I tried this query but this does not work: ``` { "query": { "bool": { "should": [ { "match": { "conditionIds": "5e24b2f02bd0d76df4615c82" } }, { "match": { "conditionIds": "5e24b2f02bd0d76df4615c82" } }, ], "filter": [ { "query_string": { "default_field": "name", "query": "*" } } ], "must": [ { "match": { "categoryIds": “fc57hj5-0bx-4sha-aw7u-c11cd32eec2a" } }, { "match": { "categoryIds": "d2c5a505-01bb-41ba-ad7e-c11cd32eec2a" } } ] } } } ``` And my document schema: ``` "conditionIds": [ "5e24b2f02bd0d76df4615c81" ], "createdAt": "2020-05-08T19:07:11.756Z", "categoryIds": [ "7b913ed0-54e0-4857-b114-92f65631b6a6" ], "minPrice": 71.47, "locations": [ { "continent": "GLOBAL", "lon": 0, "lat": 0 } ], "id": "c64d03d6-4248-416c-bc07-c42b50548e3b", "maxPrice": 71.47, "statusIds": [ "5e24b2f02bd0d76df4615c81" ], "childrenCount": 1, "updatedAt": "2020-05-08T19:07:11.756Z" } ```
2020/05/17
[ "https://Stackoverflow.com/questions/61850923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13560344/" ]
I Recommend to use [cw](https://www.lucagrulla.com/cw/) . With cw, you can use below command: ``` cw tail -f my-log-group:my-log-stream-prefix ```
The `aws logs tail` command [now has a `--log-stream-name-prefix` flag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/tail.html) that you can use to only show logs from the desired log stream(s). However, you may need to [update to the latest version](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) in order to use it. For example, you could probably do this in your case: ``` aws logs tail /aws/batch/job --follow --since 1d --log-stream-name-prefix my-stream-name ``` I'm actually really excited that they have added this feature. I've been wanting something like this as well for quite some time.
757
Can I get a VST plugin of a denoiser for cubase 5? [Steinberg](http://www.steinberg.net/en/home.html) products like [Nuendo](http://www.steinberg.net/en/products/audiopostproduction_product/nuendo4.html) and [Cubase](http://www.steinberg.net/en/products/musicproduction/cubase5_product.html) are very similar, I would like to use [Cubase 5](http://www.steinberg.net/en/products/musicproduction/cubase5_product.html) like I use [Neundo 3](http://www.steinberg.net/en/products/audiopostproduction_product/nuendo4.html) for dialgoue editing and cleaning. [Steinberg Cubase http://www.steinberg.net/index.php?eID=tx\_nawsecuredl&u=0&file=uploads/pics/visual\_products\_cubase5\_jhdregfhjegsh\_82.jpg&t=1272817273&hash=d1967a4b1eb868e93e69162a3fa1491b](http://www.steinberg.net/en/products/musicproduction/cubase5_product.html)
2010/04/24
[ "https://sound.stackexchange.com/questions/757", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/243/" ]
Have a look at [iZotope RX](https://www.izotope.com/en/products/repair-and-edit/rx.html) ($349). [![iZotope RX](https://i.stack.imgur.com/301qI.jpg)](https://www.izotope.com/en/products/repair-and-edit/rx.html) (source: [izotope.com](http://www.izotope.com/products/audio/RX/images/denoiser_ss.jpg))
There's the [Waves Bundle](https://www.waves.com/plugins) with all its restoration tools that works great with Cubase and Nuendo (VST, Dx, RTAS)($1860). [![Waves Noise suppressor](https://i.stack.imgur.com/ojOfe.jpg)](https://www.waves.com/plugins) (source: [waves.com](http://www.waves.com/objects/images/large_screenshots/large_WNS.jpg))
39,017,192
Suppose that we have these strings in MATLAB: ``` xx = 'C:/MY_folder/This_gg/microsoft/my_file'; ``` or ``` xx = 'C:/end_folder/This_mm/google/that_file'; ``` I want remove expression after end `/` (`my_file` and `that_file`). How can I do this using regular expression in MATLAB?
2016/08/18
[ "https://Stackoverflow.com/questions/39017192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2991243/" ]
I know you're asking for a regular expression but there's a simpler way: ``` pathStr = fileparts(xx) ``` Or, if you want all parts of the file ``` [pathStr, name, ext] = fileparts(xx) ```
1. If you want to **also remove the final `/`**, use ``` yy = regexprep(xx, '/[^/]*$', ''); ``` The regexp pattern `'/[^/]*$'` matches a `/` followed by any number of non-`/` at the end of the string. The match is replaced ([`regexprep`](http://es.mathworks.com/help/matlab/ref/regexprep.html)) by the empty string. 2. If you want to **keep the final `/`**, you can modify the regexp with a [lookbehind](http://www.regular-expressions.info/lookaround.html) assertion: ``` yy = regexprep(xx, '(?<=/)[^/]*$', ''); ``` or in 1 replace by `'/'` instead of by `''`: ``` yy = regexprep(xx, '/[^/]*$', '/'); ```
74,653,746
Consider: ``` let N = 12 let arr = [1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1] ``` Your task is to find the maximum number of times an odd number is continuously repeated in the array. What is the approach for this? This is the hint: 1 is repeated 4 times from index 0 to index 3 → 4 times 2 is repeated 5 times from index 4 to index 8 → 5 times 1 is repeated 3 times from index 9 to index 11 → 3 times The odd numbers in array are 1s. 1 occurs 4 times and 3 times continuously, so 4 is the maximum number of times an odd number is continuously repeated in this array. ``` function longestRepeatedOdd(N, array) { // Write code here let count = 0; for (let i = 0; i <= array.length-1; i++){ if (array[i] % 2 !== 0){ count++ }else if (array[i] % 2 === 0){ break; } } console.log(count) } ```
2022/12/02
[ "https://Stackoverflow.com/questions/74653746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20655704/" ]
Since you are using a SQL Server DB, you can use `EXCEPT`: ``` SELECT bold_id FROM ( SELECT 354469477 AS bold_id UNION ALL SELECT 354469536 UNION ALL SELECT 354469500 UNION ALL SELECT 987359 ) listofValues EXCEPT SELECT bold_id FROM TripEvent; ``` OR: ``` SELECT bold_id FROM ( VALUES (354469477), (354469536), (354469500), (987359) ) listofValues(bold_id) EXCEPT SELECT bold_id FROM TripEvent; ``` Have a look in the [documentation](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-except-and-intersect-transact-sql?view=sql-server-ver16)
Found this query on another places. Seems to work. Thanks for the good response :) ``` SELECT * from (values (354469477),(354469536),(354469500),(987359)) as v(id) WHERE NOT EXISTS (SELECT BOLD_ID FROM TripEvent WHERE TripEvent.BOLD_ID = v.id) ```
48,520,855
I have the below sequence of the chained loop which I want to return using promises but I get the response before the forEach is executed in my code... Can anyone tell me where I am going wrong... I would like to do it using native Promises and would not prefer to use await/async so I get a better understanding of how Promises function. ``` Details.find(function(err,details){ if(err){ res.send(err) }else{ console.log("----------First Promise------------") return details } }).then(result1 => { result1.forEach(function(item){ renderData = {} OrgChart.findOne({GID:item.gid},function(err,detail){ console.log("Detail is ------> " + detail.DISPLAY_NAME) if(err){ res.send(err) }else{ return detail.DISPLAY_NAME } }).then( result2 => { renderData.gid = result2.DISPLAY_NAME renderData.pageouttime = item.pageouttime renderData.createdAt = item.createdAt renderData.oncall = item.oncall renderData.comments = item.comments renderData.actionLink = item._id.toString() console.log(renderData) dataArr.push(renderData) }) }) }).then(result3 => { console.log("Final Result is ----> " + result3) response.data = result3 res.json(response) }) ``` Inside the forEach, I want to get a value using a value of the row. I am new to node js and Promises... I want to achieve something like below but using Promises. Example sequence I want to Achieve through Promises ``` var someArray = [] var DetailsObj = Details.find() DetailsObj.each(function(item){ var newMap = {} newMap.prop1=item.prop1 newMap.prop2 = item.prop2 newMap.prop3 = OrgChart.find({id:item.prop3}).displayName someArray.push(newMap) }) ``` Please, can anyone let me know where I am going wrong? Update 1(Not Working) ``` return Promise.all(result1.map(function(item){ renderData = {} OrgChart.findOne({GID:item.gid},function(err,detail){ console.log("Detail is ------> " + detail.DISPLAY_NAME) if(err){ res.send(err) }else{ return detail.DISPLAY_NAME } }).then(result2 => { renderData.gid = result2.DISPLAY_NAME renderData.pageouttime = item.pageouttime renderData.createdAt = item.createdAt renderData.oncall = item.oncall renderData.comments = item.comments renderData.actionLink = item._id.toString() console.log(renderData) dataArr.push(renderData) }) })) ``` Still i get an empty array Update 2 (Added return from the map callback--- Still not Working) ``` return Promise.all(result1.map(function(item){ renderData = {} OrgChart.findOne({GID:item.gid},function(err,detail){ console.log("Detail is ------> " + detail.DISPLAY_NAME) if(err){ res.send(err) }else{ return detail.DISPLAY_NAME } }).then(result2 => { renderData.gid = result2.DISPLAY_NAME renderData.pageouttime = item.pageouttime renderData.createdAt = item.createdAt renderData.oncall = item.oncall renderData.comments = item.comments renderData.actionLink = item._id.toString() console.log(renderData) dataArr.push(renderData) }) return dataArr }) ) ``` Update 3(Updated after returning from the `then()` callback in the `Promise.all()` block --- Still not Working) ``` return Promise.all(result1.map(function(item){ renderData = {} OrgChart.findOne({GID:item.gid},function(err,detail){ console.log("Detail is ------> " + detail.DISPLAY_NAME) if(err){ res.send(err) }else{ return detail.DISPLAY_NAME } }).exec().then(result2 => { renderData.gid = result2.DISPLAY_NAME renderData.pageouttime = item.pageouttime renderData.createdAt = item.createdAt renderData.oncall = item.oncall renderData.comments = item.comments renderData.actionLink = item._id.toString() return renderData }) }) ) ```
2018/01/30
[ "https://Stackoverflow.com/questions/48520855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4681491/" ]
First of all, you should properly [promisify](https://stackoverflow.com/q/22519784/1048572) your functions: ``` function findDetails() { return new Promise((resolve, reject) => { Details.find((err, details) => { if (err) reject(err); else resolve(details); }); }); } function findChart(gid) { return new Promise((resolve, reject) => { OrgChart.findOne({GID:item.gid}, (err, detail) => { if (err) reject(err); else resolve(detail); }); }); } ``` or, as your library seems to support for simplicity (notice we're not passing any callbacks!): ``` function findDetails() { return Details.find().exec(); } function findChart(gid) { return OrgChart.findOne({GID:item.gid}).exec(); } ``` Now we can build the promise chain from those (notice all the `return` statements!): ``` findDetails().then(details => console.log("----------First Promise------------"); return Promise.all(details.map(item => { // ^^^^^^ return findChart(item.gid).then(detail => // ^^^^^^ console.log("Detail is ------> " + detail.DISPLAY_NAME) const renderData = { gid: detail.DISPLAY_NAME, pageouttime: item.pageouttime, createdAt: item.createdAt, oncall: item.oncall, comments: item.comments, actionLink: item._id.toString(), }; console.log(renderData); return renderData; // ^^^^^^ }); })); }).then(dataArr => { console.log("Final Result is ----> " + dataArr); response.data = dataArr; res.json(response); }, err => { res.send(err); }); ```
If it is Sails you are using (should add the tag in the question and mention it) then according to the [documentation](https://sailsjs.com/documentation/reference/waterline-orm/queries#promises) it supports promises. But the documentation says that promises are an **alternative** to `exec` So your code should look like this: ``` Details.find() .then( result => Promise.all( result.map( item=> OrgChart.findOne({GID:item.gid}) .then(//here is where your code is confusing // does detail have detail.DISPLAY_NAME.DISPLAY_NAME? // I assume it has not details=>({ gid : details.DISPLAY_NAME, pageouttime : item.pageouttime, createdAt : item.createdAt, oncall : item.oncall, comments : item.comments, actionLink : item._id.toString() }) ) ) ) ) .then( results=>{ console.log("results are:",results); } ) .catch( err=>console.error("Something went wrong:",err) ); ```
5,552
I have a very general question which bothers me but i want to add some details first. I'm a core Java programmer. I have independently created some small games in Java for fun. Now, the more I'm looking into professional game development the more I'm getting confused. This is because, whenever I Google about some game development topics or visit any fora etc., I come across different suggestions. Some will say C++ is good, while some will say JAVA may be better, while still others will say some other language is the ur-language, like Python, Lua, UnrealScript, etc. Also it is suggested that one ought to have knowledge of game engines like Unreal, Torque, Blender, Panda, etc and knowledge of OpenGL, AI, Collision Detection is required. I have even created a game using Android SDK. What I want to ask is: * What is the basic skill set that a Professional Game Programmer needs to have? Is it any 1 Programming Language + 1 Scripting language + 1 Game engine knowledge + OpenGL? (Phew!!) * If I want to enter into Game Industry as Gameplay Programmer or AI programmer then can I get into it with my current skills and portfolio (as stated above)? * Is learning one programming language is enough for Game Development? Any guideline will be helpful.
2010/11/15
[ "https://gamedev.stackexchange.com/questions/5552", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/3212/" ]
There is another very important skill needed that seems to be a little overlooked. You need to know how to fit in and work with a team of people, going from other game devs, to designers and project managers and stuff. It's not a technical skill, but it's still very important, as you could be the best dev in the house and if you can't get on with people, make large games is going to be a problem! Also, as ShrimpCrackers kowing one language well is better than roughly knowing 5 languages, and understanding what goes on under the hood of that one language you are goot at is even better, as for games, you need to know how to get the best performance out of the language. Last but not least, knowing a little about hardware, GPU in particular won't hurt!
For programming social games there are to main skills that are the only ones needed. 1. Program action script (you can use an elipse environment and a svn), this is used for the front end of the game (the webpage) 2. Program java (which can also be done on eclipse an use svn), this is used for the server side actions to take from the requests of the webpage.
68,748,937
I have written this code in a react native project not in a component, I only have to store an array: ``` fetch(url, {}) .then(res => res.json()) .then(data => console.log(data)) ``` And everything works, but I would like to store what I printed. Instead using `console.log(data)` I have tried to use `const newData = data` but printing it I have noticed I have got `undefined`.
2021/08/11
[ "https://Stackoverflow.com/questions/68748937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15508573/" ]
no need for `touchableopacity` because `Text` has `onPress` prop. ```js <Text style={{fontSize:10,textAlign:'center'}}> By clicking Sign up, you agree to Companys <Text onPress={() => alert("Terms of Service is clicked")} style={{fontSize:10, color:'blue'}}> Terms of Service </Text> and <Text onPress={() => alert("Privacy Policy is clicked")} style={{fontSize:10, color:'blue'}}> Privacy Policy. </Text> </Text> ```
If you switch the surrounding `<Text>` to `<View>` the texts will be vertically aligned: ```js const styles = StyleSheet.create({ paragraph: { flexDirection: 'row', flexWrap: 'wrap', justifyContent:'center', }, text: { fontSize: 10, }, link: { color: 'blue', }, }) // Extend the hit area of the links by 15pt vertically and 5pt horizontally: const hitSlop = { top: 15, left: 5, bottom: 15, right: 5 } <View style={[styles.paragraph]}> <Text style={[styles.text]}>By clicking Sign up, you agree to Company's </Text> <TouchableOpacity hitSlop={hitSlop}> <Text style={[styles.text, styles.link]}>Terms of Service</Text> </TouchableOpacity> <Text style={[styles.text]}> and </Text> <TouchableOpacity hitSlop={hitSlop}> <Text style={[styles.text, styles.link]}>Privacy Policy</Text> </TouchableOpacity> <Text style={[styles.text]}>.</Text> </View> ``` Please note that the spaces behind `Company's` and around `and` are required to have natural spaces around the links.
42,824,281
I am new to DynamoDB and I am finding it hard to think of how I should decide my partition key. I am using a condensed version of my use case: I have an attribute which is a boolean value => B For a given ID, I need to return all the data for it. The ID is either X or Y attribute. For the given ID, if B is true, I need to read attribute X, else Y. While inserting into the table I know the the value of B and hence I can fill it in either X or Y depending on the value of it. However while fetching, I just am given an ID, and I need to figure out whether it exists in column X or column Y ( I won't be getting the value of B in the input). In a RDBMS I could run a query like `select * from tab where (B == true && X == ID) || (B==false && Y == ID)`. I think creating a GSI in DynamoDB will be the way to go about solving this in Dynamo. However I am not able to figure out the best way to approach this. Could I get suggestions?
2017/03/16
[ "https://Stackoverflow.com/questions/42824281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692342/" ]
You can attach an `onDisconnect()` handler to any location in your database and remove or write data to that location. But realize that `onDisconnect()` works by sending the write operation to the Firebase servers up front. So you can write any value, as long as that value can be calculated on the client when you attach the `onDisconnect` listener.
It's very simple. It's even their in the docs: <https://firebase.google.com/docs/database/web/offline-capabilities#section-connection-state> ``` var connectedRef = firebase.database().ref(".info/connected");//reference to a location in the database with the data as true. This will be read-only connectedRef.on("value", (snap) => { if (snap.val() == true) { //code for when we are connected } else { //update your data here } }); ```
33,445,134
I want to find a delimiter being used to separate the columns in csv or text files. I am using TextFieldParser class to read those files. Below is my code, ``` String path = @"c:\abc.csv"; DataTable dt = new DataTable(); if (File.Exists(path)) { using (Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(path)) { parser.TextFieldType = FieldType.Delimited; if (path.Contains(".txt")) { parser.SetDelimiters("|"); } else { parser.SetDelimiters(","); } parser.HasFieldsEnclosedInQuotes = true; bool firstLine = true; while (!parser.EndOfData) { string[] fields = parser.ReadFields(); if (firstLine) { foreach (var val in fields) { dt.Columns.Add(val); } firstLine = false; continue; } dt.Rows.Add(fields); } } lblCount.Text = "Count of total rows in the file: " + dt.Rows.Count.ToString(); dgvTextFieldParser1.DataSource = dt; ``` Instead of passing the delimiters manually based on the file type, I want to read the delimiter from the file and then pass it. How can I do that?
2015/10/30
[ "https://Stackoverflow.com/questions/33445134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5508691/" ]
Mathematically correct but totally useless answer: It's not possible. Pragmatical answer: It's possible **but** it depends on how much you know about the file's structure. It boils down to a bunch of assumptions and depending on which we'll make, the answer will vary. And if you can't make any assumptions, well... see the mathematically correct answer. For instance, can we assume that the delimiter is one or any of the elements in the set below? ``` List<char> delimiters = new List<char>{' ', ';', '|'}; ``` Or can we assume that the delimiter is such that it produces elements of equal length? Should we try to find a delimiter that's a single character or can a word be one? Etc. Based on the question, I'll assume that it's the first option and that we have a limited set of possible characters, precisely one of which is be a delimiter for a given file. How about you count the number of occurrences of each such character and assume that the one that's occurring most frequently is the one? Is that sufficiently rigid or do you need to be more sure than that? ``` List<char> delimiters = new List<char>{' ', ';', '-'}; Dictionary<char, int> counts = delimiters.ToDictionary(key => key, value => 0); foreach(char c in delimiters) counts[c] = textArray.Count(t => t == c); ``` I'm not in front of a computer so I can't verify but the last step would be returning the **key** from the dictionary the **value** of which is the maximal. You'll need to take into consideration a special case such that there's no delimiters detected, there are equally many delimiters of two types etc.
In python we can do this easily by using csv sniffer. It will cater for text files and also if you just need to read some bytes from the file.
19,912,971
The second output of the `libsvmread` command is a set of features for each given training example. For example, in the following MATLAB command: ``` [heart_scale_label, heart_scale_inst] = libsvmread('../heart_scale'); ``` This second variable (heart\_scale\_inst) holds content in a form that I don't understand, for example: ``` <1, 1> -> 0.70833 ``` What is the meaning of it? How is it to be used (I can't plot it, the way it is)? PS. If anyone could please recommend a good LIBSVM tutorial, I'd appreciate it. I haven't found anything useful and the README file isn't very clear... Thanks.
2013/11/11
[ "https://Stackoverflow.com/questions/19912971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2097126/" ]
The definitive tutorial for LIBSVM for beginners is called: [A Practical Guide to SVM Classification](http://www.csie.ntu.edu.tw/~cjlin/papers/guide/guide.pdf) it is available from the site of the authors of LIBSVM. The second parameter returned is called the instance matrix. It is a matrix, let call it M, M(1,:) are the features of data point 1 and so on. The matrix is sparse that is why it prints out weirdly. If you want to see it fully print full(M). ``` [heart_scale_label, heart_scale_inst] = libsvmread('../heart_scale'); ``` with heart\_scale\_label and heart\_scale\_inst you should be able to train an SVM by issuing: ``` mod = svmtrain(heart_scale_label,heart_scale_inst,'-c 1 -t 0'); ``` I strong suggest you read the above linked guide to learn how to set the c parameter (and possibly, in case of RBF kernel the gamma parameter), but the above line is how you would train with that data.
I think it is the probability with which test case has been predicted to heart\_scale label category
2,074,447
We have to find all value of $\theta,$ between $0$ & $\pi,$ which satisfy the equation; $\cos\theta \cdot \cos2\theta \cdot \cos 3\theta = \dfrac{1}{4}$ I tried it a lot. But every time I got stuck and get no result.
2016/12/28
[ "https://math.stackexchange.com/questions/2074447", "https://math.stackexchange.com", "https://math.stackexchange.com/users/356141/" ]
We have, $$\cos \theta \cos 2\theta \cos 3\theta =\frac{1}{4}$$ $$\Rightarrow 4\cos \theta \cos 2\theta \cos 3\theta =1$$ $$\Rightarrow (2\cos 3\theta \cos \theta)2\cos 2\theta =1$$ $$\Rightarrow (\cos 4\theta +\cos 2\theta)2\cos 2\theta -1=0$$ $$\Rightarrow 2\cos 2\theta \cos 4\theta +\cos 4\theta =0$$ This gives us, $$\cos 4\theta =0\mid \cos 2\theta =-\frac{1}{2}$$ where $\mid$ stands for "or". I hope you will be able to take it from here.
HINT: Use [Werner Formulas](http://mathworld.wolfram.com/WernerFormulas.html) $2\cos x\cos3x=\cos2x+\cos4x$ and $2\cos4x=\cos^22x-1$ to form a cubic equation in $\cos2x$
41,382
For Loading product by sku i'm using following function. For some skus its working fine where as for some sku's not working.And these sku products existed in back end. ``` $_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku); ``` Can you help anyone?
2014/10/25
[ "https://magento.stackexchange.com/questions/41382", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/5373/" ]
If neither of the following are working. 1. `Mage::getModel('catalog/product')->load($sku, 'sku');` 2. `Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);` Then you could always use the resource model, `Mage_Catalog_Model_Resource_Product`, to get the product id via the function `getIdBySku` and then simply do a normal load.
**\*`loadByAttribute()`** basically load the ***product collection and filter those collection by sku and then it return that collection first item as a result***. That ***particular sku does not exits*** at result ***because of*** `that particular product' does not exits to the products collection` ``` $collection = $this->getResourceCollection() ->addAttributeToSelect($additionalAttributes) ->addAttributeToFilter($attribute, $value) ->setPage(1,1); ``` As per as,magento ***a product does not visible at collection because of Product's*** [flat setting enable](http://inchoo.net/magento/flat-tables-in-magento-and-product-collection/) and ***due to some reason like magento condition like visibility, stock, website,store*** ,a product not include at product flat collection. If you load the product by load by `Mage::getModel('catalog/product')->load($id);` And this code is **direct called of product model** that you can get ***result and also it does not called from collection,just call a particular model by id*** that
18,634,222
I have this code in C#/ASP.net ``` foreach (String projectType in ProjectsByProjectType.Keys) { HtmlTableRow trh = new HtmlTableRow(); HtmlTableCell tdProjectType = new HtmlTableCell(); tdProjectType.InnerHtml = projectType; trh.Controls.Add(tdProjectType); tableLocal.Controls.Add(trh); } ``` When this line runs ``` tdProjectType.InnerHtml = projectType; ``` I'd like the text within the `innerHTML` to be in a bold font type (so take the string referenced by 'projectType' and make it bold). How do I do this?
2013/09/05
[ "https://Stackoverflow.com/questions/18634222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2123529/" ]
You can try ``` foreach (String projectType in ProjectsByProjectType.Keys) { HtmlTableRow trh = new HtmlTableRow(); HtmlTableCell tdProjectType = new HtmlTableCell(); tdProjectType.InnerHtml = "<b>"+projectType+"</b>"; trh.Controls.Add(tdProjectType); tableLocal.Controls.Add(trh); } ```
I think the semantically correct way would be to use one of the following in preferential order `tdProjectType.InnerHtml = "<h2>" + projectType "</h2>";` or whichever h tag you want to use `tdProjectType.InnerHtml = "<strong>" + projectType "</strong>";` `tdProjectType.InnerHtml = "<b>" + projectType "</b>";`
3,488,698
I recently tested a Cappuccino app I was working on with Chrome and Safari. I get the error: ``` INVALID_STATE_ERR: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable. ``` The lack of information is frustrating. What object and where did I attempt to use it? Chrome tries to answer the second question but the line number it gives, 465, doesn't mean anything when the file it gives is just 94 lines long. Without more information I don't even know where to start looking.
2010/08/15
[ "https://Stackoverflow.com/questions/3488698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250138/" ]
This can also happen when Javascript tries to `document.write()` into an XHTML page (`Content-Type: application/xhtml+xml`).
Both Chrome and Safari have built in debuggers. Make sure you use the index-debug.html file to launch your application to get easy to read code. In Safari, go to Preferences and activate the Developer menu. Then go to Develop > Start Debugging JavaScript. Use the pause icon in the lower left to set the debugger to pause on errors. The next time you hit the problem the debugger will pause at the offending line and show you how it got there through the stack trace.
14,611,008
What is the best practice for iterating over an integer in Python? I find that I need to do so often, typically with verbose results. For example, here are two functions I wrote for [Project Euler](https://projecteuler.net) problems: ``` def is_permutation_of(n, m): """ Return True if n is a permutation of m, else False """ if len(str(n)) != len(str(m)): return False for d in str(n): if d not in str(m): return False return True ``` And another: ``` def has_even_digit(n): """ Return True if n has an even digit, else False """ evens = ['0', '2', '4', '6', '8'] for e in evens: if e in str(n): return True return False ``` In addition to the verbosity, 1) there must be a computational expense associated with each type conversion and 2) it just feels completely inelegant. Is there another way of dealing with this issue? Am I going about these functions in entirely the wrong way, i.e. should I not have to ever iterate over an integer? Thanks for any help.
2013/01/30
[ "https://Stackoverflow.com/questions/14611008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1830334/" ]
I personally find `for e in str(n)` very readable. What I do find less pleasing to the eye are the repeated calls to `str(n)` inside loops (where `n` is invariant). Anyhow, I would implement both functions completely differently ``` def is_permutation_of(n, m): return sorted(str(n)) == sorted(str(m)) def has_even_digit(n): if n == 0: return True while n != 0: if n % 2 == 0: return True n //= 10 return False ```
For iterating over even digits, you can use [range's `step`](http://docs.python.org/2/library/functions.html#range) parameter: `range(start, end, step)` So, in your code, you could do: `for e in range(0, 8, 2):`
39,237
As my kids are counting down to Christmas, I came to wonder how did people measure time through history. More precisely I wonder about unit systems for precision time keeping of years past gone. I am wondering this, because the other two most prominent units (length and mass), have had many systems of units, which still echo from the past (some louder some less so). So even though I know of fathoms and leagues or slugs and stones, I don't ever remember encountering any other unit system other than that of second, hour, day, month, year. I've checked Wikipedia at [History of timekeeping devices](https://en.wikipedia.org/wiki/History_of_timekeeping_devices), but only devices are mentioned (see hourglasses, burning incenses etc). However, nothing I could find about the actual names of units. Has anyone else found the names of the actual units? **UPDATE**: Thanks everybody for their responses. All of the answers so far for me had merit, even though on hindsight the question was not strictly engineering - it is more on measuring, which I perceive as a vital part of engineering. I've got to admit that the response is even better that I had hoped. I learned a lot of new things. Hopefully, there will be in *time* even more informational answers.
2020/12/21
[ "https://engineering.stackexchange.com/questions/39237", "https://engineering.stackexchange.com", "https://engineering.stackexchange.com/users/19906/" ]
Judaism has a long history of tracking both days and times. Most of this is centered around Jewish holidays, particularly the need for Passover to take place in the spring. The basic date measurements are the day, lunar month (basically alternates between 29 and 30 days) and the year. The year is measured as a combination lunar/solar year, approximately 354 days in a regular (12 months) year and 383 days in a leap (13 months) year. Originally the months were set by witnesses of the new moon (the first sighting of the moon in the monthly cycle) and leap year determination was made based on a number of factors. Eventually a set cycle for the days of each month (most months always the same, Cheshvan and Kislev varying) and leap years (3rd, 6th, 8th, 11th, 14th, 17th and 19th years of 19 year cycle) was set. This was finalized sometime between ~ 850 and 1,700 years ago. See [the fixing of the Hebrew calendar](https://en.wikipedia.org/wiki/Hebrew_calendar#The_fixing_of_the_calendar) for more details. Times are measured in two ways: Seasonal hours (as mentioned in other answers) = 1/12th of the daytime or nighttime. These are used for determining [times for prayers and other observances](https://en.wikipedia.org/wiki/Zmanim) on a given day or night. For most calculations, a full hour or a large fraction thereof (e.g., Plag Hamincha = 1-1/4 seasonal hours before sunset) is used - precision to exact minutes and seconds is only practical today with modern clocks. Absolute hours = 1/24th of a solar day. But in addition to hours, the calculations for the months (see above) actually goes down to [Chalakim](https://en.wikipedia.org/wiki/Helek). There are 1,080 Chalakim per hour, or 3-1/3 seconds per Chelek. The key is that by measuring at the Chelek level, specifically 29 days 12 hours and 793 Chalakim per lunar month, the total Jewish calendar for 19 years works out to 365.2468222 days per solar years, incredibly close to the modern calculated value of approximately 365.2422 days - see [Tropical Year](https://en.wikipedia.org/wiki/Tropical_year) for more details.
In ancient India, multiple hindu texts have [measured time](https://en.wikipedia.org/wiki/Hindu_units_of_time) (**kāla**, which is eternal) ranging from microseconds to trillions of years. Some of these texts date back as far as 2nd millennium BCE. For example, **Rig Veda** - oldest known Vedic Sanskrit text - gives base / smallest unit of measurement as Paramāṇu (परमाणु) which is ≈ 25 µs. Longer measurement of time is based on lunar, solar, tropical and cosmic events - measuring in multiples of hours, days and years. The **[Hindu calendar](https://en.wikipedia.org/wiki/Hindu_calendar)** has been in use in the Indian subcontinent since the Vedic time, which is a lunisolar calendar. Unlike the Gregorian calendar which adds an extra day - it inserts an extra full month by complex rules, once every 32–33 months, to ensure that the festivals and crop-related rituals fall in the appropriate season. On cosmic metrics, hindu mythologies suggests the time repeats in **[cycles of four yugas](https://en.wikipedia.org/wiki/Yuga_Cycle)** (चतुर युग - longest measurement of time) - namely Satya, Treta, Dvapara, and Kali⁠ - where eternal time repeats general events (symbolizing stages in rise and falls of humans). We are currently in the Kali yuga, last in the cycle. Also, interestingly, there is also a concept of **[time dilation](https://en.wikipedia.org/wiki/Time_dilation)** in the mythology (with no scientific explanation) - wherein different entities experience different elapsed time. There is also a suggestion that our forefathers experienced time slower than what we do. Most of these ways to measure time is rarely used in modern India - their use is limited only to religious rituals.
20,266,184
Friendship in my DB is a two way street. Check screenshot: ![enter image description here](https://i.stack.imgur.com/ncFAe.png) So user id 14 and 1 are friends. I want a query that can be initiated by either party and that deletes two way street completely removing both rows. How would I go about doing this? This is not simple WHERE asked asker = id.
2013/11/28
[ "https://Stackoverflow.com/questions/20266184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use `AND` and `OR` to create a condition from simpler conditions, like ``` (asker_user_id = 14 AND asked_user_id = 1) OR (asked_user_id = 14 AND asker_user_id = 1) ```
``` DELETE FROM friendship WHERE (asker_user_id = 14 AND asked_user_id = 1) OR (asker_user_id = 1 AND asked_user_id = 14) ```
5,186,815
I have an issue with a memory leak. I have a base-class pointer. From it, I use `new` to allocate different derived classes. Then, when I try to `delete` those classes with the reference (not typecasted), I get a memory leak. I researched the problem and found that I should add a virtual destructor to the base-class, but I tried this and I still have a memory leak; that is, according to my task-manager, the memory usage continues to rise with each allocation and deletion of the derived class using the base-class pointer. I tried making it an abstract destructor and added destructors to the derived classes, but I got an undefined reference error. I also tried typecasting the pointer as a derived-class pointer for the `delete`, but apparently this crashes the program. Does anyone have any idea what I should do? Example code: ``` class A { public: A(); ~A() {}; virtual ~A(); /*or*/ virtual ~A()=0; /*or*/ /*or nothing?*/ } class B: private A { public: B(); ~B() {}; /*this?*/ /*or nothing?*/ } ```
2011/03/03
[ "https://Stackoverflow.com/questions/5186815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586652/" ]
How sure are you that there really is a memory leak? Normally, the task manager won't be much help here, since it cannot tell how much of the memory belonging to your process is actually allocated. Even memory that is freed still belongs to your process, and may be used at later times by the memory management (normally malloc-like system library). Use a tool such as mallocdebug, valgrind, purify etc. to find out if there's really a memory leak. These tools will replace the malloc implementation by a new one that keeps track of allocated memory and reports memory that is not freed upon process termination. Note: On most systems, memory that is freed from a process is not returned to the system before the process exits. It is availabe for new allocations from within the same process, though.
You can use: ``` virtual ~A(){} ``` or ``` virtual ~A()=0; // as long as there is also: A::~A(){} // inline in the header file or non-inline in the cpp file. ``` This means that: ``` A* base; ... delete base; ``` will call all the destructors of the derived classes in the correct order. Note that a pure virtual destructor: `virtual ~A()=0;` can be useful if you need to have an abstract base class when no other member functions are pure virtual.
9,633,934
I have a windows form without running it in an application. this is the core function that i have to call within the form... there are some class variables the only really important one is the closingpermission. the user has to press a button to close the window. Unfortunately i cant get it to update and process events. `this.Update()`, `this.Refresh()` wont do the trick. ``` internal short ask(String question, String RegExFilter, out String answer) { this.RegExFilter = RegExFilter; this.Text = question; this.Show(); while (!closingpermission) { //Window needs to process its events and allow the user to interact. } answer = answerBox.Text; this.Close(); return RetVal; } ``` EDIT: "Application" means the singleton Application - i dont have that. The loop has to keep the form displayed - i think the soution is something [Hans Passant](https://stackoverflow.com/users/17034/hans-passant) wrote. I need to pump a message loop. The solution of [Ken2K](https://stackoverflow.com/users/870604/ken2k) does not work for me. Edit #2: Here is a compileable Example - the update methos refreshes my window but i can not edit the textbox - nevermind about the button or what i will do next with the text. I cant even edit the text. ``` using System.Windows.Forms; using System.Drawing; //System.Drawing.dll namespace StackOverFlowDemo { class Example { public static void Main() { Input input = new Input(); input.Ask("Something"); } } class Input : Form { TextBox textbox = new TextBox(); public Input() { this.Controls.AddRange(new Control[] { textbox }); this.Bounds = new Rectangle(0, 0, 500, 500); this.textbox.Bounds = new Rectangle(10, 10, 480, 200); } internal void Ask(string question) { this.Text = question; this.Show(); while (true) { this.Update(); } } } } ``` Edit #3 I think what i want can not be done. I read up on the Topic and it seems that you need "something" that calls `protected override void WndProc(ref Message m);` all the time. That something seems to be Application. I am unaware of any way to do this in an application that does not have an application. Please disagree with me :)
2012/03/09
[ "https://Stackoverflow.com/questions/9633934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536874/" ]
From what I understand, you're trying to pop-up a Form to the user and ask him to enter some text. Don't do an infinite loop, it won't work. `Update` and `Refresh` are pointless too. You could use a modal form (often preferable for a pop-up that prompts a value to the user) and the `Cancel` property of the [`FormClosingEventArgs`](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx): ``` public partial class Form2 : Form { private bool preventClose = true; public string ResultString { get { // Returns the content of a textbox return this.textBox1.Text; } } public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // Closes only when button1 is clicked this.preventClose = false; this.Close(); } private void Form2_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = this.preventClose; } } using (Form2 frm = new Form2()) { frm.ShowDialog(); string res = frm.ResultString; } ```
The simple solution will be to use `Application.DoEvents();` but I'm a bit confused by your title.
10,248,893
I get this error message: ``` pg_dump: too many command-line arguments (first is "demo_db") Try "pg_dump --help" for more information. rake aborted! Error dumping database Tasks: TOP => db:structure:dump (See full trace by running task with --trace) ``` This used to work under Rails 3.1. I'm using Rails 3.2.3 and PostgreSQL 9.0.5. Other tasks like db:migrate or db:rollback work just fine.
2012/04/20
[ "https://Stackoverflow.com/questions/10248893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235297/" ]
Thanks to dbenhur I found the issue. I have a space in the path of my filename. Changing line 392 of `activerecord/lib/active_record/railties/databases.rake` to ``` pg_dump -i -s -x -O -f '#{filename}' #{search_path} #{abcs[Rails.env]['database']} ``` (adding the single quotes around `#{filename}`) fixes the issue.
I fixed this (dark) issue by creating a new app with postgresql as database (`rails new MyApp -d postgresql`), and then move all my old app files (/app folder, migrations, and some /config files) to new one. Now when I run rake db:migrate, there are no pg\_dump error. I hope this helps someone.
47,371,869
I use [this solution](https://stackoverflow.com/a/36248168/1354580) to change the button text of `<input type="file" />.` It works, but it have a small drawback - after a file was chosen the user will not see what file was selected, because this info is not displayed (it is hidden with the original button). How to make visible this information without to display the original (hidden) button? The code: ``` <input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('file').click();" /> <input type="file" style="display:none;" id="file" name="file"/> ```
2017/11/18
[ "https://Stackoverflow.com/questions/47371869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354580/" ]
You can just use a [mid-rule action](https://www.gnu.org/software/bison/manual/html_node/Mid_002dRule-Actions.html): ``` fun_decl : type {declare_fonction($1);} fun {end_fonction();}; ``` This has the advantage that bison knows the type of `$1`. It never tries to figure out the type of `$0` because it is not possible in the general case. As discussed in the manual, mid-rule actions can create shift-reduce conflicts. "Marker" (empty) non-terminals, like your `routine`, can also create shift-reduce conflicts, and roughly under the same circumstances. But that will be a different question.
I just found the solution to my problem, I had to specify the type of $0, to let Bison know the size to take in the stack. In my case : ``` routine : {declare_fonction($<type_object>0);}; ```
31,945,069
I have a computed field in Odoo with a function. Everything works fine when I don't add the store argument. When I add the store argument, it doesn't execute the code at all. My code: ``` class opc_actuelewaardentags(models.Model): _name = 'opc_actuelewaardentags' unit = fields.Char(compute='changeunit') def changeunit(self): print "print" allrecords_actwaardent = self.search([]) obj_taginst = self.env['opc_taginstellingen'] allrecords_taginst = obj_taginst.search([]) for i in allrecords_actwaardent: for j in allrecords_taginst: if i.tagnaam == j.tagnaam and i.unit != j.unit: i.unit = j.unit ``` So: when I call the code like this: ``` unit = fields.Char(compute='changeunit') ``` The code is executed (shows "print"). When I call the code like this: ``` unit = fields.Char(compute='changeunit', store=True) ``` The code is not executed (doesn't show "print"). Is there anything wrong in my code? Or is this a bug? It seems so strange to me... I need to be able to store the values in the database so I can filter on unit in the tree view. **edit:** I applied Juan Salcedo's tip. Didn't work... This is how I did it: ``` unit = fields.Char(default = changeunit) def changeunit(self): print "print" allrecords_actwaardent = self.search([]) obj_taginst = self.env['opc_taginstellingen'] #Hier dan i.p.v. self werken met dat obj_taginst allrecords_taginst = obj_taginst.search([]) for i in allrecords_actwaardent: for j in allrecords_taginst: if i.tagnaam == j.tagnaam and i.unit != j.unit: i.unit = j.unit return i.unit ``` Gives error: > > NameError: name 'changeunit' is not defined > > > I also tried putting the unit field below def changeunit(self), but didn't work either.
2015/08/11
[ "https://Stackoverflow.com/questions/31945069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5088498/" ]
Store=True without @api.depends means it will execute only once while the column/field is going to be created. so the effect you want to fire that method everytime will not be achieve with store=True without @api.depends or you need to remove store=True then it will calculate everytime when you access this field. This are the changes you required to update in your code but before that you need to remove that column from database and after that restart server and upgrade module then it will come to there. ``` class opc_actuelewaardentags(models.Model): _name = 'opc_actuelewaardentags' unit = fields.Char(compute='changeunit') @api.multi def changeunit(self): print "print" for obj in self: allrecords_actwaardent = self.search([]) obj_taginst = self.env['opc_taginstellingen'] allrecords_taginst = obj_taginst.search([]) for i in allrecords_actwaardent: for j in allrecords_taginst: if i.tagnaam == j.tagnaam and i.unit != j.unit: obj.unit = j.unit break ``` Another way: store = False never stored any value in database so if you want to store that value in database and don't won't to be updated (means it's fixed when create or update record) then you just need to override create/write method and inside update this field's value. ``` @api.model def create(self, vals): vals.update({'field':value}) return super(class_name,self).create(vals) ```
i noticed this issue too, but in my case it was not necessary to store it in the database. so i kept it as store=false and the computed field worked and it has a value in the view and that's what mattered, only to have the values in the view.. so when you set store=true, only new records will have a value in the computed field, while old data won't have values in the computed field therefore you have to reset the values of the fields used in the computation of the field(depend fields) by writing a write statement inside the compute function, to reassign these fields their own values again, as if they are just created ``` for record in self.env['class'].search([]): record.field= record.field ``` record.field ->>> the fields used in field computation or api.depends(fields)
38,412,207
I'm sending an activation email. The user must click a button to activate their account, but the link boundaries are extending beyond the button. How do I fix this problem without inserting the `a tags` inside the main element? Then, the text would be clickable, but not the parent div. ```html <table width='100%' border='0' cellspacing='0' cellpadding='0'> <tr> <td align='center'> <div style='border: 1px solid #CCC;width:538px;font-family:Helvetica; padding: 30px'> <span style='font-size: 30px;text-align: center;color: #606060;font-weight: bold;'> Just one more step... </span> <br> <br> <br> <a href='#' style='text-decoration: none'> <div style='color: white; padding: 20px 50px 20px 50px; background: #69B8D6; border: 1px solid #69B8D6;text-align: center;width: 156px;font-size: 18px;font-weight: bold;border-radius:3px;'> Activate Account </div> </a> </div> </td> </tr> </table> ```
2016/07/16
[ "https://Stackoverflow.com/questions/38412207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6567645/" ]
I already wrote some code but it's not finished at all... Maybe you can start with that and try to complete what I've done if you want ;) I'll continue working on it this week in order to provide you with a solution... Here is what I've done so far : ```js var ajaxResult = [ "Inter has ruinarum varietates a Nisibi quam tuebatur accitus Vrsicinus, cui nos obsecuturos iunxerat imperiale praeceptum, dispicere litis exitialis certamina cogebatur. Inter has ruinarum varietates a Nisibi quam tuebatur accitus Vrsicinus, cui nos obsecuturos iunxerat imperiale praeceptum, dispicere litis exitialis certamina cogebatur. Inter has ruinarum varietates exitialis certamina cogebatur", "Inter has ruinarum varietates a Nisibi quam tuebatur accitus", "Inter has ruinarum varietates a Nisibi quam tuebatur accitus Vrsicinus, cui nos obsecuturos iunxerat imperiale praeceptum, dispicere litis exitialis certamina cogebatur. Inter has ruinarum varietates a Nisibi quamos iunxerat imperiale praeceptum, dispicere litis exitialis certamina cogebatur. Inter has ruinarum varietates exitialis certamina cogebatur", ]; /************************************************************* * * LIST OF CONTENT EDITABLE DIVS MANAGEMENT * **************************************************************/ // Create the editable divs window.onload = function(){ var contentEditables = createContentEditables(); document.body.appendChild(contentEditables); } // Remember all the content editable elements in the order they appear in the dom var _currentEdit, _edits = []; function createContentEditables(){ var div; var result = document.createDocumentFragment(); for (var i = 0, n = ajaxResult.length ; i < n ; i++){ div = createContentEditable(ajaxResult[i]); _edits.push(div); result.appendChild(div); } return result; } function getPreviousEdit(edit){ // Search for the edit index var index = _edits.indexOf(edit); if(index == 0) return; // Return the previous one return _edits[index - 1]; } function getNextEdit(edit){ // Search for the edit index var index = _edits.indexOf(edit); if(index == _edits.length - 1) return; // Return the previous one return _edits[index + 1]; } /************************************************************* * * CONTENT EDITABLE MANAGEMENT * **************************************************************/ // We need to define the line height of the div to be able to retrieve the number of lines var LINE_HEIGHT = 16; // variables to keep trace of relevant information about the div var _lines, _caretPosition; /* * Create a div with contenteditable set to true with the text * received from the server */ function createContentEditable(text){ var element = document.createElement('div'); element.className = 'contenteditable'; element.innerHTML = text; element.style.lineHeight = LINE_HEIGHT + 'px'; element.setAttribute('contenteditable', true); // Set listeners element.addEventListener('mouseup', onEdit_mouseup); element.addEventListener('keydown', onEdit_keydown); element.addEventListener('focus', onEdit_focus); return element; } function onEdit_keydown(domEvent){ // Update caret position _caretPosition = getCaretPosition(domEvent.target); switch(domEvent.keyCode){ case 37: // left arrow if (_caretPosition.index == 0){ var previousEdit = getPreviousEdit(domEvent.target); if(previousEdit){ console.log("go to end of previous edit"); console.log(previousEdit); previousEdit.focus(); } } break; case 38: // up arrow if (_caretPosition.line == 1){ var previousEdit = getPreviousEdit(domEvent.target); if(previousEdit){ console.log("go to previous edit keeping the caret offset"); console.log(previousEdit); previousEdit.focus(); } } break; case 39: // right arrow if (_caretPosition.index == domEvent.target.innerHTML.length){ var nextEdit = getNextEdit(domEvent.target); if(nextEdit){ console.log("go to beginning of next edit"); console.log(nextEdit); nextEdit.focus(); } } break; case 40: // down arrow if (_caretPosition.line == getLines(domEvent.target)){ var nextEdit = getNextEdit(domEvent.target); if(nextEdit){ console.log("go to next edit keeping the caret offset"); console.log(nextEdit); nextEdit.focus(); } } break; } } function onEdit_mouseup(domEvent){ // Update caret position _caretPosition = getCaretPosition(domEvent.target); } function onEdit_focus(domEvent){ // Add listeners _currentEdit = domEvent.target; _currentEdit.addEventListener('blur', onEdit_blur); window.addEventListener('resize', onWindow_resize); } function onEdit_blur(domEvent){ // Remove listeners domEvent.target.removeEventListener('blur', onEdit_blur); window.removeEventListener('resize', onWindow_resize); } function onWindow_resize(domEvent){ // Update caret position _caretPosition = getCaretPosition(_currentEdit); } /************************************************************* * * HELPERS * **************************************************************/ //http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022 //http://stackoverflow.com/questions/5528004/how-to-get-number-of-rows-in-contenteditable-area-and-current-caret-line-positio function getCaretPosition(element){ var caretPosition = {index: 0, line: 0}; var doc = element.ownerDocument || element.document; var win = doc.defaultView || doc.parentWindow; var elemOffsetTop = element.offsetTop; var sel; // Get the x position of the caret if (typeof win.getSelection != "undefined") { sel = win.getSelection(); if (sel.rangeCount > 0) { var range = win.getSelection().getRangeAt(0); // Retrieve the current line var rects = range.getClientRects(); var caretOffsetTop; if (typeof rects[1] != "undefined"){ caretOffsetTop = rects[1].top; } else if (typeof rects[0] != "undefined"){ caretOffsetTop = rects[0].top; } else{ // Create dummy element to get y position of the caret var dummy = document.createElement('CANVAS'); dummy.id = 'findCaretHelper'; range.insertNode(dummy); caretOffsetTop = dummy.offsetTop; element.removeChild(dummy); } var preCaretRange = range.cloneRange(); preCaretRange.selectNodeContents(element); preCaretRange.setEnd(range.endContainer, range.endOffset); // Remember caret position caretPosition.index = preCaretRange.toString().length; caretPosition.line = Math.ceil((caretOffsetTop - elemOffsetTop)/LINE_HEIGHT) + 1; } } // support ie //else if ( (sel = doc.selection) && sel.type != "Control") { //var textRange = sel.createRange(); //var preCaretTextRange = doc.body.createTextRange(); //preCaretTextRange.moveToElementText(element); //preCaretTextRange.setEndPoint("EndToEnd", textRange); //caretPosition.x = preCaretTextRange.text.length; //} return caretPosition; } function getLines(element){ return element.clientHeight/LINE_HEIGHT;; } ``` ```css .contenteditable{ border: solid 1px #aaa; margin: 10px 0; } ``` I managed getting information about the current line, the current character index in the content editable div and some other stuff... I still have to work on focusing an other content editable div in order to put the caret at the right place... I hope this beginning of a solution will help you!
You could simply make the parent element / containing element `contenteditable` as opposed to each paragraph. This will automatically add / remove `p` tags accordingly. <https://jsfiddle.net/ewesmwmv/2/>
7,393,483
I am having a problem using the remote property of the data-anotation. I am having a model for user which stores the data: ``` [DataType(DataType.EmailAddress,ErrorMessage="please enter valid email")] [DisplayName("Email Address")] [Required(ErrorMessage = "Email is Required")] [Remote("CheckUniqueEmail","User",ErrorMessage="An account with this email address already exists.")] public string Email { get; set; } ``` and I am checking the distinct user email while creating the new one... When I try to login with the email and password in the different controller, it still calls the Remote and checks for the unique email... I think I have to exclude the email and password property in the Login controller - but I don't know how.
2011/09/12
[ "https://Stackoverflow.com/questions/7393483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/927002/" ]
You should use another model for logging in at LoginController. These validations will be used everywhere you use this model.
You can also use the `MetadataType` to reuse the same base model and apply different validations. Example [Here](https://stackoverflow.com/questions/7276530/mvc-partial-model-updates/7276720#7276720).
1,650,514
I've been give some *lovely* Java code that has a lot of things like this (in a loop that executes about 1.5 million times). ``` code = getCode(); for (int intCount = 1; intCount < vA.size() + 1; intCount++) { oA = (A)vA.elementAt(intCount - 1); if (oA.code.trim().equals(code)) currentName= oA.name; } ``` Would I see significant increases in speed from switching to something like the following ``` code = getCode(); //AMap is a HashMap strCurrentAAbbreviation = (String)AMap.get(code); ``` **Edit:** The size of vA is approximately 50. The trim *shouldn't* even be necessary, but definitely would be nice to call that 50 times instead of 50\*1.5 million. The items in vA are unique. **Edit:** At the suggestion of several responders, I tested it. Results are at the bottom. Thanks guys.
2009/10/30
[ "https://Stackoverflow.com/questions/1650514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16487/" ]
I'd say yes, since the above appears to be a linear search over vA.size(). How big is va?
I think the dominant factor here is how big vA is, since the loop needs to run n times, where n is the size of vA. With the map, there is no loop, no matter how big vA is. So if n is small, the improvement will be small. If it is huge, the improvement will be huge. This is especially true because even after finding the matching element the loop keeps going! So if you find your match at element 1 of a 2 million element list, you still need to check the last 1,999,999 elements!
698,072
I just wanted to know how to convert the result of a calculation into a simple `YES` or `NO` outcome. I.e. if the value is *less than* `X` then 'YES' you need to reorder, if the value is *greater than* `X` then `NO` you don't need to reorder. I'm sure it is probably simple, but I'm a graphics type hippy and this is out of my normal comfort zone :)
2014/01/07
[ "https://superuser.com/questions/698072", "https://superuser.com", "https://superuser.com/users/287493/" ]
Your connection speed is **54Mbps** so you're probably connecting with the **802.11g** protocol. Then the 3MB/s is the expected speed. Ideally you would get to around 3.5MB/s but that would be the absolute maximum. Have a look at [this site](http://www.speedguide.net/faq_in_q.php?qid=374). There ~20Mbps downstream is mentioned. (just ~2.5MB/s) Please note the difference in Mbps (Mega-**bit**/s) and MB/s (Mega-**byte**/s). Your 3MB/s is (x8) 24Mbps. You can also look at [this answer](https://superuser.com/questions/302943/whats-the-maximum-actual-bit-rate-of-an-802-11g-connection#302951). It has some lovely technical explanations. > > In real world conditions I'm happy as long as it's over 15 megabits/sec. (1,8MB/s) > > > The rule of thumb for 802.11 is that you can get TCP throughput of > 50-60% of the signalling rate you're getting, and you only get the > best signaling rate under the best conditions. > > > So 50% - 60% of 54Mbps is 3,3MB/s - 4MB/s --- Now for the (*maybe*) good news. Your Atheros AR9285 should be **802.11n** capable. Your ASUS RT-N10U should also be a 802.11n router so if you connect with 802.11n the speed should be higher. (Your router goes up to 150Mbps, so not really the actual 11n standard but it might be a bit faster). But if your router is in 802.11-**a/b/g/n** mode it will connect much slower (somehow 11g and 11n don't mix well). If you don't have devices which need 802.11b or g, set the router to **802.11n only**. If you get a link-speed of just 64Mbps after doing this, switch back to 802.11g only because you'll only get an unstable connection this way (and you'll need to *live* with 3MB/s or buy new hardware). If you get a link-speed of 150Mbps you should see a much higher throughput.
A variety of factors will affect transfers like this, and network quality is not your only issue. Here's some possible problems: * slow storage devices. Are you transferring to/from a slow USB stick or SD card? * Protocol overhead will slow down your total transfer rate when you're working with small files. Try using `tar` or `zip` to compress your files first * excessive disk use on either machine will slow things down. If you're running a backup engine like Crashplan, that could be burning your bandwidth Here's a few diagnostics you can try: * do an internet speed test from both your machines to the internet (<http://speedtest.net>). If both machines have a nice, fast uplink, then you know the router isn't to blame, as your machines can connect quickly to the Internet.
580,584
I have a bunch of long-running scripts and applications that are storing output results in a directory shared amongst a few users. I would like a way to make sure that every file and directory created under this shared directory automatically had `u=rwxg=rwxo=r` permissions. I know that I could use `umask 006` at the head off my various scripts, but I don't like that approach as many users write their own scripts and may forget to set the umask themselves. I really just want the filesystem to set newly created files and directories with a certain permission if it is in a certain folder. Is this at all possible? **Update**: I *think* it can be done with [POSIX ACLs](http://www.vanemery.com/Linux/ACL/POSIX_ACL_on_Linux.html), using the Default ACL functionality, but it's all a bit over my head at the moment. If anybody can explain how to use Default ACLs it would probably answer this question nicely.
2009/02/24
[ "https://Stackoverflow.com/questions/580584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67829/" ]
To get the right ownership, you can set the group setuid bit on the directory with ``` chmod g+rwxs dirname ``` This will ensure that files created in the directory are owned by the group. You should then make sure everyone runs with umask 002 or 007 or something of that nature---this is why Debian and many other linux systems are configured with per-user groups by default. I don't know of a way to force the permissions you want if the user's umask is too strong.
It's ugly, but you can use the setfacl command to achieve exactly what you want. On a Solaris machine, I have a file that contains the acls for users and groups. Unfortunately, you have to list all of the users (at least I couldn't find a way to make this work otherwise): ``` user::rwx user:user_a:rwx user:user_b:rwx ... group::rwx mask:rwx other:r-x default:user:user_a:rwx default:user:user_b:rwx .... default:group::rwx default:user::rwx default:mask:rwx default:other:r-x ``` Name the file acl.lst and fill in your real user names instead of user\_X. You can now set those acls on your directory by issuing the following command: ``` setfacl -f acl.lst /your/dir/here ```
25,822,722
As the question itself is self explanatory, How do i check if a given point is inside a given frame of view.
2014/09/13
[ "https://Stackoverflow.com/questions/25822722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438864/" ]
You can achieve it through many ways 1. `UIView` `pointInside` method. It returns a Boolean value indicating whether the receiver contains the specified point. `-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event` 2. `CGGeometry` `CGRectContainsPoint`method. It returns whether a rectangle contains a specified point. `bool CGRectContainsPoint (CGRect rect, CGPoint point);` 3. `CGGeometry` `CGPointEqualToPoint`method.It returns whether two points are equal. `bool CGPointEqualToPoint (CGPoint point1, CGPoint point2);`
``` CGRectContainsPoint(view.frame, point); ``` Reference: [`CGRectContainsPoint`](https://developer.apple.com/documentation/coregraphics/1456316-cgrectcontainspoint?language=objc)
4,278,148
I have div element with left and top defined, **without absolute position**, and I want to read the left and top values using jQuery. Using `$("#MyId").css("left")` gave the expected result in IE browser (IE8) but in Chrome it returned "auto" instead, although the values are explicitly written in the element style. Here is the test case: <http://jsfiddle.net/qCDkb/2/> Note the difference between IE and Chrome. Also, this is working well in jQuery 1.4.2 and "failing" in jQuery 1.4.3 and above. Any insights are welcome. :-)
2010/11/25
[ "https://Stackoverflow.com/questions/4278148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/447356/" ]
Try `$("your selector").position().top;`
I know this is an old post, but I ran into this same problem and thought I would suggest a couple of solutions. It seems that this problem is not specific to Chrome, as I was able to reproduce in Firefox as well. I was able to solve this one of two ways. Either place you CSS styles in the same file as your HTML, instead of using a separate CSS file. OR, call the function inside of window.onload. Looks like the values are not available to the browser until everything has loaded, IF the styles are in an external style sheet. Hope this is helpful.
39,936,502
I have an issue in Phpmaker and I have no clue how to solve it. I created a MySQL database (InnoDB) and a PHPMaker interface, where I copy the HTML code generated by IMDB site, at this url: www.imdb.com/plugins This code gives me the movie rating by users. I paste into my textarea input field and save. The data saved into the column of MySQL receives a `<x>` in the middle of code. This is the original (copied) code, from IMDB: ``` <span class="imdbRatingPlugin" data-user="ur21152180" data-title="tt3228904" data-style="p3"> <a href="http://www.imdb.com/title/tt3228904/?ref_=plg_rt_1"> <img src="http://g-ecx.images-amazon.com/images/G/01/imdb/plugins/rating/images/imdb_37x18.png" alt=" Empire (2015) on IMDb" /> </a> </span> <script> (function(d,s,id){ var js,stags=d.getElementsByTagName(s)[0]; if(d.getElementById(id)){return;} js=d.createElement(s); js.id=id; js.src="http://g-ec2.images-amazon.com/images/G/01/imdb/plugins/rating/js/rating.min.js"; stags.parentNode.insertBefore(js,stags);}) (document,'script','imdb-rating-api'); </script> ``` And this is what is saved on mysql: ``` <span class="imdbRatingPlugin" data-user="ur21152180" data-title="tt3228904" data-style="p3"> <a href="http://www.imdb.com/title/tt3228904/?ref_=plg_rt_1"> <img src="http://g-ecx.images-amazon.com/images/G/01/imdb/plugins/rating/images/imdb_37x18.png" alt=" Empire (2015) on IMDb" /> </a> </span> <s<x>cript> (function(d,s,id){ var js,stags=d.getElementsByTagName(s)[0]; if(d.getElementById(id)){return;} js=d.createElement(s); js.id=id; js.src="http://g-ec2.images-amazon.com/images/G/01/imdb/plugins/rating/js/rating.min.js"; stags.parentNode.insertBefore(js,stags);}) (document,'script','imdb-rating-api'); </script> ``` The `<x>` is being inserted in the middle of `<script>` tag. Can anyone shed a light over this issue?
2016/10/08
[ "https://Stackoverflow.com/questions/39936502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/963764/" ]
This is a nice puzzle. As my main DBMS is Teradata I wrote a solution for it using Analytical functions (needs TD14.10+): ``` SELECT dt.*, -- find the last item in the stack with the same position Last_Value(val IGNORE NULLS) Over (PARTITION BY pos ORDER BY i) AS top_of_stack_val FROM ( SELECT st.*, -- calculate the number of items in the stack Sum(CASE WHEN op = 'I' THEN 1 ELSE -1 end) Over (ORDER BY i ROWS Unbounded Preceding) AS pos FROM stack_trace AS st ) AS dt; ``` This solution works for Oracle, too, but PostgreSQL & SQL Server don't support the `IGNORE NULLS` option for `LAST_VALUE` and emulating it is quite complicated, e.g see Itzk Ben-Gan's [The Last non NULL Puzzle](http://sqlmag.com/t-sql/last-non-null-puzzle) Edit: In fact it's not that complex, I forgot Itzik's 2nd solution, the old piggyback trick ;-) Martin Smith's approach will work for all four DBMSes.
Teradata ======== ``` select s.i ,first_value (s.val) over ( partition by s.depth order by s.i reset when s.op = 'I' ) as top_of_stack_val from (select s.i ,s.val ,s.op ,sum (case s.op when 'I' then 1 else -1 end) over ( order by s.i rows unbounded preceding ) as depth from stack_trace s ) s order by i ; ```
20,155,871
is it possible to make something like **round include** in C? `example: in ial.h - #include "adt.h" and in adt.h - #include "ial.h"`
2013/11/22
[ "https://Stackoverflow.com/questions/20155871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1580952/" ]
This is called a **circular dependency**, and while it's possible, you **should not**. Avoid designing around the concept at all costs. What you should do is extract the common ground from both headers and create a third one, that both `include`. ``` bad good a <---> b a b | | -> c <- ``` If you find you can't do this, then most likely `a` and `b` are the same semantic unit, and belong in the same header.
I guess you should be able to do it by using `#ifndef`: In `ial.h`: ``` #ifndef IAL_H #define IAL_H ... #include "adt.h" ... #endif ``` In `adt.h`: ``` #ifndef ADT_H #define ADT_H ... #include "ial.h" ... #endif ``` Whether it is a good idea or not, I would say don't do it.
87,325
I'm learning asymmetric encryption in the use case of ssl/tls protocol. I can understand that the public key (like a padlock) can encrypt (lock) something and only the private key can decrypt (open) it. But I just can't understand the other way around. How can the public key verify digital signatures encrypted by CA's private key? A lot of material says that a public key can't be used for decryption (that's fine, if imagine the public key is a padlock, then that's for sure, you're not able to unlock things). Then how can public keys be used to verify digital signatures, given that it can't be used to decrypt? I can understand that public keys/private keys are used for client server verification. A server encrypts some secrets and ask the client to decrypt it, and compares the results, then I can know whether you're the holder of the private key. But as for digital signatures, it's a different story, because I think in the digital signature, it doesn't contain the private key of the issuer, right? Then how can the above verification can be done without private key decrypting?
2015/05/02
[ "https://security.stackexchange.com/questions/87325", "https://security.stackexchange.com", "https://security.stackexchange.com/users/73596/" ]
The whole concept of trying to explain signatures with the terminology of encryption is flawed. It simply does not work. So let's unravel the whole thing, and this will require some formalism. --- **Formally**, a *cryptographic signature system* consists in three algorithms: * **KeyGen**: takes as input a "security parameter" (say, the length of the key we want to obtain), and produces a new public/private key pair (*K*p, *K*s). * **Sign**: takes as input a message *m* and a private key *K*s; output is a signature *s*. * **Verify**: takes as input a message *m*, a signature *s* and a public key *K*p; output is a boolean (**true** on success, **false** if the signature is not valid). The system is said to be *sound* if the algorithms operate as advertised (**Sign** produces signatures that **Verify** accepts, using key pairs produced by **KeyGen**). The system is said to be *cryptographically secure* if it is computationally infeasible to make *forgeries*: given a public key *K*p, and without knowing *K*s\_, it should not be feasible (within the limits of existing technology) to produce a (*m*, *s*) pair such that **Verify**(*m*, *s*, *K*p) = **true**. The definition implies, in particular, that the private key should not be computable from the public key alone, because otherwise forgeries would be easy. None of the above says anything about *how* the algorithms work. Various systems have been invented, described and standardized. --- [RSA](http://en.wikipedia.org/wiki/RSA_%28cryptosystem%29) is a very well-known asymmetric algorithm, but that's wrong, because RSA is not *one* algorithm. RSA is the name for an internal operation called a *trapdoor permutation*, from which an asymmetric encryption system *and* a signature system have been derived. The RSA operation is, roughly, the following: * Let *n* be a big integer such that *n = pq*, where *p* and *q* are two big, distinct primes. Knowledge of *p* and *q* is the "private key". Let *e* be some (usually small) integer, called the "public exponent"; *e* must be such that it is relatively prime to both *p-1* and *q-1*. Traditional values for *e* are 3 and 65537. * Given an integer *x* modulo *n* (an integer in the *0* to *n-1* range), the RSA forward operation is computing *x**e* mod *n* (*x* is raised to exponent *e* modulo *n*). This is easy enough to do. It so happens that this operation is a permutation of integers modulo *n* (each *y* modulo *n* is equal to *x**e* mod *m* for exactly one *x*). The "magic" part is that, for some reason, nobody found an efficient way to compute the reverse operation (getting *x* from *x**e* mod *n*) without knowing *p* and *q*. And that's not for lack of trying; [integer factorization](http://en.wikipedia.org/wiki/Integer_factorization) has been studied by the finest minds for more than 2500 years. When you know *p* and *q*, the RSA reverse operation becomes easy. The knowledge of *p* and *q* is thus called the *trapdoor*. Now that we have this trapdoor permutation, we can design a signature algorithm which works the following way: * **KeyGen**: given a target length *k*, produce two random primes *p* and *q* of length about *k*/2 bits, such that *p-1* and *q-1* are both relatively prime to an *a priori* chosen *e* (e.g. *e* = 3), and *n* = *pq* has length *k* bits. The public key is (*n*, *e*), the private key is (*p*, *q*, *e*). * **Sign**: take message *m*, hash it with some hash function (e.g. SHA-256), and "turn" the hash output (a sequence of 256 bits in the case of SHA-256) into an integer *y* modulo *n*. That transform is what the *padding* is about, because the standard method (as described in [PKCS#1](https://www.rfc-editor.org/rfc/rfc3447)) is writing the hash output with some extra bytes, and then interpreting the result as an integer (in big-endian convention in the case of PKCS#1). Once the hashed message has been converted through the padding into an integer *y*, the private key owner applies the trapdoor (the reverse RSA operation) to compute the *x* such that *x**e* = y mod *n* (such a *x* exists and is unique because the RSA operation is a permutation). The signature *s* is the encoding into bytes of that integer *x*. * **Verify**: given a signature *s*, decode it back into an integer *x* modulo *n*, then compute *y* = *x*e modulo *n*. If this value *y* is equal to what would be the padding of *h*(*m*) (hash of message *m*), then the signature is accepted (returned value is **true**). **RSA encryption** is another, distinct system, that also builds on the RSA trapdoor permutation. *Encryption* is done by raising an integer *x* to the exponent *e* modulo *n*; *decryption* is done by reversing that operation thanks to the knowledge of the private key (the *p* and *q* factors). Since such a system processes only big integers, and we want to encrypt and decrypt *bytes*, then there must also be some sort of conversion at some point, so a padding procedure is involved. Crucially, the security requirements for the encryption padding are quite distinct from those for the signature padding. For instance, the encryption padding MUST include a substantial amount of randomness, while the signature padding MUST include a substantial amount of determinism. In practice, the two padding systems are quite different. When people looked at RSA signatures and RSA encryption, they found it fit to describe signatures as a kind of encryption. If you look at it, the RSA forward operation (raising to the exponent *e*) is done for RSA encryption, and also for RSA signature verification. Similarly, the reverse operation is done for RSA decryption, and for RSA signature generation. Furthermore, as a stroke of genius if genius was about confusing other people, some noticed that the RSA reverse operation can *also* be mathematically expressed as "raising an integer to some power modulo *n*", just like the forward operation (but with a different exponent). Thus they began to call that reverse operation "encryption". At that point, RSA encryption, RSA decryption, RSA signature generation and RSA signature verification are all called "encryption". For some weird psychological reason (I blame the deleterious effects of post-Disco pop music), many people still find it pedagogically sound to try to explain four different operations by first giving them the same name. --- We described RSA; let's have a look at another, completely different algorithm called [DSA](http://en.wikipedia.org/wiki/Digital_Signature_Algorithm). DSA does not use a trapdoor permutation. In DSA, we do computations modulo a big prime (traditionally called *p*) and modulo another, smaller prime (called *q*) which is such that *p-1* is a multiple of *q*. *p* and *q* are known to everybody. There is an operation-that-goes-one-way in DSA. Given an integer *g* modulo *p* (strictly speaking, in a specific subset of *p* called the subgroup of order *q*) and an integer *x* modulo *q*, everybody can compute *g**x* mod *p*; however, recovering *x* from *g**x* mod *p* is computationally infeasible. While this somehow looks like RSA, there are crucial differences: * Here, the operation is raising *g* to exponent *x*, where the actual input is *x* (the exponent), because *g* is a fixed, conventional value. * This is not a permutation, because *x* is an integer modulo *q* and *g**x* mod *p* is an integer modulo *p*, a quite different set. * This is certainly not a trapdoor: there is no "secret knowledge" that allows recovering *x*, except if you already know that exact value *x*. However, a signature algorithm can be built on that operation. It looks like this: * **KeyGen**: the *p*, *q* and *g* integers are already fixed, and potentially shared by everybody. To generate a new private key, produce a random integer *x* between 1 and *q*-1. The public key is *y* = *g*x mod *p*. * **Sign**: + Given a message *m*, hash it, then convert the hash value into an integer *h* modulo *q*. + Generate a new, fresh, discard-after-use random integer *k* between 1 and *q-1*. + Compute *r* = *g*k mod *p* mod *q* (the exponentiation is done modulo *p*, then the result is furthermore reduced modulo *q*). + Compute *s* = (*h* + *xr*) / *k* mod *q*. The signature is (*r*, *s*). * **Verify**: + Hash message *m* to recompute *h*. + Compute *w* = 1 / *s* mod *q*. + Compute *u1* = *hw* mod *q*. + Compute *u2* = *rw* mod *q*. + Compute *v* = *g**u*1 *y**u*2 mod *p* mod *q*. + If *v* = *r*, the signature is valid; otherwise, it is not. Now good luck with trying to describe that as some sort of "encryption". If you find that it is unclear what is being encrypted here, it is because *nothing* is encrypted here. This is not encryption. --- However, there *is* an hand-waving conceptual description of signatures that works with both RSA, DSA, and many other signature algorithms. You can view signatures as a specific kind of authentication. In **authentication**, one person (the *prover*) demonstrates his identity to another (the *verifier*). The prover does this by performing some action that only that person can do, but in such a way that the verifier can be convinced that he witnessed the genuine thing. For instance, a very basic authentication system is called "show-the-password": the prover and the verifier both know a shared secret (the "password"); the prover demonstrates his identity to the verifier by uttering the password. For *signatures*, we want something a bit more complex: * The signature is asynchronous. The signer acts once; verification is done afterwards, possibly elsewhere, and without any further active help from the signer. * The verifier should not need to know any secret. The signature should be convincing for everybody. * By signing, the signer shall not *reveal* any secret. His private key should not be consumed (yes, I know there are signature schemes that work with consumption; let's not go there). * The signature should be specific to a given message *m*. One rather generic structure for authentication schemes is based on *challenges*: the verifier sends to the prover a challenge, that the prover can answer to only thanks to his knowledge of his secret. If you look at RSA, then you can see that it is a challenge-based authentication mechanism. The challenge is the hashed-and-padded message. The signer demonstrates his mastery of the private key by applying the RSA reverse operation on that challenge, something that only he can do; but everybody can apply the RSA forward operation to see that the challenge was indeed well met. If you look at DSA, then you can again see a challenge-based authentication mechanism. The signer first *commits* to a secret value *k* by publishing *r*; then the challenge is (again) the message *h* combined with the commitment *r*; the signer can answer to that challenge only by using his private key *x*. In DSA, the signer has a permanent private key *x*, produces a one-shot private value *k*, and demonstrates his knowledge of *x/k* mod *q*. (This does not leak information on *x* because *k* is used only once.) --- **Summary:** signature algorithms are not encryption algorithms, and explanations of signatures based on encryption can only be, at best, utterly confusing. A much better explanation is by showing that a signature algorithm is, in fact, a specific kind of authentication mechanism, by which the signer demonstrates his knowledge of the private key in response to a synthetic challenge that involves the signed message. This authentication is convincing for bystanders as long as the said challenge is sufficiently well specified that it is provably not cooked in the advantage of the signer. In RSA, it is the result of a deterministic hashing and padding (and the padding takes care to avoid the values where the RSA reverse operation becomes easy). In DSA, the challenge is computed from a prior commitment of the signer. Indeed, any [zero-knowledge authentication system](http://en.wikipedia.org/wiki/Zero-knowledge_proof) can be turned into a signature mechanism by making it non-interactive: since a ZK system works by commitments, challenges and responses to these challenges, you can make the signer compute all his commitments, hash them all along with the message to sign, and use the hash value as the challenges. This does not mean that a ZK proof lurks within all signature algorithms; however, if you find that DSA kinda looks like that, well, there are good reasons for that.
For RSA encryption, the public and private keys can both be used for encryption or decryption. The only difference between them is that you keep one key private while you advertise the other. What your text is referring to is that, when you're encrypting a message to send to someone, you use their public key to encrypt it. You, of course, couldn't use their private key because it's private. This secures the message as only they have their private key. But both keys work for the cryptography operations. So for digital signature, the author encrypts their hash using their private key and you validate by decrypting with their public key. This is not true for all asymmetric encryption algorithms.
18,519,573
I am editing the standard twentythirteen theme that comes with the latest wordpress. I need to add a few of my own .css files into the wp\_head but I'm not sure how to do this. I'm currently calling my files outside of wp\_head but this is messy and would like to do it properly. ``` <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width"> <title><?php wp_title( '|', true, 'right' ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script> <![endif]--> <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo("template_url"); ?>/bootstrap.css" /> <script type="text/javascript" src="<?php bloginfo("template_url"); ?>/js/bootstrap.min.js"></script> <?php wp_head(); ?> ``` Where is it being defined what goes into wp\_head and how do I add my own to it?
2013/08/29
[ "https://Stackoverflow.com/questions/18519573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648610/" ]
@cale\_b My plugins are based on jQuery library and calling the jQuery from the wp\_head() function was not successful on this way > > wp\_enqueue\_script('jquery', 'get\_stylesheet\_uri(); . > 'js/jquery.min.js'); > > > the proper way is adding this to the header.php before everything... ``` <?php wp_enqueue_script("jquery"); ?> <?php wp_head(); ?> ``` It's very important that you call jquery first before the wp\_head(); hook of the other imports... The WordPress comes with the jQuery library because he is using it for the wp-admin pages and some other $post and $get requests on the page... Using their script is much more secure and easier way then adding your own jquery.min.js file inside the themes directory... wp\_head(); function is just the best way calling the stylesheets but when it gets to the Javascripts and Javascript libraries it can get buggy. Also note that sometimes the WordPress wont render your **' $ '** as a jQuery variable and you will get errors for TypeError, which of course is correct. In that case you should change all of the ' $ ' with ' jQuery ' which is also a defined variable inside the WordPress jQuery library... Also note that sometimes you will need an inline javascript, etc ``` <script> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> ``` All of these inline scripts should not be inside your index.php nor your header.php nor footer.php... You can list all of them inside another your-inline-scripts.js and call them like this just where they should have been listed before like this: ``` <script type="text/javascript" src="<?php bloginfo("template_url"); ?>/js/your-inline-scripts.js"></script> ``` or ``` <script type="text/javascript" src="<?php echo get_stylesheet_directory_uri(); ?>/js/yourScript.js"></script> ``` I prefer this second option...
Hmm yes to the above but it's also possible to link to your sheets after wp\_head is called so ``` <?php wp_head(); ?> <link href="/wp-content/themes/YourTheme/cssFolder/YourOtherStyleSheet.css"> ``` This is usually what i do as it's clearer to read. In addition I'd also recommend using something like <http://html5blank.com> for a nice clean blank wp theme instead of trying to alter the default theme (so no child theme just a different theme altogether)
9,524,200
I'm looking into using queues with delayed\_job. I've found [this page](https://github.com/collectiveidea/delayed_job/wiki/Named-Queues-Proposal) which outlines various ways of starting workers, however I'd like to keep my currently Capistrano method: ``` set :delayed_job_args, "-n 2 -p ecv2.production" after "deploy:start", "delayed_job:start" ... ``` I was wondering how I could modify the delayed\_job\_args to handle spawning 1 worker with a specific queue, and 1 worker for every other job. So far, all I have is overriding each task like so: ``` namespace :delayed_job do task :restart, :roles => :app do run "cd #{current_path}; RAILS_ENV=#{rails_env} script/delayed_job -p ecv2.production --queue=export restart" run "cd #{current_path}; RAILS_ENV=#{rails_env} script/delayed_job -p ecv2.production restart" end end ``` ... But that's no fun. Any suggestions?
2012/03/01
[ "https://Stackoverflow.com/questions/9524200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/605753/" ]
I split my jobs into two queues with one worker isolated to each queue with this setup in my `deploy.rb` file: ``` namespace :delayed_job do task :start, roles: :app do run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i queue_one --queue=one start" run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i queue_two --queue=two start" end task :stop, roles: :app do run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i queue_one --queue=one stop" run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i queue_two --queue=two stop" end task :restart, roles: :app do run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i queue_one --queue=one restart" run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i queue_two --queue=two restart" end end ``` The `-i name` part of the command is very important. That's the part that allows multiple `delayed_job` instances to run. If you want to add workers to specific queues, then you would expand them out like this (where I have two workers exclusively on queue one, and one worker exclusively on queue two): ``` namespace :delayed_job do task :start, roles: :app do run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i one1 --queue=one start" run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i one2 --queue=one start" run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i two --queue=two start" end task :stop, roles: :app do run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i one1 stop" run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i one2 stop" run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i two stop" end task :restart, roles: :app do run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i one1 --queue=one restart" run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i one2 --queue=one restart" run "cd #{current_path}; #{rails_env} bundle exec script/delayed_job -i two --queue=two restart" end end ```
After a bit of messing around, the trick I found was to revert to the 'set :delayed\_job\_args' and use --queues= (plural) instead of --queue= (singular). Hope this helps anyone else who runs into the same issue. ``` set :delayed_job_args, "-n 2 -p ecv2.production --queues=cache,export" ``` **UPDATE: What I'm using now...** ``` after "deploy:stop", "delayed_job:stop" after "deploy:start", "delayed_job:start" after "deploy:restart", "delayed_job:restart" namespace :delayed_job do # See 'man nice' for details, default priority is 10 and 15 is a bit lower task :start, :roles => :app do run "cd #{current_path}; #{rails_env} nice -n 15 ruby script/delayed_job -n 1 -p yourapp.#{application} start" end task :restart, :roles => :app do stop start end end ```
5,984,808
Good time of a day! I have a MVC project with query in controller: ``` var getPhotos = (from m in db.photos join n in db.comments on m.id equals n.photoid where n.ownerName == User.Identity.Name orderby n.id descending select new { m.imgcrop, m.id, n.commenterName, n.comment }).Take(10); ``` How to pass this query to view model, and the model to view. Spend all evening to find the examples, but cant. Thanks for help! **UPDATED** Full Model Class ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace photostorage.Models { public class GlobalModel { public class PhotoViewModel { public photos Photos { get; set; } public profiles Profile { get; set; } public IQueryable<comments> Comments { get; set; } public IQueryable<photos> NextPrev { get; set; } } public class UserPhotoList { public IQueryable<photos> Photos { get; set; } public profiles Profile { get; set; } } public class UserProfileView { public IQueryable<photos> Photos { get; set; } public profiles Profile { get; set; } } public class GetLastComments { public IQueryable<photos> uPhoto { get; set; } public IQueryable<comments> uComments { get; set; } } } } ``` Controller: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using photostorage.Models; namespace photostorage.Controllers { public class HomeController : Controller { private photostorageEntities db = new photostorageEntities(); public ActionResult Index() { if(Request.IsAuthenticated) { GlobalModel.GetLastComments model = new GlobalModel.GetLastComments(); var getPhotos = (from m in db.photos join n in db.comments on m.id equals n.photoid where n.ownerName == User.Identity.Name select new { m.imgcrop, m.id, n.commenterName, n.comment }).Take(10); return View("Index_Auth", model); }else{ ViewBag.Message = "Welcome to ASP.NET MVC!"; return View("Index"); } } public ActionResult About() { return View(); } } } ```
2011/05/12
[ "https://Stackoverflow.com/questions/5984808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/608356/" ]
In this case you can make a "view model" that will only be used by your view and not by the rest of your application. Something like the following: ``` public class CommentsViewModel { public int MessageId { get; set; } public string ImageCrop { get; set; } public string CommenterName { get; set; } public string Comment { get; set; } } ``` Then change your query like so: ``` var getPhotos = (from m in db.photos join n in db.comments on m.id equals n.photoid where n.ownerName == User.Identity.Name orderby n.id descending select new CommentsViewModel { ImageCrop = m.imgcrop, MessageId = m.id, CommenterName = n.commenterName, Comment = n.comment }).Take(10).ToList(); ``` Make your view strongly typed to the new class and pass the data to it like so: ``` View("name_of_your_view", getPhotos); ```
If you wanted to do this, like you had: ``` var getPhotos = (from m in db.photos join n in db.comments on m.id equals n.photoid where n.ownerName == User.Identity.Name select new { m.imgcrop, m.id, n.commenterName, n.comment }).Take(10); ``` You could actually have this without creating a new "CommentsViewModel", but just use what should be the existing tables and models: ``` var getPhotos = (from m in db.Photos join n in db.Comments on m.Id equals n.PhotoId where n.OwnerName == User.Identity.Name select new { ImageCrop = m.ImageCrop, Id = m.Id, CommenterName = n.CommenterName, Comment = n.Comment }).Take(10); ``` The models would be something like these examples, if you had a foreign key relationship on the Photo.Id to Comments.PhotoId: ``` public class Photos { public int Id { get; set; } public string ImageCrop { get; set; } [ForeignKey("PhotoId")] public virtual Comments Comment { get; set; } } public class Comments { public int Id { get; set; } public int PhotoId { get; set; } public string CommenterName { get; set; } public string OwnerName { get; set; } public string Comment { get; set; } } ``` Just a note: The models you displayed in your question had none of these columns, yet you were building a query against them. It's best to remember to give a complete picture when asking for help.
45,131,258
I am trying to input dates using `datalines` but it is not working: ``` data demographic; input Subj @5 DOB mmddyy6. @16 Gender $ Name $; format dob ddmmyy10.; datalines; 001 10/15/1960 M Friedman 002 08/01/1955 M Stern 003 12/25/1988 F McGoldrick 005 05/28/1949 F Chien ; run; ``` What seems to be the problem?
2017/07/16
[ "https://Stackoverflow.com/questions/45131258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559878/" ]
Abstract the building of that button into some sort of factory or function. This way, you don't have to constantly manually reconfigure the button nor do you have to worry about copying / cloning (which can get very messy) ``` public JButton createButton(string caption) { //Create button here } ```
Ok then, you can copy that button and paste in another panel. Go back to the old frame. Copy that button code. Just come back to the next frame. Click on the button action and paste it. ☺
12,563,954
I've used this code to force an orientation change back to portrait when the user is finished watching the video (it allows viewing in landscape mode), before popping the video view controller off the navigation controller: ``` //set statusbar to the desired rotation position [[UIApplication sharedApplication] setStatusBarOrientation:UIDeviceOrientationPortrait animated:NO]; //present/dismiss viewcontroller in order to activate rotating. UIViewController *mVC = [[[UIViewController alloc] init] autorelease]; [self presentModalViewController:mVC animated:NO]; [self dismissModalViewControllerAnimated:NO]; [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone]; ``` This worked perfectly until `iOS 5.1.1`. I've even tried to use the new present/dismiss methods after reading in another post that those should be used now: ``` [self presentViewController:mVC animated:NO completion:NULL]; [self dismissViewControllerAnimated:NO completion:NULL]; ``` The problem is it doesn't work at all. After I rotated the video viewer to landscape and then pop it, my settings view (table view controller) comes back, but also in landscape mode. I've even tried the tip from [Here](http://9to5mac.com/2012/06/25/apple-pushes-ios-6-0-update-to-devs/) "The `setStatusBarOrientation:animated:` method is not deprecated outright. However it now works only if the `supportedInterfaceOrientations` method of the topmost full screen view controller returns 0. This puts the responsibility of ensuring that the status bar orientation is consistent into the hands of the caller." So I've experimented with setting a flag to force `supportedInterfaceOrientations` to `return 0` (before calling the first code block above) but it doesn't work either. Does anybody have a solution for this? Thanks for your time and effort.
2012/09/24
[ "https://Stackoverflow.com/questions/12563954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1623844/" ]
`setStatusBarOrientation` method has changed behaviour a bit. According to Apple documentation: > > The setStatusBarOrientation:animated: method is not deprecated > outright. It now works only if the supportedInterfaceOrientations > method of the top-most full-screen view controller returns 0 > > >
Your root view controller should answer false to the method `shouldAutorotate` in order that your app responds to `setStatusBarOrientation:animated` From Apple Documentation: "if your application has rotatable window content, however, you should not arbitrarily set status-bar orientation using this method" To understand that, put a breakpoint in the `shouldAutorotate` method and you will see that it is called juste after setting the status bar orientation.
138,924
I have a linux reseller account and i manage through WHM I have created a cpanel account for my client. He wanted the port 5222 to be open. I am not aware of it. How to check the status, and whether it is open or not? How to turn it on /off?
2010/05/05
[ "https://serverfault.com/questions/138924", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
``` telnet <hostname> 5222 ```
With HostGator at least, clientdomain.com/cpanel redirects to clientdomain.com:2082. I'm not aware if you can change that, but the best place to ask would be your hosting company's support. Like solefald said, you can use the `telnet` command to test whether TCP ports are open.
40,074
The last few images in Robert A. Braeunig's [Apollo 11's Translunar Trajectory; and how they avoided the heart of the radiation belts](https://web.archive.org/web/20171124132216/http://braeunig.us:80/apollo/apollo11-TLI.htm) are fascinating and a bit perplexing as discussed in [this answer](https://space.stackexchange.com/a/40072/12102) and the comments below it. This got me wondering what it would take to reconstruct the trajectories of one or more of the Apollo missions from scratch. * only the crewed components that NASA tracked carefully because there were people on board * primarily outside of Earth's atmosphere where I can numerically integrate trajectories without aerodynamics Are there raw data out there somewhere? Perhaps range-rate, Doppler etc.? I'm assuming these were recorded and analyzed post mission and written up post-mission, with some tables, but are there large tables of state vectors? Is the raw data available somehow? **Question:** If I wanted to reconstruct an entire Apollo mission's crewed spacecraft trajectories, what are the key sources of historical data I'd look for? Where might I find some of them? There may be some promising leads in answers to [Where to look for historical or reconstructed orbit data for early NASA missions - Mercury-Atlas 6 for example](https://space.stackexchange.com/q/19402/12102). Maybe some day we can get the final answer to [Puzzler: Precisely what maximum distance from the Earth did the Apollo 13 astronauts achieve?](https://space.stackexchange.com/q/33211/12102)
2019/11/24
[ "https://space.stackexchange.com/questions/40074", "https://space.stackexchange.com", "https://space.stackexchange.com/users/12102/" ]
To answer the question literally: you'd be looking for NASA Apollo Trajectory (NAT) data files. The report [Apollo Mission 11, Trajectory Reconstruction and Postflight Analysis Volume 1 (PDF)](https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19700014995.pdf) provides a summary for Apollo 11 and mentions that the raw NAT data is available in Volume 2 of the report. I have yet to find Volume 2 though, perhaps because > > The listing is not generally distributed but is available from NASA/MSC upon request. > > > Also [Earth Departure Trajectory Reconstruction of Apollo Program Components Undergoing Disposal in Interplanetary Space](http://www.aiaahouston.org/Horizons/ApolloEarthDeparturesR7.pdf) mentions the availability of NAT data, but without reference. I requested the document at NASA STI, but: > > Thank you for contacting the NASA STI Information Desk. Unfortunately, we do not have the requested document in our repository. > > > So I asked the author of the paper where to find them. I was thinking about huge data files, but turns out that the available NAT data is a single table that can be found in the Mission Reports. For example, for Apollo 11, it's table 7-II in the [Apollo 11 Mission Report](https://www.hq.nasa.gov/alsj/a11/a11mr.html). [![Trajectory parameters for Apollo 11](https://i.stack.imgur.com/GmyML.png)](https://i.stack.imgur.com/GmyML.png) *(Trajectory parameters for Apollo 11 from Apollo 11 Mission Report)* For Apollo 17, I found ["Apollo/Saturn 5 postflight trajectory: AS-512"](https://ntrs.nasa.gov/search.jsp?R=19760012111) on NTRS, which contains a wealth of information. Similar documents likely exist for the other Apollo missions, but I have not yet been able to locate them.
I found a method to directly plot the full trajectory of S-IVB (NASA id: -399110) from launch to CSM separation and beyond, being data available on NASA Horizon server: [Full trajectory w.r.t. Earth](http://win98.altervista.org/space/exploration/3d/space-explorer-tracker.html?orbiter=-399110&orbitername=Apollo%2011%20S-IVB&center=@399&bodyName=moon&radius=6341&start=1969-JUL-16%2016:50&stop=1969-JUL-21%2000:06:3&3dx=10000&step=1h&3dzoom=300000): [![full trajectory w.r.t. Earth](https://i.stack.imgur.com/p1eOC.png)](https://i.stack.imgur.com/p1eOC.png) [Full trajectory w.r.t Moon](http://win98.altervista.org/space/exploration/3d/space-explorer-tracker.html?orbiter=-399110&orbitername=Apollo%2011%20S-IVB&center=@301&radius=6341&start=1969-JUL-16%2016:50&stop=1969-JUL-21%2000:06:3&3dx=10000&step=1h&3dzoom=300000): [![Full trajectory w.r.t Moon](https://i.stack.imgur.com/Lx02e.png)](https://i.stack.imgur.com/Lx02e.png) Unfortunately there are no data for CSM and LM of Apollo 11, but there are for Apollo 10, I write them here below separately. Apollo 10 data -------------- * [-399100 Apollo 10 S-IVB (spacecraft)](http://win98.altervista.org/space/exploration/3d/space-explorer-tracker.html?orbiter=-399100&orbitername=Apollo%2011%20S-IVB&center=@301&radius=6341&start=1969-MAY-18%2019:45&stop=1969-MAY-29%2000:06:39&3dx=10000&step=1h&3dzoom=300000) - Available period: 1969-MAY-18 19:45 - 1969-MAY-29 00:06 * [-399101 Apollo 10 LM (spacecraft)](http://win98.altervista.org/space/exploration/3d/space-explorer-tracker.html?orbiter=-399101&orbitername=Apollo%2011%20S-IVB&center=@301&radius=6341&start=A.D.%201969-MAY-23%2005:38&stop=1969-MAY-28%2000:06:39&3dx=10000&step=1h&3dzoom=300000) - Available period: 1969-MAY-23 05:38 - 1969-MAY-28 00:06 I don't put images here, not to mess up with the answer, but you've just to replace the **orbiter** parameter in the url: * orbiter=-399110 --> orbiter=-**399100** (Apollo 10 S-IVB) * orbiter=-399110 --> orbiter=-**399101** (Apollo 10 LM) Note: in case of "network error", remove "s" from "https" in the url. [Apollo 10 S-IVB Timeline](https://history.nasa.gov/SP-4029/Apollo_10i_Timeline.htm): * Apollo 10 S-IVB / CSM separation: 1969-MAY-23 19:51:42 * Descent orbit insertion ignition - 20:35:01 22-May-69 * LM closest approach to lunar surface - 21:30:43 22-May-69 * LM separation maneuver ignition 05:32:23 23-May-69 * LM ascent propulsion system ignition 05:41:05 23-May-69 **<<<---- LM ephemeris available from here** * LM ascent propulsion system depletion 05:45:14 23-May-69 --- **See here for a full list of available spacecrafts:** [https://ssd.jpl.nasa.gov/horizons\_batch.cgi?batch=1&COMMAND=%27\*%27](https://ssd.jpl.nasa.gov/horizons_batch.cgi?batch=1&COMMAND=%27*%27)
2,422,588
I have a a project that resides on a "thumb drive" (a.k.a. memory stick). Due to Windows ability to change drive letters of thumb drives, I would like to specify the location of sub-projects using an environment variable. This allows me to set the thumb drive drive letter, depending on the PC that I am using; or change the variable when the drive letter changes (such as happens when adding a hard drive to the PC). This issue has sub parts: 1. How do I tell Visual Studio (2008) to use environment variable *when adding an existing project using the GUI*? 2. Which files do I need to modify with the environment variable (\*.dcp, \*.vcproj, \*.sln)? 3. Do I need to delete the platform specific `vcproj` files, such as `*.vcproj.`*host\_name*? {Since I use different host PCs with the thumb drive, there are different `vcproj` files.} I am using MS Visual Studio 2008, C++, on Vista and Windows XP (at least two platforms).
2010/03/11
[ "https://Stackoverflow.com/questions/2422588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225074/" ]
I do not think there is a built in method of achieving the smart structure you seem to be asking for. Below is the what I think is the most straight forward implementation out of the various possible methods. ``` stringdata = "h1\th2\n1\t2\n3\t4\n5" h1 h2 1 2 5 4 3 Clear[ImportColumnsByName]; ImportColumnsByName[filename_] := Module[{data, headings, columns, struc}, data = ImportString[filename, "TSV"]; headings = data[[1]]; columns = Transpose[PadRight[data[[2 ;; -1]]]]; MapThread[(struc[#1] = #2) &, {headings, columns}]; struc ] Clear[test]; test = ImportColumnsByName[stringdata]; test["h1"] test["h2"] Sort[test["h1"]] ``` outputs: ``` {1, 3, 5} {2, 4, 0} {1, 3, 5} ``` Building on ragfield's solution, this is a more dynamic method, however every call to this structure makes a call to Position and Part. ``` Clear[ImportColumnsByName]; ImportColumnsByName[filename_] := Module[{data, temp}, data = PadRight@ImportString[filename, "Table"]; temp[heading_] := Rest[data[[All, Position[data[[1]], heading][[1, 1]]]]]; temp ] Clear[test]; test = ImportColumnsByName[stringdata]; test["h1"] test["h2"] Sort[test["h1"]] ``` outputs: ``` {1, 3, 5} {2, 4, 0} {1, 3, 5} ```
Starting from ragfield's code: ``` table = Import["file.csv", "Table"]; colname = "X117" x117 = Drop[table[[All, Position[tb[[1, All]], colname]//Flatten]], 1]//Flatten; sorted = Sort[x117]; ```
754,787
I would like to create a url just like followings : * <http://localhost/news/announcement/index> * <http://localhost/news/health/index> * <http://localhost/news/policy/index> announcement, health, policy are controller so I make a new url route map like this : ``` routes.MapRoute( "News", "news/{controller}/{action}/{id}", new { controller = "Announcement", action = "Index", id = "" } ); ``` It works fine but, following two urls show same page : * <http://localhost/news/announcement/index> * <http://localhost/announcement/index> I would like to prevent second url. What shoud I do? Thanks Kwon
2009/04/16
[ "https://Stackoverflow.com/questions/754787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If there is any default route mapping then move it to the end of your mappings. If that doesn't help then you can try [Url Routing Debugger](http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx).
Logically speaking second url should not work. Because **news** is your application name which is hosted in IIS and i guess you might have put that in Default website. So if you are accessing the application URL will be always <http://localhost/>**news**/controller/action and if you give this <http://localhost/controller/action>, it doesnt know which application to look. i suggest you to create a virtual directory 'news' if you have not created one and then publish everything there. Also make sure you have not published your application files in Inetpub\wwwroot\ directory. Am waiting for your reply to continue.
1,205,652
I'm struggling a bit with solving a limit problem using L'Hopital's Rule: $$\lim\_{x\to\infty} \left(1+\frac{1}{x}\right)^{2x}$$ My work: $$y = \left(1+\frac{1}{x}\right)^{2x}$$ $$\ln y = \ln \left(1+\frac{1}{x}\right)^{2x} = 2x \ln \left(1+\frac{1}{x}\right)$$ $$=\frac{\ln \left(1+\frac{1}{x}\right)}{(2x)^{-1}}$$ Taking derivatives of both the numerator and the denominator: $$f(x) = \ln\left(1+\frac{1}{x}\right)$$ $$f'(x) = \left(\frac{1}{1+\frac{1}{x}}\right)\left(-\frac{1}{x^2}\right) = (x+1)\left(-\frac{1}{x^2}\right) = -\frac{(x+1)}{x^2}$$ $$g(x) = (2x)^{-1}$$ $$g'(x) = (-1)(2x)^{-2}(2) = -\frac{2}{(2x)^{2}} = -\frac{1}{2x^{2}}$$ Implementing the derivatives: $$\lim\_{x\to\infty} \frac{-\frac{(x+1)}{x^2}}{-\frac{1}{2x^2}} = -\frac{(x+1)}{x^2} \cdot \left(-\frac{2x^2}{1}\right) = 2(x+1) = 2x+2$$ However, I'm not sure where to go from here. If I evaluate the limit, it still comes out to infinity plus 2, and I don't know how much further to take the derivative or apply L'Hopital's Rule. Any suggestions would be appreciated!
2015/03/25
[ "https://math.stackexchange.com/questions/1205652", "https://math.stackexchange.com", "https://math.stackexchange.com/users/135393/" ]
There is, but as with most of the checks of the field axioms using Dedekind Cuts, it isn't pretty. First recall that multiplication is given by, for $A,B$ positive \begin{equation} A\cdot B =\{a\cdot b \mid a\in A \wedge 0<a \wedge b \in B \wedge 0<b \} \cup \{ q\in \mathbb{Q}\mid q\leq 0\}. \end{equation} More generally, we define \begin{equation} A\cdot B= \begin{cases} \overline{0} & \text{If $A=\overline{0}$ or $B=\overline{0}$,} \\ -(A\cdot (-B)) & \text{If $\overline{0}<A$ and $B<\overline{0}$,} \\ -((-A)\cdot B) & \text{If $A<\overline{0}$ and $\overline{0}<B$,} \\ (-A)\cdot (-B) & \text{If $A<\overline{0}$ and $B<\overline{0}$.} \end{cases} \end{equation} We want to show that $A\cdot (B+C)=A\cdot B+A\cdot C$. Sadly, since this means that we now must take into account three variables, we have ourselves a case-by-case nightmare. First let us suppose that $A$, $B$, and $C$ are all positive. Let $d\in A\cdot (B+C)$; if $d\leq 0$, then $d \in A\cdot B+A\cdot C$ since it is the sum of two positive Dedekind cuts. Otherwise we have $0<d$; $d$ can hence be written as $d=a\cdot (b+c)$ where $0<a \in A$, $b \in B$, and $c \in C$ where $0<b+c$. We can assume that $b$ and $c$ are positive because at least one must be positive; without loss of generality assume $b$ is positive. If $c$ is negative, then $b+c<b$, so that because $B$ is downwards closed it follows that $b+c\in B$. Then take a positive element $c'<b+c$ of $C$ and let $b'=b+c-c'$ which is necessarily positive by our choice of $c'$. Then $b'+c'=b+c$ with $0<b'\in B$ and $0<c'\in C$. Thus, we will simply assume that $b$ and $c$ are positive. Hence, $ab\in A\cdot B$ and $ac\in A\cdot C$ and thus $d=ab+ac\in A\cdot B+A\cdot C$, so that $A\cdot (B+C) \subset A\cdot B + A\cdot C$. Similarly, if $d\in A\cdot B+A\cdot C$, then there exists $d\_1\in A\cdot B$ and $d\_2\in A\cdot C$ such that $d=d\_1+d\_2$. If $d\_1$ and $d\_2$ are positive, then there are $0<a,a'\in A$, $0<b\in B$, and $0<c\in C$ such that $ab=d\_1$ and $a'c=d\_2$. We may assume that $a=a'$, as otherwise we can let $a''=\frac{ab+a'c}{a+a'}$ which gives us $a''b+a''c=d$ and replace $a$ and $a'$ with $a''$. Then $ab+a'c=ab+ac=a(b+c)$ so that $d=a(b+c)\in A\cdot (B+C)$. If $d\_1$ and $d\_2$ are both non-positive, then $d\_1+d\_2$ is non-positive and thus lies in $A\cdot (B+C)$. Finally, if one of $d\_1$ and $d\_2$ is non-positive while the other is positive -- say $d\_1$ is positive and $d\_2$ non-positive -- then $d\_1=ab$ for $0<a\in A$ and $0<b\in B$, so taking $c$ to be any positive rational number in $C$ we find that $d\_1+d\_2<ab+ac=a(b+c)\in A\cdot (B+C)$, so that because $A\cdot (B+C)$ is downwards closed, we see that $d=d\_1+d\_2\in A\cdot (B+C)$, thus establishing the fact that $A\cdot B+A\cdot C\subset A\cdot (B+C)$. A tool we shall make use of in the remaining cases is that $-(A+B)=(-A)+(-B)$: $(A+B)+(-(A+B))=\overline{0}$ and $A+B+(-A)+(-B)=\overline{0}$, so that $(A+B)+(-(A+B))=(A+B)+(-A)+(-B)$, and cancellation of the term $A+B$ gives us the desired result. * If $A=\overline{0}$, then $A\cdot (B+C)=A\cdot B=A\cdot C=\overline{0}$, and thus $A\cdot B+A\cdot C=\overline{0}=A\cdot (B+C)$. * When $A$, $B$, and $C$ are all negative, $B+C$ is negative, so $A\cdot (B+C)=(-A)\cdot (-(B+C))=(-A)\cdot ((-B)+(-C))=(-A)\cdot (-B)+(-A)\cdot (-C)=A\cdot B+A\cdot C$. \item When $A$ is negative and $B$ and $C$ are positive, $B+C$ is positive and $A\cdot (B+C)=-((-A)\cdot (B+C))=-((-A)\cdot B+(-A)\cdot C)=(-((-A)\cdot B))+(-((-A)\cdot C))=A\cdot B+A\cdot C$. * If $B=\overline{0}$, then $A\cdot (B+C)=A\cdot (\overline{0}+C)=A\cdot C=A\cdot \overline{0}+A\cdot C=A\cdot B+A\cdot C$. The same argument shows the case for $C=\overline{0}$. * If $A$ and $C$ are negative and $B$ is positive, then we have three cases: if $B+C$ is positive, negative, or zero. In the last case, $B=(-C)$ and $A\cdot (B+C)=A\cdot \overline{0}=\overline{0}=(A\cdot B)+(-(A\cdot B))=A\cdot B+A\cdot (-B)=A\cdot B+A\cdot C$. If $B+C$ is negative, then \begin{align} A\cdot C & =A\cdot ((B+C)+(-B)) \\ & =(-A)\cdot (-((B+C)+(-B))) \\ & =(-A)\cdot ((-(B+C))+B) \\ & = (-A)\cdot (-(B+C))+(-A)\cdot B \\ & = A\cdot (B+C)+(-(A\cdot B)) \end{align} Adding $A\cdot B$ to both sides gives us the desired result. If $B+C$ is positive, then \begin{align} A\cdot B & =A\cdot ((B+C)+(-C)) \\ & =-((-A)\cdot ((B+C)+(-C))) \\ & = -((-A)\cdot (B+C)+(-A)\cdot (-C)) \\ & = -((-(A\cdot (B+C)))+A\cdot C) \\ & = A\cdot (B+C)+(-(A\cdot C)). \end{align} Adding $A\cdot C$ to both sides gives us the desired result. The same arguments hold for $B$ negative and $C$ positive by interchanged the roles of $B$ and $C$ above. * If $A$ and $B$ are positive and $C$ is negative, then we have three cases: if $B+C$ is positive, negative, or zero. In the last case, $B=(-C)$ and $A\cdot (B+C)=A\cdot \overline{0}=\overline{0}=(A\cdot B)+(-(A\cdot B))=A\cdot B+A\cdot (-B)=A\cdot B+A\cdot C$. If $B+C$ is negative, then \begin{align} A\cdot C & = A\cdot ((B+C)+(-B)) \\ & = -(A\cdot (-((B+C)+(-B)))) \\ & = -(A\cdot ((-(B+C))+B)) \\ & = -(A\cdot (-(B+C))+A\cdot B) \\ & = (-(A\cdot(-(B+C))))+(-(A\cdot B)) \\ & = A\cdot (B+C)+(-(A\cdot B)) \end{align} Adding $A\cdot B$ to both sides gives us the desired result. If $B+C$ is positive, then \begin{align} A\cdot B & =A\cdot ((B+C)+(-C)) \\ & = A\cdot ((B+C)+(-C)) \\ & = A\cdot (B+C)+A\cdot (-C)) \\ & = A\cdot (B+C)+(-(A\cdot C)) \end{align} Adding $A\cdot C$ to both sides gives us the desired result. The same arguments hold for $B$ negative and $C$ positive by interchanging the roles of $B$ and $C$ above. (If there's a prettier way to prove this with Dedekind Cuts, I certainly don't know it. At first glance the proof that Rudin gives in Principles of Mathematical Analysis is shorter, but that's because he doesn't actually do it all (rather, says "similar to our above proofs"))
I tried to prove your above claim for positive cuts, that is, cuts containing some positive rationals. This is the first time I've tried to prove this, so I apologize in advance if it is a bit hard to follow or if it contains mistakes. > > Addition and multiplication of positive Dedekind cuts are defined as follows. > > > $$\alpha+\beta=\{a+b\mid a\in\alpha, b\in\beta\}\\ > \alpha\beta = \{x\in\Bbb Q\mid \exists a\in\alpha,b\in\beta(a>0, b>0, ab\ge x)\}$$ > > > Let $x,y,z$ be positive Dedekind cuts. First, let's show that every member of $x(y+z)$ is a member of $xy+xz$. Let $\lambda\in x(y+z)$. There exists a positive $a\in x$ as well as $b\in y$ and $c\in z$ such that $b+c>0$ and $\lambda\le a(b+c)$. Since such $b$ and $c$ exist, there also exist such $b$ and $c$ that not only is their sum positive, but $b$ and $c$ are themselves positive. This is easy to see as there exists a positive rational in every $x,y,z$ and we can increase the nonpositive $b$ or $c$ to that positive rational. So, there exist $a\in x, b\in y, c\in z$, all positive, such that $\lambda\le a(b+c)=ab+ac$. $ab$ is a product of positive members of $x$ and $y$, so it is a member of $xy$. $ac$ is a product of positive members of $x$ and $z$, so it is a member of $xz$. $ab+ac$ is the sum of members of $xy$ and $xz$, so it is a member of $xy+xz$. Since $\lambda\le ab+ac$, $\lambda$ is also a member of $xy+xz$. And now let's show that every member of $xy+xz$ is a member of $x(y+z)$. Let $\kappa\in xy+xz$. $\kappa$ is then the sum of members of $xy$ and $xz$, call them $\kappa\_1$ and $\kappa\_2$. There exist positive $a\_1\in x,b\in y$ such that $\kappa\_1\le a\_1b$ and positive $a\_2\in x,c\in z$ such that $\kappa\_2\le a\_2c$. Choose $a=\max\{a\_1,a\_2\}$. Then $\kappa=\kappa\_1+\kappa\_2\le a\_1b+a\_2c\le ab+ac=a(b+c)$. $b+c$ is a sum of members of $y$ and $z$, so it is a member of $y+z$. $a(b+c)$ is a product of positive members of $x$ and $y+z$, so $\kappa$ is a member of $x(y+z)$. Every member of $x(y+z)$ is a member of $xy+xz$ and vice versa, therefore $$x(y+z)=xy+xz$$
138,589
**Bug introduced in 10.4 and fixed in 11.0** --- I type ``` l = 3 r = ImplicitRegion[(x^2 + y^2)^3 == l *x^2* y^2, {x, y}]; RegionPlot[r] ``` and I obtain [![enter image description here](https://i.stack.imgur.com/gWKWa.jpg)](https://i.stack.imgur.com/gWKWa.jpg) How could I obtain a good graph for viewing the implicit region, similar to what I obtain if I type `<=` instead of `==` [![enter image description here](https://i.stack.imgur.com/9OF6i.jpg)](https://i.stack.imgur.com/9OF6i.jpg)
2017/02/24
[ "https://mathematica.stackexchange.com/questions/138589", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/6543/" ]
This is a bug in 10.4. One-dimensional regions embedded in the plane will not be plotted by `RegionPlot`. For example, ``` RegionPlot[ImplicitRegion[x^2 + y^2 == 1, {x, y}]] ``` renders as an empty. In 10.3 and in 11.0.1, it can be plotted without problems. However, the specific region you show has another problem, present even in 10.3 and 11.0. Only part of the region is shown: ![](https://i.stack.imgur.com/oHicx.png) A good workaround for 10.3 is to manually specify the boundaries. Well, we can do it semi-automatically using `RegionBounds`. ``` RegionPlot[r, PlotRange -> RegionBounds[r]] ``` ![](https://i.stack.imgur.com/PRDf3.png) Unfortunately, specifying the `PlotRange` in 11.0 causes a hang. --- As you can see, there are at least 3 seemingly distinct bugs here, which affect different versions: * 10.4 won't plot 1D regions embedded in 2D. 10.0-10.3 and 11.0 do not suffer from this. * 10.0-11.0 will only plot a quarter of this specific region unless the `PlotRange` is manually specified. Also discussed in: [Cannot reproduce TransformedRegion example shown in documentation](https://mathematica.stackexchange.com/q/129812/12) * 10.4 and 11.0 hang if the `PlotRange` is manually specified for this region. This problem is not present in 10.0-10.3. Note: I have not actually tested 10.1 and 10.2. I assumed that when 10.0 and 10.3 behave identically, so do any versions in-between.
Or: ``` r = ImplicitRegion[(x^2 + y^2)^3 < 3 x^2 y^2, {x, y}]; RegionPlot[r, PlotStyle -> White] ``` Incidentally, your `l = 3` is irrelevant to the question (and should have a semicolon anyway) and should be removed.
15,479,827
I created 2 radio buttons ``` <input type="radio" name="ApprovalGroup" runat="server" id="ApprovedOnly" value="true" />Approved <input type="radio" name="ApprovalGroup" runat="server" id="UnapprovedOnly" value="false" />Unapproved ``` And was able to access them from js with `$("input[name=ApprovalGroup]:checked").val()` But then I needed to add `runat="server"` so I could access the radio button in the code behind. The problem I have is the radio button name is being changed because of the content place holder. I'm using `ClientIDMode="Static"` but it only protects the id value, not the name. The radio button is rendered as ``` <input value="true" name="ctl00$cphContent$ApprovalGroup" type="radio" id="ApprovedOnly" />Approved <input value="false" name="ctl00$cphContent$ApprovalGroup" type="radio" id="UnapprovedOnly" />Unapproved ``` Is it possible to prevent the name from changing?
2013/03/18
[ "https://Stackoverflow.com/questions/15479827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051183/" ]
You could use the `$=` selector, which selects attributes whose values end with the given substring: ``` $("input[name$=ApprovalGroup]:checked") ```
.NET wants the name for its own purposes, but that doesn't stop you for using a CSS class name for your own. That way you can use `$('.classname').val()`. You can use individual class names for fields, or share them to make groups.
29,412,357
Consider the following code ``` List<string> one = new List<string>(); List<string> two = new List<string>(); ``` List one contains 3 strings ``` Test 1 Test 1 Test 2 ``` How would I match the string `Test 1` and put each matching string in `List two` and remove the matching strings from list one so it's left with only `Test 2` string This is what I have so far ``` if (one.Any(str => str.Contains("Test 1"))) { //What to do here } ``` If I use `AddRange()` it adds the entire list one to list two
2015/04/02
[ "https://Stackoverflow.com/questions/29412357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3793448/" ]
So you want to remove all "Test1" from `one` and add them to `two`. So actually you wants to transfer them from one list to another? ``` string toFind = "Test 1"; var foundStrings = one.Where(s => s == toFind); if(foundStrings.Any()) { two.AddRange(foundStrings); one.RemoveAll(s => s == toFind); } ``` Here's a non-LINQ version that is more efficient but perhaps not as readable: ``` // backwards loop because you're going to remove items via index for (int i = one.Count - 1; i >= 0; i--) { string s1 = one[i]; if (s1 == toFind) { two.Add(toFind); one.RemoveAt(i); } } ```
If you want to check against this string: ``` string match = "Test1"; ``` then use this: ``` two.AddRange(one.Where(x => x == match)); ``` to place all matching records from list `one` into list `two`. Then, use this: ``` one.RemoveAll(x => x == match); ``` to remove all matching records from list `one`.
21,624
*Jacques Cartier*, le 6 septembre 1535, lors de son [deuxième voyage](https://fr.wikipedia.org/wiki/Jacques_Cartier#Le_deuxi.C3.A8me_voyage_.281535-1536.29), traite ainsi de ce qu'il voit : [![enter image description here](https://i.stack.imgur.com/pmlyS.jpg)](https://i.stack.imgur.com/pmlyS.jpg) [ Extraits de deux éditions ([Gallica](http://gallica.bnf.fr/ark:/12148/bpt6k84126j/f39.image), [Books](https://books.google.com/books?id=w7UTAAAAYAAJ&dq=cartier%20voyage%20couldres&pg=PA135#v=onepage&q=cartier%20voyage%20couldres&f=false)) des *Voyages de découverte au Canada, entre les années 1534 et 1542*, de Jacques Cartier ; voir surtout le manuscrit 5653 de la [*Seconde navigation*](http://gallica.bnf.fr/ark:/12148/bpt6k109478b/f1.image), de la main de Cartier ; aussi [documentaire](https://www.onf.ca/film/pour_la_suite_du_monde/). ] --- Il s'agit d'une description de l'[*Île **aux** Coudres*](http://www.toponymie.gouv.qc.ca/ct/toposweb/Fiche.aspx?no_seq=15427) sur le fleuve Saint-Laurent. Le [*coudre*](http://www.cnrtl.fr/definition/coudre/1) est un noisetier. On fait usage de la préposition archaïque [*ès*](http://www.cnrtl.fr/definition/%C3%A8s), aujourd'hui réservée à des trucs figés et aux noms de lieux (on donne souvent en toponymie l'exemple *Riom-ès-Montagnes*), par contraction de la préposition avec l'article défini au pluriel dans *en les*.1 C'est presque [exclusivement](http://bdl.oqlf.gouv.qc.ca/bdl/gabarit_bdl.asp?t1=1&id=4406) employé avec un nom au pluriel. Au *LBU14* on en discute (§580), et dans une note (H5) on signale que « [*a*]*u* et parfois *aux* ont absorbé les formes contractées avec en » mais pourtant on dit plus loin que généralement *ès* est assimilé à une préposition avec pour valeur essentiellement *en*. De plus, dans les dictionnaires, on ne mentionne pas ([*Larousse*](http://larousse.fr/dictionnaires/francais/%C3%A8s/30910/difficulte), [*Wiktionnaire*](https://fr.wiktionary.org/wiki/%C3%A8s#frm)) la préposition *à* avec l'article (*au/aux*) et on réfère toujours uniquement à *en/dans/en matière de*. * Que voulait-on dire exactement avec ce *ès* dans *Île ès Coudres* ; est-ce un emploi particulier par métonymie qui diffère des autres emplois de *ès* dans le texte ; au final *Île ès Coudres* et *Île aux Coudres* sont-ils équivalents ? * Si on modernise des noms (de lieux) en France et ailleurs, qui contenaient *ès* (nom *ès* nom), est-ce avec la préposition *à* (*au/aux*), avec *en (les)/dans (les)*, ou avec *les* seul ; pourquoi ? --- 1 *[Ens](https://apps.atilf.fr/lecteurFEW/index.php/page/lire/e/144296) ès* ; voir aussi *ille*, en article, au [*FEW*](https://apps.atilf.fr/lecteurFEW/index.php/page/lire/e/141899) ; on peut aussi explorer dans l'[*ALF*](http://cartodialect.imag.fr/cartoDialect/carteTheme) la prononciation de l'article ([les arbres](http://cartodialect.imag.fr/cartoDialect/seadragon.jsp?carte=CarteALF0052), [aux autres](http://cartodialect.imag.fr/cartoDialect/seadragon.jsp?carte=CarteALF0076), [aux quilles](http://cartodialect.imag.fr/cartoDialect/seadragon.jsp?carte=CarteALF1122)) etc. dans les dialectes du français.
2016/08/23
[ "https://french.stackexchange.com/questions/21624", "https://french.stackexchange.com", "https://french.stackexchange.com/users/-1/" ]
Je n'ai pas en tête d'exemple de modernisation de noms de lieux comportant la préposition *ès*, en revanche il semble qu'elle signifie plus souvent *en*, *dans* ou *au milieu de* que *aux*. Je pense aux noms de Val-ès-Dunes en Normandie ou de Pierrefitte-ès-bois dans le Loiret par exemple. Concernant l'Île-aux-coudres, le texte de Jacques Cartier que vous citez sert d'introduction à un beau film que Pierre Perrault et Michel Brault y tournèrent dans les années 1960: *Pour la suite du monde*. L'île est alors entourée de troncs d'arbres, plantés dans l'eau pour servir de piège dans la chasse aux marsouins. Cette technique n'existait probablement pas lorsque Cartier arriva sur les lieux, mais donne *a posteriori* une autre dimension au *ès* qui vous pose problème!
« Pourquoi Cartier n'a-t-il pas utilisé *des*, par exemple ?» Parce qu'il n'écrivait pas au XXIe siècle :-) Ça fait longtemps aussi qu'on ne dit plus « pour ce. » Rien de bizarre à ça.
4,097,104
Is there a tool that allows to see the whole page oulined in the browser? For example, I have a lot of hidden divs or images, may be overflown by some other elements and I want to see all the elements outlined, just to see what is placed in what place. If you ever used Adobe Illustrator, you could understand what I mean if you switched to outlines mode there by clicking CTRL+Y. I use FireBug now for something like that, but may be there is something more advanced for that?
2010/11/04
[ "https://Stackoverflow.com/questions/4097104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135829/" ]
I love Firebug plug-in for Firefox. Firebug allows you to navigate around the page, and it will highlight the element you've selected. It's a very powerful tool and it makes it very easy to see how your site hangs together. Plus it's got loads of other debugging tools built into it. If you're developing web sites, you should be using Firebug. There are similar tools available for other browsers. Recent versions of IE have the "developers tools" built in, though it's not as easy to use or as powerful as Firebug. Chrome and Safari also have a Developers Tools feature, which is quite powerful. Personally I still prefer Firebug, but they are all useful tools. Hope that helps.
Web-developer on fire-fox has been very helpful for me. I particularly like the outline block elements which has been helpful for me building sound structures and see how my elements are lining up as I go, and view style information that allows you to hover over all of your elements and see the css path. It sounds like outline block elements would be what you are looking for.
23,431
So imagine I have car D with the dead battery and car G with the good battery. Initially, both cars are turned off. I hook up car G to car D in the proper order. Before I start either car, won't there be a complete circuit going from battery G to battery D in the form of a back current? Because, AFAIK, the internal resistance of car batteries are so small, won't that mean the back current is rather large? So how is this procedure safe? Thanks, John
2015/12/15
[ "https://mechanics.stackexchange.com/questions/23431", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/13695/" ]
in practice the voltage on a resting depeleted battery while receiving a moderate charge and the voltage on a good battery at is about the same. so some current will flow into the flat battery, maybe 20A or so, but this is not much compared to the starter current. Also if you're doing it right the leads on the broken car go to the top end of the started cable (battery positive terminal) and to the engine block, so when starting is attempted the resistance of the path through the starter will be lower than the path through the battery. Charging the "dead" battery isn't actually a bad thing, The depelted battery does receive some charge, the smaller jumper cables (like 100A or 200A) won't carry enough current to start the engine, their use relies on the depleted battery receiving some charge anf giving some assistance before the engine can be started.
Yes, there will be some back current flowing into the dead battery, but the same regulation circuit in the G car will protect it from doing damage. You can connect the D car with the G car running to get more current. I have done this many times, and never had a problem - you'll notice a spark once you complete the circuit, but this is normal.
21,552,833
The "other java proposals" that allows you to use the Ctrl+Space shortcut is missing from my Kempler install. I have redownloaded and reinstalled fresh from Eclipse and still do not have access to the shortcut from "other java proposals". When searching here it's been suggested it should be checked in the advanced section of the editor preferences for Java. I can't find anything about how to enable to disable it here or in the Eclipse help files so I thought I would ask. Thanks, Omega
2014/02/04
[ "https://Stackoverflow.com/questions/21552833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2563518/" ]
Kepler doesn't have "Other java proposals" but just `Java Proposals`. This option (or `Java Proposals (Task-Focused)`) is sometimes left unchecked when importing the project to Kepler from a workspace on an older version of eclipse. Hence, your problem might be with workspace than the eclipse dist you are using.
I just thought I would "answer" this question incase someone else had the same problem. It turns out that Synergy+ uses the same keystroke to lock screens. Even when it's closed, and the service is still running it holds on to key binds. So, how I fixed it was to go through task manager and kill processes one at a time until I was able to use the shortcut, then went in to Synergy and changed the keybind.
23,661,078
I am trying to write a code that sums the digits of a number and it should work, but I can't find where I am doing it wrong, I have a working code in Python for this and I tried to do it the same way in C# but.. Here are the two codes Python: ``` number = "12346546" summ=0 for i in number: summ+=int(i) print summ ``` C#: ``` string num = "2342"; int sum = 0; for (int i = 0; i < num.Length; i++) { int number = Convert.ToInt32(num[i]); sum += number; } Console.WriteLine(sum); ``` Edit: I used the Debugger and I found that when I am converting the numbers they turn out to be completely different numbers, but if I convert the whole string then it is converting correctly... how to fix this?
2014/05/14
[ "https://Stackoverflow.com/questions/23661078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3637700/" ]
replace `Convert.ToInt32(num[i])` by ``` Convert.ToInt32(num[i].ToString()) ``` else, you will get an ascii value... (cause `num[i]` is a `char`) see [msdn](http://msdn.microsoft.com/en-us/library/ww9t2871%28v=vs.110%29.aspx)
A one line solution using Linq: ``` string num = "2342"; int sum = num.Sum(c=> Convert.ToInt32(c.ToString())); ``` Here's a fiddle: <https://dotnetfiddle.net/3jt7G6>
285,484
I have a spreadsheet with about 2000 rows that I need to group together based on the contents of about 12 columns. The key here is that the rows may differ in a number of different columns, but for those specific 12 columns, if they have equivalent values for each row in each respective column, I want to group them together and assign them a number,name,whatever. What's the best way to do this? Is there an easy way? The problem with filtering based on a certain column's value is that each column could have several different values in it, and the number of combinations is huge so for me to manually select each combination would be a huge headache.
2011/05/18
[ "https://superuser.com/questions/285484", "https://superuser.com", "https://superuser.com/users/81892/" ]
Try **pivot tables**. They will let you group, summarise, filter and sort your data with a great amount of flexibility. There are a few requirements on the way your source data should be laid out for pivoting to be most effective. Without seeing your data it is difficult to know how suitable it is.
Maybe you should have a look at [ASAP Utilities](http://www.asap-utilities.com/download-asap-utilities.php). It's an addon for Excel that, among a lot of things, lets you do conditional row and column select. It's free (for non commercial use) so you might as well give it a try.
17,830,702
I want to use [preg\_match()](https://www.php.net/manual/en/function.preg-match.php) in my code, but the result is nothing ... (or null or empty ?) ``` $domain = "stackoverflow.com"; $uriToTest = "http://stackoverflow.com/"; $pattern = "/^http(s)?://(([a-z]+)\.)*".$domain."/"; echo preg_match($pattern, $uriToTest); ``` What is the problem?
2013/07/24
[ "https://Stackoverflow.com/questions/17830702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2515673/" ]
You need to escape your forward slashes and the `.` in the domain name ``` $domain = "stackoverflow.com"; $uriToTest = "http://stackoverflow.com/"; $escapedDomain = str_replace('.', '\.', $domain); $pattern = "/^http(s)?:\/\/(([a-z]+)\.)*".$escapedDomain."/"; echo preg_match($pattern, $uriToTest); ```
``` $domain = "stackoverflow.com"; $uriToTest = "http://stackoverflow.com/"; $pattern = "^http(s)?://(([a-z]+)\.)*" . $domain . "^"; preg_match($pattern, $uriToTest, $matches); print_r($matches); ```
59,671,114
I want to generate **4** random numbers and they can't have repeated digits. For instance `4567`, (it doesn't have a repeated value like `4557`). I want them to be **random**. Is there any way to achieve this?
2020/01/09
[ "https://Stackoverflow.com/questions/59671114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12685104/" ]
I'm obsessed with streams nowadays. But streams are pretty slow. To show the slowness I wrote following main method. "generateWithLoop" method covers @WJS's answer. ``` public static void main(String[] args) { long nanoStart = System.nanoTime(); generateWithStreams(); long nanoEnd = System.nanoTime(); System.out.println("Elapsed time with Streams : " + (nanoEnd - nanoStart) + " nano seconds"); nanoStart = System.nanoTime(); generateWithLoop(); nanoEnd = System.nanoTime(); System.out.println("Elapsed time with Loop : " + (nanoEnd - nanoStart) + " nano seconds"); } ``` Console output : > > Elapsed time with Streams : 81367089 nano seconds > > > Elapsed time with Loop : 75093 nano seconds > > > With stream : ``` public static void generateWithStreams() { List<Integer> orderedList = getOrderedList(); for (int i = 0; i < 4; i++) { List<Integer> shuffledList = getShuffledList(orderedList); System.out.println(get4DigitNumber(shuffledList)); } } public static List<Integer> getOrderedList() { return IntStream.range(0, 10).boxed().collect(Collectors.toList()); } public static List<Integer> getShuffledList(List<Integer> list) { return list.stream().sorted((o1, o2) -> ThreadLocalRandom.current().nextInt(-1, 2)).collect(Collectors.toList()); } public static Integer get4DigitNumber(List<Integer> shuffledList) { final Integer LIMIT = shuffledList.get(0).equals(0) ? 5 : 4; return shuffledList.stream().limit(LIMIT).reduce(0, (sum, current) -> sum * 10 + current); } ``` With loop : ``` public static void generateWithLoop() { Random r = new Random(); for (int k = 0; k < 4; k++) { int val = gen(r); System.out.println(val); } } static int[] base = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public static int gen(Random r) { int val = 0; int s = 10; for (int i = 0; i < 4; i++) { int n = r.nextInt(s); val = val * 10 + base[n]; int save = base[n]; base[n] = base[--s]; base[s] = save; } return val < 1000 ? val * 10 + base[r.nextInt(s)] : val; } ```
``` public static void main(String[] args) { List<Integer> list= new ArrayList<>(); for(int j = 0; j < 10; j++){ list.add(j); } Collections.shuffle(list); String randomDigit= ""; for(int j = 0; j < 4; j++){ randomDigit+= list.get(j).toString(); } System.out.println(randomDigit); } ``` This is converting the string to int. But this will work you can use it.
2,956,251
[![enter image description here](https://i.stack.imgur.com/VGvSB.png)](https://i.stack.imgur.com/VGvSB.png) I stopped understanding the proof at "since $f$ is". I don't understand why $f$ is necessarily continuous on $[a,b]$ and differentiable on $(a,b)$. After all, $f$ is some kind of abstract function, it can be anything.
2018/10/15
[ "https://math.stackexchange.com/questions/2956251", "https://math.stackexchange.com", "https://math.stackexchange.com/users/161005/" ]
Regarding your comment about how you stopped understanding the proof at "since $f$ is," the continuity of $g$ follows from the theorems (often called) algebraic continuity theorem (a.c.t.): Let $[a,b]$ be a closed interval of some field (if your field if just $\mathbb{R}$ you will of course be fine). Assume your hypotheses ($f$ is continuous on $[a,b]$ and differentiable on the open interval $(a,b)$ ). Since $fa,$ $fb,$ $a,$ and $b$ are all constants(scalars) with $a\neq b$, $\text{ }\text{ }\frac{fb-fa}{b-a}\text{ }\text{ }$ is a (defined) constant. Recall that the identity function is continuous. Then by a.c.t, the functions (of variable $x$) defined by $\text{ }\text{ }\text{ }x-a\text{ }\text{ }\text{ }$ and $\text{ }\text{ }\text{ }\frac{fb-fa}{b-a}(x-a)\text{ }\text{ }\text{ }$ are continuous on $[a,b]$. Hence, again because $fa$ is just a constant, the function defined by $\frac{fb-fa}{b-a}(x-a)+fa$ is continuous on $[a,b]$. Therefore, by assumption of continuity of $f$ and the a.c.t, $g$ defined by $\text{ }\text{ }\text{ } fx-\frac{fb-fa}{b-a}(x-a)+fa\text{ }\text{ }\text{ }$ is continuous on $[a,b].\blacksquare$ The differentiability of $g$ follows similarly.
To apply Rolle's theorem of course $g(x)$ needs to be continuous on $[a,b]$ and differentiable on $(a,b)$ therefore also $f(x)$ needs to be continuous on $[a,b]$ and differentiable on $(a,b)$.
8,123
The standard meaning for this word seems to be “well”, sometimes positive, sometimes negative, sometimes simply as a placeholder (as was also [explained in answers here](https://german.stackexchange.com/questions/6948/what-are-the-differences-between-jein-and-naja)). But this seems to be only the case when it is at the start of a sentence. However, I have also seen it used a lot as an interjection on its own with an exclamation point (“Naja!”). Does this change the meaning of the word? What is one trying to say by simply responding “Naja!”?
2013/10/05
[ "https://german.stackexchange.com/questions/8123", "https://german.stackexchange.com", "https://german.stackexchange.com/users/3518/" ]
The meaning of a single "naja" would depend on its context. Prosody might be a stronger indicator than the actual word itself. You won't find it much in written language, too, apart from direct speech maybe, or colloquial texts. Basically, I'd describe it as some kind of "meh"-like utterance (or "well", as you said), signaling (implied) lack of importance/relevance of something said, for example to change topic, or to save someone's face while still criticizing. A: ... und deswegen sind wir dann im Kino gelandet. Naja! Später hat Heiner ... (A: ... and that's why we ended up in cinema. Well! Later, Heiner has ...) A: Papa fände es bestimmt auch schöner, wenn hier nicht so ein Chaos wäre. Naja! Essen ist fertig. (A: Dad would surely prefer, too, if it wasn't such a mess in here. Oh well! Dinner's ready.) But it can also have a dimension of not-really-agreeing. Then it might even appear as a doubled "naja", functioning mainly as a turn taking instrument introducing an objection. A: Jedenfalls sind wir zu dem Schluss gekommen, dass das so schon richtig war. B: Naja, naja! Also, ich denke ... (A: Anyway, we came to the conclusion that it was the right thing to do. B: Wait a minute, actually, I think ...) The "naja" signals disagreement which is explained in the following utterance. The disagreement does not always have to be further explained, though that might leave a communicative gap which the other participant(s) will want to close. A: Mamas Spätzle sind einfach die besten. B: Naja. A: Wie meinst du das? (A: Mom's spaetzle still are the best. B: Meh. A: What do you mean?) Sorry for the rough translations, my English is probably not good enough to convey the exact same meaning. All in all, it's a highly contextual kind of word which predominates in oral communication and thus is difficult to pin point, especially if you don't know how it is pronounced. Still, it's an everday expression flowing in many conversations, so if you are actually talking to someone, it might not be that much of a problem after all.
> > What is one trying to say by simply responding “Naja!”? > > > When "simply responding *Naja*", that can be for closure of a (possibly but not necessarily unpleasant) topic. You'd lower your tone here. > > **Naja.** > > as in > > **Let's leave it like that** > > > --- It can be used to announce an objection or a further thought, too. In this case, however, the intonation is rising and it *must* follow something (objection/thought) > > **Naja!** [..] > > >
10,878,262
So i am parsing an xml file and display on screen the dates that i parse. The dates are like : Thu , 31 May 2012 20:43:54 GMT. How can i convert the date to this format : dd/mm/yy ? i dont need the time. --- Well it crashes. I tried : ``` NSString *date = [[stories objectAtIndex: storyIndex] objectForKey: @"date"]; //changing dates format NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss Z"]; NSDate *myDate = [dateFormatter dateFromString:date]; NSString *dateText = [[NSString alloc] initWithString:[dateFormatter stringFromDate:myDate]]; ``` Any ideas?
2012/06/04
[ "https://Stackoverflow.com/questions/10878262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1372498/" ]
You can use `NSDateFormatter` For example: ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss Z"]; NSDate *myDate = [dateFormatter dateFromString:yourString]; ``` See <http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns> for dateformat patterns
Alternatively for the second part You can use NSDateComponents. after: ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"EEE, d MMM YYYY HH:mm:ss Z"]; NSDate *date = [dateFormatter dateFromString:theDateString]; [dateFormatter release]; //Get NSComponents from date object.. [NSString stringWithFormat:@"%@/%@/%@",dateComponent.date,dateComponent.month,dateComponent.year]; ```
8,240,166
How to send e-mail on ASP .Net using outlook address?? I've tried this code but no luck: ``` Dim mailMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage() mailMessage.From = New System.Net.Mail.MailAddress("fromAddress") mailMessage.To.Add(New System.Net.Mail.MailAddress("toAddress")) mailMessage.Priority = Net.Mail.MailPriority.High mailMessage.Subject = "Subject" mailMessage.Body = "test" Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient("xxx.outlook.com", portNumber) smtpClient.Send(mailMessage) //--> got error here ``` But while I'm execute the code, it got this error message: ``` The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated ``` I've tried to add a line of code: **smtpClient.Credentials = New System.Net.NetworkCredential(username, password)** But still can't send the e-mail. Anyone can help?
2011/11/23
[ "https://Stackoverflow.com/questions/8240166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/897733/" ]
* Try `smtpClient.UseDefaultCredentials = false;` before you set new Credentials * Try to set `smtpClient.EnableSsl` to true / false depending on your environment
I'm guessing you are using Exchange 2007 or later as backend? Anyway, your mail server does not allow you to send mails anonymously. You'll either need to supply a username/password in your code or allow unauthenticated relaying from your webserver. Talk to your IT guys what they prefer.
7,787,736
I've got a string of: ``` test1.doc,application/msword,/tmp/phpDcvNQ5,0,23552 ``` I want the first part before the comma. How do I get the first part 'test1.doc' on it's own without the rest of the string? The string came from an array I imploded: ``` $uploadFlag=implode( ',', $uploadFlag ); echo $uploadFlag; ``` If it's easier to extract just the first value off the array on it's own that would also do the job. I don't think the array has any keys. Thanks in advance.
2011/10/16
[ "https://Stackoverflow.com/questions/7787736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318972/" ]
Use this code: ``` $part = substr($uploadFlag , 0, strpos($uploadFlag , ',')); ```
`echo array_shift(array_slice($uploadFlag, 0, 1));` will output the first element of your array beit an associative or numbered array.
11,118,106
I've written a simple UDP server using Netty. The server listens on one port on a certain interface. ``` ChannelFactory factory = new NioDatagramChannelFactory( Executors.newCachedThreadPool()); ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(factory); bootstrap.getPipeline().addLast("MyHandler", new TestHandler()); bootstrap.bind(new InetSocketAddress(InetAddress.getByName("192.168.1.100"), 8080)); ``` I use a client that sends a lot of UDP datagrams to the server. When I profile my app with VisualVM, I see that there are only one thread (named New I/O worker #1) that processes the incoming messages. Is it as expected? If yes, how a single thread can handle a big amount of incoming messages? I've already written an application with Spring integration that listens on a port for UDP datagrams (using a UDP inbound channel adapter), and there is one thread that listens on the port but this thread passes the incoming messages for processing to other threads of a pool. Thanks
2012/06/20
[ "https://Stackoverflow.com/questions/11118106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1002972/" ]
Keep your message property files outside the classpath(WEB-INF/classes) and define the bean as below ``` <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/messages"/> <property name="cacheSeconds" value="1"/> ``` As per the doc ReloadableResourceBundleMessageSource provides you benefit of changing the messages on the fly which spring fetches through the cachSeconds. This class differs from ResourceBundleMessageSource only in specifying the resource location.
Though to many this sounds foolish, but the mistake my code had that we had written our own MessageSource. Which was calling Spring's MessageSource. But in the code it was like (MessageSource(MessageSource)). Hence we were doing look up over look up. Removed the extra call, and its working now.
6,530
I teach a computer science course and I like to share sample solutions to assignments after the assignment is due. I think it helps students learn to see a solution sheet with sample solutions and notes on common mistakes, immediately after the assignment is due. However, I face all too much cheating: some students upload these solutions to websites like Course Hero, and then when I reuse those problems in a future semester, now it's all too easy and tempting for other students to search and find those solutions and copy from them. I would prefer to avoid that situation. Are there any technical solutions that would allow me to share solutions with students, but in a way that makes it more difficult for them to share the solutions with others? Right now I share solutions as a PDF. Unfortunately it's very easy to download that PDF and then upload it to a site like CourseHero. Is there some better way to allow students to view solutions, while making it harder for students to upload them elsewhere? I know I'm not going to make it impossible -- if nothing else, students can take a sequence of screenshots -- but if I make it tedious enough, then I suspect that would help. I suspect many of the students who upload solutions are not doing it to be malicious, but because of dark patterns at sites like CourseHero that pressure them to upload something, so if I can make it more onerous to upload solutions, they might upload something else instead. Does anyone know of any technology that might meet this need? --- I'm not interested in answers that tell me to never reuse problems in a future semester. I ask for your trust that I am aware of the pedagogical tradeoffs and have valid reasons to do so. I am willing to elaborate if you feel you need to hear that, but I suspect it is a tangent.
2020/09/10
[ "https://cseducators.stackexchange.com/questions/6530", "https://cseducators.stackexchange.com", "https://cseducators.stackexchange.com/users/1106/" ]
> > I'm not interested in answers that tell me to never reuse problems in a future semester. > > > Well in that case the answer is simple: you can't stop people from sharing these example solutions. Obfuscation or any kind of self destructing documents are trivially circumvented by just taking a screenshot. If you could block taking screenshots in the OS you couldn't block the user from running it in a VM and screenshotting that. If you'd detect and block VMs they could take a picture with a phone. If you'd only show them in a protected environment and forbid phones they could just write things down manually. This is a race to the bottom you could never win.
First, the obvious disclaimer: it is not possible to completely avoid that they share your solutions. You need to provide *something*\* to the students, and that something they will be able to share. Second, try to produce a bit of variation between your assignments. For example, I may resolve a problem with a given file, and then change the order of the columns in the assignment file, just to force the students to do a little more than copying the provided recipe. The needed change is trivial, yet every year some student fail to do that. ☹ In some cases you may be able to create an assignment template, from which you can then easily create multiple variations (different numbers, names, even the order of the sentences might allow some tweaking...). Third, watch the resources hat your students may be using, and try to avoid them the temptation. You may set search alerts for full phrases from your solutions, be aware of Stack Overflow questions similar to your assignment whose answers may be tempting to copy. If you have published on the website for the subject a set of solved assignments from past years, and you hand out a lab exam using one of them, disable the resource during the exam. Fourth, detection. You may want to keep a local copy of the assignments handed out past years by other students (assuming this is allowed) so that you could find the original if someone submits the same solution as a previous year student [different than themselves]. You may want to tag your pdf with some hidden text, use weird variable names unlikely they would come up with or even intentionally include minor spelling mistakes that act as a brown M&M when you review it. You may distribute solutions in such way that each student receives a different document. That could be for yourself to know the submitter, such as an entry on document metadata or steganographically tagging the solutions. Or it may be a document clearly watermarked with the student personal details, as that would discourage them to share it (they could be removed, but that requires more effort than simply uploading the file you gave them). Fifth, make sure to make clear what can and cannot be done. Even if it's already buried on the institution honor code, it doesn't harm to include a redundant note on your own Syllabus saying that copying without attribution is cause on its own for failing the whole subject (not just that exam). On the other hand, I'd recommend to also list what *can* be done. While some people with no regards for the others work, other students would completely avoid acceptable resources afraid of this rule. Finally, for a different type of course, pdf marked as not-copyable and pages as images may be appropriate. However, in Computer Science you often have problems where the students *should* copy the code, compile and run the professor solution, compare its output with the one of its own solution, etc. I'd dare most students won't do that, albeit that would greatly help them acquire the concepts being taught.
2,440
I like to have at least one side project going at all times and often get bored with one and would like to play with another. Sometimes I find myself (as now) unable to come up with an inspiring, quick side-project. As I was thinking about it I thought it might be nice to have a community record of projects that people have thought up and thought about working on but never had the time to do. I don't really expect that anyone will look at this list and want to do these things exactly, but I *do* think it's likely that this would serve as good inspiration. Also I can only imagine that it'll be cool to see what the people here think up to do.
2019/02/25
[ "https://mathematica.meta.stackexchange.com/questions/2440", "https://mathematica.meta.stackexchange.com", "https://mathematica.meta.stackexchange.com/users/38205/" ]
Core Data Structures Package(s) =============================== Background ---------- Mathematica is basically a data-structure free zone. This sucks. Using data structures efficiently makes code cleaner, faster, easier to maintain, and quicker to develop. They're great. Idea ---- It'd be great if there were a package with some core data-structures built out and supported, either via `LibraryLink` libraries or via high-level Mathematica coding, like I do for [some of my packages](https://github.com/b3m2a1/mathematica-ChemTools/tree/master/Packages/DataStructures). Ever since I moved to not using a bunch of `List` and `Association` args I was able to rapidly develop a bunch of new code off the data-structures I wrote because I didn't have to think about the nastiness of dealing with free-floating lists and ensuring good structure/behavior. It'd be fantastic to have lots of these that people could just drop into a package as a dependency. Implementation Thoughts ----------------------- I have this [`InterfaceObjects` paclet](https://github.com/b3m2a1/InterfaceObjects) that makes it easy to create an object in the mold of like `SparseArray` and friends. They're immutable, `Association`-based creatures that are designed to not memory-leak, cause memory-bloat when reused, or to have unexpected unpacking or things like that. The `InterfaceObjects` package can be dropped into a BTools-style package as a dependency (I do this already for some of my stuff) and makes it pretty easy to rapidly make new objects as it handles much of the nastiness of type-checking, property management, methods, etc. I got at least four robust, highly-useful objects out of it in about one day of coding and I use them all over my packages. I'm picturing this providing the basic object structure and then methods/properties being bolted onto this. In the cases where a `LibraryLink` library may be used, this would basically mean the constructor to the `InterfaceObject` creates a `LibraryLink` object and allows the `InterfaceObject` to hold this and provide methods on top of that. Where that's not possible, methods on the internal stored data (like a `PackedArray`) can be used to allow for methods and manipulation to easily be implemented in an efficient, modular way.
IDE Stylesheet and Package ========================== Background ---------- The Mathematica FE could provide a nice lightweight FE for editing small/medium size projects. Idea ---- By creating a `"ProjectManager`"` package with all the necessary project-management functions and a nice stylesheet for hooking into this we could create a little IDE inside Mathematica by providing a tree-view to the .wl and .m files inside a folder. This little IDE could support plugins and extensions so that people can easily build off of it Implementation Thoughts ----------------------- The `"ProjectManager"` package could hook into the project-management functions I already package up into my BTools package. All it would really need would be a `Stylesheet` that provides access to these functions via a `DockedCell` and a nice `ProjectObject` that exposes project details so that people can write extensions easily off of these projects. The .m and .wl files can be loaded via `NotebookOpen[..., Visible->False]` and dumped into a main notebook pane. Tabbing can be done by simply keeping track of the current files open and putting these as little tab names under the main `DockedCell` pane. Saving can just dispatch to either `NotebookSave` for the regular .nb files or to a `ExportPacket[..., "SaveRename"]` for .m and .wl files. Custom stylesheets might be a bit harder to support... but for simple IDE work we can just ignore that or save the other `Notebook` options when loading a tab and just export the notebook content. Or we can figure out a way to make this basically a `DockedCell`-only package where we don't even need a custom `Stylesheet`
63,648
I have around 20 commands and I have to send all of this to Unix shell and copy the result, but I don't know how to do it. I am not sure about what shell I have, because it is a small program connected to Mobile Network Managment, and with this small program we have access to send commands by line and recive the results by scream, for that reason I cannot use scripts for sending the commmands. **Command 1** - Connect with a server. Wait until command 1 finish **Command 2**- Update all the information from server 1 finish Wait. **Command 3**. Get some parameter. ... and more such commands. I **tried** with `cmd1 | cmd2 | cmd3` **and** `cmd1 & cmd2 & cmd3` and `cmd1;cmd2` The problem is with `cmd1` its connected to a RNC(Network element) and takes aroud 15 seconds, after that `cmd2` has sense. but just work for the first cmd. Any clue, how to run this?
2013/02/04
[ "https://unix.stackexchange.com/questions/63648", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/31743/" ]
You may want to look into `sleep`, if your environment allows it. The complete sequence would then be something like `cmd1 && sleep 10s && cmd2`. Here is the relevant [man page for sleep](http://linux.die.net/man/1/sleep).
Just use a script, a file containing the commands to run one after the other, like: ``` #!/bin/sh command-01 command-02 ... command-20 ``` The first line (shebang) tells to run the following commands using `/bin/sh`, make the file executable (`chmod u+x your-little-script`) then you can run it by `./my-little-script`. This way you won't leave some step out ;-) Read the manual for the shell, it provides a full programming language. Check out `bash(1)` if that is what is available, or else the Korn shell `ksh(1)`. They offer lots of useful features for controlling the flow of control in scripts (or interactively, for that matter).
47,211,842
I tried to do that with `replace($val, 'amp;', '')`, but seems like `&amp;` is atomic entity to the parser. Any other ideas? I need it to get rid of double escaping, so I have constructions like `&amp;#8112;` in input file. UPD: Also one important notice: I have to make this substitution only inside of specific tags, not inside of every tag.
2017/11/09
[ "https://Stackoverflow.com/questions/47211842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2693851/" ]
If you serialize there is always (if supported) the disable-output-escaping hack, see <http://xsltransform.hikmatu.com/nbUY4kh> which transforms ``` <root> <foo>a &amp; b</foo> <bar>a &amp; b</bar> </root> ``` selectively into ``` <root> <foo>a & b</foo> <bar>a &amp; b</bar> </root> ``` by using `<xsl:value-of select="." disable-output-escaping="yes"/>` in the template matching `foo/text()`: ``` <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="foo/text()"> <xsl:value-of select="." disable-output-escaping="yes"/> </xsl:template> </xsl:transform> ``` To achieve the same selective replacement with a character map you could replace the ampersand in `foo` `text()` children (or descendants if necessary) with a character not used elsewhere in your document and then use the map to map it to an unescaped ampersand: ``` <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:output use-character-maps="doe"/> <xsl:character-map name="doe"> <xsl:output-character character="«" string="&amp;"/> </xsl:character-map> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="foo/text()"> <xsl:value-of select="replace(., '&amp;', '«')"/> </xsl:template> </xsl:transform> ``` That way ``` <root> <foo>a &amp; b</foo> <bar>a &amp; b</bar> </root> ``` is also transformed to ``` <root> <foo>a & b</foo> <bar>a &amp; b</bar> </root> ``` see <http://xsltransform.hikmatu.com/pPgCcoj> for a sample.
If your XML contains &#8112; and you believe that this is a double-escaped representation of the character with codepoint 8112, then you can convert it to this character using the XPath expression ``` codepoints-to-string(xs:integer(replace($input, '&#([0-9]+);', $1))) ``` remembering that if you write this XPath expression in XSLT, then the `&` must be written as `&amp;`.
18,621,155
I'm having the worst time rendering a .json.erb file from my controller while being able to test it with RSpec. I have api\_docs/index.json.erb and the following controller: ``` class ApiDocsController < ApplicationController respond_to :json def index render file: 'api_docs/index.json.erb', content_type: 'application/json' end end ``` The explicit `render file` line seems unnecessary, but if I don't do that or `render template: 'api_docs/index.json.erb'`, then I get an error about "Missing template api\_docs/index". Likewise if I do have to pass the file name, it sucks even more that I have to give the exact directory--Rails should know that my ApiDocsController templates live in the api\_docs directory. If I have `render file` or `render template`, then I can visit the page and get the JSON contents of my index.json.erb file, as expected. However, this RSpec test fails: ``` let(:get_index) { ->{ get :index } } ... describe 'JSON response' do subject { get_index.call JSON.parse(response.body) } it 'includes the API version' do subject['apiVersion'].should_not be_nil end end ``` It fails on the `JSON.parse(response.body)` line and if I `raise response.body`, it's an empty string. If I do `render json: {'apiVersion' => '1.0'}.to_json` in the controller, then the test passes just fine. So, how can I always render the JSON template when I go to /api\_docs (without having to put `.json` at the end of the URL), and in a way that works both in the browser and in my RSpec test? And can I render the template without having to have some long `render` call in which I pass the full path of the view?
2013/09/04
[ "https://Stackoverflow.com/questions/18621155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38743/" ]
`parent()` in jQuery will parse only one level up the DOM, you should use `.parents()/.closest()`. This will fix your issue. **NOTE:** `.live()` is turned into `.on()` in latest jQuery versions. Better to use `.on()/.click()`
in jQuery, [.parent()](http://api.jquery.com/parent/) only goes up the DOM once. What you should be using it [.parents()](http://api.jquery.com/parents/) to look up the DOM until it finds `table`
44,809,013
I'm editing the `app.yaml` file so that all files within a particular folder are not uploaded to GAE. Following the instructions found [here](https://cloud.google.com/appengine/docs/standard/python/config/appref), I've tried the following: ``` skip_files: - /tester/^(.*/)?\.^(.*/)?$ skip_files: - /tester/.* skip_files: - /tester/^(.*/)?#.*#$ ``` None of the above seems to work, as new files added to the folder `tester` keep being pushed to GAE.
2017/06/28
[ "https://Stackoverflow.com/questions/44809013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1068250/" ]
If your directory is nested inside the project: ``` skip_files: - ^(.*/)?.*/some_dir/.* ```
Seems that this works: ``` skip_files: - ^tester/*.* ``` Based on the results I got, it seems that: * the initial `/` should not be included. * the caret (`^`) is needed to tell the system where the string to interpreted begins; * to include any file, the notation `*.*` seems to work. Any comment is welcome!
35,969
My understanding of French is extremely limited so I am not sure who is correct in this situation. A Twitter user contends that the French writer Maurice Druon once said "Tradition [is nothing but a](https://twitter.com/littlestjames/status/275360511162462209) progress which has succeeded". As best I can find, Druon's original [quote in French](http://www.linternaute.com/citation/25465/une-tradition--ce-n-est-jamais-qu-un-progres-qui-a-reussi---maurice-druon/) is "Une tradition, ce n'est jamais qu'un progrès qui a réussi". So far my basic efforts indicate the Druon quote actually means the opposite of what the person on Twitter contends, yet at the same time I found [one resource indicating](https://context.reverso.net/translation/french-english/Une+tradition%2C+ce+n%27est+jamais+qu%27un+progr%C3%A8s+qui+a+r%C3%A9ussi.) that sometimes "ce n'est jamais" means "is always". So in the context of this specific quote, is tradition always, or never, a progress which has succeeded? If it does actually mean what the Twitter user contends, what contextual clues would guide me in this instance?
2019/04/28
[ "https://french.stackexchange.com/questions/35969", "https://french.stackexchange.com", "https://french.stackexchange.com/users/20562/" ]
Generally speaking, [French doesn't do double negation](https://french.stackexchange.com/questions/27255/what-is-the-meaning-of-ne-serait-ce-que-in-a-negative-sentence/28130#28130). A sentence is either negative or not. But it can be difficult to figure out, because the words involved can have multiple meanings, and because the language is changing. In formal or literary French, there is [only one word that conveys negation: *ne*](https://french.stackexchange.com/questions/11083/personne-ne-va-rien-faire-double-n%C3%A9gation/11088#11088) (which is abbreviated to *n'* before a vowel sound). Other words such as *pas*, *jamais*, *rien*, *personne*, etc. [are not negative in themselves](https://french.stackexchange.com/questions/20096/should-the-2nd-negative-particle-be-defined-positively-only/20097#20097), they only characterize what is being negated: a yes/no statement, a time period, a thing, a person, etc. > > Je ne comprends rien.   (*I do not understand anything.*) > > Je ne comprends jamais rien.   (*I never understand anything.* The sentence is negative because it contains *ne*, and the two words *jamais* and *rien* cause the negation to apply to both time and object.) > > Je ne comprends plus jamais rien.   (*I never understand anything anymore.*) > > > One complication is that [when *ne* is paired with *que*](https://french.stackexchange.com/questions/22974/je-ne-comprends-que-lorsque-is-ne-the-ne-expl%C3%A9tif-here), it takes a somewhat different meaning: it means “only”. In French, we see “only” as the negation of everything else, but most languages don't regard this as a negation. > > Je ne vois que tes yeux.   (*I only see your eyes.* In French, we think of it as “I do not see things other than your eyes”. There is a similar phrasing in English, but it's a lot less common than in French: “I see nothing but your eyes”.) > > > Adding a negation-characterization word doesn't flip the negation around. > > Je ne vois jamais que tes yeux.   (*I only ever see your eyes.*) > > > It can sometimes be hard to figure out whether a sentence contains the *ne … que* negation-like construction, or just happens to have a negative clause followed by another clause introduced by *que*. > > Je ne comprends rien à ce que tu écris.   (*I understand nothing of what you are writing.*) > > Je ne comprends rien que ce que tu écris.   (*I understand nothing but what you are writing.*) > > > Now that we have the necessary background, let's look at Druon's sentence. > > Une tradition, ce n'est jamais qu'un progrès qui a réussi. > > > The verb *est* needs a complement (an *attribut du sujet*). The only possible way to parse the sentence is that this complement is the clause “*un progrès qui a réussi*”, and *ne … que* means “only”. As I explained above, *jamais* is not negative in itself, it only characterizes what is being negated. *Jamais* is almost always about time, but in this case it isn't really about time. The expression “*X n'est jamais que …*” is an idiom that means roughly “X is only …, you shouldn't look for anything more complicated”. A more idiomatic translation is “X is nothing but …”. So the translation you found is correct, and it's mostly idiomatic except for “a progress” which doesn't really work in English (“progress” is not countable). --- Just because this wasn't complicated enough, what I wrote above is not always true. The particle *ne* usually indicates negation, but [sometimes](https://french.stackexchange.com/questions/135/jai-bien-peur-que-tu-naies-raison-faut-il-mettre-le-mot-ne) it can mean … [nothing](https://fr.wikipedia.org/wiki/Expl%C3%A9tif#La_semi-n%C3%A9gation_%C2%AB_ne_%C2%BB). The “negation flavor” words *jamais*, *rien*, etc. *can* be negative on their own in some cases, for example in a short answer that doesn't contain a verb. > > Est-ce que tu fumes ? — Jamais.   (*Do you smoke? — Never.*) > > > Most importantly, in informal French, *ne* is omitted from negative sentences. So in informal French, the words *pas*, *plus*, *jamais*, *rien*, *personne*, etc. are really negative particles, and so is *que* when it means “only”. > > Je comprends jamais rien. [informal]   (*I never understand anything.*) > > J'ai plus qu'une chose à dire. [informal]   (*I only have one thing left to say.* By the way, in this sentence, [the final S in *plus* is silent](https://french.stackexchange.com/questions/268/when-does-one-pronounce-the-s-in-plus/275#275). To make things really confusing, you can say this sentence with the S in *plus* sounded, and then it means something completely different: “I have more than one thing to say”. The silent-S interpretation is the one that comes to mind when reading the sentence out of context, however.) > > >
This use of "jamais" appears to be neither "always" nor "never" but to be equivalent to "seulement" (only). I infer that from a translation in a Robert-Collins dictionary: "Ce n'est jamais qu'un enfant" (He is only a child). So, "nothing but" (rien que) is a good translation. The form is generally "**SUBJECT\_ne\_être\_que\_COMPLÉMENT**". * La pomme n'est jamais qu'un fruit commun. * Ce n'est jamais que la pluie qui crée des inondations. * Un arbre n'est jamais qu'une herbe qui s'est endurcie et qui a grandi.
74,088,508
Ok, so i got in to this problem running query in my app based on: * Remix app framework * Postgres as a db * Prisma as ORM I have simple loader function, which basically loads post types from my db. So, after i hit browser reload button for a couple of times i get this error > > Error querying the database: db error: FATAL: sorry, too many clients already > > > The only one way is get rid of error is restart the app.
2022/10/16
[ "https://Stackoverflow.com/questions/74088508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11653338/" ]
In development Remix purges the require cache before each request. This is to support `LiveReload` You need to store the Prisma client on the global object to survive the purge. You’ll see an example of this on the Jokes tutorial. <https://github.com/remix-run/examples/blob/main/jokes/app/utils/db.server.ts>
The solution is quite simple, we should init our prisma client before the render starts. To do this, [follow the remix guideline](https://remix.run/docs/en/v1/tutorials/jokes#connect-to-the-database). This way it will reuse object after server update. --- Second thing you need to do is to increase your connection limit, by passing number to connect url in this way: postgresql://postgres:@localhost:5432/db?connection\_limit=13 The number is: > > (Quantity of cores on your computer \* 2) + 1 > > > To get more info about optimizing prisma connection pull, [follow](https://www.prisma.io/docs/guides/performance-and-optimization/connection-management).
15,457,914
I want to store large numbers in a data structure, to do so, I want to use hash function, so that insertion, deletion or searching could be fast. But I am unable to decide which hash function should i use ? And in general, I want to know how to decide a hash function is good for any particular problem ? **EDIT :** I think a made people confused with using term "random". Here with random, what I mean is, I dont have any particular range of numbers from where I have to choose[any 32 bit integer], but I have the total no which will be given to store in the data structure like some 5000 numbers. So suggest me best hash function for this scenario and why you conclude it to be best ?
2013/03/17
[ "https://Stackoverflow.com/questions/15457914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769260/" ]
If the numbers are uniformly random, just use a hash function which selects the low bits. ``` unsigned hash_number(long long x) { return (unsigned) x; } ```
Your question doesn't make sense to me. Using a hashing algorithm to store some random numbers is overkill. If there is something more to the problem, the choice of data structure will depend on what this something more is (which you don't say). If these numbers really are random or pseudorandom then all you need is a stack or circular buffer - the capability to add (push) a new random number into the data structure and the capability to remove (pop) an existing random number from the structure. If you want to retrieve them in order, use a circular buffer. A hashing function is worse in every respect than a simple stack (or circular buffer) for holding a list of random numbers - it is more complex, runs slower, and uses more memory. Most languages/environments provide hash functions which can be used (or are provided as) "dictionary" classes, and these come with guidance as to efficiency. Generally, you can make dictionary classes faster by allocating more memory - they slow down when hash keys collide. So the "density" of actual numbers amongst all possible numbers matters. So if you had to hold 100 such numbers, you could use a hash function which looked only at the last 12 bits. This gives 2^12 = 4096 possible hashes, so collisions will only occur 100/2048 of the time, less than 5%. On the other hand, you are using over 20 times as much memory as you should. (This function is the same as taking the modulus of the number to base 2^12, and is similar to what Epp suggested.) Writing a storage class based on a hash function which properly handles hash collisions (as it must), gracefully handles duplicated data, won't freak if you chuck it bad data (like every number the same), and is efficient, is not a trivial task. On the other hand, implementing a stack or circular buffer is extremely simple, very efficient, and has entirely predictable behaviour. Are you sure you aren't making this more complicated than it needs to be?
43,286,178
I'm having trouble understanding how the object\_hook functionality from json.loads() actually works. I found a similar question [object\_hook does not address the full json](https://stackoverflow.com/questions/38234765/object-hook-does-not-address-the-full-json) here, but I've tried to follow what I understand from it, and it's still not working for me. I already gathered that the object\_hook function is called recursively in some way, but I'm failing to understand how to use it to construct complex object hierarchies from the json string. Consider the following json string, classes, and object\_hook function: ``` import json from pprint import pprint jstr = '{"person":{ "name": "John Doe", "age": "46", \ "address": {"street": "4 Yawkey Way", "city": "Boston", "state": "MA"} } }' class Address: def __init__(self, street=None, city=None, state=None): self.street = street self.city = city self.state = state class Person: def __init__(self, name=None, age=None, address=None): self.name = name self.age = int(age) self.address = Address(**address) def as_person(jdict): if u'person' in jdict: print('person found') person = jdict[u'person'] return Person(name=person[u'name'], age=person[u'age'], address=person[u'address']) else: return('person not found') return jdict ``` (I define classes with keyword args to provide defaults so that the json need not contain all elements, and I can still ensure that the attributes are present in the class instance. I will also eventually associate methods with the classes, but want to populate the instances from json data.) If I run: ``` >>> p = as_person(json.loads(jstr)) ``` I get what I expect, ie: ``` person found ``` and p becomes a Person object, ie: ``` >>> pprint(p.__dict__) {'address': <__main__.Address instance at 0x0615F3C8>, 'age': 46, 'name': u'John Doe'} >>> pprint(p.address.__dict__) {'city': u'Boston', 'state': u'MA', 'street': u'4 Yawkey Way'} ``` However, if instead, I try to use: ``` >>> p = json.loads(jstr, object_hook=as_person) ``` I get: ``` person found Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "C:\Program Files (x86)\Python27\lib\json\__init__.py", line 339, in loads return cls(encoding=encoding, **kw).decode(s) File "C:\Program Files (x86)\Python27\lib\json\decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Program Files (x86)\Python27\lib\json\decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) File "<interactive input>", line 5, in as_person TypeError: string indices must be integers, not unicode ``` I have no idea why this would happen, and suspect there is some subtlety around how the object\_hook mechanism works that I'm missing. In an attempt to incorporate the notion from the aforementioned question, which was that the object\_hook evaluates each nested dictionary from the bottom up (and replaces it in the traverse?) I also tried: ``` def as_person2(jdict): if u'person' in jdict: print('person found') person = jdict[u'person'] return Person2(name=person[u'name'], age=person[u'age'], address=person[u'address']) elif u'address' in jdict: print('address found') return Address(jdict[u'address']) else: return('person not found') return jdict >>> json.loads(jstr, object_hook=as_person2) address found person found Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "C:\Program Files (x86)\Python27\lib\json\__init__.py", line 339, in loads return cls(encoding=encoding, **kw).decode(s) File "C:\Program Files (x86)\Python27\lib\json\decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Program Files (x86)\Python27\lib\json\decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) File "<interactive input>", line 5, in as_person2 AttributeError: Address instance has no attribute '__getitem__' ``` So, clearly, the proper form of the object\_hook function is escaping me. Can someone explain in detail how the object\_hook mechanism works, and how the resulting object tree is supposed to be recursively constructed from the bottom up, why my code doesn't work as expected, and either fix my example or provide one that uses an object\_hook function to build a complex class, given that you only get the one object\_hook function?
2017/04/07
[ "https://Stackoverflow.com/questions/43286178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7834317/" ]
Through experimentation, I have answered my own question; this may not be the best solution, and I welcome further analysis or a better way, but this sheds light on how the object\_hook process works, so it may be instructive to others facing the same issues. The key observation was that, at every level of the json tree walk, the object\_hook mechanism expects you to return a *dictionary*, so if you want to change the subdictionaries into class instances, you have to replace the current object\_hook function invocation's input dictionary *values* with objects, and not just return the object instances. The solution below allows a bottom-up means of building up the object hierarchy. I've inserted print statements to show how the loads object\_hook is called on on subsections of the json string as it's processed, which I found quite illuminating, and helpful to me in build a working function. ``` import json from pprint import pprint jstr = '{"person":{ "name": "John Doe", "age": "46", \ "address": {"street": "4 Yawkey Way", "city": "Boston", "state": "MA"} } }' class Address: def __init__(self, street=None, city=None, state=None): self.street=street self.city=city self.state = state def __repr__(self): return('Address(street={self.street!r}, city={self.city!r},' 'state={self.state!r})'.format(self=self)) class Person: def __init__(self, name=None, age=None, address=None): self.name = name self.age = int(age) self.address=address def __repr__(self): return('Person(name={self.name!r}, age={self.age!r},\n' ' address={self.address!r})'.format(self=self)) def as_person4(jdict): if 'person' in jdict: print('person in jdict; (before substitution):') pprint(jdict) jdict['person'] = Person(**jdict['person']) print('after substitution:') pprint(jdict) print return jdict elif 'address' in jdict: print('address in jdict; (before substitution):'), pprint(jdict) jdict['address'] = Address(**jdict['address']) print('after substitution:') pprint(jdict) print return jdict else: print('jdict:') pprint(jdict) print return jdict >>> p =json.loads(jstr, object_hook=as_person4) jdict: {u'city': u'Boston', u'state': u'MA', u'street': u'4 Yawkey Way'} address in jdict; (before substitution): {u'address': {u'city': u'Boston', u'state': u'MA', u'street': u'4 Yawkey Way'}, u'age': u'46', u'name': u'John Doe'} after substitution: {u'address': Address(street=u'4 Yawkey Way', city=u'Boston', state=u'MA'), u'age': u'46', u'name': u'John Doe'} person in jdict; (before substitution): {u'person': {u'address': Address(street=u'4 Yawkey Way', city=u'Boston', state=u'MA'), u'age': u'46', u'name': u'John Doe'}} after substitution: {u'person': Person(name=u'John Doe', age=46, address=Address(street=u'4 Yawkey Way', city=u'Boston', state=u'MA'))} >>> p {u'person': Person(name=u'John Doe', age=46, address=Address(street=u'4 Yawkey Way', city=u'Boston', state=u'MA'))} >>> ``` Note that what is returned is still a dictionary, where the key is 'person', and the value is the Person object (rather than just a Person object), but this solution does provide an extensible bottom-up object construction method.
I agree it's non-intuitive, but you can simply ignore the dictionary passed when it's not the kind of object you're interested in. Which means that this would probably be the simplest way: (As you can also see, you don't need all those `u` string prefixes, either.) ``` import json jstr = '{"person": { "name": "John Doe", "age": "46", \ "address": {"street": "4 Yawkey Way", "city": "Boston", "state": "MA"} } }' class Address: def __init__(self, street=None, city=None, state=None): self.street = street self.city = city self.state = state def __repr__(self): # optional - added so print displays something useful return('Address(street={self.street!r}, city={self.city!r}, ' 'state={self.state!r})'.format(self=self)) class Person: def __init__(self, name=None, age=None, address=None): self.name = name self.age = int(age) self.address = address def __repr__(self): # optional - added so print displays something useful return('Person(name={self.name!r}, age={self.age!r},\n' ' address={self.address!r})'.format(self=self)) def as_person3(jdict): if 'person' not in jdict: return jdict else: person = jdict['person'] address = Address(**person['address']) return Person(name=person['name'], age=person['age'], address=address) p = json.loads(jstr, object_hook=as_person3) print(p) ``` Output: ```none Person(name=u'John Doe', age=46, address=Address(street=u'4 Yawkey Way', city=u'Boston', state=u'MA')) ```
5,295,442
Hi I am trying to implement conditional compilation in python similar to [this in C](http://ideone.com/ttndK),I have seen [this thread](https://stackoverflow.com/questions/560040/conditional-compilation-in-python) and [this thread](https://stackoverflow.com/questions/3496592/conditional-import-of-modules-in-python). But [this](http://ideone.com/u7BO8) is not working. I am relatively new to python,how can we fix this ?
2011/03/14
[ "https://Stackoverflow.com/questions/5295442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324553/" ]
Looks like you are trying to use this to submit solutions to an online judge. For gcc, the judge machine supplies a paramater `-D ONLINE_JUDGE`. This has the same effect as having the following in your code: ``` #define ONLINE_JUDGE ``` Python does not have a preprocessor. So there is no way of defining a macro (in the same sense as in C) either within your code or from the command line when you invoke the interpreter. So, I think it is unlikely that the online judge provides a similar option for Python. But it might provide something as a command line argument that you might be able to use via `sys.argv[1:]`. Check the command used to invoke Python (must be mentioned somewhere on their website) at the online judge.
You need to define the ONLINE\_JUDGE variable - this is an "if", not really an "ifdef". ``` ONLINE_JUDGE = 0 if ONLINE_JUDGE: import math ```
20,531,990
How can I subtract a Series from a DataFrame, while keeping the DataFrame struct intact? ``` df = pd.DataFrame(np.zeros((5,3))) s = pd.Series(np.ones(5)) df - s 0 1 2 3 4 0 -1 -1 -1 NaN NaN 1 -1 -1 -1 NaN NaN 2 -1 -1 -1 NaN NaN 3 -1 -1 -1 NaN NaN 4 -1 -1 -1 NaN NaN ``` What I would like to have is the equivalent of subtracting a scalar from the DataFrame ``` df - 1 0 1 2 0 -1 -1 -1 1 -1 -1 -1 2 -1 -1 -1 3 -1 -1 -1 4 -1 -1 -1 ```
2013/12/11
[ "https://Stackoverflow.com/questions/20531990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3075686/" ]
Maybe: ``` >>> df = pd.DataFrame(np.zeros((5,3))) >>> s = pd.Series(np.ones(5)) >>> df.sub(s,axis=0) 0 1 2 0 -1 -1 -1 1 -1 -1 -1 2 -1 -1 -1 3 -1 -1 -1 4 -1 -1 -1 [5 rows x 3 columns] ``` or, for a more interesting example: ``` >>> s = pd.Series(np.arange(5)) >>> df.sub(s,axis=0) 0 1 2 0 0 0 0 1 -1 -1 -1 2 -2 -2 -2 3 -3 -3 -3 4 -4 -4 -4 [5 rows x 3 columns] ```
If a1 is a dataframe made of n columns and a2 is a another dataframe made by just 1 column, you can subtract a2 from **each** column of a1 using numpy ``` np.subtract(a1, a2) ``` You can achieve the same result if a2 is a Series making sure to transform to DataFrame ``` np.subtract(a1, a2.to_frame()) ``` I guess that, before computing this operation, you need to make sure the indices in the two dataframes are coherent/overlapping. As a matter of fact, the above operations will work if a1 and a2 have the same number of rows and different indices. You can try ``` a1 = pd.DataFrame([[1, 2], [3, 4]], columns=['a','b']) a2 = pd.DataFrame([[1], [2]], columns=['c']) np.subtract(a1, a2) ``` and ``` a1 = pd.DataFrame([[1, 2], [3, 4]], columns=['a','b']) a2 = pd.DataFrame([[1], [2]], columns=['c'], index=[3,4]) np.subtract(a1,a2) ``` will give you the same result. For this reason, to make sure the two DataFrames are coherent, you could preprocess using something like: ``` def align_dataframes(df1, df2): r = pd.concat([df1, df2], axis=1, join_axes=[df1.index]) return r.loc[:,df1.columns], r.loc[:,df2.columns] ```
32,257,515
I have a string like this: ``` $string = 'rgb(178, 114, 113)'; ``` and I want to extract the individual values of that ``` $red = 178; $green = 114; $blue = 113; ```
2015/08/27
[ "https://Stackoverflow.com/questions/32257515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4485533/" ]
If your string will always start with `rgb(` and end with `)`, then you can [truncate the string](http://php.net/manual/en/function.substr.php) to just `178, 114, 113` with ``` $rgb = substr($string, 4, -1); //4 is the starting index, -1 means second to last character ``` Then to [convert the list to an array](http://php.net/manual/en/function.explode.php): ``` $vals = explode(', ', $rgb); //or you could use just ',' and trim later if your string might be in the format `123,123, 123` (i.e. unknown where spaces would be) ``` At this point, `$vals[0]` is red, `$vals[1]` is green, and `$vals[2]` is blue.
Using preg\_match\_all and list, you can get the variables you want: ``` $string = "rgb(178, 114, 113)"; $matches = array(); preg_match_all('/[0-9]+/', $string, $matches); list($red,$green,$blue) = $matches[0]; ``` Please note that this doesn't validate that the original string does in fact have three integer values.
228,229
Usually I receive a PDF contract that I need to sign and send back online. I am wondering what is the easiest way to do so on computer, to avoid the hassle of print/sign/scan process?
2012/12/12
[ "https://askubuntu.com/questions/228229", "https://askubuntu.com", "https://askubuntu.com/users/19019/" ]
There are best tools available in Ubuntu for pdf editing like **PDF-Shuffler**, **pdftk**, **inkscape**. Visit this [link](https://askubuntu.com/questions/162037/how-to-edit-pdfs) for pdf editing in different scenarios.
You could try installing Oracle PDF Import Extension in Libreoffice. You can find it [here](http://extensions.services.openoffice.org/project/pdfimport).
14,541
Two related questions about bounded depth computing: 1) Suppose that you start with n bits, and to start with bit i can be 0 or 1 with some probability p(i), independently. (If it makes the problem simpler we can assume that all p(i)s are 0,1, or 1/2. ~~or even that all of them are 1/2.~~) Now you make a bounded number of computation round. In each round you apply reversible classical gates on disjoint sets of bits. (Fix your favorite set of universal classical reversible gates.) At the end you get a probability distribution on strings on n bits. Are there results on restriction of such distributions? I am looking to something analogous to Hastad switching lemme, Boppana result that the total influence is small or LMN theorem. 2) The same question as 1) but with bounded depth quantum circuits.
2012/11/29
[ "https://cstheory.stackexchange.com/questions/14541", "https://cstheory.stackexchange.com", "https://cstheory.stackexchange.com/users/712/" ]
There are some relatively recent papers by Emanuele Viola et al., which deal with the complexity of sampling distributions. They focus on restricted model of computations, like bounded depth decision trees or bounded depth circuits. Unfortunately they don't discuss reversible gates. On the contrary there is often loss in the output length. Nevertheless these papers may be a good starting point. [Bounded-Depth Circuits Cannot Sample Good Codes](http://link.springer.com/article/10.1007/s00037-012-0039-3) [The complexity of Distributions](http://epubs.siam.org/doi/abs/10.1137/100814998?journalCode=smjcat)
### Short answer. For quantum circuits, there is at least one *non*-limitation result: arbitrary bounded-depth quantum circuits are unlikely to be simulatable with small multiplicative error in the probability of the outcome, even for *polynomial*-depth classical circuits. This, of course, does not tell you what resctrictions $\mathsf{QNC^0}$ circuits will actually have; particularly if you're interested in decision problems with bounded error, rather than probability distributions. However, it does mean that an analysis in terms of decision trees, as with [Håstad’s Switching Lemma](http://www.contrib.andrew.cmu.edu/~ryanod/?p=811), is not likely to be in the offing for classical simulation of these circuits. ### Details We may consider the definition of polylog-depth quantum circuits as given by [Fenner et al. (2005)](http://arxiv.org/abs/quant-ph/0312209): > > *Definition.* $\mathsf{QNC^k}$ is the class of quantum circuit families $\{C\_n\}\_{n\geqslant0}$ for which there exists a polynomial $p$ for which each $C\_n$ contains $n$ input qubits and at most $p(n)$ fresh ancillas, uses only single-qubit gates and controlled-not gates, and has depth $O(\log^k(n))$. > > > The single-qubit gates must be from a fixed finite set, though this suffices to simulate any fixed unitary on a constant number of qubits to any fixed precision. We also allow any subset of the qubits at then end of the circuit to be used to represent the output of the circuit family (e.g. a single qubit for boolean functions). [Bremner, Jozsa, and Sheppard (2010)](http://arxiv.org/abs/1005.1407) note (see Section 4) that, using an adaptation of the gate-teleportation technique due to [Terhal and DiVincenzo (2004)](http://arxiv.org/abs/quant-ph/0205133), post-selection on some of the qubits in a $\mathsf{QNC^0}$ circuit makes it possible to decide problems in $\mathsf{PostBQP = PP}$. Using their results on simulating postselected circuits, this implies that the problem of classically sampling from the output distribution of an arbitrary $\mathsf{QNC^0}$ circuit with boolean output, with multiplicative error at most $\sqrt 2$ in the sampling probability, is in impossible with random polynomial depth circuits unless the polynomial hierarchy partially collapses (specifically $\mathsf{PH} \subseteq \Delta\_3$).
50,975,970
I need to go into a directory [named 'People'] and pull the names of folders and then construct some HTML that builds links using the contents of the directories. I take a folder named: article-number-one and display a title, link, thumbnail, and excerpt based on the folder name. Here is my code. It works except for the ordering. It is alphabetical. I want it to be by date created...newest on top: ``` <?php $files = glob("people/*"); foreach($files as $file) { echo '<div class="block"><a href="people/'.basename($file).'"><img src="people/'.basename($file).'/'.basename($file).'-thumbnail.jpg" height="180" width="320" alt="'.basename($file).'"/></a><br/><br/>'; echo '<a href="people/'.basename($file).'">'.str_replace('-', ' ', basename($file, "")).'</a><br/><div class="excerpt">'; include 'people/'.basename($file).'/'.basename($file).'-excerpt.txt'; echo '</div><hr></div>'; } ?> ``` Please help me to order the resulting HTML newest to oldest.
2018/06/21
[ "https://Stackoverflow.com/questions/50975970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9974735/" ]
You're resetting `previous_guess` to 0 every time the loop begins again, hence throwing away the actual previous guess. Instead, you want: ``` previous_guess = 0 while True: guess = .... ```
You need to initialize previous guess before while loop Otherwise it will be initialized again and again. You have to set the value of previous guess to x the computer generator and when you move on after loop you have to update the previous guess to next simply like this: 1. Add before while { previous\_guess = x } 2. Add After While { previous\_guess += x } ``` ###Guessing Game import random n = 100 x = random.randint(1,n) print("I'm thinking of a number between 1 and ", n) ##print(x) ## testing/cheating. count = 0 previous_guess = x while True: # Should update with old guess to be compared with new guess previous_guess += x guess = int(input("Guess the number, or enter number greater that %d to quit." % n)) count += 1 print(previous_guess) print("Guesses: ", count) if guess > n: print("Goodbye.") break elif count < 2 and guess != x: print("Unlucky.") previous_guess = guess ##### elif count >= 2 and guess != x: if abs(guess - x) < abs(previous_guess - x): previous_guess = guess ##### print("Getting warmer...") else: previous_guess = guess ##### print("Getting colder...") elif guess == x: print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count)) break ``` [Picture When u win](https://i.stack.imgur.com/HCt74.png) [Picture When u loose](https://i.stack.imgur.com/os89k.png)
427,903
1. Does a scratched DVD result in lost data? 2. How do I fix a scratched DVD?
2012/05/23
[ "https://superuser.com/questions/427903", "https://superuser.com", "https://superuser.com/users/84812/" ]
> > Does a scratched DVD result in lost data? > > > Not necessarily. The data is not actually stored on the surface of the disk - it's actually stored more towards the center. There is a protective layer of plastic-coating *(polycarbonate)* surrounding the data. ![DVD layers](https://i.stack.imgur.com/tGzoj.gif) --- > > How do I fix a scratched DVD? > > > If only the protective layer is scratched, it can be filled in using the CD/DVD repair kits available at electronics stores (or even Wal-mart). If the scratch is deep enough to damage the data, however, you're out of luck. *(Others have mentioned that DVDs use error-correction codes. This is true, but if the drive is saying the data is corrupt/can't be read, that already means the ECC wasn't able to recover the data, so that knowledge does not really help you)*
Scratches on the bottom (clear) portion of the disk cause data read errors by interrupting the laser beam's path to the data. The actual data may still be intact, just unreachable (think overwriting words on a page with a black marker, the words are still there but not visible.) Such scratches *may* be filled in or polished out using various products/techniques. Try googling for "CD repair". Scratches on the top (metallic) portion of the disk actually remove the data bearing layer and are not physically recoverable. If you can see light through the disk, the data is no longer there. In either case the error correction protocols noted in other answers are used to rebuild lost data, up to a point.
14,309,256
I am trying to use NanoHTTP to serve up an HTML file. However, NanoHTTP is relatively un-documented, and I am new to Android. My question is, where do I store the html file, and how specifically can I serve it up using NanoHTTP.
2013/01/13
[ "https://Stackoverflow.com/questions/14309256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1092323/" ]
A late answer but may be useful to others. Here is a simple hello Web Server, not exactly what you ask, but you can continue from here. The following program supposes you have a `www` directory in the root of the SD Card and a file `index.html` inside. Main activity `Httpd.java`: ``` package com.inforscience.web; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.util.Log; import java.io.*; import java.util.*; public class Httpd extends Activity { private WebServer server; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); server = new WebServer(); try { server.start(); } catch(IOException ioe) { Log.w("Httpd", "The server could not start."); } Log.w("Httpd", "Web server initialized."); } // DON'T FORGET to stop the server @Override public void onDestroy() { super.onDestroy(); if (server != null) server.stop(); } private class WebServer extends NanoHTTPD { public WebServer() { super(8080); } @Override public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parameters, Map<String, String> files) { String answer = ""; try { // Open file from SD Card File root = Environment.getExternalStorageDirectory(); FileReader index = new FileReader(root.getAbsolutePath() + "/www/index.html"); BufferedReader reader = new BufferedReader(index); String line = ""; while ((line = reader.readLine()) != null) { answer += line; } reader.close(); } catch(IOException ioe) { Log.w("Httpd", ioe.toString()); } return new NanoHTTPD.Response(answer); } } } ``` Obviously the `NanoHTTPD` class must be in the same package. You need to grant internet permission in `AndroidManifest.xml`. ``` <uses-permission android:name="android.permission.INTERNET" /> ``` and read external storage permission. ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> ``` **EDIT:** To access the server open you web browser with the IP of your device, e.g. `192.168.1.20:8080`. **NOTES:** * Tested in Android 2.3 * The use of port 80 is restricted to the root user(<http://www.mail-archive.com/android-developers@googlegroups.com/msg47377.html>).
Updated `WebServer` class (see rendon's reply) that works with current NanoHTTPD version: ```java private class WebServer extends NanoHTTPD { public WebServer() { super(8080); } @Override public Response serve(IHTTPSession session) { String answer = ""; try { // Open file from SD Card File root = Environment.getExternalStorageDirectory(); FileReader index = new FileReader(root.getAbsolutePath() + "/www/index.html"); BufferedReader reader = new BufferedReader(index); String line = ""; while ((line = reader.readLine()) != null) { answer += line; } reader.close(); } catch(IOException ioe) { Log.w("Httpd", ioe.toString()); } return newFixedLengthResponse(answer); } } ```
39,059,040
Im developing a library in Java using IntelliJ IDEA, also I use gradle for the project. My problem is that when I build an artifact of my project the .jar file that is built does not include any of my javadocs and the names of the method arguments in interfaces are also lost. How can I generate a .jar that also includes javadoc in it using IntelliJ IDEA in a Gradle project?
2016/08/20
[ "https://Stackoverflow.com/questions/39059040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5646324/" ]
``` task sourcesJar(type: Jar, dependsOn: classes) { classifier = 'sources' from sourceSets.main.allSource } task javadocJar(type: Jar, dependsOn: javadoc) { classifier = 'javadoc' from javadoc.destinationDir } artifacts { archives sourcesJar archives javadocJar } ```
It is intended behavior. But there is a default 'javadoc' task which generates javadoc into 'build/docs' directory. So you can do this like: ``` task makeJavadoc (type :Jar, dependsOn: javadoc){ from docsDir classifier='docs' description='Creates a Javadoc Jar' } ``` The resulting javadoc has to be attached manually.
58,531
Sorry if this question comes across a little basic. I am looking to use LASSO variable selection for a multiple linear regression model in R. I have 15 predictors, one of which is categorical(will that cause a problem?). After setting my $x$ and $y$ I use the following commands: ```r model = lars(x, y) coef(model) ``` My problem is when I use `coef(model)`. This returns a matrix with 15 rows, with one extra predictor added each time. However there is no suggestion as to which model to choose. Have I missed something? Is there a way I can get the lars package to return just one "*best*" model? There are other posts suggesting using `glmnet` instead but this seems more complicated. An attempt is as follows, using the same $x$ and $y$. Have I missed something here?: ```r cv = cv.glmnet(x, y) model = glmnet(x, y, type.gaussian="covariance", lambda=cv$lambda.min) predict(model, type="coefficients") ``` The final command returns a list of my variables, the majority with a coefficient although some are =0. Is this the correct choice of the "*best*" model selected by LASSO? If I then fit a linear model with all my variables which had coefficients `not=0` I get very similar, but slightly different, coefficient estimates. Is there a reason for this difference? Would it be acceptable to refit the linear model with these variables chosen by LASSO and take that as my final model? Otherwise I cannot see any p-values for significance. Have I missed anything? Does ``` type.gaussian="covariance" ``` ensure that that `glmnet` uses multiple linear regression? Does the automatic normalisation of the variables affect the coefficients at all? Is there any way to include interaction terms in a LASSO procedure? I am looking to use this procedure more as a demonstration of how LASSO can be used than for any model that will actually be used for any important inference/prediction if that changes anything. Thank you for taking the time to read this. Any general comments on LASSO/lars/glmnet would also be greatly appreciated.
2013/05/08
[ "https://stats.stackexchange.com/questions/58531", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/25419/" ]
Using `glmnet` is really easy once you get the grasp of it thanks to its excellent vignette in <http://web.stanford.edu/~hastie/glmnet/glmnet_alpha.html> (you can also check the CRAN package page). As for the best lambda for `glmnet`, the rule of thumb is to use ``` cvfit <- glmnet::cv.glmnet(x, y) coef(cvfit, s = "lambda.1se") ``` instead of `lambda.min`. To do the same for `lars` you have to do it by hand. Here is my solution ``` cv <- lars::cv.lars(x, y, plot.it = FALSE, mode = "step") idx <- which.max(cv$cv - cv$cv.error <= min(cv$cv)) coef(lars::lars(x, y))[idx,] ``` Bear in mind that this is not exactly the same, because this is stopping at a lasso knot (when a variable enters) instead of at any point. Please note that `glmnet` is the preferred package now, it is actively maintained, more so than `lars`, and that there have been questions about `glmnet` vs `lars` answered before (algorithms used differ). As for your question of using lasso to choose variables and then fit OLS, it is an ongoing debate. Google for OLS post Lasso and there are some papers discussing the topic. Even the authors of Elements of Statistical Learning admit it is possible. **Edit**: Here is the code to reproduce more accurately what `glmnet` does in `lars` ``` cv <- lars::cv.lars(x, y, plot.it = FALSE) ideal_l1_ratio <- cv$index[which.max(cv$cv - cv$cv.error <= min(cv$cv))] obj <- lars::lars(x, y) scaled_coefs <- scale(obj$beta, FALSE, 1 / obj$normx) l1 <- apply(X = scaled_coefs, MARGIN = 1, FUN = function(x) sum(abs(x))) coef(obj)[which.max(l1 / tail(l1, 1) > ideal_l1_ratio),] ```
`lars` and `glmnet` operate on raw matrices. To includ interaction terms, you will have to construct the matrices yourself. That means one column per interaction (which is per level per factor if you have factors). Look into `lm()` to see how it does it (warning: there be dragons). To do it right now, do something like: To make an interaction term manually, you *could* (but maybe *shouldn't*, because it's slow) do: ``` int = D["x1"]*D["x2"] names(int) = c("x1*x2") D = cbind(D, int) ``` Then to use this in lars (assuming you have a `y` kicking around): ``` lars(as.matrix(D), as.matrix(y)) ``` I wish I could help you more with the other questions. I found this one because lars is giving me grief and the documentation in it and on the web is very thin.
132,008
I need a lo-fi way of mounting a PCB (Tessel plus RFID card) under a table. The easiest method by far would be velcro but I'm worried about static discharge frying my circuitry. Should I be?
2014/10/05
[ "https://electronics.stackexchange.com/questions/132008", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/54575/" ]
The Velcro is probably no worse than any other plastic (nylon) that is close to your circuit, as far as ESD is concerned. It may be a problem if you frequently rip the Velcro off, as you may cause the friction to generate a charge. But a big problem with Velcro is that it does not last very long. The self-adhesive side will stick OK to begin with, but will dry out and let go in a comparatively short time. I've seen this happen on a regular basis with electronic modules fixed to housings with Velcro. They all came back with the modules dropped off but the Velcro-to-Velcro interface intact. The Velcro had just come unglued from the inside of the housing.
Usually for a properly designed fully assembled board ESD isn't really a problem. And if I were you unless the desk is made of material that is unsuitable I would just bolt the board to the desk with a few screws. All my boards have mounting holes for this.
21,343
I noticed that after a few attempts using google to search in Chinese, every result I was getting was written in traditional characters (even despite me searching in Mandarin, simplified characters). Does anyone know why this might happen? How can I set it to give me simplified characters? Are simplified characters actually not as useful as traditional characters if it gives me everything in traditional characters?
2016/10/05
[ "https://chinese.stackexchange.com/questions/21343", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/15304/" ]
> > Are simplified characters actually not as useful as traditional > characters if it gives me everything in traditional characters? > > > Traditional characters are used in HongKong and Taiwan and simplified characters are used in mainland China. The answer to your question depends on where you are going and how you are going to use the language. If you want search results in simplified Chinese, you can try some Chinese search websites. The most common one would be [Baidu](https://www.baidu.com).
**Interface Language: Simplified or Traditional, that's your choice** You can select add simplified Chinese to your languages and also add it in your profile. Then the Google interface will be in simplified. So Google will interact with you in simplified. And the reverse is true for traditional. That covers how the Google interface interacts with you. **Queries returned: it depends on your input script and is always limited to Google reach** Now about the queries being returned. If you type a query in simplified, the results will be mostly from simplified Chinese sources. Bear in mind that simplified sources are in China proper. If you type a query in traditional script, the reverse is true, the results would then mostly be from Hong Kong and Taiwan. So it depends what you want. Should you want China proper results, use simplified script in the query. If you want Hong Kong or Taiwan results, use traditional script in the query. **Google reach in China is very limited: want real Chinese sources? Use baidu instead...** The truth of the matter, however, is that Google is not good for returning sites from China. And the Google maps for China are not accurate. The street level views also don't work. If you want to know about China, use baidu.com The sites this search engine returns are good and the maps are accurate and street level view works like a charm. You can use Baidu from the US without any problems. Some non-Chinese speakers while in China insist on trying to use Google over vpn (because Google is blocked in China -that is another story-). I personally don't think it's worth the trouble; the samples Google returns about China are not anywhere as useful as Baidu. **Google could be a whole lot better for Chinese** I think if Google wanted to truly make a useful product, it would provide an option to switch the delivery script on the fly, no matter where the source is. In essence, truly treat the simplified/traditional as a user-selected delivery font. So if the source was say, Hong Kong (in traditional) but you were a simplified script user based in the US, you could still read it with ease. And of course the reverse could also be done. That would open up the mainland to 华人 (Chinese established outside China for generations, therefore still using traditional). Or maybe you could be a Google user in China using Google over VPN to read Hong Kong sites ;-). Anyway, the bottom line is that Google's hits from China sources are not anywhere as good as Baidu's. So, it's not just about script... **Traditional vs Simplified is a complex question** I speak Mandarin and have traveled a lot to China and also lived in China. I learned Chinese in the US using simplified script. Most schools in the US rightly teach simplified script because that is what is used in China. Bear in mind 1.3 billion people use simplified script in China. So it is important to understand that the vast majority of Chinese speakers in the world today use simplified script. Also, the truth is that many outside China people of Chinese origin (华人, huaren) actually cannot hand-write Chinese anymore. This is certainly true of American Born Chinese (ABCs). Also, another aspect of this, is while traditional characters are "in use" in Hong Kong and Taiwan, one has to realize that in these places, unlike China, English is essentially on par with Chinese. In other words not only do most people also speak English in Hong Kong and Taiwan, they **use** English in their daily lives. English is everywhere on public signs. English is prevalent at the working place. For example, English is the language of work in Hong Kong. You can live and work there and not speak one word of Chinese. This is not true of China. The fact that in Hong Kong and Taiwan, English is the de-facto language of education/work/business etc. has an impact on the effective literacy, to be more precise, on the ability to hand- write Chinese characters. In China, the ability to hand-write Chinese characters and to use Chinese is complete, and is never competing with English on an on-par basis. This high level of education relies on the simplification of the script. This is why simplified is such a good thing. It has been extremely successful. This is perhaps one of the most successful social advances that China implemented. Bear in mind that the Chinese written language has undergone many modifications in its history; ancient Chinese characters are very different than so-called traditional ones. So the issue of traditional vs. simplified is rather complex. **Limiting your view to one script is limiting your reach into Chinese diversity** I read some comments here that basically go along the lines of "I don't want to see simplified when I do my searches etc... etc..." Again, this is not simply a font issue: if you limit your view to traditional script, essentially all you see is Hong Kong and Taiwan material. So you don't see anything mainland Chinese: you don't really see China. The issue is whether Google, despite having itself kicked out of China, can find a way to get back in somehow. Facilitating segregation of material is not the right way to go I think. Actually, Bing.com is doing a pretty good job in China, they don't seem to have any problems there -they found a way to work while respecting Chinese law-, so maybe Google could learn a thing or two from the competition...
4,124,793
It is possible to configure Eclipse PDT to format my php code after a standard like MySource or Zend?
2010/11/08
[ "https://Stackoverflow.com/questions/4124793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319331/" ]
Just to give the full answer all at once: 1. from klemens: You need to add the file to your `.gitignore` file somewhere above the undesired file in the repo. i.e. $ cd $ cat >> .gitignore development.log C-d 2. from m. narebski: You then need to remove the file from the repo by executing "`git rm --cached <file>` and then committing this removal" If you were also hoping to make the repo look as if it had never tracked that file, that is much more complicated and highly discouraged as it not only creates brand new commits for every single commit in your history, thus destroying interoperability in a nasty way between other people who have cloned your repo, but it also leaves every one of those commits untested (assuming you test your commits before making them). With that caveat in mind, the tool you're looking for if that's your goal is [`filter-branch`](http://git-scm.com/docs/git-filter-branch). The first example does exactly what I'm describing.
To stop tracking the file, simply use `git rm --cached <filename>`. But as pointed out by the others here, adding the file to .gitignore might prevent you from accidentally adding it again later.
19,154,310
I have a quite large Java application, that I may thinking to do some performance increase, but I am very new at this and wonder where should I start. I guess I have to first perform some code test and see where most calculation and resource/time spend on which part of code before starting increase performance. Are there any tool that I can use and any general tips where to start and how to increase performance?
2013/10/03
[ "https://Stackoverflow.com/questions/19154310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2412555/" ]
My problem was that when I was creating the dialog, I was extending the `Android.Theme.Dialog` style which made it shrink In this style `R.style.ParticipantsDialog` - I removed the parent theme, and it grew to full size like i wanted
Try following code ``` int DisplayWidth, DisplayHeight; Dialog dialog; Display display =((WindowManager)Your_context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); DisplayWidth = display.getWidth(); DisplayHeight = display.getHeight(); dialog = new Dialog(activity_context); // Set your dialog width and height dynamically as per your screen. Window window = dialog.getWindow(); window.setLayout(DisplayWidth , DisplayHeight); window.setGravity(Gravity.CENTER); dialog.show(); ```
7,669,527
I've been using a try/catch statement to run through whether or not an element exists when I parse through it. Obviously this isn't the best way of doing it. I've been using LINQ (lambda expressions) for the majority of my parsing, but I just don't know how to detect if an element is there or not. One big problem with some solutions I found is that they take 3-4 times more code than using the try/catch block, which kind of defeats the purpose. I would assume the code would look something like this: ``` if(document.Element("myElement").Exists()) { var myValue = document.Element("myElement").Value; } ``` I did find this [link](http://blog.linqexchange.com/index.php/using-linq-defaultifempty-to-test-if-an-element-exists/), but the looping is unecessary in my case as I can guarantee that it will only show up once if it exists. Plus the fact of having to create a dummy element which seems unecessary as well. Doesn't seem like it's the best way (or a good way) of checking. Any ideas?
2011/10/06
[ "https://Stackoverflow.com/questions/7669527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200015/" ]
Any() is the Linq command. ``` Assert.IsFalse( new [] { 1, 2, 3, 4 }.Any( i => i == 5 )); ```
`Any()` is the simplest way to check if an element exists. If you have to make sure that the element is unique, you'll have to do something like `.Count() == 1`. Alternatively you could implement your own extension method, but this would be only a wrapper around `.Count == 1`.
72,531
Whenever I near yellow or red lights, I slow down and pedal backwards as I coast so that I can continue to get exercise while I wait for the light to turn green before I reach the intersection. (It's a mountain bike; it doesn't have a coaster brake.) Is this bad? From what I've read, crank-arms are supposed to tighten themselves as you pedal, so does that mean pedaling backwards loosens it? (The only thing I can find when doing a web-search on this is about whether it's physically beneficial to pedal backwards on a recumbent bike, not about the effects on a bicycle.) Note: Some people have mentioned that it's not exercise because of the low resistance, but that's like saying that a motor with no load doesn't burn any fuel or battery to turn. It may not be a hard exercise, but it's still movement. Moreover, there is another point to coasting toward the intersection in that coming to a complete stop at the light requires a lot of exertion to get back up to speed and it's very frustrating to feel rushed, trying to get across while cars wait. By coasting, I'm able to much more easily get through the intersection quickly once the light turns green.
2020/10/04
[ "https://bicycles.stackexchange.com/questions/72531", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/52979/" ]
I always used to pedal backwards on corners. Once when abroad I hired a bike with a coaster brake. Therefore nearly killed myself on the first corner and trained myself out of that habit rather quickly. So possibly bad for the bike if it ends up crushed at the same time as you. I would recommend losing the habit.
It depends on the type of bike you have. And like RLH said also by how it was designed threadwise. It is risky of the chain coming off. If you have a kids type bike the brakes are often operated by pedaling backwards but you cant go very far that way.
1,631,817
I observe "Remote System Explorer Operation" in Progress view of Eclipse after each save of Java file (so it might be related to compiling?). It makes the Eclipse unusable for 1 to 10 seconds. In some projects (of about the same size) it's quicker, in some it's slower. I have no idea which plugin might be the cause for it. I have `Build id: 20090920-1017`. I have quite a few [plugins installed](http://so.pastebin.com/f3120dfe2). I have tried turning all the remote systems to `enabled=false` under Preferences | Remote Systems (whatever it means). I didn't help. Any idea how to solve it? EDIT: 1. It doesn't happen when `Project | Build automatically` is turned off. So it's some part of the building process.
2009/10/27
[ "https://Stackoverflow.com/questions/1631817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118587/" ]
For me at this time for Spring Tool Suite 3.9.4. Release disabling remote system via preferences menu fixed the issue. [Here](http://www.programmersstack.com/2016/02/eclipse-freeze-for-few-seconds-due-to.html) is the reference that helped me. but after a while, the problem is there again!
Switched to eclipse photon one week, didn't see the annoying "remote system...." any longer.
11,990
I see a lot of Excel questions, but also ones involving command lines, batch files, and other similar scripts, that entail some mental challenge. I'm not referring to ones where a novice needs some basics and the solution is straightforward. Users will post what looks like a good answer, reflecting a significant time investment to figure out the solution and write it up. Often, the solution is obtuse, or long and complex, not something you can glance at and recognize that it will obviously work. The author may include explanations of how and why the components of the formulas should work. **The Problem** But people sometimes don't bother to actually test it, or fully test it against the range of conditions in the question. Even if they test it, they don't go the last mile to include a demonstration of the results, like a screenshot of the output, so there's no way to know the extent of any testing. In some cases, the sample output could also add value by showing exactly what the results will look like, which can make it easier to understand the formulas. Without that, I can't tell if it's correct without investing the time to recreate the spreadsheet. Sometimes just dissecting the formulas can miss the same error as the author did on something untested that looks superficially like it should probably work. There have been countless times where somebody has posted a solution that looked great, then the OP or another reader commented that it didn't work, or the author returned later and changed it because they discovered that it didn't work. **The Ramifications** So I don't like to upvote the answer if I don't know that it actually works. If I happen to catch it later, and the OP has accepted it or commented that it worked, I can take that as evidence. But at least for me, a lot of contributors are leaving easy upvotes on the table by not "finishing" the answer. I suppose I could leave a comment. But then I would look like the only dummy for whom the result wasn't obvious. And the author may have discarded their work by the time I comment, so going back to reconstruct it may seem like too much effort at that point. My guess is that the author is focused on satisfying the OP, and expects that the OP will be doing the verification. But that misses the community at large. Good answers should address the audience beyond the OP; "proven" solutions. **Questions** It could be that my expectation is excessive relative to the majority of users, so my questions: * In terms of the potential scope of lost rep opportunity for contributors, do people besides me not upvote answers that they can't easily verify? * Do others agree that on non-obvious or non-trivial answers, it's important to include the results as proof? * If so, is there something we can do to educate and encourage authors to do that?
2016/12/23
[ "https://meta.superuser.com/questions/11990", "https://meta.superuser.com", "https://meta.superuser.com/users/364367/" ]
Answers which present a valid approach to solve the OP's problem are good answers by my standards, even if they contain mistakes. While I certainly appreciate answers which are tested to perfection, I never expect code found on SE to be 100% plug&play, and I always test it before using. How you set standards for upvotes / downvotes is very subjective, you might as well refrain from upvoting a 100% correct answer which is riddled with spelling mistakes and slang.
> > In terms of the potential scope of lost rep opportunity for contributors, do people besides me not upvote answers that they can't easily verify? > > > Yes, I agree. I upvote only answers which I can verify (AND which I consider to be useful, gives additional information to previous answers, ...) > > Do others agree that on non-obvious or non-trivial > answers, it's important to include the results as proof? > > > In general, yes. (of course there're also exceptions) > > If so, is there something we can do to educate and encourage authors to do that? > > > I've experience mainly with Excel questions. There are two types of questions here: * questions **asking for formula** ([worksheet-function](https://superuser.com/questions/tagged/worksheet-function "show questions tagged 'worksheet-function'")): here, adding a screenshot which shows the formula and the correct result could be a quick win, this would already increase the quality of the answer to an acceptable minimum, however that still doesn't make it a good one (see this question too: [Should I write detailed answers to trivial questions?](https://meta.superuser.com/questions/11696/should-i-write-detailed-answers-to-trivial-questions)) When I see answers with the formula only, or even worst: "try this...", I'm tempted to flag it as comment only * answers containing **VBA**: for some people on this site writing (short) macros is a quick win for answering, even if OP asked for a formula, or the questions is of a low quality. I find very few good quality questions asking for code (containing: what do you need? what you've tried?) and really hate when people comes here just asking for the code (Is there a macro, which can...?) As I generally don't agree with the approach, I'm more strict here: upvote only answers which are answers of a good question and also add some explanation to the code. For the original question regarding education: for me adding a proof here is a low priority, before they should understand: answer good questions only; consider coding level of the OP (if you write a code for a novice in VBA, then also include link for VBA tutorials to teach him how to use it).
28,795,214
I have a array with x array in it with always same keys in these arrays . ``` Array ( [foo] => Array ( [q] => "12r3" [w] => "3r45" [e] => "67e8" ) [foo1] => Array ( [q] => "féEt" [w] => "Ptmf" [e] => "4323" ) [foo2] => Array ( [q] => "axa" [w] => "dfvd" [e] => "hjh" ) ) ``` and I need to merge all these arrays in one like: ``` [foo] => Array ( [q] => Array ( [0] => "12r3", [1] => "féEt", [2] => "axa", ) [w] => Array ( [0] => "3r45", [1] => "Ptmf", [2] => "dfvd", ) ... ``` How can I do that? Thanks.
2015/03/01
[ "https://Stackoverflow.com/questions/28795214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4408533/" ]
This should work for you: (Here I just go through the first array and grab all columns with [`array_column()`](http://php.net/manual/en/function.array-column.php) from the entire array with the keys from the first array.) ``` <?php $arr = [ "foo" => [ "q" => "12r3", "w" => "3r45", "e" => "67e8" ], "foo1" => [ "q" => "féEt", "w" => "Ptmf", "e" => "4323" ], "foo2" => [ "q" => "axa", "w" => "dfvd", "e" => "hjh" ] ]; foreach($arr["foo"] as $k => $v) { $results[$k] = array_column($arr, $k); } print_r($results); ?> ``` Output: ``` Array ( [q] => Array ( [0] => 12r3 [1] => féEt [2] => axa ) [w] => Array ( [0] => 3r45 [1] => Ptmf [2] => dfvd ) [e] => Array ( [0] => 67e8 [1] => 4323 [2] => hjh ) ) ```
``` $newArray = []; foreach($array as $value) { foreach($value as $key => $data) { $newArray[$key][] = $data; } } var_dump($newArray); ``` or ``` $newArray = []; foreach($array as $value) { $newArray = $newArray + $data; } var_dump($newArray); ```
254
We've already rolled out Windows XP SP2 (no hope of going to Vista or Windows 7 in the foreseeable future unfortunately) across the enterprise and our latest internal roll-out actually incorporates SP3 as well - but unfortunately IE is explicitly being kept at version 6. Regardless of the numerous security warnings our there and lack of applicability in the greater world wide web, my manager still sees intranet apps written for IE6 as the main reason to stay on it. What can we do to swing the vote in our favour? We're tired of supporting an ailing browser when users call us up constantly complaining that website don't look right, and more and more people asking for browser tabs "because that's what they've got at home". Any arguments we can put forward would be great!
2009/04/30
[ "https://serverfault.com/questions/254", "https://serverfault.com", "https://serverfault.com/users/246/" ]
Have you tested your intranet apps with IE7 or IE8? We had several that we thought were IE6-only that actually work with IE7. If the intranet apps are in-house developed, then you need to asses how expensive the compatibility work will be; if they are external then you need to contact the suppliers. Just identifying the actual roadblocks can be good, as you often find they are much less than you thought.
Hiring an intern to update the intranet apps should be probably less costly than doing extensive cleanup of the network due to a security breach, because of using an insecure and standards-ignorant browser both for intranet and internet.
39,488,751
I try to use [Bean Validation](http://beanvalidation.org/1.1/spec/) for my REST API with Apache CXF. I read [Apache CXF Documentation](https://cwiki.apache.org/confluence/display/CXF20DOC/ValidationFeature) and it works fine for root resources, but it doesn't work with [sub resource locators](http://cxf.apache.org/docs/jax-rs-basics.html#JAX-RSBasics-Sub-resourcelocators.). The constraints are ignored for sub resources. **Maven dependencies:** ```xml <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>3.1.5</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.apache.bval</groupId> <artifactId>bval-jsr</artifactId> <version>1.1.0</version> </dependency> ``` **Java code:** ``` @Named @Path("test") public class TestResource { @Inject private TestSubResource subResource; @Path("sub") public TestSubResource getSubResource() { return subResource; } @GET public void find(@NotNull @QueryParam("value") String value) { } } @Named public class TestSubResource { @GET public void find(@NotNull @QueryParam("value") String value) { } } ``` **CXF configuration:** ```xml <bean id="validationProvider" class="org.apache.cxf.validation.BeanValidationProvider" /> <bean id="validationInInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor"> <property name="provider" ref="validationProvider" /> </bean> <jaxrs:server address="/rest" id="test" staticSubresourceResolution="true"> <jaxrs:serviceBeans> <ref bean="testResource" /> </jaxrs:serviceBeans> <jaxrs:inInterceptors> <ref bean="validationInInterceptor" /> </jaxrs:inInterceptors> </jaxrs:server> ``` I found following issues: * <https://issues.apache.org/jira/browse/CXF-6297> * <https://issues.apache.org/jira/browse/CXF-6296> but both are about validation of return value not about validation of request parameters. The question [CXF in Karaf: how to configure bean validation on subresources (preferably using Blueprint)?](https://stackoverflow.com/questions/35742557/cxf-in-karaf-how-to-configure-bean-validation-on-subresources-preferably-using) is similar, but about Karaf and Blueprint and contains no solution for my question.
2016/09/14
[ "https://Stackoverflow.com/questions/39488751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277820/" ]
I would say custom invoker is the way to go. But I guess you already knew that based on your comment. ```xml <bean id="validationProvider" class="org.apache.cxf.validation.BeanValidationProvider" /> <bean id="validationInInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor"> <property name="provider" ref="validationProvider" /> </bean> <bean id="validationInvoker" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInvoker"></bean> <jaxrs:server address="/rest" id="test" staticSubresourceResolution="true"> <jaxrs:serviceBeans> <ref bean="testResource" /> </jaxrs:serviceBeans> <jaxrs:inInterceptors> <ref bean="validationInInterceptor" /> </jaxrs:inInterceptors> <jaxrs:invoker> <ref bean="validationInvoker" /> </jaxrs:invoker> </jaxrs:server> ``` I tried that on your example, and it works. But I think you need to use an `ExceptionMapper`, as you don't get proper exceptions. I think `ValidationExceptionMapper` would be the right one. Edit- Updated exception mapper class based on comment
I don't think bean validation will work on the subresource, refer to the source code for [`BeanValidationInInterceptor`](http://grepcode.com/file/repo1.maven.org/maven2/org.apache.cxf/cxf-core/3.0.0/org/apache/cxf/validation/BeanValidationInInterceptor.java#BeanValidationInInterceptor), which is extended by `JAXRSBeanValidationInInterceptor` and is used as the validation interceptor. If you notice the method `handleValidation`, it is clear that the validation happens on the arguments of the resource object. Now, this validation is happening before the actual service method is invoked on the resource (that's how it is looking at least) and at this time, the subresource instance is not known (does not exist), so in general, subresource parameters at this juncture cannot be validated. My impression is that with the current mechanism in CXF under discussion (interceptor), subresource parameters probably cannot be bean validated in the normal way. You could probably take a workaround, with reference to the [JAX-RS Reference](http://docs.jboss.org/resteasy/docs/1.0.1.GA/userguide/html/JAX-RS_Resource_Locators_and_Sub_Resources.html), you could try to bean validate the parameter (especially if it is a request JSON), manually i.e. instantiate a Validator object and then validate it with that e.g. ``` package validator; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import org.apache.bval.jsr303.ApacheValidationProvider; public class DataBean { @Max(10) public int x = 0; @Pattern(regexp= "this_string") public String y = "this_string"; // also matches null public static void main(String[] args) { ValidatorFactory avf = Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory(); DataBean bean = new DataBean(); Validator validator = avf.getValidator(); Set<ConstraintViolation<DataBean>> violations = validator.validate(bean); System.out.println(violations); } } // calss closing ```