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
40,143,861
after running code i get no result in window. and i cant find problem result have to be string created from charCode. ```js function rot13(str) { var te = []; var i = 0; var a = 0; var newte = []; while (i < str.length) { te[i] = str.charCodeAt(i); i++; } while (a != te.length) { if (te[a] < 65) { newte[a] = te[a] + 13; } else newte[a] = te[a]; a++; } var mystring = String.fromCharCode(newte); return mystring; } // Change the inputs below to test rot13("SERR PBQR PNZC"); ```
2016/10/20
[ "https://Stackoverflow.com/questions/40143861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3225277/" ]
Try this code: Answer 1: ``` func tableView(tableView:UITableView!, numberOfRowsInSection section: Int) -> Int { yourTableViewName.estimatedRowHeight = 44.0 // Standard tableViewCell size yourTableViewName.rowHeight = UITableViewAutomaticDimension return yourArrayName.count } And also put this code inside your Cell for incase... yourCell.sizeToFit() ``` Answer 2: ``` override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } ```
in viewDidLoad Add this ``` tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension ``` Just add these two lines and your problem will b solved
2,229,054
Basically, what I'm looking for is some kind of class or method to implement a dictionary in PHP. For example, if I was building a word unscrambler - lets say I used the letters 'a,e,l,p,p'. The number of possibilities for arrangement is huge - how do I only display those which are actual words (apple, pale etc )? Thanks!
2010/02/09
[ "https://Stackoverflow.com/questions/2229054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246637/" ]
you can also consider pspell <http://php.net/manual/en/book.pspell.php> ``` $ps = pspell_new("en"); foreach(array('alppe', 'plape', 'apple') as $word) if(pspell_check($ps, $word)) echo $word; ```
Store a list of words in a file or a database, and then just try all the combinations. You could also consider the likely position of vowels vs consonants to potentially speed it up. Rather than making your own word list, you could use something like [WordNet](http://wordnet.princeton.edu/wordnet/).
46,666,787
Validation is not working. All the form fields are coming dynamically. It depends on the user how many fields he chooses.If he chooses 2 and it will display 2 fields in the view. If select 3 then it will display 3 fields and so on.I have more than 30 fields I set 3 arrays(for testing purpose I set only 3. It will be total no of fields ) in my form validation page. If I remove the last array than validation is working because I am getting only 2 fields in the view. I am not able to use the more than 2 array in my form validation page. Is it mandatory to require the number of fields in view is equal to a number of sets of rules array in form validation? View This is my dynamic view page ``` <?php echo form_open('formbuilder_control/enxample_from_view'); foreach ($data as $key) {// I am getting output $exp_fields_name=$key->fields_name; $exp_fields_type=$key->fields_type; $exp_form_elements=$key->form_elements; $abc=explode(',',$exp_form_elements); foreach ($abc as $value) { if ($exp_fields_name == $value) {?> <div class="form-group row label-capitals"> <label class="col-sm-5 col-form-label"><?php echo $exp_fields_name;?></label> <div class="col-sm-7"> <input type="<?php echo $exp_fields_type;?>" name="<?php echo $exp_fields_name;?>" placeholder="<?php echo $value;?>" class="form-control" /> <?php echo form_error($exp_fields_name); ?> </div> </div> <?php }}}?> <div class="form-buttons-w btn_strip"> <input type="submit" name="submit" value="Save" class="btn btn-primary margin-10"> </div> <?php echo form_close(); ?> ``` **Form\_validation.php** ``` $config = array( 'test'=>array( array('field' =>'firstname', 'label' => 'First Name', 'rules' => 'required' ), array('field' => 'lastname', 'label' => 'lastname', 'rules' => 'required' ), array('field' => 'middlename', 'label' => 'middlename', 'rules' => 'required' ) ), ); ``` Controller ``` public function test() { if($this->form_validation->run('test') == TRUE) { echo "working"; } $this->load->view('test1'); } ```
2017/10/10
[ "https://Stackoverflow.com/questions/46666787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Of course it will fail. Your validation rules define a 'middlename' field as `required`, and that field doesn't even exist in the form. A missing field cannot satisfy a `required` rule.
As others have mentioned, you are requiring a field that does not exist. You either need to: * Add a field in your view with the name `middlename` * Remove the validation rule that requires a field `middlename` to exist Not contributing to your issue, but in a usability aspect, you likely want to change the label in your `lastname` and `middlename` rules to make them more user friendly. ``` $config = array('test'=>array( array('field' =>'firstname', 'label' => 'First Name', 'rules' => 'required' ), array('field' => 'lastname', 'label' => 'lastname', 'rules' => 'required' ), array('field' => 'middlename', 'label' => 'middlename', 'rules' => 'required' ) ), ); ``` Also, the documentation has other helpful tips for different custom rules if you're not trying to require the `middlename` but want to sanitize or validate its format prior to insertion into a database. <https://www.codeigniter.com/userguide3/libraries/form_validation.html#form-validation-tutorial>
30,892,945
Using `Ctrl`+`Shift`+`B` I added a default tasks.json file and uncommented the second task runner block. I have a typescript file in the root of the directory and a tsconfig.json. Everytime I compile I get 'error TS5023: Unknown compiler option 'p'. What is the correct definition to allow me to compile a typescript file? Can all files be compiled in one go even if they are in subdirectories? I have tried changing the args below to `["${file}"]` which simply allows me to compile the file that is open. This works. I've also run the tsc command from the command prompt and no -p or -project arguments exists. tasks.json ``` { "version": "0.1.0", // The command is tsc. Assumes that tsc has been installed using npm install -g typescript "command": "tsc", // The command is a shell script "isShellCommand": true, // Show the output window only if unrecognized errors occur. "showOutput": "silent", // Tell the tsc compiler to use the tsconfig.json from the open folder. "args": ["-p", "."], // use the standard tsc problem matcher to find compile problems // in the output. "problemMatcher": "$tsc" } ``` tsconfig.json ``` { "compilerOptions": { "target": "ES5", "module": "amd", "sourceMap": true } } ``` VS Code: v0.30 TypeScript: v1.4
2015/06/17
[ "https://Stackoverflow.com/questions/30892945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40986/" ]
I had the same problem. It was a wrong PATH variable to the TypeScript compiler. (try to type `tsc -v` in a command window). The `tsconfig.json` is supported in TypeScript version 1.5. My PATH variable was set to version 1. When I changed the system PATH variable to the updated installation folder (`C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.5`) and a restart of Visual Studio Code, everything was fine. (Remove all entries from the `args`!) Like: ```js { "version": "0.1.0", // The command is tsc. Assumes that tsc has been installed using npm install -g typescript "command": "tsc", // The command is a shell script "isShellCommand": true, // Show the output window only if unrecognized errors occur. "showOutput": "always", // Tell the tsc compiler to use the tsconfig.json from the open folder. "args": [], // use the standard tsc problem matcher to find compile problems // in the output. "problemMatcher": "$tsc" } ```
I struggled until I understood how npm was installing the typescript 1.5 beta (or not) on my windows laptop. The key to getting this to work for me was: 1. uninstall current version of typescript (for me, this was version 1.4.1) > > npm uninstall -g typescript > > > 2. install 1.5.1-beta version > > npm install -g typescript@1.5.0-beta > > (npm will print an error message & list all versions if you use an incorrect version) > > > 3. Locate the tsc.cmd file - created under the npm folder. On my Windows 8.1 machine, this was stored at: C:\Users\Bob.Chiverton\AppData\Roaming\npm\tsc.cmd 4. Add this to the tasks.json file: "command": "C:\Users\Bob.Chiverton\AppData\Roaming\npm\tsc.cmd", Now re-try ctrl-Shift-B. -bob
3,262,947
Please help me with this Herstein exercise (Page 103,Sec 2.12, Ques 16). \begin{array} { l } { \text { If } G \text { is a finite group and its } p \text { -Sylow subgroup } P \text { lies in the center of } } \\ { G , \text { prove that there exists a normal subgroup } N \text { of } G \text { with } P \cap N = (e)} \\ { \text {and } P N = G . } \end{array} I got to know about more general theorems like Schur-Zassenhaus Theorem or Burnside's normal p-complement theorem from which this can be deduced as corollary. But, I want a solution which just uses theory built in Herstein's book. The question just before this is \begin{array} { l } { \text { Let } G \text { be a finite group in which } ( a b ) ^ { p } = a ^ { p } b ^ { p } \text { for every } a , b \in G , } \\ { \text { where } p \text { is a prime dividing } o ( G ) \text { . Prove } } \\ { \text { (a) The } p \text { -Sylow subgroup of } G \text { is normal in } G \text { . } } \\ { \text { (b) If } P \text { is the } p \text { -Sylow subgroup of } G , \text { then there exists a normal } } \\ { \text { subgroup } N \text { of } G \text { with } P \cap N = ( e ) \text { and } P N = G \text { . } } \\ { \text { (c) } G \text { has a nontrivial center. } } \end{array} I have solved it by first proving, for $p^n|o(G)$ and $p^{n+1} \not| o(G)$, $$P=\{x\in G : x^{p^n}=e\}$$ is unique $p-Sylow$ sugroup of G and then taking a homomorphism $\phi:G\to G$ defined by $\phi(g)=g^{p^n}$, where $p^n$ is order of $p-Sylow$ subgroup of G. Then $\phi(G)= N$
2019/06/15
[ "https://math.stackexchange.com/questions/3262947", "https://math.stackexchange.com", "https://math.stackexchange.com/users/446929/" ]
Let $G' = [G,G]$ be the [derived subgroup](https://en.wikipedia.org/wiki/Commutator_subgroup) of $G$. Let $\pi$ be the natural projection of $G$ onto the quotient $Q = G/G'$ (also called the abelization of $G$). The Abelian group $Q$ splits as a direct product $Q = \pi(P) \times M$. The group you are looking for is $N = \pi^{-1}(M)$. The fact that $P \cap N = \{e\}$ derives from the [Focal subgroup theorem](https://en.wikipedia.org/wiki/Focal_subgroup_theorem#Statement_of_the_theorem) stating that $P \cap G' = P\_0 = \{x^{-1}y \mid x \in P,\exists g\in G, y = g^{-1}xg\}$, which in this case is the trivial group.
The basic idea is that you know that because $P$ lies in the center it is the only $p$-Sylow subgroup. That fact is enough to tell you that every element can be decomposed into a "$P$ part" and a "not $P$ part", and each "part" is a subgroup. Here is how that decomposition works: $G$ is a finite group, therefore it is finitely generated, and so we can write down the generators of $G$, let them be $\mathcal{A} = \{a\_1, \dots, a\_n\}$. Now, let $ \mathcal{P} = \{p\_1, \dots, p\_m\} \subset \mathcal{A}$ such that $<\mathcal{P}> = P$. Now let $\mathcal{H}$ be the set of all words in $G$ that do not contain any letters (generators) from $\mathcal{P}$, and let $H = <\mathcal{H}>$. Because $P$ commutes with every element in $G$, it is clear that every word $g \in G$ can be decomposed into a pair $(h,q) \in H\times P$ s.t. $g = h \cdot p$. What's left to prove is that $H$ is a subgroup. Let $a,b \in H$ be arbitrary non-identity elements (the identity case is easy). We must show that $a \cdot b^{-1} \in H$. By definition, we must simply show that $a\cdot b^{-1} \in <\mathcal{H}>$. We proceed by contradiction: assume that $a\cdot b^{-1} \in <\mathcal{A} \setminus \mathcal{H}>$. By Lagrange's theorem we know that $p|gcd(o(a),o(b^{-1}))$. Without loss of generality we take $p \mid o(a)$. Since $a \in H$ that means that $<a> \not\subset P$, which means that the index of $P$ is divisible by $p$, which is a contradiction to the maxamality of a $p$-Sylow subgroup. This shows that it must be the case that $a\cdot b^{-1} \in G\setminus P$, as desired. This is a normal subgroup because every element is decomposed into being either in H or in the center of $G$, which is enough for the orbit of conjugation to be $H$.
62,558,602
Im trying to `import numpy as np` (im using VS2019 as the IDE) and I get the error `"No module names 'numpy'"`. So I tried going to the windows cmd and did `pip install numpy` and I get the error: `"'Pip' is Not Recognized as an Internal or External Command."` I tried watching [this video](https://www.youtube.com/watch?v=emYR6vVHxp8), and have located my Python3 folder (I cant find Python27), but there is no `pip.exe` file in there, so now I don't know what to do. Any help would be much appreciated!
2020/06/24
[ "https://Stackoverflow.com/questions/62558602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11041361/" ]
On of my friends had the same problem. We simply reinstalled python on his Windows 10 laptop and we paid attention to add python to PATH and select an option to install pip with python. This worked pretty much, I think the python Win10 installer is sometimes a little bit to complicated on Win10.
First check if pip is already installed by running this command pip - - version If it is installed then change the os path and if not check if python is correctly installed or not by running this command python - - version If python is installed then try this command python get-pip.py
22,370,922
A chart on a form I created has two overlapping areas. The overlapping part works just fine. The problem is that visible graph only takes up half the height of the chart control: ![enter image description here](https://i.stack.imgur.com/P0EAu.png) The bottom half of the control is left empty (presumably because that's where the second area would have gone were the two areas not aligned?). I can't figure out how to get the chart to use the entire control. The code is below: ``` chart1.Dock = DockStyle.Fill; chart1.Legends.Add(new Legend { Name = "Legend1" }); chart1.Location = new Point(435, 3); chart1.Name = "chart1"; chart1.Size = new Size(426, 287); chart1.TabIndex = 2; chart1.Text = "chart1"; var firstArea = chart1.ChartAreas.Add("First Area"); var seriesFirst = chart1.Series.Add("First Series"); seriesFirst.ChartType = SeriesChartType.Line; seriesFirst.Points.Add(new DataPoint(10, 55)); seriesFirst.Points.Add(new DataPoint(11, 56)); seriesFirst.Points.Add(new DataPoint(12, 59)); var secondArea = chart1.ChartAreas.Add("Second Area"); secondArea.BackColor = Color.Transparent; secondArea.AlignmentOrientation = AreaAlignmentOrientations.All; secondArea.AlignmentStyle = AreaAlignmentStyles.All; secondArea.AlignWithChartArea = firstArea.Name; secondArea.AxisY.LabelStyle.Enabled = false; secondArea.AxisX.LabelStyle.Enabled = false; var seriesSecond = chart1.Series.Add("Second Series"); seriesSecond.ChartType = SeriesChartType.Line; seriesSecond.ChartArea = secondArea.Name; seriesSecond.Points.Add(new DataPoint(10, 1001)); seriesSecond.Points.Add(new DataPoint(11, 1015)); seriesSecond.Points.Add(new DataPoint(12, 1016)); ```
2014/03/13
[ "https://Stackoverflow.com/questions/22370922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/852757/" ]
If you're using GCC or compilers with [`__int128`](https://gcc.gnu.org/onlinedocs/gcc/_005f_005fint128.html) like Clang or ICC ``` unsigned __int128 H = 0, L = 0; L++; if (L == 0) H++; ``` On systems where `__int128` isn't available ``` std::array<uint64_t, 4> c[4]{}; c[0]++; if (c[0] == 0) { c[1]++; if (c[1] == 0) { c[2]++; if (c[2] == 0) { c[3]++; } } } ``` In inline assembly it's much easier to do this using the carry flag. Unfortunately most high level languages don't have means to access it directly. Some compilers do have intrinsics for adding with carry like [`__builtin_uaddll_overflow`](https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html) in GCC and [`__builtin_addcll`](https://clang.llvm.org/docs/LanguageExtensions.html) Anyway this is rather wasting time since the total number of particles in the universe is only about 1080 and you cannot even count up the 64-bit counter in your life
Neither of your counter versions increment correctly. Instead of counting up to `UINT256_MAX`, you are actually just counting up to `UINT64_MAX` 4 times and then starting back at 0 again. This is apparent from the fact that you do not bother to clear any of the indices that has reached the max value until all of them have reached the max value. If you are measuring performance based on how often the counter reaches all bits 0, then this is why. Thus your algorithms do not generate all combinations of 256 bits, which is a stated requirement.
623,208
I have a framed window (currently iframe but may possibly be frame) - I do not have control over this. I would like to detect if my content is inside an iframe (or frame). I wanted to compare the location of the current document with the one the top object holds but it appears it is the same object (top === window). After extensive googling I got to this [IEMobile blog entry](http://blogs.msdn.com/iemobile/archive/2007/05/15/ie-mobile-standards-support.aspx) and in one of the comments there is this answer: > > iemoblog said: > > > No, you can't access any part of the > parent's DOM from script in an iframe > in IE Mobile. > > December 20, 2007 12:12 PM > > > I can't seem to find any documentation about this - can anyone help confirm this or even better - suggest a way to detect if the page is "framed"?
2009/03/08
[ "https://Stackoverflow.com/questions/623208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48317/" ]
If you're using Linux, you can install the "strace" utility to see what the Ruby process is doing that's consuming all the CPU. That will give you a good low-level view. It should be available in your package manager. Then you can: ``` $ sudo strace -p 22710 Process 22710 attached - interrupt to quit ...lots of stuff... (press Ctrl+C) ``` Then, if you want to stop the process in the middle and dump a stack trace, you can follow the guide on using GDB in Ruby at <http://eigenclass.org/hiki.rb?ruby+live+process+introspection>, specifically doing: ``` gdb --pid=(ruby process) session-ruby stdout_redirect (in other terminal) tail -f /tmp/ruby_debug.(pid) eval "caller" ``` You can also use the ruby-debug Gem to remotely connect to debug sockets you open up, described in <http://duckpunching.com/passenger-mod_rails-for-development-now-with-debugger> There also seems to be a project on Github concerned with debugging Passenger instances that looks interesting, but the documentation is lacking: <http://github.com/ddollar/socket-debugger/tree/master>
I had a ruby process related to Phusion Passenger, which consumed lots of CPU, even though it should have been idle. The problem went away after I ran ``` date -s "`date`" ``` as suggested in [this thread](http://www.redmine.org/boards/2/topics/31731). (That was on Debian Squeeze) Apparently, the problem was related to a leap second, and could affect many other applications like MySQL, Java, etc. More info in [this thread on lklm](https://lkml.org/lkml/2012/7/1/176).
5,492,258
I guess you all know by now easyacordion: <http://www.madeincima.eu/blog/jquery-plugin-easy-accordion/> but i just find the documentation invisible for this.. lets say i have my acordion: ``` <div id="intro_web"> <dt>una</dt> <dd>descripcion una</dd> <dt>dos</dt> <dd>descripcion una</dd> <dt>dos</dt> <dd>descripcion una</dd> </div> ``` and i want to have, separately, buttons to handle the accordion, like: ``` <a href="" onclick="acordion_slide(1)">una</a> <a href="" onclick="acordion_slide(2)">dos</a> <a href="" onclick="acordion_slide(3)">dos</a> ``` So, how would: ``` function acordion_slide(num){ // slide and jump acordion to slidenum = num return false } ``` this should look if i SET the accordion (on document ready) like this??? ``` $('#intro_web').easyAccordion({ autoStart: true, slideInterval: 6000 }); ```
2011/03/30
[ "https://Stackoverflow.com/questions/5492258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533941/" ]
Google re-ranks the sites it has regularly. If the site changes, the ranking very well could... if more or fewer people link to it or if the terms on the site (the content) is different. The effect might be good or bad, but uploading different content isn't going to make their rank go away overnight or anything like that.
Page Rank is most about incoming links. So if the incoming links won't be broken page rank will not be affected that much. Though, overall ranking is not just Page Rank, so... further discussion is needed
1,393,683
I have two profiles in my Google Chrome: Joe and Sam. I would like to rename the name of my profile into "JoeJobs" but I can't find any way to do it. I'm only getting "Manage people" and "Remove this person". Is there any way to rename my username profile. Deleting it and re-creating it is truely ridiculous - I saved a lot of bookmarks and there's a ton of website settings saved in my profile
2019/01/13
[ "https://superuser.com/questions/1393683", "https://superuser.com", "https://superuser.com/users/588467/" ]
I just found this out after looking around for a while. this method works as of 2019-May 30th, on Chrome 74. Other versions may change how it's done. 1) Open Chrome, make sure you are on the profile you want to change the name or icon picture of. * Change profiles by clicking on the icon on the upper right of Chrome, it is the second to last thing on upper right, just before the 3 dots / menu button. 2) Once you're the profile to edit, click on the menu (the 3 dots on upper right) and click on '**Settings**' at the bottom of the list (just above 'Help') 3) The top Settings box is for '**People**'. The third line is '**Chrome name and picture**'. Click that line. 4) You should see the settings window show 'Edit person' with a line to change the profile name and the icon. To finish and save any changes, click on the back (left pointing) arrow next to the words 'Edit person'
There are two parts to the Chrome Profile as shown in the dropdown menu from the current user. Like this: Company (Client Project) In this example "Company" is the firstname of the Google Account, which can be changed under name at: <https://myaccount.google.com/personal-info> "Client Project" comes from the Chrome Profile Chrome Name and Picture at: chrome://settings/manageProfile If you work with several companies and clients (and also potentially share Chrome Profiles to coordinate bookmarks and extensions) this naming structure helps keep all the Companies and Client Projects straight.
22,644,884
The header file will not compile into my main test program. Why would this be the case. I have looked on line but found no simple reason why this would be the case. I have tried a couple of `#ifndef`, and `#define` and am still not sure as to why the file will not include into my test program. Below are the error message that I receive when I try and compile my test program. This has to do with the header file but I am not really sure how to fix this simple problem. Strangely i have used C++ before and did not remember having this trouble with the header file. error: > > Error 1 error C2015: too many characters in constant c:\users\itpr13266\desktop\c++\testproject\testproject\testproject.cpp 10 1 TestProject > > > Error 2 error C2006: '#include' : expected a filename, found 'constant' c:\users\itpr13266\desktop\c++\testproject\testproject\testproject.cpp 10 1 TestProject > > > Error 3 error C1083: Cannot open include file: '': No such file or directory c:\users\itpr13266\desktop\c++\testproject\testproject\testproject.cpp 10 1 TestProject > > > code ``` #include "stdafx.h" #include "iostream" #include <iostream> #include <fstream> #include <math.h> #include <iostream> #ifndef MYDATESTRUCTURES_H #define MYDATESTRUCTURES_H #include'myDataStructures.h' <-- name of my include file #endif using namespace std; #define MY_NAME "Alex" void f(int); void DoSome(int, char); enum color { red, green, blue }; enum color2 { r, g=5, b }; class CVector { public: int x,y; CVector () {} CVector (int a, int b) : x(a), y(b) {} void printVector() { std::cout << "X--> " << x << std::endl; std::cout << "Y--> " << y << std::endl; } }; CVector operator+ (const CVector& lhs, const CVector& rhs) { CVector temp; temp.x = lhs.x + rhs.x; temp.y = lhs.y + rhs.y; return temp; } template<typename T> void f(T s) { std::cout << s << '\n'; } template<typename P, typename N> void DoSome(P a, N b) { std::cout << "P--> " << a << '\n'; std::cout << "N--> " << b << '\n'; } void testMath() { int result = ceil(2.3) - cos(.2) + sin(8.0) + abs(3.44); cos(4.1); } void testStorageTypes() { int a; register int b; extern int c; static int y; } color temp = blue; color2 temp2 = r; int _tmain(int argc, _TCHAR* argv[]) { std::getchar(); return 0; } ``` code (header file) ``` #include <iostream> int myAdd1(int, int); int myAdd2(int, int, int, int, int); struct myFirst1 { } struct myFirst2 { } int myAdd1(int x, int y) { return x + y; } int myAdd2(int x, int y, int z, int m, int y) { return x + y; } ```
2014/03/25
[ "https://Stackoverflow.com/questions/22644884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This line isn't valid: ``` #include'myDataStructures.h' <-- name of my include file ``` In C/C++, single quotes are used to quote *character literals*, not string literals. You need to use double quotes: ``` #include "myDataStructures.h" ``` The error messages are slightly less helpful than they could be because it is actually possible to have a [multi-character constant, but its value is implementation-defined](https://stackoverflow.com/questions/7755202/multi-character-constant-warnings), making their use not very portable and therefore rare.
You need to use double quotes `"MyIncludeFile.h"` when including files.
2,558,197
I wanted to create a page with a simple button which runs away from the user when he tries to click it. Lets call it the Run away button? Is there a simple 'jQuery' snippet which will allow me to do the same? Regards, Karan Misra
2010/04/01
[ "https://Stackoverflow.com/questions/2558197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207426/" ]
Use `aggregate` to summarize across a factor: ``` > df<-read.table(textConnection(' + egg 1 20 + egg 2 30 + jap 3 50 + jap 1 60')) > aggregate(df$V3,list(df$V1),mean) Group.1 x 1 egg 25 2 jap 55 ``` For more flexibility look at the `tapply` function and the `plyr` package. In `ggplot2` use `stat_summary` to summarize ``` qplot(V1,V3,data=df,stat="summary",fun.y=mean,geom='bar',width=0.4) ```
@Jyotirmoy mentioned that this can be done with the `plyr` library. Here is what that would look like: ``` DF <- read.table(text= "Widget Type Energy egg 1 20 egg 2 30 jap 3 50 jap 1 60", header=TRUE) library("plyr") ddply(DF, .(Widget), summarise, Energy=mean(Energy)) ``` which gives ``` > ddply(DF, .(Widget), summarise, Energy=mean(Energy)) Widget Energy 1 egg 25 2 jap 55 ```
18,358,675
I'm trying to use the ng-if expression to render posts as images or text, depending on the content. The first of theese lines render true sometimes and false sometimes in a ng-repeat-loop, however both the image and the span are shown in each itteration. ``` <a href="{{post.url}}"> {{post.type == 0}} <img ng-if="post.type == 0" src="{{post.content}}" /> <span ng-if="post.type == 1">{{post.content}}<span> </a> ```
2013/08/21
[ "https://Stackoverflow.com/questions/18358675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350080/" ]
You are defining the value of "post.type" to equal 0 or 1. Use the "==" operator to determine if the value is equal to the comparison ``` <a href="{{post.url}}"> {{post.type = 0}} <img ng-if="post.type == 0" src="{{post.content}}" /> <span ng-if="post.type == 1">{{post.content}}<span> </a> ``` A different approach: ``` {{post.type = 1}} <a ng-if="post.type == 0" href="#"><img ng-if="post.type == 0" src="{{post.content}}" /></a> <a ng-if="post.type == 1"><span>{{post.content}}</span></a> ```
1. Sometimes in a complex HTML not closing tags can create an issue and your span isn't closed (no ). 2. Just for a test case try to change to ng-show. 3. JB Nizet gave u a working plnkr in the comments so I think there is an issue before that.
63,540,492
When the `space` key is pressed, I want the button to not trigger; how can I implement that functionality? I have found a similar [post](https://stackoverflow.com/questions/58388744/how-to-stop-spacebar-from-triggering-a-focused-qpushbutton) but it is written in [c++](/questions/tagged/c%2b%2b "show questions tagged 'c++'"), how could I translate it to [python](/questions/tagged/python "show questions tagged 'python'"), but modifying its behavior to what I want?
2020/08/22
[ "https://Stackoverflow.com/questions/63540492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281485/" ]
If you want any keyboard event that triggers the button then just implement an event filter: ``` import sys from PyQt5 import QtCore, QtWidgets class Listener(QtCore.QObject): def __init__(self, button): super().__init__(button) self._button = button self.button.installEventFilter(self) @property def button(self): return self._button def eventFilter(self, obj, event): if obj is self.button and event.type() == QtCore.QEvent.KeyPress: return True return super().eventFilter(obj, event) App = QtWidgets.QApplication(sys.argv) w = QtWidgets.QWidget() lay = QtWidgets.QVBoxLayout(w) btn = QtWidgets.QPushButton() lay.addWidget(btn) w.show() btn.clicked.connect(print) listener = Listener(btn) sys.exit(App.exec()) ```
Setting noFocus policy for button also works. Button stops reacting to spacebar. ``` self.button= QPushButton() self.button.setFocusPolicy(Qt.NoFocus) ```
18,588
One of my colleagues is in charge of QA (acceptance testing), and I keep on having to double check his work, and when I do, I find bugs - it is becoming tedious. Short of double checking his work, how can I improve the process so that it is more efficiently done?
2016/06/30
[ "https://pm.stackexchange.com/questions/18588", "https://pm.stackexchange.com", "https://pm.stackexchange.com/users/20871/" ]
Let's divide QA(Quality Assurance) from QC(Quality control), check the [difference](http://www.diffen.com/difference/Quality_Assurance_vs_Quality_Control). Short term solution for manual QC would be to create test plans, acceptance criteria's, force your QC to add test evidence(Screenshots, screencasts, logs, SQL query results), which prove that all ok, you should also plan the number of bugs based on previous development history. For instance, on one of my projects, used only manual QC, there was 0.8-1.2 bug for each 10 hours of development. That means that for 40h feature there must be from 3.2 to 4.8 defects. So I shall plan to find at least to find at least 5 of them. General advice would be to switch from QC to QA. On all stages of the project. [Example](http://codemanship.co.uk/parlezuml/tutorials/agile_qa/Example_Agile_Quality_Assurance_Strategy.pdf).
Clearly document the *finds* in emails to your colleague, and CC this colleague's direct boss (and maybe the one above them). After 3 such emails it's appropriate to ask the boss to request your colleague to either shape up or ship out. (Most times, after one such email+CC your colleague will make sure to clean up their act.)
22,331,911
I have two end-points that are giving the following error when viewing the list of end-points: > > **Error while fetching Revision** > > > APIProxy revision *[revision #]* does not exist for APIProxy *[end-point-name]* in organization *[org name]* > > > If I try to delete the end-point from the "Api Proxies" list I get the same message as above with the title of "**Error while deleting Api**" If I go to the details for the end-point in question and select the revision mentioned from the drop down the page just spins the waiting symbol. A co-worker started experiencing the same problem today as well and we would greatly like to be able to correct the situation and delete the bad revision.
2014/03/11
[ "https://Stackoverflow.com/questions/22331911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3407199/" ]
Don't know previous iOS but Setting **Build Active Architecture** Only to `YES` in **iOS 8** did the trick. ![enter image description here](https://i.stack.imgur.com/fHDfK.png)
I just changed the Debug from Yes to No, ``` Build Settings -> Architectures -> Build Active Architecture Only -> Debug -> NO. ``` This one fixed my error.![enter image description here](https://i.stack.imgur.com/vjSHD.png)
72,602,523
Here's what I got: ```c enum X { NONE = 0x00000000, FLAG_1 = 0x00000001, FLAG_2 = 0x00000002, FLAG_3 = 0x00000004, FLAG_4 = 0x00000008, FLAG_5 = 0x00000010, // ... FLAG_32 = 0x80000000 } ``` Is there a way to make "bit numbering" automatic so I could like insert a flag so all that goes next get "renumbered"? I'm just designing an API and I want to keep related flags together, ordered in a specific sequence. The problem is when I add something that goes in the middle I have to manually reassign all numbering that goes after the inserted item. Let's say in my example I want to add FLAG\_2A = 0x00000004, and FLAG\_3 should be 0x00000008 and so on. Is there a "full auto" way of doing it? OK, here's the first thing that comes to mind: ```c #include <stdio.h> enum { __FLAGS1_BASE = __COUNTER__ }; #define __FLAGS1_CT 1 << (__COUNTER__ - __FLAGS1_BASE - 1) typedef enum __TEST1 { FLAG1_0 = 0, FLAG1_1 = __FLAGS1_CT, FLAG1_2 = __FLAGS1_CT, FLAG1_3 = __FLAGS1_CT, FLAG1_4 = __FLAGS1_CT } TEST1; enum { __FLAGS2_BASE = __COUNTER__ }; #define __FLAGS2_CT 1 << (__COUNTER__ - __FLAGS2_BASE - 1) typedef enum __TEST2 { FLAG2_0 = 0, FLAG2_1 = __FLAGS2_CT, FLAG2_2 = __FLAGS2_CT, FLAG2_3 = __FLAGS2_CT, FLAG2_4 = __FLAGS2_CT } TEST2; int main() { printf("X = %u\n", FLAG2_3); // should output 4. return 0; } ``` Is it the only way, or is there something simpler than that?
2022/06/13
[ "https://Stackoverflow.com/questions/72602523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126537/" ]
Here is an alternative approach: ``` enum X_bits { B0, // replace Bx with actual flag name B1, B2, //... B32 }; #define FLAG(x) FLAG_##x = 1U << x enum X { NONE = 0, FLAG(B0), // will define FLAG_B0 with the appropriate value 0x1 FLAG(B1), FLAG(B2), //... FLAG(B32) }; ``` Actual bit numbers and bit marks are computed automatically.
My last take: flags.h header: ```c #pragma once #define BIT_FLAG_BASE(base) enum { base = __COUNTER__ + 1 } ///< Sets the base for the bit flag counter. #define BIT_FLAG(base) 1U << (__COUNTER__ - base) ///< Gets the next bit for the bit flag counter. ``` Used like this: ```c #include "flags.h" BIT_FLAG_BASE(MyFlag); enum MyFlags { B1 = BIT_FLAG(MyFlag), B2 = BIT_FLAG(MyFlag), // ... B31 = BIT_FLAG(MyFlag) }; ```
36,901,154
I'm writing test visualization program based on test results. I want to run jupyter notebook via terminal and generate html page to show it to user without showing the editable scripts to user. Can I do that? Or suggest the better way to show visualized test results.
2016/04/27
[ "https://Stackoverflow.com/questions/36901154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019664/" ]
Yes you can and it's quite easy and a built in feature ``` jupyter nbconvert --to html notebook.ipynb ``` That will generate a *notebook.html* file. Output [can be customized](http://nbconvert.readthedocs.io/en/latest/customizing.html). Also check out the slideshow functionality (View>Cell-Toolbar>Slideshow) which can also be used with nbconvert. Also the *notebook.ipynb* Jupyter file can be uploaded to Github where the current version gets rendered. Depending on what you want that information might be useful too Also check out line/cell magic. You can run bash commands directly in your jupyter cell like so: ``` %%bash convert graphviz/MyPic.jpg -resize 70% graphviz/MyPic_sm.jpg ```
I developed jupyter-runner (<https://github.com/omar-masmoudi/jupyter-runner>) which is a simple wrapper around "jupyter nbconvert". Several notebooks can be executed, with parameters, with parallel workers, input/output located in S3 and mail sending capabilities.
4,757,469
I'm using `Zend_Mail` and the following code to send my email messages. ``` $mail = new Zend_Mail('UTF-8'); $mail ->setBodyText($plainBody) ->setBodyHtml($htmlBody) ->setSubject($subject) ->setFrom(FROM_ADDR, FROM_NAME) ->addTo($email, $name ) ->addHeader(MY_HEADER, serialize( array( 'foo' => 'bar' ) ) ) ; ``` I need to check the **spam rating** for the prepared message and I'd like to do it using SpamAssassin. I thought to create a file with the contents and running something such as `exec('spamc $filename')`, but how to get the file content with the full MIME body? I noticed that there's a `_buildBody()` function in Zend\_Mail\_Abstract class (`library/Zend/Mail/Transport/Abstract.php`) that's return that, but that's a `protected` function. Thanks
2011/01/21
[ "https://Stackoverflow.com/questions/4757469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/474376/" ]
we finally ended up with the following solution (not exactly what Valentin suggested, but +1 for help!): The `ServiceReferences.ClientConfig` contains both binding and endpoint configurations like this: ``` <configuration> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="DefaultBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> <security mode="None" /> </binding> </basicHttpBinding> <customBinding> <binding name="SecureBinding"> <textMessageEncoding messageVersion="Soap12WSAddressing10" /> <httpsTransport maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" /> </binding> </customBinding> </bindings> <client> <endpoint address="/services/DefaultService.svc" binding="basicHttpBinding" bindingConfiguration="DefaultBinding" contract="OurNamespace.IOurContractAsync" name="DefaultEndpoint" /> <endpoint address="/services/DefaultService.svc" binding="customBinding" bindingConfiguration="SecureBinding" contract="OurNamespace.IOurContractAsync" name="SecureEndpoint" /> </client> </system.serviceModel> </configuration> ``` On initialization, we read the `App.Current.Host.Source.Scheme` Property. The Service client is generated by the `ChannelFactory`, the code is similar to this snippet: ``` protected string EndpointName { get { return (App.Current.Host.Source.Scheme == "https") ? "SecureEndpoint" : "DefaultEndpoint"; } } protected IOurContractAsync CreateInterface() { var channelFactory = ChannelFactory<IOurContractAsync>(EndpointName); return channelFactory.CreateChannel(); } ``` Hope this helps! Best regards, Thomas
I think there can be a number of ways one is to provide initparams to SL app from your web pages like > > param name="initParams" > value="Https=true" > > > for https page and false for html page. parse it inside SL and set up security mode for endpoint. You can create/edit endpoint proxy programmatically in your SL app. Another way could be setting transport behaviour based on link inside SL app without initparams (if begins with https ->transport else none) I believe once sl app is downloaded link should be not relative and this should be a working solution. You can make a factory method to create service proxy and put this setup proxy logic inside it , which would be simpler than completely removing this serviceconfig file. You would simply call ``` MyServiceClient client = Factory.MakeClient() ``` and I think its an elegant enough solution. in MakeClient you decide what transport security to use and its done.
49,694,326
I have this piece of code: ``` var dashboardPanel1 = Ext.create('Ext.Panel', { renderTo: Ext.getBody(), collapsible: true, margin: '0 0 50 0', layout: { type: 'hbox', align: 'stretch' }, defaults: { // applied to each contained panel bodyStyle: 'padding:20px', flex: 1, border: 0 }, title: '<span class="mytitle" id="keySettings"><a href="#" style="">Key settings</a></span>', items: [{ html: '<img src="https://i.imgur.com/n7gOYrE.png" style="width: 20px; height: 20px">', flex: 0.2 }, { html: 'Your key is active' }, { html: 'Expiring date: 27.04.2018' }, { html: '<img src="https://i.imgur.com/n7gOYrE.png" style="width: 20px; height: 20px">', flex: 0.2 }, { html: 'Your key is inactive' }, { html: 'Expiring date: 27.03.2018' }] }); ``` It is displaying a panel with some content. But how can I display this "Your key is inactive" and expiring date in a new row. If I choose `table` layout I cannot get the content `streched` (maximum width). So I have to use `hbox`. Any suggestion?
2018/04/06
[ "https://Stackoverflow.com/questions/49694326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4195212/" ]
You can always nest boxes. Depending on your requirements, either use vboxes inside a hbox: ![](https://i.imgur.com/x4dnGsL.png) or even hboxes inside a vbox inside a hbox: ![](https://i.imgur.com/0L8AwGo.png) Or maybe you can use a table layout and add a width to the [`tableAttrs`](http://docs.sencha.com/extjs/6.2.1/classic/Ext.layout.container.Table.html#cfg-tableAttrs) to make it stretch: ``` layout: 'table', tableAttrs: { width: '100%' } ```
I haven't verified this, its not a great answer either. It assumes this layout is static and not changing which I don't think is what you are looking for. But for fun here is an example I came up with that should emulate what your looking for. ```js var dashboardPanel1 = Ext.create('Ext.Panel', { renderTo: Ext.getBody(), collapsible: true, margin: '0 0 50 0', flex: 1, layout: { type: 'hbox', align: 'stretch' }, defaults: { flex: 0.5, border: 0 }, title: '<span class="mytitle" id="keySettings"><a href="#" style="">Key settings</a></span>', items: [{ xtype: 'container', layout: { 'type': 'vbox' }, items: [{ xtype: 'box', html: '<img src="https://i.imgur.com/n7gOYrE.png" style="width: 20px; height: 20px">', }, { xtype: 'container', layout: { type: 'hbox' }, defaults: { flex: 0.5 }, items: [{ xtype: 'box', html: 'Your key is active' }, { xtype: 'box', html: 'Expiring date: 27.04.2018' } ] } ] }, { xtype: 'container', layout: { 'type': 'vbox' }, items: [{ xtype: 'box', html: '<img src="https://i.imgur.com/n7gOYrE.png" style="width: 20px; height: 20px">', }, { xtype: 'container', layout: { type: 'hbox' }, defaults: { flex: 0.5 }, items: [{ xtype: 'box', html: 'Your key is active' }, { xtype: 'box', html: 'Expiring date: 27.04.2018' } ] } ] } }); ```
57,952,706
Has someone an idea how to solve the following problem? Take the numbers 1,...,100000 and permute them in some way. At first you can make a swap of two numbers. Then you have to compute how many rounds it would take to collect numbers in ascending order. You have to collect numbers by every round by going left to right. In how many ways you can swap two numbers at the beginning to collect numbers in ascending order with minimum number of rounds? For example, if numbers are from one to five and those at the beginning in order 3, 1, 5, 4, 2, then you can collect them in three rounds: On first round you collect 1, 2, on the second round 3, 4 and finally 5. But you can do one swap in three different ways to collect numbers in two rounds, namely ``` 3, 4, 5, 1, 2 3, 1, 4, 5, 2 3, 1, 2, 4, 5 ``` Five number sequence can be solved easily by brute force and I found an algorithm to collect 1000 numbers, but 100000 numbers needs maybe some kind of trick to compute fast how a specific swap at the beginning affects how many rounds it takes to collect numbers. Another example: Take 10 numbers in order [6, 1, 4, 10, 7, 2, 3, 9, 5, 8]. You can swap 4 and 9 to collect numbers in three rounds. But my code returns that there are 3 ways to make a swap. Where is my mistake? ``` from bisect import bisect_left, bisect_right from functools import cmp_to_key def longest_subsequence(seq, mode='strictly', order='increasing', key=None, index=False): bisect = bisect_left if mode.startswith('strict') else bisect_right # compute keys for comparison just once rank = seq if key is None else map(key, seq) if order == 'decreasing': rank = map(cmp_to_key(lambda x,y: 1 if x<y else 0 if x==y else -1), rank) rank = list(rank) if not rank: return [] lastoflength = [0] # end position of subsequence with given length predecessor = [None] # penultimate element of l.i.s. ending at given position for i in range(1, len(seq)): # seq[i] can extend a subsequence that ends with a lesser (or equal) element j = bisect([rank[k] for k in lastoflength], rank[i]) # update existing subsequence of length j or extend the longest try: lastoflength[j] = i except: lastoflength.append(i) # remember element before seq[i] in the subsequence predecessor.append(lastoflength[j-1] if j > 0 else None) # trace indices [p^n(i), ..., p(p(i)), p(i), i], where n=len(lastoflength)-1 def trace(i): if i is not None: yield from trace(predecessor[i]) yield i indices = trace(lastoflength[-1]) return list(indices) if index else [seq[i] for i in indices] def computerounds(lines): roundnumber = 1 for i in range(len(lines)-1): if lines[i] > lines[i + 1]: roundnumber += 1 return roundnumber if __name__ == '__main__': lines = [[3,1,5,4,2],[6, 1, 4, 10, 7, 2, 3, 9, 5, 8]] case = 1 ways_to_change = len(longest_subsequence(lines[case], mode='strictly', order='decreasing', key=None, index=False)) print(len(lines[case]), computerounds(lines[case]), ways_to_change) # Should return 10 3 1 ``` Effort 1: I guess the hardest part is to find a permutation that guarantees you collect the numbers with minimum number of moves. I also heard that Dilworth's theorem tells me that the minimal decomposition into ascending subsequences is equal to the size of the maximal descending subsequence. <https://artofproblemsolving.com/community/c163h1906044_an_algorithm_to_collect_numbers_in_ascending_order> Effort 2: I tried to run the code by jferard and solve the problem for the case `junar9.in` found in `https://www.ohjelmointiputka.net/tiedostot/junar.zip`. The file contains fir the number of numbers in the first line and then the rest of the lines gives the numbers as in original order. It looks it takes too much memory. The output was in Linux Mint: ``` (base) jaakko@jaakko-Aspire-E1-572:~/.config/spyder-py3$ python3 temp.py Killed ``` Here is the code from `temp.py` ``` # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import os.path import requests import zipfile import warnings def invert(L): M = [None] + [0 for _ in range(len(L))] for i, k in enumerate(L): M[k] = i return M def perform_data(read_data): s = "" for i in range(len(read_data)): if read_data[i].isnumeric(): s += read_data[i] else: s += " " s = s[:-1] s = s.split(" ") tmp = [] for i in range(1, len(s)): if s[i] != '': tmp.append(int(s[i])) return tmp def download_zipfile(url): if not os.path.isfile('/tmp/junar.zip'): with open('/tmp/junar.zip', 'wb') as out: out.write(requests.get(url).content) def read_zipfile_item(filename): with zipfile.ZipFile('/tmp/junar.zip') as zip_file: with zip_file.open(filename) as f: return f.read().decode('utf8') def generate_original_rounds(A): B =[0]*(len(A)-1) print(A) roundno = 1 for i in range(1,len(A)): if A.index(i) < A.index(i+1): B[i-1] = roundno else: roundno += 1 B[i-1] = roundno print(roundno) return B def classify_moves(L): M = invert(L) N = len(L) good_moves, bad_moves = [None], [None] for k in range(1, N+1): good_move, bad_move = find_moves(k, L, M, N) good_moves.append(good_move) bad_moves.append(bad_move) return good_moves, bad_moves def find_moves(k, L, M, N): def in_range(a, b): return set(L[j] for j in range(a, b)) good_move = set() bad_move = set() if k == 1: if M[k+1] < M[k]: good_move |= in_range(0, M[k+1]+1) else: # M[k] < M[k+1] bad_move |= in_range(M[k+1], N) elif k == N: if M[k] < M[k-1]: good_move |= in_range(M[k-1], N) else: # M[k-1] < M[k] bad_move |= in_range(0, M[k-1]+1) elif M[k-1] < M[k+1]: if M[k] < M[k-1]: good_move |= in_range(M[k-1], M[k+1]) elif M[k+1] < M[k]: good_move |= in_range(M[k-1]+1, M[k+1]+1) if M[k-1] < M[k]: bad_move |= in_range(0, M[k-1]+1) if M[k] < M[k+1]: bad_move |= in_range(M[k+1], N) else: # M[k+1] < M[k-1] if M[k+1] < M[k] < M[k-1]: good_move |= in_range(0, M[k+1]+1) | in_range(M[k-1], N) elif M[k] < M[k+1]: bad_move |= in_range(M[k+1], M[k-1]) else: # M[k-1] < M[k]: bad_move |= in_range(M[k+1]+1, M[k-1]+1) return good_move, bad_move def collate_moves_aux(L): good_moves, bad_moves = classify_moves(L) N = len(L) swaps_by_removed = {} for i in range(1, N+1): for j in range(i+1, N+1): removed = 0 if j in good_moves[i]: if i in good_moves[j]: removed = 2 elif i not in bad_moves[j]: removed = 1 elif j not in bad_moves[i] and i in good_moves[j]: removed = 1 if abs(i-j) <= 1: # don't count twice removed -= 1 if removed > 0: swaps_by_removed.setdefault(removed, []).append((i,j)) return swaps_by_removed def collate_moves(L): swaps_by_removed = collate_moves_aux(L) if __name__ == '__main__': # Testing url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip' download_zipfile(url=url) rawdata = read_zipfile_item('junar9.in') data = perform_data(rawdata) numbers = data A = collate_moves(numbers) print(A) ``` Idea 1: Is it helpful to compute permutation inversions somehow, <http://mathworld.wolfram.com/PermutationInversion.html> ? There are some algorithms to compute all permutation inversions in <https://www.geeksforgeeks.org/counting-inversions/> but does this helps solve the problem? I think it is somehow related to compute the permutation inversions of the form (n,n+1). Effort 3: I tried to apply the idea from jferard's answer. I think it computest wrong answer how many rounds it takes to collect numbers `[6, 1, 4, 10, 7, 2, 3, 9, 5, 8]`. It returns 4 but it takes five rounds, first 1, 2, 3, second 4, 5, third 6, 7, 8, fourth 9, and fifth 10. ``` def compute_original_rounds(M): c = 1 for i in range(2, len(M)): if M[i] < M[i-1]: c += 1 return c if __name__ == '__main__': lines = [[3,1,5,4,2],[6, 1, 4, 10, 7, 2, 3, 9, 5, 8]] verygoods = 0 lista = lines[1] best = 0 drops = [0,0,0] for k in range(2,len(lista)): a = lista.index(k-1)<lista.index(k) b = lista.index(k)<lista.index(k+1) c = lista.index(k-1)<lista.index(k+1) if a and b: print("Zero inversions") drops[0] += 1 if (not a and c) or (c and not b) or (b and not c) or (a and not c): print("One inversion") best = max(best,1) drops[1] += 1 if not b and not a: print("Two inversions") best = max(best,2) drops[2] += 1 ways = drops[2] if ways == 0: ways = drops[1] if ways == 0: ways = drops[0] original_rounds = compute_original_rounds(lista) print(original_rounds) print(len(lista),original_rounds - best, ways) ```
2019/09/16
[ "https://Stackoverflow.com/questions/57952706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479273/" ]
It's easy, have a function to fetch Prometheus counter value ``` import ( "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/log" ) func GetCounterValue(metric *prometheus.CounterVec) float64 { var m = &dto.Metric{} if err := metric.WithLabelValues("label1", "label2").Write(m); err != nil { log.Error(err) return 0 } return m.Counter.GetValue() } ```
It is possible to read the value of a counter (or any metric) in the official Golang implementation. I'm not sure when it was added. This works for me for a simple metric with no vector: ``` func getMetricValue(col prometheus.Collector) float64 { c := make(chan prometheus.Metric, 1) // 1 for metric with no vector col.Collect(c) // collect current metric value into the channel m := dto.Metric{} _ = (<-c).Write(&m) // read metric value from the channel return *m.Counter.Value } ``` **Update:** here's a more general version that works with vectors and on histograms... ``` // GetMetricValue returns the sum of the Counter metrics associated with the Collector // e.g. the metric for a non-vector, or the sum of the metrics for vector labels. // If the metric is a Histogram then number of samples is used. func GetMetricValue(col prometheus.Collector) float64 { var total float64 collect(col, func(m dto.Metric) { if h := m.GetHistogram(); h != nil { total += float64(h.GetSampleCount()) } else { total += m.GetCounter().GetValue() } }) return total } // collect calls the function for each metric associated with the Collector func collect(col prometheus.Collector, do func(dto.Metric)) { c := make(chan prometheus.Metric) go func(c chan prometheus.Metric) { col.Collect(c) close(c) }(c) for x := range c { // eg range across distinct label vector values m := dto.Metric{} _ = x.Write(&m) do(m) } } ```
35,617,499
how to use java script validation in after using the clone function in a form how can do separate validation in each row in java script i used in clone for add more function but i can't do validation for every row.how is this ? help me ```js var i = 0; function cloneRow() { var row = document.getElementById("clone"); var table = document.getElementById("data"); var selectIndex = 1; var clone = row.cloneNode(true); table.appendChild(clone); clone.setAttribute("style", ""); } function deleteRow(btn) { var result = confirm("Do you Want to delete this ?"); if (result) { var row = btn.parentNode.parentNode; row.parentNode.removeChild(row); } } ``` ```html <div class="row"> <div class="col-sm-12"> <div class="col-sm-7"></div> <div class="col-sm-2"> <button type="button"class="btn btn-primary default btn-xs" onclick="cloneRow()" >add more...</button> </div> </div> </div><br><br> <div class="row" id ="close"> <div class="col-sm-4"></div> <div class='col-sm-4'> <Form id="NAME_VALUE" method="POST" > <table class="table-striped" > <tbody id="data"> <tr id ="clone" style="display:none;"> <td> Name :<input type="text" name="INPUT_NAME" style="width:100px;" id="name" name="INPUT_NAME"> </td> <td> Value :<input type="text" name="INPUT_VALUE" style="width:100px;" id="value" name="INPUT_VALUE"> </td> <td> <button type="button"class="btn btn-primary default btn-xs" name ="delete" style="margin-left: 5px;" onclick="deleteRow(this); return false;"> <span class="glyphicon glyphicon-remove-circle" style="text-align:center" ></span> </button> </td> </tr> <tr> <td> Name :<input type="text" name="INPUT_NAME" style="width:100px;" id="name" name="INPUT_NAME"> </td> <td> Value :<input type="text" name="INPUT_VALUE" style="width:100px;" id="value" name="INPUT_VALUE"> </td> <td> <button type="button"class="btn btn-primary default btn-xs" name ="delete" style="margin-left: 5px;" onclick="deleteRow(this); return false;"> <span class="glyphicon glyphicon-remove-circle" style="text-align:center" ></span></button> </td> </tr> </tbody> </table><br> <button type="button"class="btn btn-primary default btn-xs" style="margin-left: 5px;" onclick="submit_login(); return false;"> save.</button> </Form> </div> </div> ``` [![I expected this type of output](https://i.stack.imgur.com/kDblj.png)](https://i.stack.imgur.com/kDblj.png) I lioke to create this type of validation every row or tr so please help me..
2016/02/25
[ "https://Stackoverflow.com/questions/35617499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945137/" ]
After trying many ways I finally made it work. First I removed all my previous installation by * `sudo apt-get remove --purge wkhtmltopdf` * `sudo apt-get autoremove` Then I opened wkhtmltopdf.org and navigated into their Downloads > Archive. In Archive section I downloaded 0.12.1 .deb version by * `wget <copy the link from website for the.deb file and paste it in terminal here>`. * `sudo dpkg -i <package name>` * `sudo cp /usr/local/bin/wkhtmltopdf /usr/bin` This is because odoo looks for wkhtmltopdf in `/usr/bin` directory otherwise gives IOError. I also set my `webkit_path` parameter in Odoo System Parameters to `/usr/bin`. Thats it. Hope this helps
I was facing same issue with wkhtmltopdf 0.12.4 installed new version of wkhtmltopdf 0.12.6-1 follow below commands to install wkhtmltopdf 0.12.6-1 ``` wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox-0.12.6-1.centos7.x86_64.rpm yum localinstall wkhtmltox-0.12.6-1.centos7.x86_64.rpm #centos specific command ```
4,411,880
I am using Entity Framework and Linq to Entities with the MySQL ADO.Net connector to access a MySQL database. There are two tables Requests and Submissions with a one to many relationship from Requests to Submissions. Accordingly, the Submissions table contains a RequestId column that is has a foreign key dependency on Requests. I need to retrieve all requests where its submissions contain a certain value. In LINQ I can do it one of two ways: ``` var r1 = foo.Submissions.Where(s => s.FieldName == "foo" && s.FieldValue == "bar").Select(s => s.Request).Distinct(); var r2 = foo.Requests.Where(r => r.Submissions.Any(s => s.FieldName == "foo" && s.FieldValue == "bar")); ``` which evaluates to ``` SELECT `Distinct1`.* FROM (SELECT DISTINCT `Extent2`.* FROM `Submissions` AS `Extent1` INNER JOIN `Requests` AS `Extent2` ON `Extent1`.`RequestId` = `Extent2`.`RequestId` WHERE ("foo" = `Extent1`.`FieldName`) AND ("bar" = `Extent1`.`FieldValue`)) AS `Distinct1` SELECT `Extent1`.* FROM `Requests` AS `Extent1` WHERE EXISTS (SELECT 1 AS `C1` FROM `Submissions` AS `Extent2` WHERE (`Extent1`.`RequestId` = `Extent2`.`RequestId`) AND ((@gp1 = `Extent2`.`FieldName`) AND (@gp2 = `Extent2`.`FieldValue`))) ``` Now the first style of query uses an INNER JOIN...is that now less efficient than the 2nd choice?
2010/12/10
[ "https://Stackoverflow.com/questions/4411880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/89593/" ]
You should be able to determine this yourself, by looking at the query plans generated for both queries in SSMS. Look specifically for any scans being done instead of seeks. Then, you can analyze both queries in SQL Profiler to see which generates fewer overall reads, and consumes less CPU cycles.
The first approach potentially involves a sort (distinct) which suggests that the EXISTS alternative will perform better when the nr of submissions for each request is large. What does the wall clock tell you?
1,821,142
An example from my textbook says the following: Five persons entered the lift cabin on the ground floor of an 8 floor house. Suppose each of them can leave the cabin independently at any floor beginning with the first. Find the total number of ways in which each of the five persons can leave the cabin at any one of the 7 floors. It provides the solution as: $$7\*7\*7\*7\*7 = 7^5$$ I would assume that since there's 5 people and 7 floors.. it would be the same as 7 questions with 5 choices which is: $$5\*5\*5\*5\*5\*5\*5 = 5^7$$ Am I wrong? Can someone explain? Thank you!
2016/06/10
[ "https://math.stackexchange.com/questions/1821142", "https://math.stackexchange.com", "https://math.stackexchange.com/users/342628/" ]
### Wrong Solution: The problem (as you guessed) lies within the following statement: > > I would assume that since there's 5 people and 7 floors.. it would be > the same as 7 questions with 5 choices > > > One issue with this statement is that "7 questions with 5 choices" implies only one of those choices can be correct (for each question), this would be equivalent to saying that only one person can get off on any floor (which doesn't really make sense!). Another problem is that if each question has 5 choices a), b), c), d), e), then the answer to all the questions *could be* a). However, in our case this would be equivalent to saying that person a) got off on all 7 floors (which also doesn't make sense!). ### Real Solution: The solution to the problem is that there are 5 people and each of these people can be assigned to any of 7 floors. In other words, each person can take one (and only one) of 7 values. You can think of this as 5 questions each with 7 possible answers. The answer is then \begin{align\*} {\text{# of Possible Arrangements}}&=(\text{# of Options for Person 1})\times\cdots\times (\text{# of Options for Person 5})\\ &={\underbrace{7\times\cdots\times7}\_{5 \text{ times}}}=7^5. \end{align\*}
The answer is definitely $7^5$. Numbering your people arbitrarily, the first person can choose any of 7 floors to exit, as can the 2nd, as can the 3rd and so on. $7\times7\times7\times7\times7=7^5$
175,309
I have a table with a sequence of data. This data is used in a graph. There are holes in this data that I want to fill in with smoothed out numbers. Take this table for example: ![sample table](https://i.stack.imgur.com/kvN31.jpg) In the example above, there are 3 gaps between 93 and 68 which I want to fill in. The sequence should go 93, 86.75, 80.5, 74.25 and then 68. What kind of formula could I use to auto-calculate the numbers in between? **Edit:** the gaps could be any number of rows, they could be going up or down.
2010/08/12
[ "https://superuser.com/questions/175309", "https://superuser.com", "https://superuser.com/users/11045/" ]
With this VBA sub you can select the cells you want to interpolate, then activate the macro. I used a button, but you'll probably want to workup a shortcut key combo. ``` Private Sub InterpolateGap() Dim Gap As Range Dim GapRows As Integer, i As Integer, Increment As Integer Set Gap = Selection If Not Gap Is Nothing Then GapRows = Gap.Rows.Count Increment = (Gap.Cells(1, 1).Offset(-1, 0) - _ Gap.Cells(1, 1).Offset(GapRows, 0)) / GapRows For i = 1 To GapRows Gap.Rows(i).Cells(1, 1) = _ Gap.Rows(i).Cells(1, 1).Offset(-1, 0) - Increment Next i End If End Sub ```
It's going to be hard to do when you don't have a steady upward or downward climb. My best advice is simply highlighting the numbers you have and then clicking on the box in the bottom right hand corner of the highlighted area, and dragging in down to let Excel do its best job at guessing. ![alt text](https://i.stack.imgur.com/mdbOi.png)
687,893
I'm making a very simple html webpage consisting only of text. How can I narrow the single column to make it easier for the reader to read? I would like the body of text to be roughly in the center of the page and left aligned, with margins of white space (roughly equal) to left and right.
2009/03/26
[ "https://Stackoverflow.com/questions/687893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75654/" ]
Using CSS... ``` body { margin:0 auto; width:600px; } ```
The width advice given by others is the key. From the usability standpoint, you definitely want to ensure that you don't have multiple columns Newspaper-style - people are just not used to reading web pages in this way. It's OK for unrelated content though.
43,752,262
I am trying to deploy add a custom script extension to an Azure VM using an ARM template, and I want to have it download files from a storage account using a SAS token. Here is the template (simplified): ``` { "name": "CustomScriptExtension" "type": "Microsoft.Compute/virtualMachines/extensions", "location": "eastus", "properties": { "publisher": "Microsoft.Compute", "type": "CustomScriptExtension", "typeHandlerVersion": "1.8", "settings": { "fileUris": [ "https://{storage-account}.blob.core.windows.net/installers/{installer}.msi?sv=2015-04-05&sig={signature}&st=2017-05-03T05:18:28Z&se=2017-05-10T05:18:28Z&srt=o&ss=b&sp=r" ], "commandToExecute": "start /wait msiexec /package {installer}.msi /quiet" }, } } ``` And deploying it results in this error: ``` { "name": "CustomScriptExtension", "type": "Microsoft.Compute.CustomScriptExtension", "typeHandlerVersion": "1.8", "statuses": [ { "code": "ProvisioningState/failed/3", "level": "Error", "displayStatus": "Provisioning failed", "message": "Failed to download all specified files. Exiting. Error Message: Missing mandatory parameters for valid Shared Access Signature" } ] } ``` If I hit the URL with the SAS token directly it pulls down the file just fine so I know the SAS token is correct. Does the custom script extension not support URLs with SAS tokens?
2017/05/03
[ "https://Stackoverflow.com/questions/43752262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1806514/" ]
I figured it out, this must be a bug in the custom script extension which causes it to not support storage account level SAS tokens. If I add `&sr=b` on the the end of the SAS token (which isn't part of the storage account level SAS token spec) it starts working. I found this info here: <https://azureoperations.wordpress.com/2016/11/21/first-blog-post/>
Currently, there is support for SAS token in VM Extension
214,119
After spending over one year working on a social network project for me using [WordPress](http://en.wikipedia.org/wiki/WordPress) and [BuddyPress](http://en.wikipedia.org/wiki/BuddyPress), my programmer has disappeared, even though he got paid every single week, for the whole period. Yes, he's not dead as I used an email tracker to confirm and see he opens my emails, but he doesn't respond. It seems he got another job. I wonder why he just couldn't say so. And I even paid him an advance salary for work he hasn't done. The problem is that I never asked for full documentation for most of the functions he coded in. And there were MANY functions for this 1+ year period, and some of them have bugs that he still didn't fix. Now it seems all confusing. What's the first thing I should do now? How do I proceed? I guess the first thing to do will be to get another programmer, but I want to start on the right foot by having all the current code documented so that any programmer can work on all the functions without issues. Is that the first thing I should do? If yes, how do I go about it? What's the standard type of documentation required for something like this? Can I get a programmer that will just do the documentation for all the codes and fix the bugs or is documentation not really important? Also, do you think getting another "individual" programmer is better or get a company that has programmers working for them, so that if the programmer assigned to my project disappears, another can replace him, without my involvement? I feel this is the approach I should have taken in the beginning.
2013/10/11
[ "https://softwareengineering.stackexchange.com/questions/214119", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/104611/" ]
This is a strange situation, and I'm quite sure you're not telling the whole story. I worked with many people, some of who left for various reasons (me being their colleague), but don't try to tell us that everything was super good and one day just no contact. But that's not problem. At least not anymore; you should learn from your mistake and try not to repeat it in the future. And yes, I'm strongly suggesting that 50% is your fault of him/her leaving. Now about solving the current problem: 1. Try to contact your programmer. He reads your email - offer him money for documentation/fixing the most crucial bugs. No one else will be able to fix those faster than him. Doesn't it work? Try to find where he works, contact that company and tell your story. A good company will not hire a person who could do the same for them. At least they'll tell him to finish the documentation for you. *NOTE: you don't want that person back, you just need finished documentation* 2. Be prepared that your one year worth of work is going to be void. He might have fled when you asked for results and he knew he couldn't deliver. It's possible that the code is full of hacks, dirty implementation and overall poor quality. Even if he comes back - he probably won't have the skills or even time to do it right. 3. Look for another person. He needs to know the same technologies (programming language, frameworks, etc.). If the code quality is good - he could continue, if not, he'll be able to refactor it. Yes, refactoring takes time with no new feature implementation, but it makes code maintainable and that's what you need. Plus, a person who can refactor bad code is a really good programmer, hold on to him/her. *NOTE: it's silly to pay money up front. The whole idea of salary is to pay for job done. Not for a promise made :)* 4. Make lists. It's in your best interests to have a plan. A technical specification that once read will allow the new programmer to understand the job and milestones. Have at least three important documents: * Overall description of the project - a document that will allow even a non-programmer to know what is the project about. * Timeline - what part and when do you expect to be ready? What is already done? * Technical specification - this is a long one. It is THE document that a programmer wants to read. Separate it into logical parts and describe in as much detail as you can the features and workflow of that specific part. Working with companies isn't really that good; your chances won't get better. And you'll overpay 10 times if you hire only one programmer. If you have a small team, let's say 3-5 people, just hire a programmer willing to be a team lead. He'll do a much better job managing the team.
So, your only programmer was [hit by a bus](https://workplace.stackexchange.com/questions/9128/how-can-i-prepare-for-getting-hit-by-a-bus), and you need replacement now. You could try to sue your former programmer, based on yout contract, or find out what's wrong with him. Assuming that he won't come back, this won't help you. * You want to get your product done, so search for a programmer who has experience in maintaining and developing existing systems. I would not focus on telling your programmer what to do in what order. Make sure you hire someone professional, who writes documentation and unit tests whenever necessary. * From your side, you can make sure that the new programmer has [everything needed for his work](http://www.joelonsoftware.com/articles/fog0000000043.html): Requirement specifications, a powerful working machine, and so on. You want a professional programmer, so provide him a professional working environment. Also, think about hiring a second developer for making this kind of difficult situations easier in the future. A tester would be useful for quality assurance as well.
4,586,894
Stumbled on some old code that is throwing and empty catching some cast exceptions (about 20 per trip :( ) What if any is the performance hit were taking due to this? Should I be worried about this or is the overhead simply in the try / catch Surprisingly lacking information on the topic of exception performance with C#. Thanks, from yours truly.
2011/01/03
[ "https://Stackoverflow.com/questions/4586894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/443688/" ]
Exceptions are expensive, performance-wise. Last time I measured these, they were taking **about a full millisecond** to throw and catch each exception. Avoid using exceptions as a flow control mechanism.
If you haven't encountered any performance problem and this is the only way you have to do that algorithm continue to use this method. Maybe before trying to cast you could see with some `if` clauses if you could do the cast.
25,678
Medicare, Medicaid, and Social Security are called "incentives" programs by some Republicans. These plans were put in place to help those disadvantage and many all ready pay federal taxes. Social Security was meant to be a sort of "retirement" plan if you will. People pay into it and once reach a certain age, you receive what you put in (in theory) Billions have been taken out of Social Security and allocated for other spending (even though it was never meant to be touched). [Now the new tax plan purposed by the GOP Under Capitol Hill’s byzantine budget](https://www.usatoday.com/story/news/politics/2017/10/19/senate-tax-budget-president-trump/782873001/) rules, the nonbinding budget resolution is supposed to lay out a long-term fiscal framework for the government. This year’s measure calls for $473 billion in cuts from Medicare over 10 years and more than $1 trillion from Medicaid. All told, Senate Republicans would cut spending by more than $5 trillion over a decade, though they don’t attempt to spell out where the cuts would come from. Even so, the measure doesn’t promise to balance the budget, projecting deficits that would never drop below $400 billion. Why than do Republicans continue to cut these programs? Do they want all three of these programs eliminated completely?
2017/10/25
[ "https://politics.stackexchange.com/questions/25678", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/9016/" ]
In addition to the answers above, I should point out that they do not "continuously" go after cuts in those programs. Social Security and Medicare are very dangerous thing to go after politically. That's why the cuts you mention aren't specified. They want to keep any cuts they do make on the low-low and many times in the past, they've been unwilling to cut those programs at all, and they've focuses their cuts on discretionary spending. The republicans have, in the past, been more comfortable when a democratic president has made those cuts. Bill Clinton agreed to some cuts when he reached a compromise with congress after their failed government shutdown. Obama made some (If I remember right) small cuts to medicare to help pay for Obamacare and the Republicans took advantage of that, appealing to AARP to vote republican and they had big wins in 2010 as a result. They might be talking about 470 billion in cuts over 10 year, but if a democrat cuts those same programs by just a few billion - they will shout about that from every rooftop. In the long run, with the large number of baby boomer retirees and relatively low economic growth rates, and steadily increasing national debt, some cuts to the mandatory programs may be unavoidable. Republicans, if they had their wish, would cut taxes and cut entitlement programs (social security, medicare, medicaid). Democrats, if they had their wish would increase taxes on the top earners and try to maintain much more of those programs. Precisely what get done is part balancing act, part slight of hand, part blame the other party and part, tiptoe around the issues to not lose votes. It's a pretty ineffective system that encourages deficit spending. I think it's much more accurate to say that Republicans WANT to cut those programs but they don't always TRY to due to fear of alienating the AARP voting block. They might be discussing cuts now, but lets wait and see what they pass first. On your last sentence, I don't believe they want to eliminate those programs completely (Maybe Rand Paul does), but they do want to measurably reduce them over time.
I don't think that Republicans necessarily want to cut those programs. However, those programs are a mainstay of the Democrats (it's how they buy votes). So, the Republicans make threats to cut those programs so they can force the Democrats to concede other points in negotiation. This is the same reason that the Democrats always go after gun rights.
27,917,304
how can i look, what i saved in the isloated storage untill now? i try to make a app where user can save more lists. And choose after that which List he wants to have and Display that.
2015/01/13
[ "https://Stackoverflow.com/questions/27917304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4448320/" ]
There's a very handy tool for viewing the files currently in the isolated storage. Here's a [link](http://msdn.microsoft.com/en-us/library/windows/apps/hh286408(v=vs.105).aspx). However, if you're planning on doing this at runtime, then I would suggest checking the following tutorial from MSDN, [here](http://msdn.microsoft.com/en-us/library/zd5e2z84(v=vs.110).aspx) This method in particular may be what you are after. ``` public static List<String> GetAllFiles(string pattern, IsolatedStorageFile storeFile) { // Get the root and file portions of the search string. string fileString = Path.GetFileName(pattern); List<String> fileList = new List<String>(storeFile.GetFileNames(pattern)); // Loop through the subdirectories, collect matches, // and make separators consistent. foreach (string directory in GetAllDirectories("*", storeFile)) { foreach (string file in storeFile.GetFileNames(directory + "/" + fileString)) { fileList.Add((directory + "/" + file)); } } return fileList; } ```
Try this Application. This is very helpful as it integrates with your device and emulator and you get the Complete Storage Access of How Data is stored in stored in your Emulator or Device and is very flexible as you can Manipulate the storage Contents in Runtime. [windows Phone Power Tools](http://wptools.codeplex.com/) Step1: Link you .xap package in debug or release mode ![enter image description here](https://i.stack.imgur.com/024Vk.png) Step2: Run the Project and you can check the contents here ![enter image description here](https://i.stack.imgur.com/WZFRn.png)
2,873,178
An example of what I am talking about is indicating multiplication by writing $$ab\equiv{a}\times{b},$$ in traditional real number algebra. I was writing some notes involving matrix multiplication. Previously in these notes I had specified that placing two tensor symbols next to each other indicates a *direct product*. For example: Let $\mathfrak{A}=\left\{A\_{ij}\right\}\_{n\times{n}}$ and $\mathfrak{v}=\left\{v\_{k}\right\}\_{n\times{1}}.$ So in the context of my definition: $$\mathfrak{A}\mathfrak{v}\equiv{\mathfrak{A}\otimes\mathfrak{v}}\equiv{\left\{A\_{ij}v\_{k}\right\}\_{n\times{n}\times{n}}}.$$ But when working with matrices in linear algebra it is common practice to use $$\mathfrak{A}\mathfrak{v}\equiv{\left\{\sum\_k A\_{ik}v\_{k}\right\}\_{n\times{1}}}.$$ Well, I want to use the latter definition in one example. When I tried to state that placing the symbols next to each other without any operator symbol between them means *matrix multiplication* in this example, I found that I have no formal terminology for doing that. I started to say "the juxtaposition of symbols...", but when I looked up the work *juxtapose*, I realized it's not what I mean. It connotes an intent to compare and contrast. Is there a formal term for implying an operation by placing two symbols next to each other?
2018/08/05
[ "https://math.stackexchange.com/questions/2873178", "https://math.stackexchange.com", "https://math.stackexchange.com/users/342834/" ]
In abstract algebra, when words are formed using letters from an alphabet, the operation of joining two words together with no symbol in-between is called **concatenation**. Now I wouldn't recommend that in a case where the left and right sides are mathematical objects of a different nature. In that case, it seems that **juxtaposition** is fine - I have seen it used at least a couple of times, and I don't feel that it carries a connotation in a mathematical context. And if you want to be extra clear, you can add some words the first time you use it, in a footnote for instance.
The third term I have heard for this is *apposition*, as in "two symbols written in apposition". (However, I concur with the other answers that *juxtaposition* is perfectly understandable.)
32,999,868
How do I select the strings in the randomImage.images array from my randomImage.imagePicker method? ``` (function() { var randomImage = { images : [ 'http://placehold.it/100x100', 'http://placehold.it/200x200', 'http://placehold.it/300x300', 'http://placehold.it/400x400' ],//images Array imagePicker : function () { return console.log(randomImage.images[2]); }()//imagePicker Method }//randomImage Object })() ``` I get the following error in the console: > > Uncaught TypeError: Cannot read property 'images' of undefined > > >
2015/10/07
[ "https://Stackoverflow.com/questions/32999868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4338703/" ]
Or if you want to specify the index of the randomImage you want to get: ``` imagePicker : function (idx) { return randomImage.images[idx]; } ``` `randomImage.imagePicker(1)` will return `http://placehold.it/200x200`
Provided you just want it to return a random image from the `images` array: [DEMO](http://jsfiddle.net/ncpqe3zo/) ``` imagePicker : function () { var index = Math.floor(Math.random() * randomImage.images.length); return randomImage.images[index]; } ``` Returning just a specific image can be done using the index: ``` imagePicker : function () { // index 0 returns 'http://placehold.it/100x100' return randomImage.images[0]; } ```
9,105,511
So is it just the shovel operator that modifies the original string? Why does this work, it looks like: ``` hi = original_string ``` is acting like some kind of a pointer? Can I get some insight as to when and how and why this behaves like this? ``` def test_the_shovel_operator_modifies_the_original_string original_string = "Hello, " hi = original_string there = "World" hi << there assert_equal "Hello, World", original_string # THINK ABOUT IT: # # Ruby programmers tend to favor the shovel operator (<<) over the # plus equals operator (+=) when building up strings. Why? end ```
2012/02/02
[ "https://Stackoverflow.com/questions/9105511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1109313/" ]
In ruby, everything is a reference. If you do `foo = bar`, now `foo` and `bar` are two names for the same object. If, however, you do `foo = foo + bar` (or, equivalently, `foo += bar`), `foo` now refers to a new object: one that is the result of the computation `foo + bar`.
> > is acting like some kind of a pointer > > > It's called *reference semantics*. As in Python, Ruby's variables refer to values, rather than containing them. This is normal for dynamically typed languages, as it's much easier to implement the "values have type, variables don't" logic when the variable is always just a reference instead of something that has to magically change size to hold different types of values. As for the actual koan, see [Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby?](https://stackoverflow.com/questions/4684446/why-is-the-shovel-operator-preferred-over-plus-equals-when-building-a) .
19,092,598
i am running queries on a table that has thousands of rows: ``` $sql="select * from call_history where extension_number = '0536*002' and flow = 'in' and DATE(initiated) = '".date("Y-m-d")."' "; ``` and its taking forever to return results. The SQL itself is ``` select * from call_history where extension_number = '0536*002' and flow = 'in' and DATE(initiated) = 'dateFromYourPHPcode' ``` is there any way to make it run faster? should i put the where `DATE(initiated) = '".date("Y-m-d")."'` before the `extension_number` where clause? or should i select all rows where `DATE(initiated) = '".date("Y-m-d")."'` and put that in a while loop then run all my other queries `(where extension_number = ...)` whthin the while loop?
2013/09/30
[ "https://Stackoverflow.com/questions/19092598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2710234/" ]
Here are some suggestions: 1) Replace `SELECT *` by the only fields you want. 2) Add indexing on the table fields you want as output. 3) Avoid running queries in loops. This causes multiple requests to SQL server. 4) Fetch all the data at once. 5) Apply `LIMIT` tag as and when required. Don't select all the records. 6) Fire two different queries: one for counting total number of records and other for fetching number of records per page (e.g. 10, 20, 50, etc...) 7) If applicable, create Database Views and get data from them instead of tables. Thanks
You should add index to your table. This way MySql will fetch faster. I have not tested but command should be like this: ``` ALTER TABLE `call_history ` ADD INDEX `callhistory` (`extension_number`,`flow`,`extension_number`,`DATE(initiated)`); ```
45,312,636
I am posting a variable to a PHP process in an attempt to find a file in a directory. The problem is the filename is much longer than what the user will submit. They will only submit a voyage number that looks like this: ``` 222INE ``` Whereas the filename will look like this: ``` CMDU-YMUNICORN-222INE-23082016.txt ``` So I need PHP to be able to look into the directory, find the file that has the matching voyage number, and confirm it's existence (I really need to be able to download said file, but that'll be for a different question if I can't figure that out). Anyway, so here is the PHP process that takes a posted variable: ``` <?php if($_POST['voyage'] == true) { $voyage = mysqli_real_escape_string($dbc, $_POST['voyage']); $files = glob("backup/................."); // <-this is where the voyage will go // it should look like this // $files = glob("backup/xxxx-xxxxxxxx-222INE-xxxx.txt"); if(count($files) > 0) { foreach($files as $file) { $info = pathinfo($file); echo "File found: " . $info["name"]; } } else { echo "File doesn't exist"; } } ?> ``` The filename will always begin with CMDU. The second part may vary. Then the voyage number. The the date, followed by txt.
2017/07/25
[ "https://Stackoverflow.com/questions/45312636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4262571/" ]
Ok, first, you must do a directory listing ``` <?php if($_POST['voyage'] == true) { $voyage = $_POST['voyage']; //in this case is not important to escape $files = scandir("backup"); // <-this is where the voyage will go ***HERE YOU USE DIR LISTING*** unset($files[0], $files[1]) // remove ".." and "."; if(count($files) > 0) { $fileFound = false; foreach($files as $file) { if((preg_match("/$voyage/", $file) === 1)){ echo "File found: $file \n"; $fileFound = true; } } if(!$fileFound) die("File $voyage doesn't exist"); // after loop ends, if no file print "no File" } else { echo "No files in backup folder"; //if count === 0 means no files in folder } } ?> ```
I'd use the scandir function to get a list of files in the backup directory and filter it down to the appropriate file. ``` $voyageFiles = array_filter( scandir( "backup" ), function($var) use ($voyage) { // expand this regexp as needed. return preg_match("/$voyage/", $var ); } ) $voyageFile = array_pop( $voyageFiles ); ```
66,741
The first part of code is for me very unreadable. I tried to write in another way but I'm open to your suggestion! ``` return ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value != null && ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)) ? "" : " "; //Looks in a dictionary for a key called parameterName ModelState modelState = ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value; //If I could find it I look for any error associatd to that and I return it as a single string return modelState != null && modelState.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)) ? "" : " "; ```
2014/10/15
[ "https://codereview.stackexchange.com/questions/66741", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/34992/" ]
Not only is this difficult to read, it's also *inefficient*. Cache your duplicate LINQ lookup to save time and make it more readable. As for using the ternary operator, that's up to you, but I prefer to use a full if statement when the line gets too long. Additionally swap out "" for String.Empty, it shows your intent better, and also makes it more strongly contrast against " " ``` var state =ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)); if(state.Value != null && state.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage))) { return string.Empty; } else { return " "; } ``` I'm assuming this next bit executes elsewhere, because the two return statements above would otherwise make this unreachable code. Use var when the type is obvious from the right hand side of the assignment (although in this case it's a little debatable, I'd personally use var here because the variable name mimics the type). You have a typo in your second comment. ``` //Looks in a dictionary for a key called parameterName var modelState = ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value; //If I could find it I look for any error associated to that and I return it as a single string if(modelState.Value != null && modelState.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage))) { return string.Empty; } else { return " "; } ``` Finally, structure-wise I'd recommend converting the if-statement above into a separate method, since you call it in multiple places. This will leave a single point to modify during refactoring. ``` private string ConvertModelStateErrorsToString(ModelState modelState) { if(modelState.Value != null && modelState.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage))) { return string.Empty; } else { return " "; } } ``` Leaving your other code samples as: ``` var state =ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)); return ConvertModelStateErrorsToString(state); ``` And the other sample: ``` //Looks in a dictionary for a key called parameterName var modelState = ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value; //If I could find it I look for any error associated to that and I return it as a single string return ConvertModelStateErrorsToString(modelState); ```
you should probably move it into a if-else statement: ``` if(modelState != null && modelState.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage))) return ""; else return " "; ``` This immediately say "this function returns a empty string or a string with a space depending on this condition".
48,432,846
I am searching for a way to read/write data from `Google Sheets` directly. Does anyone have an idea how to do that in **Xamarin.Forms**? Keep in your mind access `Google sheets` from Windows Form working fine with me using `Install-Package Google.Apis.Sheets.v4` Package. I Used the following link: <https://developers.google.com/sheets/api/quickstart/dotnet>
2018/01/24
[ "https://Stackoverflow.com/questions/48432846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1253921/" ]
Reading & writing data on spread sheet is not an easy thing. I would suggest you go with `WebView` that might solve you issues. Here you might found some clue to do so <https://www.twilio.com/blog/2017/03/google-spreadsheets-and-net-core.html> & here on Google.Apis.Sheets.v4 API's are <https://github.com/xamarin/google-apis> & Spreadsheets with C# [Accessing Google Spreadsheets with C# using Google Data API](https://stackoverflow.com/questions/725627/accessing-google-spreadsheets-with-c-sharp-using-google-data-api)
Despite the fact that it really isn't a good idea to use Google Sheets as your online database, there are many better alternatives, if you want to access it from a Xamarin Forms app you can do it using the Sheets API [Sheets API documentation here](https://developers.google.com/sheets/api/)
59,081,328
Is there any RegEx expression - without using replace - to match against: ``` AB.D..G ABCDEFG ``` and return in each case as a match ``` ABDG ABCDEFG ```
2019/11/28
[ "https://Stackoverflow.com/questions/59081328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10407510/" ]
You can try to use this pattern: `\w{1,}` ```js var str1 = 'AB.D..G'; var str2 = 'ABCDEFG'; var pattern = /\w{1,}/g; console.log(str1.match(pattern).join('')); console.log(str2.match(pattern).join('')); ``` `\w` means: any alphabet character `{1,}` means: one or more times `g` means: repeat this method multiple times And we use `join` method to join all of the matched characters to a string.
You can split and join the string.
61,863,826
I'm on iOS 13.5 and using Xcode 11.4 to build on to it. I'm getting this error message: [![enter image description here](https://i.stack.imgur.com/SrbVf.png)](https://i.stack.imgur.com/SrbVf.png) The `KBlackberry` is my iPhone device name. I tried restarting the device and reconnecting of course and various other things but nothing seems to fix it. My next step is to try a newer version of Xcode.
2020/05/18
[ "https://Stackoverflow.com/questions/61863826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035899/" ]
Developers who are using Xcode 11.5 and trying to install their app in iOS 13.6 device will also see this message. It's a very confusing message. All you need to do is **Download Device support files of iOS 13.6** from this link [filsv/iPhoneOSDeviceSupport](https://github.com/filsv/iPhoneOSDeviceSupport) * Close Xcode * Unzip and *paste* it in this location: **/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/** * Reopen Xcode. Now you can install the app on the iOS 13.6 device using Xcode 11.5.
If you are on iOS 13.5 and Xcode 11.5, removing the device and adding it again fixed it for me.
164,629
I am developing a asp.net website. When I used the CSS property "word-wrap", VIsual Studio 2010 is showing a warning: Validation (CSS 2.1) 'word-wrap' is not a known CSS property name. When I tested the website, it is working fine. However, can there be any issue in using this property ignoring the warning?
2012/09/12
[ "https://softwareengineering.stackexchange.com/questions/164629", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/58676/" ]
You've also got to take into account some pretty smashing features offered by github that I've yet to see mentioned. * github pages with github flavored markdown * github mobile app * github eclipse plugin * github for mac * [github jobs](http://jobs.github.com/) * github for windows * github ticketing/bug tracking system * github developer api which allows for seamless third party integration * frequent UI updates/enhancements (you can literally see the changes from one day to the next i.e. [search text box now dynamically expands on focus](https://github.com/blog/1264-introducing-the-command-bar), watch became the new star button, etc.) * github [gists](https://gist.github.com/gists) (good for utility scripts, short code snippets, etc.) * seamless github integration via [hub](https://github.com/defunkt/hub) Other sites may have these features but I'm pretty sure no site out there has them all. These guys are practically everywhere...slowly dispersing their technical goodies throughout the web and desktop alike. They're only [getting bigger and better](http://go.bloomberg.com/tech-deals/2012-07-09-github-takes-100m-in-largest-investment-by-andreessen-horowitz/) as we speak and they hire the finest of engineers (they even managed to steal Phil Haack from Microsoft...go figure).
To be honest, the most important thing of Git for myself when I see it: 1. Network Graph or Should I call the History(also commenting) 2. Branch and Pull Request 3. It's more powerful, really, I would say it's so feels like I have a secretary holding all my work, and I can told that sec to wrote down anything for me, the change, everything! 4. It's easy to rollback Just it. Feels sexy using it
10,271,985
With Visual Studio 2010 (possibly 2008 as well) I am noticing behavior where Intellisense will suggest the fully qualified namespace for enums. For example, I can write code like this: ``` element.HorizontalAlignment = HorizontalAlignment.Right; element.VerticalAlignment = VerticalAlignment.Bottom; ``` But when I try to write it, it suggests I write it like this: ``` element.HorizontalAlignment = System.Windows.HorizontalAlignment.Right; element.VerticalAlignment = System.Windows.VerticalAlignment.Bottom; ``` This unnecessary extra code can really add up and makes it less readable, and I have to basically fight with Intellisense to avoid it. Is there I reason for this? Can I just turn it off? I assume the reason is that the name of the enum is the same as the name of the property. But that's really not a good reason. **EDIT:** Here's another example that demonstrates why fully qualified naming is not necessary. ``` using SomeOtherNamespace; namespace SomeNamespace { public class Class1 { public Class2 Class2 { get; set; } public Class1() { // These all compile fine and none require fully qualified naming. The usage is context specific. // Intellisense lists static and instance members and you choose what you wanted from the list. Class2 = Class2.Default; Class2.Name = "Name"; Class2.Name = Class2.Default.Name; Class2 = Class2; } } } namespace SomeOtherNamespace { public class Class2 { public static Class2 Default { get; set; } // public static Class2 Class2; (This throws an error as it would create ambiguity and require fully qualified names.) // public static string Name { get; set; } (This also throws an error because it would create ambiguity and require fully qualified names. public string Name { get; set; } } } ```
2012/04/22
[ "https://Stackoverflow.com/questions/10271985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/852555/" ]
This indeed seems to be the same name for property & the type. Here is the smallest reproducible example that mimics things (could be smaller but this reveals more)... ``` namespace Company.Project.SubProject.Area.Test.AndSomeMore { public class TestClass { public TestEnum MyEnum { get; set; } public TestEnum TestEnum { get; set; } public SndTestEnum NewEnum { get; set; } } public enum TestEnum { None, One, Two } public enum SndTestEnum { None, One, Two } } namespace MyCallerNS { public class MyTestClass : TestClass { public MyTestClass() { this.TestEnum = Company.Project.SubProject.Area.Test.AndSomeMore.TestEnum.One; this.MyEnum = Company.Project.SubProject.Area.Test.AndSomeMore.TestEnum.Two; this.NewEnum = SndTestEnum.None; } } } ``` Both `MyEnum` and `TestEnum` properties (targetting `TestEnum` enum) offer 'fully qualified' names (other has different name than its property type but the type matches other property's name, so both are 'tainted') - while SndTestEnum has different naming (for type, property) and works fine in either case. ...funny thing is that even if you remove `namespace MyCallerNS` and put all under the 'long namespace' - it'd still add `AndSomeMore.` in front. There is not solution as I see it (short of Re# and 3rd party tools), this seems to be the IntelliSense not being as smart as the compiler case, as @Rick suggested. Or rather - compiler takes its time to resolve things (with all the info at hands), while IntelliSense does not have that 'depth' and insight into things (I'm guessing, simplifying really - we need @Eric on this:) and makes fast/easiest choices sort of. Actually, on my previous thought, it's more about the 'job' that each perform - and IntelliSense (as a completion 'service') has to present you with all the choices (both the property name and the type) in the list (I don't see them both being present, but a guess. And having one choice to cover both would probably be a pain to handle) So to differentiate it adds the fully qualified names. And where it 'fails' (sort of) is to 'paste' the 'short version' in the end - which indeed it should I think.
I *suppose* you are working in WPF environment (I see element) and you have *somehow* the reference to `System.Windows.Forms` dll. My deduction is based on fact that `HorizontalAlignment` can be found in both namespaces: in [System.Windows.Forms.HorizontalAlignment](http://msdn.microsoft.com/en-us/library/system.windows.forms.horizontalalignment.aspx) and in [System.Windows.FrameworkElement.HorizontalAlignment](http://msdn.microsoft.com/it-it/library/system.windows.frameworkelement.horizontalalignment%28v=vs.95%29.aspx) Having two references pointing to the same type, VS asks to specify what namespace *exactly* you mean.
15,914,387
I am trying to implement an accordion with jQuery, however I am having a problem. When I press the button it is supposed to `slideToggle` the info but instead it is just sliding in and out. I don't know why it's behaving this way, I am learning and I will appreciate if someone could help me with this. This is my JavaScript: ``` $(".wrap-faq a").on("click",accordion); function accordion() { if($(this).attr("class") != "active"){ $(".wrap-faq li p").slideDown(); $(this).next().slideToggle(); $(".wrap-faq a").removeClass("active"); $(this).addClass("active"); } } ``` I also leave the link to my JSFiddle demo: <http://jsfiddle.net/zZaTf/>
2013/04/09
[ "https://Stackoverflow.com/questions/15914387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2130184/" ]
I think that you are looking for `process_vm_readv` and `process_vm_writev`. > > These system calls transfer data between the address space of the > calling process ("the local process") and the process > identified by pid ("the remote process"). The data moves directly > between the address spaces of the two processes, without passing > through kernel space. > > > See the man page for details.
nope there is no reverse of vmsplice operation, there is a project going on now for putting DBUS in kernel you might want to take a look at it. I too have the same requirement and was investigating this whole vmsplice thing.
44,454,668
I'm doing a school project to read the temperature through the sensor mlx90615. In my code an error appears: Traceback (most recent call last): File "/home/p/12345.py", line 21, in Import i2c Importerror: no module named 'i2c'
2017/06/09
[ "https://Stackoverflow.com/questions/44454668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8136255/" ]
Do you know that your entity references are actually `EntityReference` objects in this line: ``` entity[attribute.Key] = attribute.Value; ``` Perhaps they're `Entity` or `EntityDto` objects, in which case you'll get an `InvalidCastException`. If you're not sure, and unable to debug, you could type check them and instantiate an `EntityReference`: ``` foreach (var attribute in entityDto.Attributes) { if (attribute.Value is Entity) { entity[attribute.Key] = new EntityReference(((Entity)attribute.Value).LogicalName, ((Entity)attribute.Value).Id); } // Check if EntityDto... } ```
You cannot use `entity[attribute.Key] = attribute.Value;` for all datatypes. Invoice & InvoiceDetail are possessing parent/child relationships, so Parent Invoice Id will be available as Entityreference (lookup) in Detail entity. You have to check the datatype of each attribute & do the mapping inside foreach loop of Attributes. ``` entity[attribute.Key] = attribute.Value.ToEntityReference(); ``` or ``` entity[attribute.Key] = new EntityReference("entity_name",Id); ```
32,765,762
javascript newbie here, but I was wondering if it is possible to set a timeout after a user clicks a HTML Link, now I was wondering this because I am making a simple maths game, and it uses the alert method, which means that once a user clicks the link, the page in which the link is placed, is still visible in the background, which doesn't look very good. I was looking around and found a method called "window.setTimeout" and I was wondering if I could tie that method to the anchor tag in the HTML Code. Thanks :) My Code: (Note the game isn't finished yet :) ) ```html <html> <head> <title>Maths Game 0.1 Beta</title> <link rel="stylesheet" type="text/css" href="styling.css"> <script type="text/javascript"> var num1 = prompt("What is 2x10?"); if (num1 == '20') { alert("Nice Job!"); } else { alert("Oh well, try again."); } </script> </head> <body> </body> </html> ```
2015/09/24
[ "https://Stackoverflow.com/questions/32765762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5372909/" ]
For example, if you have a `<a id="foo" href="#"> </a>` in your HTML, once could do ``` document.getElementById("foo").onclick = function() { setTimeout(function() { // do stuff }, 5000); // triggers the callback after 5s }; ```
If I understand you correctly, you want to actually load a new page and *then* have the alert pop up, right? Well, timeouts won't run once the user has left your page. But there are at least two ways to do what you're asking: 1. Fake the page. You can include everything that would be on the "next page" on the current page, but hide it with `display:none`, and once the user clicks your link, you first make the content of the original page invisible, then make the content of the "next" page visible, and then show the alert. 2. Pass a value to the next page, and do the alert there. Since this is all client-side, I suggest using [`window.location.hash`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location), like On the current page: ``` <script> document.write('<a href="next_page.html#' + prompt('What is 2x10?') + '">Next page</a>'); </script> ``` On the next page: ``` <script> var num1 = window.location.hash.substr(1); // To get rid of the # if(num1 == '20') { alert("Nice Job!"); } else { alert("Oh well, try again."); } </script> ```
73,297,069
i'm trying to add a v-tooltip in a entire row in vuetify data table, i just want to add in a specific row of the array, when the item.confirmed is false then the line that has it will have a tooltip , i managed to do it but just with one value and not with a entire row. The tooltip message is in the array and the vuetify tooltip structure makes more difficult to do it, anyone could help me? Code: ``` <app-table :loading="loading.tableDetails" :headers="headersDetailTable" :items="uploadTable.lines" :items-per-page="5" > <template #body="{ items }"> <tbody> <v-tooltip bottom> <template #activator="{ on }"> <tr v-for="(item, index) in items" :key="index" v-on="on"> <td> {{ item.sku }} </td> <td>{{ item.productName }}</td> <td>{{ item.quantity }}</td> <td>{{ item.value }}</td> <td>{{ item.totalValue }}</td> <td v-if="!item.confirmed">{{ item.invalidLine }}</td> </tr> </template> <span>{{ item.detail }}</span> </v-tooltip> </tbody> </template></app-table > ```
2022/08/09
[ "https://Stackoverflow.com/questions/73297069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19729708/" ]
Here's a solution that's a little more terse. It can accommodate any number of breaks, and you can define additional break types if you want. I think the only assumption is that work always follows a break, but that could probably be adjusted if need be. ``` BEGIN declare @temp table (emp varchar(10),t1 time, t2 time, opt varchar(10)) declare @index table (optval varchar(10),eval int,shiftname varchar(10)) insert into @temp values --this is your original data ('Bob','7:30','16:00','Shift'), ('Bob','10:15','10:30','Break'), ('Bob','12:45','13:15','Lunch'), ('Bob','15:00','15:15','Break'), ('Frank','8:30','17:00','Shift'), ('Frank','10:30','10:45','Break'), ('Frank','12:00','12:30','Lunch'), ('Frank','15:15','15:30','Break') insert into @index values --auxiliary definitions ('Break',0,'Work'), ('Break',1,'Break'), ('Lunch',0,'Work'), ('Lunch',1,'Lunch'), ('Shift',0,'error'), ('Shift',1,'Work') select aa.emp,aa.s,aa.t1,aa.shiftname from (select a.*,lag(a.t1,1) over(partition by emp order by a.emp,a.t1) as s,i.shiftname from ((select emp,t1,opt,0 as e from @temp) union all (select emp,t2,opt,1 as e from @temp)) a left join @index i on i.optval=a.opt and i.eval=a.e ) aa where aa.s is not null order by aa.emp,aa.s END ``` And the results: | emp | start\_time | end\_time | shiftname | | --- | --- | --- | --- | | Bob | 07:30:00 | 10:15:00 | Work | | Bob | 10:15:00 | 10:30:00 | Break | | Bob | 10:30:00 | 12:45:00 | Work | | Bob | 12:45:00 | 13:15:00 | Lunch | | Bob | 13:15:00 | 15:00:00 | Work | | Bob | 15:00:00 | 15:15:00 | Break | | Bob | 15:15:00 | 16:00:00 | Work | | Frank | 08:30:00 | 10:30:00 | Work | | Frank | 10:30:00 | 10:45:00 | Break | | Frank | 10:45:00 | 12:00:00 | Work | | Frank | 12:00:00 | 12:30:00 | Lunch | | Frank | 12:30:00 | 15:15:00 | Work | | Frank | 15:15:00 | 15:30:00 | Break | | Frank | 15:30:00 | 17:00:00 | Work | Thanks for reading, let me know if you want additional commentary!
So, let's do this with the following caveats: 1. Your table layout is precisely how you indicated at the top where you have four rows per person. 2. Each person has a pattern of WORK-BREAK-WORK-LUNCH-WORK-BREAK-WORK. You can use a combination of CTE's with some UNIONed queries such as this. I changed a few column names because they are reserved words (start, end, option). ``` with breaks as ( select emp, c_start, c_end, rank() over (partition by emp order by c_start asc) as b_rank from my_table where category = 'Break' ), lunch as ( select emp, c_start, c_end from my_table where category = 'Lunch' ), shift as ( select emp, c_start, c_end from my_table where category = 'Shift' ) select distinct t.emp, s.c_start as c_start, b.c_start as c_end, 'Work' as category from my_table t join breaks b on t.emp = b.emp join shift s on t.emp = s.emp where b.b_rank = 1 union select distinct t.emp, b.c_start as c_start, b.c_end as c_end, 'Break' as category from my_table t join breaks b on t.emp = b.emp where b.b_rank = 1 union select distinct t.emp, b.c_end as c_start, l.c_start as c_end, 'Work' as category from my_table t join breaks b on t.emp = b.emp join lunch l on t.emp = l.emp where b.b_rank = 1 union select distinct t.emp, l.c_start as c_start, l.c_end as c_end, 'Lunch' as category from my_table t join lunch l on t.emp = l.emp union select distinct t.emp, l.c_end as c_start, b.c_start as c_end, 'Work' as category from my_table t join lunch l on t.emp = l.emp join breaks b on t.emp = b.emp where b.b_rank = 2 union select distinct t.emp, b.c_start as c_start, b.c_end as c_end, 'Break' as category from my_table t join breaks b on t.emp = b.emp where b.b_rank = 2 union select distinct t.emp, b.c_end as c_start, s.c_end as c_end, 'Work' as category from my_table t join breaks b on t.emp = b.emp join shift s on t.emp = s.emp where b.b_rank = 2 order by 1,2 ``` Output: | emp | c\_start | c\_end | category | | --- | --- | --- | --- | | Bob | 07:30:00 | 10:15:00 | Work | | Bob | 10:15:00 | 10:30:00 | Break | | Bob | 10:30:00 | 12:45:00 | Work | | Bob | 12:45:00 | 13:15:00 | Lunch | | Bob | 13:15:00 | 15:00:00 | Work | | Bob | 15:00:00 | 15:15:00 | Break | | Bob | 15:15:00 | 16:00:00 | Work | | Frank | 08:30:00 | 10:30:00 | Work | | Frank | 10:30:00 | 10:45:00 | Break | | Frank | 10:45:00 | 12:00:00 | Work | | Frank | 12:00:00 | 12:30:00 | Lunch | | Frank | 12:30:00 | 15:15:00 | Work | | Frank | 15:15:00 | 15:30:00 | Break | | Frank | 15:30:00 | 17:00:00 | Work | Db-fiddle can be found [here](https://www.db-fiddle.com/f/gf1kh6YFbzAPYVmXxxS5zP/2).
133,756
I know that as the DM I can make up whatever I want and put the heroes of Faerûn wherever I choose in the story. What I am looking for is answers that are in other modules (published adventures) that I do not own yet. For example: I think Drizzt shows up in *Out of the Abyss*, so I can hint as to where he is during the counsel meeting in *Rise of Tiamat*. The reason I ask is that I know that my players will be asking where they (the heroes) are and also will want to know: *why aren't they helping*? Specific heroes I am interesting in are: Elminster, Minsc, Farideh, Isteval, and the Grey Hand enforcers.
2018/10/16
[ "https://rpg.stackexchange.com/questions/133756", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/39432/" ]
Well, let's see what we can find... Timeline Background =================== The *Tyranny of Dragons* storyline kicks off in 1489 DR. *Princes of the Apocalypse* happens in 1491 DR. The pre-plot of *Out of the Abyss* got kicked off around 1485/1486, but the module itself doesn't specify when it actually happens - Chris Perkins said it happens 'right about the same time' as ToD and PotA. Elminster ========= The Sage of Shadowdale does not lead a dull life. 1487 DR covered the events of the end of the Second Sundering, in which Elminster was intimately involved. He was quite busy preventing other people from ascending to the position of god of magic, and in restoring Mystra to her former power (recorded in the novel *The Herald*). In the year 1491, when PotA was happening, Elminster was in Waterdeep helping Larael Silverhand investigate the murder of several Masked Lords (recorded in the novel *Death Masks*). What he was doing in the intervening years is unknown. Minsc ===== Minsc is a character that only exists in video games, and video game tie-in comics (particularly *Baldur's Gate* and *Neverwinter*). In the *Neverwinter* game, events take place that do not match with the events taking place in published modules. Minsc is one such case. The *Neverwinter* game's Module 6 (*Elemental Evil*) places Minsc working alongside the Emerald Enclave working against the Cults of Elemental Evil. Events in the game played out quite differently than they did in the published campaign. Because he exists in a world that doesn't match up with the current published adventures, one cannot say what he was up to during the published adventures. Farideh ======= We have no information whatsoever on the location or state of Farideh post 1486 DR. This is the time period in which the last book in the *Brimstone Angels* series was written, so we have no further information on what she is up to in the time period that the 5E published adventures are taking place. Sir Isteval =========== Isteval turns up in the *Tyranny of Dragons* storyline. He is the representative of Daggerford for the Lord's Alliance at the Council of Waterdeep. It is emphasized that Isteval is a *retired* adventurer who now walks with a cane and has settled into a more political and advisory role... explaining his absence from actively helping out. > > He also works "secretly" for Cormyr, but is too honorable to actually keep it a secret. > > > Gray Hands ========== Presumably, Force Grey is still around, as they are mentioned in the *Waterdeep: Dragon Heist* adventure. However, Force Grey's operations are mostly confined to Waterdeep and its surrounding areas. While this is not directly supported, it is likely that they are being retained by Waterdeep to tackle any threats that directly approach Waterdeep, while other Adventurers are supported and dispatched to deal with more distant threats. One callout of note, however, is that an auxiliary member of Force Grey shows up in the *Storm King's Thunder* adventure. > > Harshnag the Frost Giant > > > Drizzt ====== The storyline of Drizzt's novels actually contradicts the events of *Out of the Abyss*. In this storyline... > > Only Demogorgon was summoned, and Drizzt (with a lot of psionic support) is the one who 'kills' him back to the Abyss. > > > Because his story contradicts the existing modules, it is hard to place him within them. However, this 'version' of the OOtA story takes place in 1486DR, technically prior to all the published campaigns. Which places him... > > Living in Luskan/Gauntlgrym, happily married to Cattie-brie, who is pregnant with his child. > > > Or, perhaps, off on some other adventure that hasn't yet been written. The Out-of-lore answer ====================== Just so this is here...the obvious answer for 'where were they' is 'somewhere else, so the PCs can have the spotlight.' If Elminster and his allies showed up to try to solve the problem, there wouldn't be much left for the PCs to do.
Our DM had Isteval show up as part of the council meeting not sure if that is written as part of the story or he added it. but he did nothing to help us in our fight.
1,830,875
I'm using Vim for a C++ project that I've started working on and I've been spending a lot of time lately browsing through the existing code to get a hang of it. To make the browsing easier, I've setup ctags and cscope in Vim to jump to definitions and find references. However, I find that neither of them are intelligent enough to know which class a member variable/function belongs to. For example: ``` class Square; ... Square a; ... a.rotate(); ``` Attempting to find the definition of `rotate()` will bring up member functions from other classes too, like Triangle. I use `g]` in Vim to bring up a list of matching tags and fortunately ctags lists the associated class for each entry. However, when there are 200 classes with the same member function, it can be tiresome to hunt down the correct tag. Also, if I am at a function definition: ``` Square::rotate() { ... } ``` Attempting to find all calls to `rotate()` using cscope brings up calls to Triangle's and other classes' rotate functions. Because of this, I find myself jumping to **Visual Slickedit** every now and then to find the definition or reference to a member function or member variable. Is there any way I can accomplish this in good old **Vim**?
2009/12/02
[ "https://Stackoverflow.com/questions/1830875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222616/" ]
[SrcExpl](http://vim.sourceforge.net/scripts/script.php?script_id=2179) might be the plugin you needed. Try it.
Seems like this would be a good candidate <http://vim.wikia.com/wiki/C%2B%2B_code_completion>. I had some good luck with it doing similar things in Java. Not entirely sure it gets you everything you're trying to do though.
40,587,940
I have ha a WinForms app with some `textboxes`. At the moment the app is simple and i only want to test how it will work. It will get mutch more complex in the future. What i tried to do create a rule to ignore empty `textboxes` or if empty use the value 0. The code i have is this one: ``` decimal ata; decimal a1; decimal a2; decimal a3; decimal a4; decimal a5; decimal j = 0; a1 = decimal.TryParse(textBox1.Text, out j); a2 = decimal.Parse(textBox2.Text); a3 = decimal.Parse(textBox4.Text); a4 = decimal.Parse(textBox10.Text); a5 = decimal.Parse(textBox24.Text); ata = a1 + a2 + a3 + a4 + a5; resposta.Text = ata.ToString(); ``` i get an error "Cannot implicitly convert type 'bool' to 'decimal' in the line: ``` a1 = decimal.TryParse(textBox1.Text, out j); ``` Can anyone help me with this problem. Thanks in advance,
2016/11/14
[ "https://Stackoverflow.com/questions/40587940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7115573/" ]
Use `decimal.TryParse(textBox1.Text, out j);` instead of `a1 = decimal.TryParse(textBox1.Text, out j);`. Your value is returned in `j`
You are trying to assign a **bool** value to a **decimal variable** that's why getting this error. Decimal.TryParse() will return bool value, Please take a look [here](https://msdn.microsoft.com/en-us/library/9zbda557(v=vs.110).aspx) you can use this value to check parsing is successful or not. You will get result in your out parameter i.e j.
37,999,286
I use Angular2 [Webpack Starter](https://github.com/AngularClass/angular2-webpack-starter) in [this newest version](https://github.com/AngularClass/angular2-webpack-starter/commit/a4019da853c286ecbbc3d67ad669bf92b4ccaf55) and in file ./src/app/app.routes.ts I add 'my-new-route' and i want to name it as: "my.route" ``` export const routes: RouterConfig = [ { path: '', component: Home }, { path: 'home', component: Home }, // make sure you match the component type string to the require in asyncRoutes { path: 'about', component: 'About' }, { path: 'my-new-route', component: 'Dashboard', name:"my.route" }, { path: '**', component: NoContent }, ]; ``` but there is a problem - it not working! TypeScript writes: (name) "... is not assignable to type Route[]". I check file node\_modules/@angular/router/config.d.ts (which was pointed in index.d.ts) and indeed - there is no 'name' field in RouterConfig (Route class). So how to do named routes in Angular2 ?
2016/06/23
[ "https://Stackoverflow.com/questions/37999286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/860099/" ]
I would just use [ng2-translate](https://github.com/ocombe/ng2-translate) and create the link for each language in your JSON files.
RC.3 is most recent Angular2 version and the new router V3-alpha7 doesn't support names. Name was removed because it didn't work out with lazy loading of routes.
42,453,375
My module.ts, ``` import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule,Router } from '@angular/router'; import { AppComponent } from './crud/app.component'; import { Profile } from './profile/profile'; import { Mainapp } from './demo.app'; import { Navbar } from './header/header'; // import {ToasterModule, ToasterService} from 'angular2-toaster'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule,FormsModule, ReactiveFormsModule , RouterModule.forRoot([ { path: '', component:AppComponent}, { path: 'login', component:AppComponent}, { path: 'profile', component:Profile} ]) ], declarations: [ AppComponent,Mainapp,Navbar,Profile ], bootstrap: [ Mainapp ] }) export class AppModule { } ``` Here i want to call a function from main.ts on every route change and how can i do that.Can anyone please help me.Thanks. My mainapp.ts, ``` export class Mainapp { showBeforeLogin:any = true; showAfterLogin:any; constructor( public router: Router) { this.changeOfRoutes(); } changeOfRoutes(){ if(this.router.url === '/'){ this.showAfterLogin = true; } } } ``` I want to call this changeofRoutes() for every route change and how can i do that?Can anyone please help me.
2017/02/25
[ "https://Stackoverflow.com/questions/42453375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7597629/" ]
you can call `activate` method from main `router-outlet` like this ``` <router-outlet (activate)="changeOfRoutes()"></router-outlet> ``` which will call every time when route will change. Update - ======== Another way to achieve the same is to subscribe to the router events even you can filter them out on the basis of navigation state may be start and end or so, for example - ``` import { Router, NavigationEnd } from '@angular/router'; @Component({...}) constructor(private router: Router) { this.router.events.subscribe((ev) => { if (ev instanceof NavigationEnd) { /* Your code goes here on every router change */} }); } ```
You can call directive in Routes like below: ``` { path: 'dashboard', component: DashboardComponent , canActivate: [AuthGuard] }, ``` Your AuthGuard component is like below where you put your code: **auth.guard.ts** ``` import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { if (localStorage.getItem('currentUser')) { // logged in so return true return true; } // not logged in so redirect to login page with the return url this.router.navigate(['/home'], { queryParams: { returnUrl: state.url }}); return false; } } ``` You should import AuthGuard component in app.module.ts file and should provide in providers: **app.module.ts:** ``` ......... Your code.......... import { AuthGuard } from './_guards/index'; ..........Your code.............. providers: [ AuthGuard, ........ ], ```
1,304,286
If I have a sample space of $A$ and I randomly select $a$ elements, mark them, put them back into the sample space, then randomly select $b$ elements and I want to know what the probability is that $a$ and $b$ have precisely $y$ elements that are the same, how might I go about this? The way I'm currently thinking about this is to break the problem into two parts: 1. In the first selection I mark $a$ elements. Thus in order for me to choose exactly $y$ elements in the second selection, I must have marked at least $y$ elements in the first selection and now I need to make sure I select exactly $y$ of the marked elements of $a$. The event, $E\_1$, that I select at least $y$ elements in the first selection I'm confused on. Do I even needs this? 2. The event, $E\_2$, that when I select $b$ elements exactly $y$ of these are ones that I selected in the $a$. Can I do this with conditional probability?
2015/05/29
[ "https://math.stackexchange.com/questions/1304286", "https://math.stackexchange.com", "https://math.stackexchange.com/users/134501/" ]
Let $x$ denote the total number of elements in $A$. --- Calculate the number of ways to choose $b$ elements from $A$, such that: * $y$ elements are marked * $b-y$ elements are not marked $$\binom{a}{y}\cdot\binom{x-a}{b-y}$$ --- Calculate the number of ways to choose **any** $b$ elements from $A$: $$\binom{x}{b}$$ --- Hence the probability is: $$\frac{\binom{a}{y}\cdot\binom{x-a}{b-y}}{\binom{x}{b}}$$
Regretfully, I do not have enough reputation to comment on your question. :S If I correctly understand and $A$ is finite, then the following can work. After marking you have two classes, the marked which has $a$ elements and the non-marked which has $|A|-a$ elements. Denote by $\xi$ the number of elements which are marked from the selected $b$. You are looking for the probability $$ P(\xi = y), $$ where $y$ is at most $b$. $$ P(\xi =y)=\dfrac{\binom{a}{y}\cdot \binom{|A|-a}{b-y}}{\binom{|A|}{b}}. $$ Here $\xi$ is said to have a hipergeometric distribution. If I misunderstood your problem, please let me know and I can delete the answer to work out other one...
722,252
I have an interesting question, I have been doing some work with javascript and a database ID came out as "3494793310847464221", now this is being entered into javascript as a number yet it is using the number as a different value, both when output to an alert and when being passed to another javascript function. Here is some example code to show the error to its fullest. ``` <html><head><script language="javascript">alert( 3494793310847464221); var rar = 3494793310847464221; alert(rar); </script></head></html> ``` This has completly baffeled me and for once google is not my friend... btw the number is 179 more then the number there...
2009/04/06
[ "https://Stackoverflow.com/questions/722252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In JavaScript, all numbers (even integral ones) are stored as IEEE-754 floating-point numbers. However, FPs have limited "precision" (see the [Wikipedia article](http://en.wikipedia.org/wiki/Floating_point) for more info), so your number isn't able to be represented exactly. You will need to either store your number as a string or use some other "bignum" approach (unfortunately, I don't know of any JS bignum libraries off the top of my head). **Edit:** After doing a little digging, it doesn't seem as if there's been a lot of work done in the way of JavaScript bignum libraries. In fact, the only bignum implementation of any kind that I was able to find is Edward Martin's [JavaScript High Precision Calculator](http://www.petting-zoo.org/Calculator.html).
Just guessing, but perhaps the number is stored as a floating type, and the difference might be because of some rounding error. If that is the case it might work correctly if you use another interpreter (browser, or whatever you are running it in)
1,475,562
I need to recursively traverse directories in C#. I'm doing something like [this](http://support.microsoft.com/kb/303974). But it throws exception when iterating through system folders. How to check it before exception is thrown?
2009/09/25
[ "https://Stackoverflow.com/questions/1475562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You would have to check the access rights, but I would urge to to catch the exceptions instead, that makes the code easier to understand and would also deal with other issues like when you want to parse directories remotely and network gets down... If you make a GUI for a directory tree you could also add some nice Lock icons on the places where you get access right exceptions and Error icons elsewhere... In C# there is already a nice [free open source component](http://www.codeproject.com/KB/miscctrl/FileBrowser.aspx) for starting that. If you want to count files and sizes there is no way to overcome the rights issue, you have to run your tool under a more privileged user.
What type of exception are you getting? If you are getting a SecurityException you should have a look at this example on [MSDN](http://msdn.microsoft.com/en-us/library/ett3th5b.aspx)
33,074,176
I have a C# WPF 4.51 app. As far as I can tell, you can not bind to a property belonging to an object that is the child of a WPF *WindowsFormsHost* control. (If I am wrong in this assumption please show me how to do it): [Bind with WindowsFormsHost](https://stackoverflow.com/questions/10885211/bind-with-windowsformshost) In my case, I have a page that contains a *WindowsFormsHost* control whose *Child* object is a *ScintillaNET* editor control: <https://github.com/jacobslusser/ScintillaNET> ``` <WindowsFormsHost x:Name="wfhScintillaTest" Width="625" Height="489" Margin="206,98,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"> <WindowsFormsHost.Child> <sci:Scintilla x:Name="scintillaCtl" /> </WindowsFormsHost.Child> </WindowsFormsHost> ``` The child control works and displays fine. If it were a normal WPF control I would bind the *Text* property of the *Scintilla* editor control to some *string* property in my *ViewModel*, so that all I had to do to update the content of the *Scintilla* editor control is update that *string* property. But since I can't bind to a property belonging to a *WindowsFormsHost* child object, I'm looking for a strategy/solution that not completely awkward or kludgy. Has anybody faced this scenario before and has a reasonable strategy that solves my binding/update problem?
2015/10/12
[ "https://Stackoverflow.com/questions/33074176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2561452/" ]
A simple approach here is you can create some dedicated class to contain just attached properties mapping to the properties from your winforms control. In this case I just choose `Text` as the example. With this approach, you can still set Binding normally but the attached properties will be used on the `WindowsFormsHost`: ``` public static class WindowsFormsHostMap { public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached("Text", typeof(string), typeof(WindowsFormsHostMap), new PropertyMetadata(propertyChanged)); public static string GetText(WindowsFormsHost o) { return (string)o.GetValue(TextProperty); } public static void SetText(WindowsFormsHost o, string value) { o.SetValue(TextProperty, value); } static void propertyChanged(object sender, DependencyPropertyChangedEventArgs e) { var t = (sender as WindowsFormsHost).Child as Scintilla; if(t != null) t.Text = Convert.ToString(e.NewValue); } } ``` ***Usage in XAML***: ``` <WindowsFormsHost x:Name="wfhScintillaTest" Width="625" Height="489" Margin="206,98,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" local:WindowsFormsHostMap.Text="{Binding yourTextProp}" > <WindowsFormsHost.Child> <sci:Scintilla x:Name="scintillaCtl"/> </WindowsFormsHost.Child> </WindowsFormsHost> ``` The `Child` should of course be a `Scintilla`, otherwise you need to modify the code for the `WindowsFormsHostMap`. Anyway this is just to show the idea, you can always tweak it to make it better. Note the code above works just for 1 way binding (from view-model to your winforms control). If you want the other way, you need to register some event handler for the control and update the value back to the attached property in that handler. It's quite complicated that way.
You can only achieve a very, very limited binding with a Windows Forms control as they binding won't receive update notifications and may need to be explicitly polled to get the results via a custom `RefreshValues()` method or something that polls each piece of data. But if all you need is to access the child control, you should do the binding in code: ``` (WFH.Child as MyWinFormsControl).Text ``` If you intend to do a lot of binding, it might be easier to create a WPF wrapper object (`UserControl` perhaps) that has all the properties you need as DependencyProperties and the underlying code each property would manually poll the WinForms control as if it were the backing field for the property. It is a little complicated at first, but easier than manually polling each property.
74,174,630
In Node, how can I convert a time zone (e.g. `Europe/Stockholm`) to a UTC offset (e.g. `+1` or `+2`), given a specific point in time? [`Temporal`](https://tc39.es/proposal-temporal/docs/index.html#Temporal-TimeZone) seems to be solving this in the future, but until then? Is this possible natively, or do I need something like [`tzdb`](https://www.npmjs.com/package/@vvo/tzdb)?
2022/10/23
[ "https://Stackoverflow.com/questions/74174630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849076/" ]
I don't know your specific use case, but in general this should be the workflow: 1. Before you send date to the server, you send it in the ISO format (independent of the time zone). You can do it with native `new Date().toISOString()` method. 2. You save ISO date in the database. 3. Once it's returned to the client, you can parse ISO date which will automatically parse it to the user's local timezone.
We can use [`Date.toLocaleString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) to get the offset in hours and minutes using the [`ia`](https://en.wikipedia.org/wiki/Interlingua) language, this will result in a UTC offset in the format GMT+HMM, `GMT+5:30` for example. We can use a regular expression to get the HHMM offset, +5:30, -8:00 for example, this can be readily converted to a UTC offset in minutes. I think in general it's best to use a library such as luxon to get the UTC offset (as shown in another answer), but it *can* be done in Vanilla JS. ```js function getUTCOffsetHHMM(date, timeZone) { const fmt = date.toLocaleString('ia', { timeZoneName: 'longOffset', timeZone }); return fmt.replace(/^.*? GMT/, ''); } function getUTCOffsetMinutes(date, timeZone) { const hhmm = getUTCOffsetHHMM(date, timeZone); return parseHHMM(hhmm); } function parseHHMM(hhmm) { const [h, m] = hhmm.split(':').map(Number); return h * 60 + (m || 0) * (h < 0 ? -1: +1); } const now = new Date(); const timeZones = ['America/Los_Angeles', 'America/St_Johns', 'Europe/Berlin', 'Asia/Kolkata', 'Asia/Tokyo']; console.log('Timezone'.padEnd(22), 'UTC Offset (hh:mm)', 'UTC Offset (minutes)'); for(let timeZone of timeZones) { console.log(timeZone.padEnd(22), getUTCOffsetHHMM(now, timeZone).padEnd(18), getUTCOffsetMinutes(now, timeZone)); } ``` ```css .as-console-wrapper { max-height: 100% !important; } ```
234,021
The idea is to have a data structure that holds any number of objects of any type. Objects can be retrieved, or removed permanently, at random. Also, it can be cleared (or emptied). This class just provides the ability to select a random object from a collection, with the option of removing it. ``` public class Sack { private List<object> objects; public Sack() { objects = new List<object>(); } public void Add<T>(T obj) { objects.Add(obj); } public object Retrieve() { int numberObjects = objects.Count; Random rand = new Random(); int selectedIndex = rand.Next(0, numberObjects); return objects[selectedIndex]; } public object Remove() { int numberObjects = objects.Count; Random rand = new Random(); int selectedIndex = rand.Next(0, numberObjects); object selectedObject = objects[selectedIndex]; objects.RemoveAt(selectedIndex); return selectedObject; } public void Empty() { objects.Clear(); } } ```
2019/12/14
[ "https://codereview.stackexchange.com/questions/234021", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/215010/" ]
* You don't use any method which is specific to `List<T>`. You should always code against interfaces if possible, meaning you should use `IList<T>` instead of `List<T>`. * If `Retrieved` is called very often in a short time it is likely that you get the same `object` each time. This is because `Random` when [instantiated](https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.8#instantiating-the-random-number-generator) will use the system clock to provide a seed value. You should have one `Random` object as a class-level field which should be instantiated in the constructor or directly. * The genericness of the method `Add<T>` doesn't buy you anything. A simple `Add(object)` would be enough and does the exact same. * `objects` should be made `readonly` because you don't change it. * For `Retrieve` and `Remove` I wouldn't introduce the `numberObjects` variable but if you want to keep it you should rename it to e.g `numberOfObjects`. Implementing the mentioned points would look like this: ``` public class Sack { private readonly IList<object> objects = new List<object>(); private readonly Random rand = new Random(); public void Add(object obj) { objects.Add(obj); } public object Retrieve() { int selectedIndex = rand.Next(0, objects.Count); return objects[selectedIndex]; } public object Remove() { int selectedIndex = rand.Next(0, objects.Count); object selectedObject = objects[selectedIndex]; objects.RemoveAt(selectedIndex); return selectedObject; } public void Empty() { objects.Clear(); } } ```
Testing your code ----------------- To make your code testable, you should allow the code that uses this `Sack` to supply a custom random number generator. In your unit test for the `Sack` class, you should create a custom `TestingRandom` class that derives from `Random` and overrides the `Next(int, int)` method. In your TestingRandom class you should ensure that the amount of requested randomness is exactly what you expect. Given a set of 5 things, when you take them all out of the `Sack`, your random number generator must have generated randomness `5 * 4 * 3 * 2 * 1`. Not more, not less. This ensures that the distribution of objects returned by the `Sack` *can* be fair. It doesn't guarantee that, but it detects mistakes quickly. Performance ----------- Do you use this class to manage millions of objects? Because if you do, the `RemoveAt` call will make it very slow as that method needs to copy half of the array on average. To improve performance, you can change the code so that it always removes the element at the end: ``` var index = RandomIndex(); var obj = objects[index]; objects[index] = objects[objects.Count - 1]; objects.RemoveAt(objects.Count - 1); return obj; ```
481,382
My problem is that I'm not able to install windows 7. Been trying to install this since past 1 week. The methods I've tried are: 1. I have a windows 7 bootable DVD which doesn't boot up. (I've set BIOS to boot from DVD ROM first but it just won't boot from the DVD). Tried to install Windows 7 from the same DVD to a friend's PC and it worked. So the DVD has no issues. 2. I tried to run 'Setup.exe' from within the DVD. The two options pop-up 'Check compatibility' and 'Install now'. On clicking install now, after sometime, an error is encountered with the message 'Windows was unable to create a required installation folder' error code:0x8007000D. I am running Windows XP Professional and there's only one user on the PC which is the Admin, so I do not know why is the setup not getting permissions. I've also uninstalled my antivirus, CD burning software, disabled firewall and disconnected all other devices, but its still the same. 3. I tried to install it from a USB device by making it bootable but that too doesnt work. (Yes the motherboard supports booting from the USB). The problem is that XP does not recognize a 'USB' device on boot. Rather it shows this USB stick as a removable 'Hard Drive'. Furthermore, i changed the order of Hard Drive boot to boot from this removable Hard Drive first, it still boots my existing OS. Is there anything else that can be done? Any help would be greatly appreciated. Please ask if any other information is required, this post is becoming increasingly long to add any other details. PS: I want to dual boot windows 7 with my existing XP, but that would be after i manage to run the windows 7 setup in the first place. PPS: Please bare with any 'not-so-technical' terms, I am a beginner with this. Again, thank you for taking the time and trying to help, really appreciate it.
2012/09/30
[ "https://superuser.com/questions/481382", "https://superuser.com", "https://superuser.com/users/162215/" ]
Use a virtualization software (VMware, Virtualbox etc) and set up a dedicated guest system. Create a snapshot of the entire clean system before you start browsing, and restore this snapshot once you're done browsing.
IE supports creating a list of [restricted sites](http://windows.microsoft.com/en-MY/windows-vista/Change-Internet-Explorer-Security-settings). > > The level of security set for Restricted sites is applied to sites > that might potentially damage your computer or your information. > Adding sites to the Restricted zone does not block them, but it > prevents them from using scripting or any active content. The security > level for Restricted sites is set to High and can't be changed. > > > To [add a website](http://windows.microsoft.com/en-MY/windows-vista/Security-zones-adding-or-removing-websites) to the Restricted zone: 1. Pull down `Tools` and select `Internet Options`. 2. Go to the `Security` tab, click `Restricted sites` and then the `Sites` button. 3. Add the site of concern. There's undoubtedly still some risk of an exploit in IE that Microsoft doesn't yet know so I would certainly want up-to-date AV software as well.
57,267,689
I have a vertical navbar menu with 2 blocks. First is nav with icons, second is text of menu. They have a different background colors. How i can make one background color for two active nav blocks? [design of menu](https://i.stack.imgur.com/rtTVH.png) ```html <div class="menu__icons"> <ul class="menu__list"> <li> <a class="menu__item" href="#"><img src="http://via.placeholder.com/50" alt=""></a> </li> <li> <a class="menu__item" href="#"><img src="http://via.placeholder.com/50" alt=""></a> </li> <li> <a class="menu__item" href="#"><img src="http://via.placeholder.com/50" alt=""></a> </li> <li> <a class="menu__item" href="#"><img src="http://via.placeholder.com/50" alt=""></a> </li> </ul> </div> <div class="menu__text"> <ul class="menu__list"> <li><a class="menu__item" href="#">First</a></li> <li><a class="menu__item" href="#">Second</a></li> <li><a class="menu__item" href="#">Third</a></li> <li><a class="menu__item" href="#">Fourth</a></li> </ul> </div> </div> ``` <https://jsfiddle.net/levan563/1g5ucmwq/2/>
2019/07/30
[ "https://Stackoverflow.com/questions/57267689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9661289/" ]
Well basically if you want to toggle `.active` and you don't want two separate markup of list. Notice that `font-awesome` is for demonstration purposes only. ```css .menu__item { width: 250px; height: 50px; text-align: left; } .menu__item.active { background-color: #e9ebfd; } .menu__item.active .menu__icon { background-color: #e9ebfd; border-left: 4px solid #2c39ec; } .menu__item.active .menu__title { background-color: #e9ebfd; } .menu__item a:hover { text-decoration: none; } .menu__icon { display: inline-flex; align-items: center; justify-content: center; width: 50px; height: 50px; background-color: #fafafa; color: #2c39ec; } .menu__title { display: inline-block; padding-left: 20px; color: #777777; } ``` ```html <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <nav class="navigation-menu"> <ul class="menu__list list-unstyled"> <li class="menu__item active"> <a href="#"> <div class="menu__icon"> <i class="fa fa-tachometer-alt"></i> </div> <div class="menu__title">Main Dashboard</div> </a> </li> <li class="menu__item"> <a href="#"> <div class="menu__icon"> <i class="fa fa-user"></i> </div> <div class="menu__title">Profile</div> </a> </li> <li class="menu__item"> <a href="#"> <div class="menu__icon"> <i class="fa fa-bell"></i> </div> <div class="menu__title">Finances</div> </a> </li> <li class="menu__item"> <a href="#"> <div class="menu__icon"> <i class="fa fa-calendar"></i> </div> <div class="menu__title">Titles</div> </a> </li> </ul> </nav> ``` Related Fiddle <https://jsfiddle.net/mhrabiee/dojL9get/28/>
Its doable using jQuery. Assuming you have same number of list items in both blocks, ``` $(function(){ $('.menu__list li').on('click', function() { var idx = $(this).index(); $('.menu__list li').removeClass('active'); $('.menu__list li:nth-child(' + idx + ')').addClass('active'); }); }); ``` also add .active class in css and give needed style to li items also ``` .active{ /**your style**/ } .active > a{ } .active img{ } ```
38,732,388
I am trying to upload a csv into MySQL using the Workbench, and so far all my attempts have proven fruitless. I initially attempted to use the "Upload" function, but it complained about any null/empty fields I had. I am now attempting to use this function: ``` LOAD DATA infile 'C:\\temp\\SubEq.csv' INTO TABLE cas_asset_register.subequipment fields terminated BY ',' lines terminated BY '\n' (seid, parentme, @vparentse, name, status, description, equipmenttype, comments, removed, active, @vsupplierid) SET ParentSE = nullif(@vparentse,''), SupplierId = nullif(@vsupplierid,'') ; ``` But again, it appears to be complaining about (possibly) the same thing: > > Error Code: 1261. Row 1 doesn't contain data for all columns > > > I have had a look at the answers for [this](https://stackoverflow.com/questions/21646781/mysql-error-1261-row-1-doesnt-contain-data-for-all-columns) and [this](https://stackoverflow.com/questions/27219491/row-does-not-contain-data-for-all-columns) question, but neither have solved my issue. The table create query: ``` CREATE TABLE `subequipment` ( `SEId` int(11) NOT NULL AUTO_INCREMENT, `ParentME` int(11) DEFAULT NULL, `ParentSE` int(11) DEFAULT NULL, `Name` varchar(255) DEFAULT NULL, `Status` varchar(100) DEFAULT NULL, `Description` varchar(255) DEFAULT NULL, `EquipmentType` int(11) DEFAULT NULL, `Comments` text, `Removed` tinyint(1) NOT NULL DEFAULT '0', `Active` tinyint(1) DEFAULT '1', `SupplierId` int(11) DEFAULT NULL, PRIMARY KEY (`SEId`), UNIQUE KEY `Unique_Constraint_ME` (`Name`,`ParentME`,`Active`), UNIQUE KEY `Unique_Constraint_SE` (`Name`,`ParentSE`,`Active`), KEY `ParentME` (`ParentME`), KEY `ParentSE` (`ParentSE`), KEY `EquipmentType` (`EquipmentType`), KEY `fk_subequipment_supplierequipment` (`SupplierId`), KEY `fk_subequipment_status_idx` (`Status`), CONSTRAINT `fk_subequipment_majorequipment` FOREIGN KEY (`ParentME`) REFERENCES `majorequipment` (`MEId`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_subequipment_status` FOREIGN KEY (`Status`) REFERENCES `componentstatus` (`StatusName`) ON UPDATE CASCADE, CONSTRAINT `fk_subequipment_subequipment` FOREIGN KEY (`ParentSE`) REFERENCES `subequipment` (`SEId`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_subequipment_supplierequipment` FOREIGN KEY (`SupplierId`) REFERENCES `supplierinfo_equipment` (`SupplierId`) ON UPDATE CASCADE, CONSTRAINT `fk_subequipment_userdefinedcode` FOREIGN KEY (`EquipmentType`) REFERENCES `userdefinedcode` (`UDCId`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` As you can see from my upload query, I am expecting "ParentSE" and "SupplierId" to be empty, even though they are foreign key fields. Each line of the csv is properly indexed (i.e. there *are* enough fields to match the table): ``` 1,1,,P7YCGPF,Abg va hfr,Nfcver Npre Yncgbc,13,"Qngr npdhverq: 61/52/7566 Zbqry: 0297T Frevny Ahzore: YKE057551588125P16156",0,1, ``` What's going wrong?
2016/08/03
[ "https://Stackoverflow.com/questions/38732388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3073006/" ]
Does your data in any of your fields in the csv file contain commas? This screws up the field termination criteria when you're trying to upload it into MySQL. If this is the case, try saving it as a tab delimited txt file and replacing ``` fields terminated BY ',' ``` with ``` fields terminated BY '\t' ``` Sorry if this is not the right answer to your question, I wanted to post this as a comment but my reputation is not high enough :P
I had the same problem and comparing the columns in the CSV file and the table in my database resolved the issue. The number of columns, the column types, and in some cases empty values for string types (e.g., "" for string type) should be the same.
57,600,957
How would I go about debugging what's wrong with a string that I believe is in Base64 format, but which in VB using the below line of code ``` Dim theImage As Drawing.Image = imageUtils.Base64ToImage(teststring) ``` throws the following exception? ``` {"Base64ToImage(): The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. "} ``` The test string itself is far too long to paste here; I tried but reached (a lot) over the character limit. I've tried a few online conversion tools and it doesn't seem to work there either. At first I thought I was passing the string wrong from my ajax call to the web method VB code behind...but I've tried hard-coding my string into the function as well with the same failure. So, I'm convinced the string itself is bad data. It looks like: ``` Dim teststring = "dataImage/ png;base64, iVBORw0KGgoAAAANSUhEUgAAB4AAAAQ4CAYAAADo08FDAAAgAElEQVR4Xuy9268sWbbe9UVE3i / rvte + V....K/1Tx5/8A736wVclDQN4AAAAASUVORK5CYII=" ``` But I also tried removing the "dataImage" part and using ``` Dim teststring = "iVBORw0KGgoAAAANSUhEUgAAB4AAAAQ4CAYAAADo08FDAAAgAElEQVR4Xuy9268sWbbe9UVE3i / rvte + V....K/1Tx5/8A736wVclDQN4AAAAASUVORK5CYII=" ``` And it doesn't make a difference. I am getting this string in javascript using this function: ``` btnFreeze.onclick = video.onclick = function (e) { e.preventDefault(); canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); alert("got here"); $hfLicenseScreenshot.val(canvas.toDataURL()); $img.css("background-image", "url(" + $hfLicenseScreenshot.val() + ")"); $("#hiddenTextbox").val($hfLicenseScreenshot.val()); //$("#save").show(); return false; }; ``` ...where ultimately the string is from ``` canvas.toDataURL() ``` and about halfway through that function there is a hidden field called $hfLicenseScreenshot, from which I am saving the value into a "hidden" textbox (I dont know why my variable was getting lost, I know it's redundant but that's why I saved the value to a textbox called hiddentextbox. I get the sstring from hiddentextbox later, like: ``` $("#hiddenTextbox").val().toString(); ``` So, I have no idea how to go about debugging this image base 64 string. I've tried different images taken from my webcam and it's just not working with any of them. Any ideas? ...I don't know if it's been serialized or not, since I think the JSON stringify method is supposed to do that. I might be confused there. ...Here is my ajax call: ``` $.ajax({ type: "POST", url: "/BackCode/FirstPage.aspx/SaveData", data: JSON.stringify({ currentData: currentData, str: makeblob(str) }), contentType: "application/json; charset=utf-8", dataType: "json", async: true, currentData: currentData, success: function (resp) { resp = resp.d; if (resp.success) { if (typeof callback === "function") callback.apply(this, [resp]); load(); } else { $.statusMessage(resp.statusMessage, "red"); } }, error: function (jsonObject, textStatus, errorThrown) { $.statusMessage(errorThrown, "red"); } }); ``` I have also been having issues with this, and it goes into the last error function a lot: ``` $.statusMessage(errorThrown, "red"); ``` So I don't know whether I'm passing it correctly either.
2019/08/22
[ "https://Stackoverflow.com/questions/57600957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11121286/" ]
You just need to map over one of the two arrays, and use the current index to retrieve the corresponding value in the other array. During each iteration, return the object you want to create: ``` cc.map((code, index) => ({ code: code, currency: ccy[index]})); ```
``` var cn =["AL","DZ","AS","AD","AO","AI","AG","AR","AM","AW","AU"]; var ccy = ["ALL","DZD","USD","EUR","AOA","XCD","XCD","ARS","AMD","AWG","AUD"]; var country = []; for (let i = 0; i < cn.length; i++) { country.push({ code: cn[i], currency: ccy[i] }); } ``` could do the work
10,941,249
I'm about to create a bunch of web apps from scratch. (See <http://50pop.com/code> for overview.) I'd like for them to be able to be accessed from many different clients: front-end websites, smartphone apps, backend webservices, etc. So I really want a JSON REST API for each one. Also, I prefer working on the back-end, so I daydream of me keeping my focus purely on the API, and hiring someone else to make the front-end UI, whether a website, iPhone, Android, or other app. **Please help me decide which approach I should take:** > > ### TOGETHER IN RAILS > > > Make a very standard Rails web-app. In the controller, do the respond\_with switch, to serve either JSON or HTML. The JSON response is then my API. > > > **Pro:** Lots of precedent. Great standards & many examples of doing things this way. > > > **Con:** Don't necessarily want API to be same as web app. Don't like if/then respond\_with switch approach. Mixing two very different things (UI + API). > > > > > ### REST SERVER + JAVASCRIPT-HEAVY CLIENT > > > Make a JSON-only REST API server. Use Backbone or Ember.js for client-side JavaScript to access API directly, displaying templates in browser. > > > **Pro:** I love the separation of API & client. Smart people say this is the way to go. Great in theory. Seems cutting-edge and exciting. > > > **Con:** Not much precedent. Not many examples of this done well. Public examples (twitter.com) feel sluggish & are even switching away from this approach. > > > > > ### REST SERVER + SERVER-SIDE HTML CLIENT > > > Make a JSON-only REST API server. Make a basic HTML website client, that accesses the REST API only. Less client-side JavaScript. > > > **Pro:** I love the separation of API & client. But serving plain HTML5 is quite foolproof & not client-intensive. > > > **Con:** Not much precedent. Not many examples of this done well. Frameworks don't support this as well. Not sure how to approach it. > > > Especially looking for advice from experience, not just in-theory.
2012/06/07
[ "https://Stackoverflow.com/questions/10941249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031790/" ]
Isomorphic rendering and progressive enhancement. Which is what I think you were headed for in option three. **isomorphic rendering** means using the same template to generate markup server-side as you use in the client side code. Pick a templating language with good server-side and client-side implementations. Create fully baked html for your users and send it down the wire. Use caching too. **progressive enhancement** means start doing client side execution and rendering and event listening once you've got all the resources downloaded and you can determine a client capabilities. Falling back to functional client-script-less functionality wherever possible for accessibility and backwards compatibility. Yes, of course write a standalone json api for this app functionality. But don't go so far that you write a json api for things that work fine as static html documents.
Building a JSON API in Rails is first class, The JSONAPI::Resources gem does the heavy lifting for a <http://jsonapi.org> spec'd API.
120,462
The idiom, *plonk (something/someone) down* means > > * to slap something down; to plop something down > * to sit or lie down on something in a careless or noisy way > * to leave someone somewhere to do this; *Dave plonked the kids in front of the TV and disappeared upstairs.* > * to put something down heavily and without taking care: > *Just plonk the shopping (down) on the table, and come and have a cup of tea*. > *Come in and plonk yourselves (down)* (= sit down) *anywhere you like*. > > > From these various definitions I can surmise why cheap wine is often called *plonk*, it's the sound of the bottle slapping down heavily on the table. But how did we get from that to “**a plonker**” which basically means a silly or stupid person. As in > > "Why did you do that, you plonker?" > > > ![Rodney from Fools and Horses](https://i.stack.imgur.com/AXDZp.jpg) Nicholas Lyndhurst who played Rodney Trotter in *Only Fools and Horses* References: [FD](http://idioms.thefreedictionary.com/plonk); [*plonker*](http://www.thefreedictionary.com/plonker) "Sir David Jason says an American remake of Only Fools And Horses won't work as there's no word over there for plonker." [CDO](http://dictionary.cambridge.org/dictionary/british/plonker?q=plonker); [*plonk*](http://dictionary.cambridge.org/dictionary/british/plonk_1?q=plonk)
2013/07/26
[ "https://english.stackexchange.com/questions/120462", "https://english.stackexchange.com", "https://english.stackexchange.com/users/44619/" ]
*Plonker* used to be slang for condoms, and sometimes for penises. There are several other possibilities, but the context makes this one seem more than plausible because it was heavily used in BBC sit-coms and they were fond of using substitute swearwords that were obscure, which those senses of *plonker* had become. Other examples would include *naff* (probably, but not certainly from Polari slang meaning "heterosexual") and *smeg* (probably, but not certainly, from *smegma*). The deliberate obtuseness as to where the word came from allows the writers to get away with it. (In the case of *naff* the meaning wouldn't be much of a problem, but the source would itself have been a bit scandalous in those days). More modern examples would be the heavy use of *feck* on "Father Ted"; which makes perfect sense in the context as it's a milder form of *fuck* in Ireland, but largely unknown in the UK, and the fondness of American writers for having British characters say *bollocks* and *wanker*, allowing them to use words of a level of offensive force above what American prime-time allows because the words aren't much used there, but acceptable for broadcast in the UK because of more lenient rules.
There are some references on the web to plonk as the lowest ranking person in the Royal Air Force (RAF), which apparently is an Aircraftman 2nd class, sometimes referred to as an [AC plonk](http://en.wiktionary.org/wiki/Transwiki%3aRAF_Speak), and another for plonk as a [slang term for mud](http://www.englishforums.com/English/OriginEarliestUsagePlonkerRodney-Plonker/hmhwv/post.htm), coined in the trenches during the Great War, so its origins could lie in the notion of a person of lowest rank or status, or someone down in the mud.
86,670
I have to set up a few servers (4 right now, more in the future) behind a firewall. The data center would like to provide a single port with a block of IP addresses, and then I'll have the firewall forward the correct IP address to the correct server. What are your recommendations for a reasonable firewall? Some additional notes: * All servers are low-traffic web servers. * The connection to the data center network is gigabit, and I'm on a 6mb burst cap. * I don't want something insanely hard to admin. I'm used to pfSense, which is very nice, but I'd rather not stick a whole additional 1U server in there for pfSense at this time. * I'll be allocated a block of 8 or 16 IP addresses to be distributed among the servers. * I'm not made of money, so please don't recommend anything $$$$$$$
2009/11/20
[ "https://serverfault.com/questions/86670", "https://serverfault.com", "https://serverfault.com/users/38118/" ]
There is always the possibility of just using each computer's built-in firewall rather than a separate appliance. If you are set on a firewall, the Netscreen line will probably do what you want -- even the entry-level SSG5 will do for "light" usage (up to 8K simultaneous connections), going up from there depending on your needs. However it is a hardware unit, which means you'll still need to find space in your rack for it.
Given that any "appliance" in your price range is almost certainly going to be a 1RU server with some sort of firewall software in it *anyway*, what's wrong with just removing the middleman, installing a 1RU server, and going with what you know? Edit (under duress): If your DC will charge you less for something that isn't a rack unit, stick an old desktop PC in the rack and put pfsense on that.
27,634,913
I have a C# project that needs to refactor. Project uses WPF+MVVM Light toolkit. I found the `MainViewModel(...)` constructor that receives about 50 parameters (factories interfaces). I think not. Am I right? I'm interested, because I want to improve my OOP thinking. Thanks. P.S. Sorry for my grammar. Check me if you find errors.
2014/12/24
[ "https://Stackoverflow.com/questions/27634913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4324624/" ]
[Clean Code: A Handbook of Agile Software Craftsmanship](https://rads.stackoverflow.com/amzn/click/com/0132350882), page 40, states that... > > The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway. > > > Consider the book as guidelines for software design, and as such, recommendations when thinking about your code structure.
You might look into using a Dependency Injector like Unity. Register all your Service, Factory, and associated Classes you need with the Unity Container and then you only need a single parameter for your ViewModel constructor which is the Unity Container. 50 parameters for a constructor seems insane to me...
26,914,819
I have a webhook that currently fires on `push` to any branch. This triggers the webhook far too frequently. Ideally, the webhook would only fire when a pull request is **merged** into `master`. I don't see that as an option, though: ![enter image description here](https://i.stack.imgur.com/AIlXE.png) Is there a way to get additional webhook options or to customize the webhook somehow?
2014/11/13
[ "https://Stackoverflow.com/questions/26914819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925897/" ]
So, you can't customize the conditions of the trigger, but as LeGec mentions you can customize your code to only trigger when the Pull Request is merged. To do that, make sure your script responds to the [PullRequestEvent](https://developer.github.com/v3/activity/events/types/#pullrequestevent). The conditions to test are: * "action" is "**closed**" * "merged" (inside of "pull\_request") is **true** This way your script can ignore all the pings it receives when any other activity occurs on the Pull Request (including closing without merging).
I don't see any way to customize the conditions of the trigger. I would suggest to rather write code on the receiving end to trigger your action only when you detect that the push fits your conditions, e.g : * `payload.ref == "refs/head/master"` * `payload.commits[0] matches the structure of a merged pull request` (<- this may require getting some extra info from the [commits API](https://developer.github.com/v3/repos/commits/))
38,770,014
I want to get the record count of a query that has a variable in it's name. ``` <cfloop query="Getteam"> <cfquery name="GetJobs#teamstaffid#" datasource="#dataSource#" > SELECT * FROM Request, Hist_Req_Assign, Hist_Req_status WHERE hist_req_assign.teamstaffid = '#teamstaffid#' AND hist_req_assign.requestid = request.requestid AND hist_req_status.requestid = request.requestid AND hist_req_status.statusid = '3' </cfquery> </cfloop> ``` GetTeam spits out the ID of each staff member in my team. And `GetJob#teamstaffid#` gets all their jobs. MY first instinct is to do: `<cfoutput>#GetJobs#teamstaffid#.RecordCount#</cfoutput>` This obviously wont work though. How can I get the record count of each team member? Thanks
2016/08/04
[ "https://Stackoverflow.com/questions/38770014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6678503/" ]
I would probably do something along these lines: ``` <cfscript> try { sql = "select * from Request, Hist_Req_Assign, Hist_Req_status where hist_req_assign.requestid = request.requestid and hist_req_status.requestid = request.requestid and hist_req_status.statusid = '3'"; principalQuery = new query(); principalQuery.setDatasource(dataSource); result = principalQuery.execute(sql=preserveSinglequotes(sql)); getJobs = result.getResult(); for(i=1;i<=listLen(teamstaffid);i++){ sql = "select request, Hist_Req_Assign, Hist_Req_status from sourceQuery where hist_req_assign=#teamstaffid[i]#"; local.queryService = new query(); local.queryService.setName("employee"); local.queryService.setDBType("query"); local.queryService.setAttributes(sourceQuery=getJobs); local.objQueryResult = local.queryService.execute(sql=sql); local.queryResult = local.objQueryResult.getResult(); writeOutput("Employee " & teamstaffid[i] & " has " & local.queryResult.recordcount & " records."); } } catch (any e){ //whatever } </cfscript> ```
The cfquery tag returns some result variables in a structure. So, we use result attribute in the cfquery tag we can able to get some details of the query. For example: 1. resultname.sql 2. resultname.recordcount ``` <cfloop query="Getteam"> <cfquery name="GetJobs#teamstaffid#" datasource="#dataSource#" result="resultname"> SELECT * FROM Request, Hist_Req_Assign, Hist_Req_status WHERE hist_req_assign.teamstaffid = '#teamstaffid#' AND hist_req_assign.requestid = request.requestid AND hist_req_status.requestid = request.requestid AND hist_req_status.statusid = '3' </cfquery> </cfloop> <cfoutput>#resultname.recordcount#</cfoutput> ```
59,653
I wonder if the "*g*" in the -ing forms is pronounced. When I hear it it seems as if it's not pronounced sometimes or just slightly, though sometimes I've been told that I should pronounce "*g*" for example in "meeting" just to avoid saying *"mitten"*. So how should I pronounce "-**ing**"? Sometimes -ing is written in an informal way as -in' such as: > > taking > > > takin' > > > Is the letter "*g*" in each case pronounced differently?
2012/02/29
[ "https://english.stackexchange.com/questions/59653", "https://english.stackexchange.com", "https://english.stackexchange.com/users/6733/" ]
Using an apostrophe in place of a "g" is an informal colloquiallism. It is usually found inside a quotation, suggesting the speaker did not use much care when enunciating. Specifically, it's used to indicate the verb was spoken such that the final "g" was omitted: "*We were walkin' to the store, not botherin' nobody, when, all of a sudden, out o' nowhere, this guy starts a-hollerin' at us for no good reason!*" (It's similar to using **o'** in place of "**of** " - as found in the preceding example). Sometimes it's also used in song titles, when the singer doesn't carefully enunciate the final "g" in an "-ing" verb (*a la* "**Takin' Care of Business**" and "**The Times They Are a-Changin'**").
Actually, in older stages of English, the -ing form was used only for the gerund, while the present participle had an "-end-" ending. The "-in'" ending in colloquial English, southern American English, and many British dialects is probably a leftover from this "-end-" inflection.
256,674
Intro ----- The Tetris Guidelines specify what RNG is needed for the piece selection to be called a Tetris game, called the Random Generator. Yes, that's the actual name (["Random Generator"](https://tetris.wiki/Random_Generator)). In essence, it acts like a bag without replacement: You can draw pieces out of the bag, but you cannot draw the same piece from the bag until the bag is refilled. Write a full program, function, or data structure that simulates such a bag without replacement. Specification ------------- Your program/function/data structure must be able to do the following: * Represent a bag containing 7 distinct integers. * Draw 1 piece from the bag, removing it from the pool of possible pieces. Output the drawn piece. * Each piece drawn is picked uniformly and randomly from the pool of existing pieces. * When the bag is empty, refill the bag. Other Rules ----------- * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte count wins! * [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * [You can use any reasonable I/O method.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) ### "Bonuses" These bonuses aren't worth anything, but imaginary internet cookies if you are able to do them in your solution. * Your bag can hold an arbitrary `n` distinct items. * Your bag can hold any type of piece (a generic bag). * Your bag can draw an arbitrary `n` number of pieces at once, refilling as needed.
2023/01/13
[ "https://codegolf.stackexchange.com/questions/256674", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77309/" ]
[JavaScript (Node.js)](https://nodejs.org), 62 bytes ==================================================== ```javascript f=_=>x.match(i=Math.random()*7|0)?f(x=x[6]?'':x):(x+=i,i);x='' ``` [Try it online!](https://tio.run/##BcFRDoIwDADQfy@y1unClwZm5QSewBjTDCYzQM1YTD@8@3zvzV/eQk6fclxlGGuN9KSruoVLmCDRjcvkMq@DLID786/BPoKS3k@P3phOsQO1lA4JvZIx1e@iZGBqPF/a1lvLGGTdZB7dLC@IgFj/ "JavaScript (Node.js) – Try It Online") I hope I understood question correctly
[Jelly](https://github.com/DennisMitchell/jelly), (4) 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ======================================================================================================================= ``` 7ẊṄ€ß ``` A full program that prints forever. **[Try it online!](https://tio.run/##y0rNyan8///hrq6HO1seNa05PP/////mAA "Jelly – Try It Online")** \$4\$ bytes - `ẊṄ€ß` - taking either an arbitrary alphabet size [TIO](https://tio.run/##y0rNyan8///hrq6HO1seNa05PP////@GRgA "Jelly – Try It Online") or an arbitrary alphabet (as a list) [TIO](https://tio.run/##y0rNyan8///hrq6HO1seNa05PP/////R6smJJeo6Cuop@ekgKiMxt7gktQjETMsszgDRufmlxakgRlFiUlImWHF6PlBTLAA "Jelly – Try It Online"). ### How? ``` 7ẊṄ€ß - Main Link: no arguments 7 - seven Ẋ - (implicit range [1..7]) shuffle € - for each: Ṅ - print with trailing newline ß - call this link again with the same arity ```
39,613,822
I have a notebook cell containing JavaScript code, and I would like the code to select this particular cell. Unfortunately, the behavior of `get_selected_cell` depends on whether I execute the cell in place, or execute and select the cell below. **Example:** ``` %%javascript var cell = Jupyter.notebook.get_selected_cell(); console.log(Jupyter.notebook.find_cell_index(cell)); ``` When executing this cell, the console output will be different whether I execute with `Ctrl+Enter` or `Shift+Enter`. In one case it logs the index of the cell that contains the JavaScript code, in the other the index of the cell below. Is there a way to select the cell I want?
2016/09/21
[ "https://Stackoverflow.com/questions/39613822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5276797/" ]
Your Javascript will have a handle on the OutputArea applying the Javascript, but not one all the way to the cell (in general, output areas can be used without cells or notebooks). You can find the cell by identifying the parent `.cell` element, and then getting the cell corresponding to that element: ``` %%javascript var output_area = this; // find my cell element var cell_element = output_area.element.parents('.cell'); // which cell is it? var cell_idx = Jupyter.notebook.get_cell_elements().index(cell_element); // get the cell object var cell = Jupyter.notebook.get_cell(cell_idx); ```
If you are writing a jupyter lab widget, you can get the cell index by iterating the `widget` array. This is what jupyter lab internally does ([source](https://github.com/jupyterlab/jupyterlab/blob/5755ea86fef3fdbba10cd05b23703b9d60b53226/packages/notebook/src/widget.ts#L1803)). ``` const cellIndex = ArrayExt.findFirstIndex( notebook.content.widgets, widget => widget.node === this.originalCell.node ); ``` Then you can assign the new active cell by changing the `activeCellIndex` property of the notebook widget: ``` notebook.content.activeCellIndex = cellIndex; ```
21,695,669
I am trying to remove last element from ``` Map<String, List<String>> map = new HashMap<String, List<String>>(); ``` My code is ``` StringTokenizer stheader = new StringTokenizer(value.toString(),","); while (stheader.hasMoreTokens()){ String tmp = stheader.nextToken(); header.add(tmp); System.out.println("tmp"+header); map.put(tmp, new ArrayList<String>()); } System.out.println(map.size()); ``` Output: ``` tmp[Sepal_Length, Sepal_Width, Petal_Length, Petal_Width, Class] map{Petal_Width=[], Class=[], Petal_Length=[], Sepal_Length=[], Sepal_Width=[]} ``` I want to remove the key Class[] from `map` or `tmp`. I tried using `.remove()` but nothing is reflecting.
2014/02/11
[ "https://Stackoverflow.com/questions/21695669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2028043/" ]
There is no order in `HashMap`, so, you can't remove the last item. Use `LinkedHashMap` to have the order of insertion.
`HashMap` doesn't arrange it's elements according to an index, but you can retrieve only the element according to it's `key`, so if you have to use a `HashMap` you have to add an incremental index to it's key, so when you put a new element that index incremented with one and put with the key in the `HashMap`, like this : ``` Map<Map<int,String>, List<String>> map = new HashMap<Map<int,String>, List<String>>(); int index = 0; StringTokenizer stheader = new StringTokenizer(value.toString(),","); while (stheader.hasMoreTokens()){ String tmp = stheader.nextToken(); header.add(tmp); System.out.println("tmp"+header); Map<int, String> temp_map = new HashMap<int, String>(); temp_map.put(index, tmp); index ++; map.put(temp_map, new ArrayList<String>()); } ``` and then you can check the value of index in the end and that will be the index of the last element.
38,523,391
Why my program is giving garbage value in O/P after providing sufficient inputs? I have given I/P as `10 & 40` & choose multiplication option as `3`. My code is as follows: ``` int main() { int a,b,c,x; printf("Enter a & b \n"); //printing scanf("%d %d, &a,&b"); printf("1. add \n 2. sub \n 3. multiply \n 4. div \n 5. mod \n 6. and \n 7. or\n 8. not \n 9. xor \n"); printf("Enter your choice \n"); scanf("%d, &x"); switch(x) { case 1: c=a+b; break; case 2: c=a-b; break; case 3: c=a*b; break; case 4: c=a/b; break; case 5: c=a%b; break; case 6: c=a && b; break; case 7: c=a || b; break; case 8: c=~a; break; case 9: c=a^b; break; default: printf("Make correct choice\n"); } printf("result is: %d",c); return 0; } ```
2016/07/22
[ "https://Stackoverflow.com/questions/38523391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6624428/" ]
EDIT: I found the real problem behind. Firebase had update. User need to update the firebase version via cocopod. After update the cocopod, can use everything normally same as firebase Doc. ========================================== I have the same problem, but cannot fix it by updating the pod-file. Finally, I find out a solution. Google teach us to import only > > import Firebase > > > Just add: > > import FirebaseDatabase > > > and everything will become fine
In your Podfile, add pod ``` pod 'Firebase/Database' ``` Then import Firebase Database in your ViewController ``` import FirebaseDatabase ``` Create a globle `var ref` that you can use it anywhere in viewcontroller ``` var ref: DatabaseReference! ``` Now, In `viewDidLoad` Define the `ref` ``` ref = Database.database().reference() ```
52,686,378
> > The lambda calculus has the following expressions: > > > > ``` > e ::= Expressions > x Variables > (λx.e) Functions > e e Function application > > ``` > > From this base, we can define a number of additional constructs, such as Booleans and conditional statements: > > > > ``` > let true = (λx.(λy.x)) > false = (λx.(λy.y)) > if = (λcond.(λthen.(λelse.cond then else))) > > ``` > > Showing your work, show the evaluation of the following program: > `if false false true`. > > > Maybe `if(false (then false ( else true then true)))`? But that would just mean exactly what it means. `if false then false else true then true`. I don't know how to approach it.
2018/10/07
[ "https://Stackoverflow.com/questions/52686378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662198/" ]
Having the definitions ```hs true = (λx.(λy.x)) false = (λx.(λy.y)) if = (λcond.(λthen.(λelse.cond then else))) ``` defined, means that ```hs true x y = x false x y = y if cond then else = cond then else ``` Thus, e.g., ```hs if true true false -- if cond then else = cond then else = true true false -- true x y = x = true ``` There's no more definitions to apply here, so we have our result. Now you can try working out your example.
Another approach: ``` if false false true {substituting name for definition} -> (λcond.(λthen.(λelse.cond then else))) false false true {beta reduction} -> (λthen.(λelse.false then else)) false true {beta reduction} -> (λelse.false false else) true {beta reduction} -> false false true {substituting name for definition} -> (λx.(λy.y)) false true {beta reduction} -> (λy.y) true {beta reduction} -> true {substituting name for definition} -> (λx.(λy.x)) ``` You can run it yourself using the interactive interpreter on [this page](https://www.easycalculation.com/analytical/lambda-calculus.php). But the interpreter only supports one-letter variable names so you have to enter the expression: ``` (λc.(λt.(λe.c t e))) (λx.(λy.y)) (λx.(λy.y)) (λx.(λy.x)) ```
163,800
I'm running the latest version of OS X and Preview is hanging whenever I try to start it. It attempts to open the documents which I previously had open, which is ~10 PDFs and ~3 PostScript files, and it seems to be permanently get stuck whilst "converting" those PostScript files (even though opening them was no issue before). Hence my question is, how do I start Preview without opening those documents? (I'm guessing there's some kind of cache I should delete.)
2014/12/28
[ "https://apple.stackexchange.com/questions/163800", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/106374/" ]
Do you want to disable the App re-open the documents when you launch the App? So, you can go to "System Preferences" > "General" and enable the "close windows when quitting and app" option.
To amplify what Nelson said above, here are the full list of steps which worked for me on OSX 10.10.2: Quit Preview if it’s running. Hold down the option key and select Go ▹ Library from the Finder menu bar. From the Library folder, delete the following items, if they exist: ``` Containers/com.apple.Preview Preferences/com.apple.Preview.LSSharedFileList.plist Preferences/com.apple.Preview.SandboxedPersistentURLs.LSSharedFileList.plist Saved Application State/com.apple.Preview.savedState ``` Log out and log back in. Launch the application and test. Credit to Linc Davis, on [this](https://discussions.apple.com/message/26961188#26961188) page.
3,255
Many approaches exist to define security requirements. To keep it simple, i would say to define a security requirement, one need to model the threat encountered when building up misuse cases for specific use cases being worked out. Still, at the end, some security requirements are at architectural level while others are at code level. Most of what I can think of as security requirements at any of these levels seem to have test cases (whether automated or not). Still, in some examples: like the need to stop an *intentional back door*, for me, it is worth being formulated in a security requirement. 1. I can't think of a test case for it though! intentional is pretty difficult to proof using a test case! Thus my question: isn't this worth being a security requirement? 2. and now to the generalized version of the question: Would not having a test case for a security requirement be considered to be an indicator that I have an improper security requirement?
2011/04/21
[ "https://security.stackexchange.com/questions/3255", "https://security.stackexchange.com", "https://security.stackexchange.com/users/74/" ]
I'd say - "yes, they need to be testable" and also "if you have an untestable requirement, you need to rewrite". But I work for DoD contracts, and my gut reaction is as much about a Pavlovian reflex to being beaten up by untestable requirements as it is based in any rational thought. I've often seen high level requirements that are untestable. And I think the "no intentional back door" requirement could be such a case. But you need to drill down to some requirements that aim at prevention measures, such as: * the system shall be reviewed for backdoors by trusted external security verification agents * reviews shall be conducted before the deployment of every major release * reviews shall include .... I'm not sure how your business uses requirements other than for testing... in mine, failure to meet agreed upon customer requirements can be a cause for contract violation, so we're careful not to let any impossible negatives into the world that would mean massive scope creap.
Security is a quality attribute rather than a functional attribute, and so you can't generally test for it. What you can test for, or at least should be able to, is the presence of a control that was specified (and if the control involves code, you can test its functionality). For example let's say that your control against an intentional back door is a code review (without wanting to open a debate as to whether that is a good or a bad or a sufficient control for this) - you can test that the review happened.
17,247,306
I have an array as follows: ``` @array = ('a:b','c:d','e:f:g','h:j'); ``` How can I convert this into the following using grep and map? ``` %hash={a=>1,b=>1,c=>1,d=>1,e=>1,f=>1,h=>1,j=>1}; ``` I've tried: ``` @arr; foreach(@array){ @a = split ':' , $_; push @arr,@a; } %hash = map {$_=>1} @arr; ``` but i am getting all the values i should get first two values of an individual array
2013/06/22
[ "https://Stackoverflow.com/questions/17247306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1770135/" ]
Its very easy: ``` %hash = map {$_=>1} grep { defined $_ } map { (split /:/, $_)[0..1] } @array; ``` So, you **split** each array element with ":" delimiter, getting bigger array, take only 2 first values; then grep defined values and pass it to other **map** makng key-value pairs.
This filters out `g` key ``` my %hash = map { map { $_ => 1; } (split /:/)[0,1]; } @array; ```
30,072
A number of different web-sites document this mysterious storey of an apparent traveller from an alternate history: > > It’s July 1954; a hot day. A man arrives at Tokyo airport in Japan. He’s of Caucasian appearance and conventional-looking. But the officials are suspicious.On checking his passport, they see that he hails from a country called Taured. The passport looked genuine, except for the fact that there is no such country as Taured – well, at least in our dimension. > > > The man is interrogated, and asked to point out where his country supposedly exists on a map. > > > He immediately points his finger towards the Principality of Andorra, but becomes angry and confused. He’s never heard of Andorra, and can’t understand why his homeland of Taured isn’t there. According to him it should have been, for it had existed for more than 1,000 years! > > > Customs officials found him in possession of money from several different European currencies. His passport had been stamped by many airports around the globe, including previous visits to Tokyo. > > > Baffled, they took him to a local hotel and placed him in a room with two guards outside until they could get to the bottom of the mystery. The company he claimed to work for had no knowledge of him, although he had copious amounts of documentation to prove his point. > > > The hotel he claimed to have a reservation for had never heard of him either. The company officials in Tokyo he was there to do business with? Yup, you’ve guessed it – they just shook their heads too . Later, when the hotel room he was held in was opened, the man had disappeared. The police established that he could not have escaped out of the window – the room was several floors up, and there was no balcony. ? > > > He was never seen again, and the mystery was never solved. > > > Sources include: * [Cool Interesting Stuff](http://coolinterestingstuff.com/the-strange-mystery-of-the-man-from-taured) * [Reddit: Unresolved Mysteries](https://www.reddit.com/r/UnresolvedMysteries/comments/1zsyz2/on_july_1954_a_man_arrives_at_tokyo_airport_in/) Is this a true series of events in the reported facts? If so, was it solved? If not, was the story exaggerated or altered in a way to make it more mysterious, and what's the real story?
2015/09/16
[ "https://skeptics.stackexchange.com/questions/30072", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/22188/" ]
This mystery was resolved by a Brazilian YouTuber, Natanael Antonioli, in [July 2019](https://www.reddit.com/r/japan/comments/cdz9kg/hi_im_an_investigative_journalist_doing_some/). Further missing pieces were added by a [Fortean researcher in March 2020](https://forums.forteana.org/index.php?threads/the-man-from-taured-japan-1959.66992/#post-1938048) (article forthcoming, in *Fortean Times* issue 405) and [a Japanese researcher in November 2020](https://www.reddit.com/r/japan/comments/jwv0qv/i_am_japanese_i_researched_an_old_newspaper_about/). A [Reddit thread](https://old.reddit.com/r/UnresolvedMysteries/comments/llbmuh/the_man_from_tauredsolved/) and [Snopes](https://www.snopes.com/fact-check/man-from-taured-parallel-universe/) both have details. The "Man from Taured" was John Allen Kuchar Zegrus, who variously gave his birth nationality as American or Ethiopian. He claimed that he had acquired citizenship in the state of "Tuared" and that he was issued a passport in the city of Tamanrasset. [Tamanrasset](https://en.wikipedia.org/wiki/Tamanrasset) in Algeria is the real home of the [Tuareg](https://en.wikipedia.org/wiki/Tuareg_people) Berbers, who speak an Afroasiatic language. According to Japanese and Canadian newspapers, Zegrus' passport bore the slogan "Negussi Habessi" which our 21st century debunkers interpret as "Kingdom of Habessinia" (Abyssinia). In October 1959, Zegrus and his South Korean wife entered Japan using homemade Tuared passports, stamped with visas they had acquired at the Japanese embassy in Taipei. (Notably, South Korea did not have diplomatic relations with Japan at this time, so it would have been hard for a South Korean to enter Japan.) Over the subsequent year, he defrauded several banks by claiming to be an Egyptian or American intelligence agent. In August 1960, Zegrus' wife was deported to South Korea. In December 1961, Zegrus was convicted of illegal entry and fraud and was sentenced to one year imprisonment. In November 2020, the Japanese researcher made a more detailed study [in Japanese](https://note.com/taraiochi/n/n13c0b07fa3a6) which no English speaker has mentioned up until now. (His source is [this 1999 book](https://www.worldcat.org/title/nazo-no-dokusaisha-kin-shonichi-tepodon-choho-tero-rachi/oclc/51200147&referer=brief_results) written by a Tokyo prosecutor who handled Zegrus' case and various spy cases.) According to this very interesting post, Zegrus' actual origin was never uncovered. Zegrus maintained that Negussi Habessi was a real place and that Japan had stolen their nuclear technology. It was found that his Tuared/Negussi Habessi passport contained many legitimate visa stamps from across Southeast Asia. After he served his year in prison Japan did not know what to do with him. They saw on his passport that he entered the country from Hong Kong, so he was deported back to there. It is not known what happened to him after that. In a sense, this story is more true than it is false because Zegrus really did stick to his guns and claim that he was from a nonexistent country, and as far as the existing sources say, his true nationality was never ascertained. He was simply deported to get rid of him, and he vanishes from known records thereafter.
So far, it seems to just be an internet story that's been passed along by word of mouth. [There are no newspaper articles referencing it](https://www.reddit.com/r/UnresolvedMysteries/comments/1zsyz2/on_july_1954_a_man_arrives_at_tokyo_airport_in/) (outside of "Weird News" articles who are just passing on the internet story). It's [referenced in a few books](https://theghostinmymachine.wordpress.com/2015/07/06/unresolved-who-was-the-man-from-taured-and-did-he-even-exist-at-all/), but never with any additional information on the source of the story.
37,811,034
I have an HTML `<table>` with many columns, so when my web page is displayed on a mobile browser, it's too small. So I'm creating a media query and I want to remove some columns (That are not important). So how to remove an html column using only css ? For example, how to remove the column "B" in the middle of the table on the next example : ```css table, th, td, tr{ border:1px solid black; } table{ width:100%; } ``` ```html <table> <th>A</th> <th>B</th> <th>C</th> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> ```
2016/06/14
[ "https://Stackoverflow.com/questions/37811034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5456540/" ]
You can use n-th child to manage table columns. ``` th:nth-child(2) { display:none; } ```
If you must use html tables I would recommend using stacktable.js. Otherwise use css display tables.
66,001,148
I am trying to grab the data from, <https://www.espn.com/nhl/standings> When I try to grab it, it is putting Florida Panthers one row to high and messing up the data. All the team names need to be shifted down a row. I have tried to mutate the data and tried, ``` dataset_one = dataset_one.shift(1) ``` and then joining with the stats table but I am getting NaN. The docs seem to show a lot of ways of joining and merging data with similar columns headers but not sure the best solution here without a similar column header to join with. Code: ``` import pandas as pd page = pd.read_html('https://www.espn.com/nhl/standings') dataset_one = page[0] # Team Names dataset_two = page[1] # Stats combined_data = dataset_one.join(dataset_two) print(combined_data) ``` Output: ``` FLAFlorida Panthers GP W L OTL ... GF GA DIFF L10 STRK 0 CBJColumbus Blue Jackets 6 5 0 1 ... 22 16 6 5-0-1 W2 1 CARCarolina Hurricanes 10 4 3 3 ... 24 28 -4 4-3-3 L1 2 DALDallas Stars 6 5 1 0 ... 18 10 8 5-1-0 W4 3 TBTampa Bay Lightning 6 4 1 1 ... 23 14 9 4-1-1 L2 4 CHIChicago Blackhawks 6 4 1 1 ... 19 14 5 4-1-1 W1 5 NSHNashville Predators 10 3 4 3 ... 26 31 -5 3-4-3 W1 6 DETDetroit Red Wings 8 4 4 0 ... 20 24 -4 4-4-0 L1 ``` Desired: ``` GP W L OTL ... GF GA DIFF L10 STRK 0 FLAFlorida Panthers 6 5 0 1 ... 22 16 6 5-0-1 W2 1 CBJColumbus Blue Jackets 10 4 3 3 ... 24 28 -4 4-3-3 L1 2 CARCarolina Hurricanes 6 5 1 0 ... 18 10 8 5-1-0 W4 3 DALDallas Stars 6 4 1 1 ... 23 14 9 4-1-1 L2 4 TBTampa Bay Lightning 6 4 1 1 ... 19 14 5 4-1-1 W1 5 CHIChicago Blackhawks 10 3 4 3 ... 26 31 -5 3-4-3 W1 6 NSHNashville Predators 8 4 4 0 ... 20 24 -4 4-4-0 L1 7 DETDetriot Red Wings 10 2 6 2 6 ... 20 35 -15 2-6-2 L6 ```
2021/02/01
[ "https://Stackoverflow.com/questions/66001148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13527775/" ]
Providing an alternative approach to @Noah's answer. You can first add an extra row, `shift` the df down by a row and then assign the header col as index 0 value. ``` import pandas as pd page = pd.read_html('https://www.espn.com/nhl/standings') dataset_one = page[0] # Team Names dataset_two = page[1] # Stats # Shifting down by one row dataset_one.loc[max(dataset_one.index) + 1, :] = None dataset_one = dataset_one.shift(1) dataset_one.iloc[0] = dataset_one.columns dataset_one.columns = ['team'] combined_data = dataset_one.join(dataset_two) ```
Just create the df slightly differently so it knows what is the proper header ``` dataset_one = pd.DataFrame(page[0], columns=["Team Name"]) ``` Then when you `join` it should be aligned properly. Another alternative is to do the following: ``` dataset_one = page[0].to_frame(name='Team Name') ```
17,134,638
If I use `get` with `defineProperty` ``` Object.defineProperty(Object.prototype,'parent',{ get:function(){return this.parentNode} }); ``` and I can call it like: `document.body.parent`, then it works. When I use `value` with `defineProperty` ``` Object.defineProperty(Object.prototype,'parent',{ value:function(x){ var temp=this.parentNode; for(var i=1;i<x;i++){temp=temp.parentNode}; return temp } }); ``` I can call it like: `document.getElementsByName("newtag").parent(2)`, means to find the parent node of newtag's parent node. **But when I put them together** it says `Uncaught TypeError: Invalid property. A property cannot both have accessors and be writable or have a value`. How can I do it so that I can call it both ways, `.parent` & `.parent(n)`? **No jQuery**
2013/06/16
[ "https://Stackoverflow.com/questions/17134638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1714907/" ]
The simplest way I see to do that is to use a foreach: ``` $myStdClass = /* ... */; $a = ''; foreach ($myStdClass as $key => $value) { if ($value) { $a .= $key; } } ```
One-liner solution: ``` $c = new stdClass(); $c->all = 0; $c->book = 0; $c->title = 1; $c->author = 1; $c->content = 0; $c->source = 0; $a = implode(',', array_keys( array_filter( (array)$c) ) ); var_dump($a); ``` Would yield ``` string(12) "title,author" ```
4,865,300
I'm looking for a way to maintain the sorting on my key-value pairs. They are sorted by variables outside of the actual key-value pairs (for better UI). I am currently using a **Hashtable**, but that does not maintain the sorting =( ``` Hashtable<Integer, String> subscriptions = getUsersSubscriptions(user); ``` Is there some simple way that Java lets one store pairs? The best idea I can think of is using **2 associated ArrayLists (one of type Integer, another of type String)**. Can someone think of something **better**?
2011/02/01
[ "https://Stackoverflow.com/questions/4865300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365985/" ]
``` SortedMap<Integer, String> myMap = new TreeMap<Integer,String>(); ``` If you have a custom sorting, pass a [`Comparator`](http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html) instance to the constructor of the [`TreeMap`](http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html). But be careful doing so, as using a Comparator that does not go well with natural Integer order would make things impossible to understand and debug.
> > Is there some simple way that Java lets one store pairs? > > > Create a custom class that stores the two properties. > > They are sorted by variables outside of the actual key-value pairs > > > Add a third property for the sort data. Then your class can implement Comparable to sort the data as required based on this property. Or you can use a custom Comparator to sort on the sort data field. Now the class instances can be stored in an ArrayList.
87,884
I am studying various ATX power supplies schematics and don't understand the need of the voltage selector as switching power supplies work at range of voltages. In most schematics i see the 110V line connected after the bridge rectifier between the resistors and filtering capacitors. Why? ![Schematics example](https://i.stack.imgur.com/o0h1S.png)
2013/11/07
[ "https://electronics.stackexchange.com/questions/87884", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/-1/" ]
In these schematics, 110VAC is connected through a [voltage doubler](http://en.wikipedia.org/wiki/Voltage_doubler#Bridge_circuit) schematic in order to get the same 310V DC after the rectifier. These solutions are pretty outdated now. The typical modern PSU is universal and can work from 90..250VAC on the input without voltage selector.
"Switching power supplies work at range of voltages." They work at a range of voltages they are designed to work at. The larger the range you want to support, the more it will cost in the design (in $, size, reliability, etc). It's one thing to make an 80W laptop supply work across 100-240V, but it's quite another to do the same for a 450W ATX supply, and the benefit to the customer is much lower. [Update: this paragraph is speculative and wrong:] The switch likely rewires the primary in the transformer so that the regulation circuit doesn't have to work over such a large range. [Update - comment added after downvotes:] OK, I've been voted down. The 2nd paragraph is speculative and wrong , so I won't protest. I am well aware than SMPS transformers don't run at line frequency, but I wasn't aware that you couldn't still have a split primary with a switch on that transformer. And the schematic was not up at the time. My ignorance of that doesn't invalidate the main point - the switched voltage doubler still serves to reduce the range over which the supply needs to adapt automatically. So that brings me to a question: is it not harder, in terms of cost/efficiency/reliability, to make a PSU that can adapt over a 1:2.6 range as opposed to 1:1.3? And, does not the tradeoff become more significant with higher power? As long as a PSU with a switch is more efficient & reliable than one without, I'll take the one with a switch for a desktop. @johnfound answer says that modern PSU are univeral without a switch - that's absolutely true for wall warts and laptop supplies, but most ATX supplies have switches. So it's a good question, and I believe my first paragraph is a good answer. But I'm prepared to learn more.
35,410,867
I'm trying to combine the Datepicker and Timepicker directives to get the date from the first and the time from the second in a combined Date object. I came across some examples that are not using these directives like this one [Combining Date and Time input strings as a Date object](https://stackoverflow.com/questions/21553132/combining-date-and-time-input-strings-as-a-date-object). However when I try to apply something similar to my case it's not working. Console returns "TypeError: $scope.dt.split is not a function". Above is the function I try to use which is called by $watch. ``` function tryCombineDateTime() { if ($scope.dt && $scope.mytime) { var dateParts = $scope.dt.split('-'); var timeParts = $scope.mytime.split(':'); if (dateParts && timeParts) { dateParts[1] -= 1; $scope.fullDate = new Date(Date.UTC.apply(undefined, dateParts.concat(timeParts))).toISOString(); } } } ``` Here is a plunker showing the problem. <http://plnkr.co/edit/tnbE3LWQTTzLhLWXLCQB?p=preview> I would prefer a solution based on my Plunker as I don't want to install other components like DateTimePicker.
2016/02/15
[ "https://Stackoverflow.com/questions/35410867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5390799/" ]
Internally it is really correct: ``` private static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count) { using (IEnumerator<TSource> enumerator = source.GetEnumerator()) { while (count > 0 && enumerator.MoveNext()) --count; if (count <= 0) { while (enumerator.MoveNext()) yield return enumerator.Current; } } } ``` If you want to skip for `IEnumerable<T>` then it works right. There are no other way except enumeration to get specific element(s). But you can write own extension method on `IReadOnlyList<T>` or `IList<T>` (if this interface is implemented in collection used for your elements). ``` public static class IReadOnlyListExtensions { public static IEnumerable<T> Skip<T>(this IReadOnlyList<T> collection, int count) { if (collection == null) return null; return ICollectionExtensions.YieldSkip(collection, count); } private static IEnumerable<T> YieldSkip<T>(IReadOnlyList<T> collection, int count) { for (int index = count; index < collection.Count; index++) { yield return collection[index]; } } } ``` In addition you can implement it for `IEnumerable<T>` but check inside for optimization: ``` if (collection is IReadOnlyList<T>) { // do optimized skip } ``` Such solution is used a lot of where in Linq source code (but not in Skip unfortunately).
Depends on your implementation, but it would make sense to use indexed arrays for the purpose, instead.
72,283
I might be wrong but I think it must be 2^6 = 64 integers?
2017/03/31
[ "https://cs.stackexchange.com/questions/72283", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/68752/" ]
Here is a more streamlined version of your proof. Notice first that $$ A \cup B = (A \setminus B) \cup (B \setminus A) \cup (A \cap B), \\ A = (A \setminus B) \cup (A \cap B), \\ B = (B \setminus A) \cup (A \cap B). $$ All these decompositions are into disjoint sets, and so $$ |A \cup B| = |A \setminus B| + |B \setminus A| + |A \cap B| |A| = |A \setminus B| + |A \cap B|, \\ |B| = |B \setminus A| + |A \cap B|. $$ A bit of algebra shows that $$ |A \cup B| = |A| + |B| - |A \cap B|. $$ Given this, $|A \cap B| \geq 0$ implies the desired result, $|A \cup B| \leq |A| + |B|$.
A similar, shorter, proof relies on the *inclusion/exclusion principle*, namely if $A$ and $B$ are finite sets, then $$ |A\cup B| = |A| + |B| - |A\cap B| $$ (If you're not familiar with this identity, look at a small Venn diagram.) So we can conclude $$ |A\cup B| = |A| + |B| - |A\cap B| \le |A| + |B| $$
41,268
we have a requirement where we need to search metadata within Salesforce for some specifc keywords? and also replace them. As an outside tool we can use Eclipse, but how it can be done within Salesforce?
2014/06/23
[ "https://salesforce.stackexchange.com/questions/41268", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/4690/" ]
I would take a look at the [Metadata Wrapper](https://github.com/financialforcedev/apex-mdapi) [Andrew Fawcett](https://salesforce.stackexchange.com/users/286/andrew-fawcett) has written - in the git hub repo linked to above, he shows how you can build a MetaData browser...so I would think you can develop that to provide native search as well...
You can access metadata for all the components in salesforce ONLY using Metadata API and for that you can use tools like Force.com IDE/ANT to download or retrieve entire metadata components which are available in eclipse and do a search for the component/variable/keyword name to see where it is referenced.
230,532
On the one hand, you lose "to" your rival. On the other hand, a defeat is done or comes "from" them (there are [some](https://www.google.ru/search?q=%22defeat%20from%22%20-%22jaws%20of%20victory%22&newwindow=1&tbm=nws&sxsrf=ACYBGNQnJswneyt4xFRkEGiVAmQQciXbQw:1574282402868&ei=oqTVXbjQNM2QrgSgxKTIAQ&start=0&sa=N&ved=0ahUKEwi4qZj70vnlAhVNiIsKHSAiCRk4MhDy0wMIUQ&biw=1536&bih=730&dpr=1.25) search results for the latter but mainly from second-rate publications). I think you can do both but 'to' is better. Am I right? I am talking about sentences in this form: > > "[subject] suffered a defeat to/from [object]" > > > For example: > > Liverpool suffered a defeat **to** Tottingham. > > The Labor Party suffered a defeat **from** the Conservative Party. > > >
2019/11/20
[ "https://ell.stackexchange.com/questions/230532", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/101901/" ]
**the dead** (when used as a noun) is what is known as an *uncountable noun*. It is similar to many other words which describe something made up of a varying number of other things, or where divisions are hard to define, such as "rice", or "music". For these words, singular vs. plural does not actually make any sense (you would not say "playing musics", because no matter how much of it you play, it's all still just (uncountable) "music"). Likewise, with uncountable nouns (as the name implies) you can't talk about numbers of them, or use the indefinite article (which implies there's potentially more than one), so for example, you also cannot say "a dead" (you would instead need to say "a dead person"). (Alternately, there is also another way to look at this in the case of **dead**: The noun "dead" is essentially short for "dead people", so it is arguably already plural. It has no singular form.)
Certain groups of people are referred to using 'the' followed by an adjective, when the group members share a condition denoted by the adjective. The young, the old, the newborn, the dead, the brave, the rich, the poor (etc). > > Adjectives are often used without nouns. > > > To refer to some well-known groups of people > > > The structure **the + adjective** is used to talk about some well-known > groups of people. Examples are: the blind, the deaf, the unemployed, > the rich, the poor, the young, the old, the dead etc. > > > [Adjectives used without nouns](https://www.englishgrammar.org/adjectives-nouns/)
22,741,824
I am using the following codes to add two button to self.navigationItem.rightBarButtonItems, and I think in iOS7, the space between two buttons are too wide, is there a way to decrease the space between these two buttons? ``` UIBarButtonItem *saveStyleButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"save.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(saveStyle)]; UIBarButtonItem *shareStyleButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(shareStyle)]; NSArray *arr= [[NSArray alloc] initWithObjects:shareStyleButton,saveStyleButton,nil]; self.navigationItem.rightBarButtonItems=arr; ``` Appreciate any hint or idea.
2014/03/30
[ "https://Stackoverflow.com/questions/22741824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1722027/" ]
My solution is using a custom view for right bar buttons. Create a horizontal stackview with equal spacing and add any number of buttons as subview. Sample code: ``` func addRightBarButtonItems() { let btnSearch = UIButton.init(type: .custom) btnSearch.setImage(UIImage(systemName: "magnifyingglass"), for: .normal) btnSearch.addTarget(self, action: #selector(MyPageContainerViewController.searchButtonPressed), for: .touchUpInside) let btnEdit = UIButton.init(type: .custom) btnEdit.setImage(UIImage(systemName: "pencil"), for: .normal) btnEdit.addTarget(self, action: #selector(MyPageContainerViewController.editButtonPressed), for: .touchUpInside) let stackview = UIStackView.init(arrangedSubviews: [btnEdit, btnSearch]) stackview.distribution = .equalSpacing stackview.axis = .horizontal stackview.alignment = .center stackview.spacing = 8 let rightBarButton = UIBarButtonItem(customView: stackview) self.navigationItem.rightBarButtonItem = rightBarButton } ```
**Swift 5** If you want to add space between two Bar Button items then add a flexible space in between, the two buttons will be pushed to the left and right edge as the flexible space expands to take up most of the toolbar. For Example: ``` let toolBar = UIToolbar() var items = [UIBarButtonItem]() let backBarButton = UIBarButtonItem(image: UIImage(named: "icon-back.png"), style: .done, target: self, action: #selector(backButtonTapped)) let nextBarButton = UIBarButtonItem(image: UIImage(named: "icon-next.png"), style: .done, target: self, action: #selector(nextButtonTapped)) let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) items.append(backBarButton) items.append(spacer) items.append(nextBarButton) toolBar.setItems(items, animated: true) ```
48,650,191
I will keep this question short. Similar questions on S/O do not address what I am wondering about, and I have struggled to find an answer. When I point to a CBV in my urls.py, I use the as\_view class method: > > ...MyView.as\_view()... > > > Looking at the actual script (django/django/views/generic/base.py), the as\_view returns a function 'view' that is specified within the actual class method itself. How come it returns the function with this line: > > return view > > > Why does it not have to specify: > > return view(request, \*args, \*\*kwargs) > > > I tried this out myself. I went and created a FBV\_1 that returned yet another FBV\_2 (the view responsible for delivering all functionality), in this same manner: > > return fbv\_2 > > > It generated an error. I had to return fbv\_2(request) to access it. Thank you in advance. Apologies for any idiomatic expression-errors, my Swedish sometimes gets the best of me.
2018/02/06
[ "https://Stackoverflow.com/questions/48650191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9121609/" ]
"view" is the function name name. In this case we have defined the function within another function - as\_view(). Think of the name "view" as a variable pointing to code rather than data. ``` view ``` is the function - we have defined it (within the as\_view() function). It already knows what arguments to expect from the line: ``` def view(request, *args, **kwargs): ... .. ``` A function is just code. To execute the function you would usually type the function name followed by parenthesis enclosing any arguments. ``` view(request, kwarg1=var1 , kwarg2=var2) ``` calls the function called view and executes the code. I hope that makes sense. Its not difficult, but a bit tricky to describe.
All functions in Python are first-class objects. You don`t have to call it before return, you can do whatever operations you like with functions without calling them, you can even set attrs for functions: ``` func.level = 5 ``` The difference is just when you call function on return, function response would be returned, and when don't the function itself is returned. Basically, is\_view method returns the same view function as you would`ve written in your views.py: ``` def view(request): ... return HttpResponse(...) ``` As you can see it always has request as the first param.
485,024
When starting out with a new application, would you rather just use an existing dependency framework and risk the possible shortcomings, or would you opt to write your own which is completely adaptable and why?
2009/01/27
[ "https://Stackoverflow.com/questions/485024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31770/" ]
I would of course use one of the available solutions. Although it starts out simple, there are some features (like various proxying features) that are definitely not simple in full featured DI frameworks. Maybe you want some AOP too ? But any decent DI framework should have little impact on the way you write your actual code, so it is possible to argue that it doesn't matter that much for your code. It may matter for whoever's paying though. In your situation I'd get a DI framework with source code available, and get to know *that* source instead of writing your own.
You can write a wrapper around the dependency injection bits so if you want to switch DI frameworks later, you don't need to worry about library dependencies or changing code anywhere. For example, instead of directly calling container.Resolve, write a factory class that calls container.Resolve for you, and only call into the factory class.
24,738,169
I need the current system datetime in the format "yyyy-mm-dd:hh:mm:ss". <https://stackoverflow.com/a/19079030/2663388> helped a lot. `new Date().toJSON()` is showing "2014-07-14T13:41:23.521Z" Can someone help me to extract "yyyy-mm-dd:hh:mm:ss" from "2014-07-14T13:41:23.521Z"?
2014/07/14
[ "https://Stackoverflow.com/questions/24738169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2663388/" ]
Seems that there is no good way to do it with original code unless using Regex. There are some modules such as [Moment.js](http://momentjs.com/) though. If you are using npm: ``` npm install moment --save ``` Then in your code: ``` var moment = require('moment'); moment().format('yyyy-mm-dd:hh:mm:ss'); ``` That may be much easier to understand.
What about: ``` new Date().toString().replace(/T/, ':').replace(/\.\w*/, ''); ``` Returns for me: ``` 2014-07-14:13:41:23 ``` But the more safe way is using `Date` class methods which works in javascript (browser) and node.js: ``` var date = new Date(); function getDateStringCustom(oDate) { var sDate; if (oDate instanceof Date) { sDate = oDate.getYear() + 1900 + ':' + ((oDate.getMonth() + 1 < 10) ? '0' + (oDate.getMonth() + 1) : oDate.getMonth() + 1) + ':' + oDate.getDate() + ':' + oDate.getHours() + ':' + ((oDate.getMinutes() < 10) ? '0' + (oDate.getMinutes()) : oDate.getMinutes()) + ':' + ((oDate.getSeconds() < 10) ? '0' + (oDate.getSeconds()) : oDate.getSeconds()); } else { throw new Error("oDate is not an instance of Date"); } return sDate; } alert(getDateStringCustom(date)); ``` Returns in node.js: `/usr/local/bin/node date.js 2014:07:14:16:13:10` And in Firebug: `2014:07:14:16:14:31`
12,197,546
I am newbie to mongodb (java). I need to execute list of commands(queries in relational) by using something similar to procedures in relational db. Is it possible in mongodb?
2012/08/30
[ "https://Stackoverflow.com/questions/12197546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1386792/" ]
MongoDB has no real sense of stored procedures. It has server side functions however these functions: * Do not work with sharding * Are slow * Must be evaled (Dr. Evil) * Are only really designed to be used within Map Reduces to stop you from having to house mutiple copies of common code within many places. However you can achieve it with `$where` or `eval`ing an actual function name within `system.js`. But then these actually don't run "server-side". Using a `exec` type command in your app to call the shell won't be a good idea either. The script files you run in shell are as much client side as your own app so that's just pointless. MongoDB also does not allow triggers however they are within the JIRA: <https://jira.mongodb.org/browse/SERVER-124> but are not scheduled. You will need to place triggers on client side within your coding. > > queries in relational > > > NoSQL is not relational. You might want to read up on how to design a proper schema for MongoDB, here is a starting point: <http://www.mongodb.org/display/DOCS/Schema+Design>. This will teach you the essence of MongoDB and how to choose the right structure.
You can create server-side javascript functions, yes. But I advise against it, because it's will be 1. quite slow; 2. not version controlled. Read more: <http://www.mongodb.org/display/DOCS/Server-side+Code+Execution#Server-sideCodeExecution-Storingfunctionsserverside>
44,565,460
I want to pass a string variable from servlet to jsp and store it's value in another variable in jsp. Here is servlet: ``` request.setAttribute("rep", docbase); request.getRequestDispatcher("Welcome.jsp").forward(request, response); ``` Here is my jsp: ``` </script> <script type="text/ajavscript"> var repository = '${rep}'; </script> <script type="text/javascript"> $(document).ready(function() { alert('.repository'); $.ajax({ url:'ServiceToFetchDocType', data: {name:repository}, type:'post', cache:false, success: function(response) { } }); }); </script> ``` The alert box is showing undefined. I'm not sure if I'm able to pass the value successfully.
2017/06/15
[ "https://Stackoverflow.com/questions/44565460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6876654/" ]
To answer your question. The problem with your insertion2 function is that the root variable will point to nullptr(NULL) at the called place and a new memory is allocated and pointed to a local reference inside insertion2() function. The reference change to a new memory location will not have any impact on the reference @ calling place. As pointed by others, this call will always leak memory in @clearer answer. To make this function to work. Move the object creation part @ calling place and leave just the insert to this function. something like the below should work. ``` void insertion2(node *root, node *new_node) { if(root==nullptr) root=new_node; else if(a<root->data) insertion2(root->left,new_node); else insertion2(root->right,new_node); } // Create the new node and call the insert function new_node = newnode(a); insertion2(root, new_node); ``` Hope it clarifies your doubt!
The Root pointer from the calling method needs to be updated as well. So, you'll have to call the Insert2 method using something similar: **Insert2(&BSTNodePtr, a)**. When you pass the address of the variable BSTNodePtr, the Insert2 method can update it's content. Try this instead: ``` void Insert2(BSTNode **root, int a){ if (*root==NULL){ *root = new BSTNode(a); } else if (a<= (*root)->data){ Insert2(&((*root)->left), a); } else{ Insert2(&((*root)->right), a); } } ```
436,302
So this is something that has been at the back of my mind for a while. I've seen mentions of it, I've read the [fitness web page](http://fitnesse.org/FitNesse.TwoMinuteExample) and I still don't quite grok it. It seems like Fitnesse is yet another testing framework like NUnit or MbUnit or any of the others because you define inputs and outputs that you want to see but it seems to be aimed at testing the application as a whole rather than as units. If that is so, how does it run? Do you have to design your application with hooks for fit testing? Where on the spectrum of testing does it actually fall? And can someone give me a good example of where and how fit tests could be used and what are some advantages/disadvantages?
2009/01/12
[ "https://Stackoverflow.com/questions/436302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
The difference between NUnit/MbUnit and FitNesse is that NUnit/MbUnit are intended to be used for unit tests, while FitNesse is for acceptance tests. Unit tests test a single, small unit of code, such as a method, to ensure that it executes as the programmer intended. For example, you might use a unit test to ensure that a factorial-computing method returns the correct results for a set of numbers, including some edge cases. Acceptance tests are intended to test whether a high-level design requirement is met. As an example, if you were writing a Pac-Man clone, and one of the requirements was "A new level begins when the last dot of the previous level is eaten," an acceptance test would test to see whether that requirement as a whole is satisfied by the code--not the specific pieces of code that consume a dot, check ending conditions, and load new levels (although that code would be exercised in the process of running the acceptance test). Acceptance tests typically are written without regard to the specific implementation of the requirement. A lot of QA departments execute long lists of acceptance tests by hand, which can be very time consuming. Fit and FitNesse are tools that assist in automating acceptance tests, which can save a lot of time. There's a lot of good information on acceptance tests at [Ward Cunningham's wiki](http://c2.com/cgi/wiki?AcceptanceTest).
`FitNesse` is basically a `wiki` which stores all the test cases. Most probably for acceptance testing. In Test first development the test cases should be written at requirement gathering stage only i.e., the customer will also be included in writing tests which tends to write the tests regarding acceptance testing... So the advantage is there is no separate acceptance testing is needed if the application meets all the user requirements. The disadvantage is when ever there is a change in the requirements the test cases also to be changed but of course it is not a big deal. Also `fitnesse` will be suitable for small and medium projects. In case of large projects it could be clumsy because `Fitnesse` cannot export PDF files it only exports spread sheets like excel or worddoc. So it is a disadvantage that it can't be used for large projects.
41,570,513
I would like to replace all non capitalised words in a text with "-".length of the word. For instance I have the following Text (German): > > Florian Homm wuchs als Sohn des mittelständischen Handwerksunternehmers Joachim Homm und seiner Frau Maria-Barbara „Uschi“ Homm im hessischen Bad Homburg vor der Höhe auf. Sein Großonkel mütterlicherseits war der Unternehmer Josef Neckermann. Nach einem Studium an der Harvard University, das er mit einem Master of Business Administration an der Harvard Business School abschloss, begann Homm seine Tätigkeit in der US-amerikanischen Finanzwirtschaft bei der Investmentbank Merrill Lynch, danach war er bei dem US-Fondsanbieter Fidelity Investments, der Schweizer Privatbank Julius Bär und dem US-Vermögensverwalter Tweedy Browne.... > > > should be transformed into > > Florian Homm ---- --- Sohn --- ------------ Handwerksunternehmers Joachim Homm --- ------ Frau Maria-Barbara „Uschi“ Homm -- ---------- Bad Homburg --- Höhe ---. .... > > >
2017/01/10
[ "https://Stackoverflow.com/questions/41570513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6743057/" ]
Try something like this ``` s.split.map { |word| ('A'..'Z').include?(word[0]) ? word : '-' * word.length }.join(' ') ```
``` r = / (?<![[:alpha:]]) # do not match a letter (negative lookbehind) [[:lower:]] # match a lowercase letter [[:alpha:]]* # match zero or more letters /x # free-spacing regex definition mode str = "Frau Maria-Barbara „Uschi“ Homm im hessischen Bad Homburg vor der Höhe auf." str.gsub(r) { |m| '-'*m.size } #=> "Frau Maria-Barbara „Uschi“ Homm -- ---------- Bad Homburg --- --- Höhe ---." "die Richter/-innen".gsub(r) { |m| '-'*m.size } #=> "--- Richter/------" "Jede(r) Anwältin und Anwalt".gsub(r) { |m| '-'*m.size } #=> "Jede(-) Anwältin --- Anwalt" ```
20,295,075
``` Insert into employee (newsalary) values ('21840'), ('15600'), ('26000'), ('28847'), ('26000'), ('28600'), ('32500'), ('39000'), ('32500'), ('13026'), ('39000'), ('13026') ``` I have oldsalary with 30% increase, so i have to add new column with new salary values in new column name (newsalary) without changing any values with any other columns within same table. how can i do that?
2013/11/30
[ "https://Stackoverflow.com/questions/20295075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050973/" ]
The character ” (U+201D RIGHT DOUBLE QUOTATION MARK) is very different from the character " (U+0022 QUOTATION MARK). The latter is defined to act as attribute value delimiter in HTML; the former has no special significance in HTML, it is just yet another data character. Thus, the attribute value specified is `”red”`´, with the right double quotation marks included, a total of five characters. It is of course an invalid color value. The error recovery that browsers apply, and that is being standardized in HTML5, see HTML5 CR, clause [2.4.6 Colors](http://www.w3.org/TR/html5/infrastructure.html#colors), is that any character that is not a hexadecimal digit is replaced by the digit 0, and then if the length of the string is not a multiple of three, 0 digits are appended to make it so. So first the browser converts `”red”` to `00ed0`, then appends `0` to get `00ed00`, a green color. This is then treated as if it were prefixed by `#`. If you use e.g. the developer tools (F12) in Chrome to inspect the element, you will see that the styles for the `font` element have `color: rgb(0, 237, 0);`, which is an alternative notation for `#00ed00`. In Firefox, using Firebug, you will see it as `#00ED00`.
If the color value isn't equal to the keywords such as "red","blue" and so on,The browser assumes that value is three **hex values**, each 2 chars long just as John Hornsby said. All the invalid chars be made 0. IF the color value length less then 6 ,the zero will be appended in the end.
872,442
In [Code Complete 2](https://rads.stackoverflow.com/amzn/click/com/0735619670) (page 601 and 602) there is a table of "Cost of Common Operations". The baseline operation integer assignment is given a value 1 and then the relative time for common operations is listed for Java and C++. For example: ``` C++ Java Integer assignment 1 1 Integer division 5 1.5 Floating point square root 15 4 ``` The question is has anyone got this data for C#? I know that these won't help me solve any problems specifically, I'm just curious.
2009/05/16
[ "https://Stackoverflow.com/questions/872442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31765/" ]
I implemented some of the tests from the book. Some raw data from my computer: Test Run #1: TestIntegerAssignment 00:00:00.6680000 TestCallRoutineWithNoParameters 00:00:00.9780000 TestCallRoutineWithOneParameter 00:00:00.6580000 TestCallRoutineWithTwoParameters 00:00:00.9650000 TestIntegerAddition 00:00:00.6410000 TestIntegerSubtraction 00:00:00.9630000 TestIntegerMultiplication 00:00:00.6490000 TestIntegerDivision 00:00:00.9720000 TestFloatingPointDivision 00:00:00.6500000 TestFloatingPointSquareRoot 00:00:00.9790000 TestFloatingPointSine 00:00:00.6410000 TestFloatingPointLogarithm 00:00:41.1410000 TestFloatingPointExp 00:00:34.6310000 Test Run #2: TestIntegerAssignment 00:00:00.6750000 TestCallRoutineWithNoParameters 00:00:00.9720000 TestCallRoutineWithOneParameter 00:00:00.6490000 TestCallRoutineWithTwoParameters 00:00:00.9750000 TestIntegerAddition 00:00:00.6730000 TestIntegerSubtraction 00:00:01.0300000 TestIntegerMultiplication 00:00:00.7000000 TestIntegerDivision 00:00:01.1120000 TestFloatingPointDivision 00:00:00.6630000 TestFloatingPointSquareRoot 00:00:00.9860000 TestFloatingPointSine 00:00:00.6530000 TestFloatingPointLogarithm 00:00:39.1150000 TestFloatingPointExp 00:00:33.8730000 Test Run #3: TestIntegerAssignment 00:00:00.6590000 TestCallRoutineWithNoParameters 00:00:00.9700000 TestCallRoutineWithOneParameter 00:00:00.6680000 TestCallRoutineWithTwoParameters 00:00:00.9900000 TestIntegerAddition 00:00:00.6720000 TestIntegerSubtraction 00:00:00.9770000 TestIntegerMultiplication 00:00:00.6580000 TestIntegerDivision 00:00:00.9930000 TestFloatingPointDivision 00:00:00.6740000 TestFloatingPointSquareRoot 00:00:01.0120000 TestFloatingPointSine 00:00:00.6700000 TestFloatingPointLogarithm 00:00:39.1020000 TestFloatingPointExp 00:00:35.3560000 (1 Billion Tests Per Benchmark, Compiled with Optimize, AMD Athlon X2 3.0ghz, using Jon Skeet's microbenchmarking framework available at <http://www.yoda.arachsys.com/csharp/benchmark.html>) Source: ``` class TestBenchmark { [Benchmark] public static void TestIntegerAssignment() { int i = 1; int j = 2; for (int x = 0; x < 1000000000; x++) { i = j; } } [Benchmark] public static void TestCallRoutineWithNoParameters() { for (int x = 0; x < 1000000000; x++) { TestStaticRoutine(); } } [Benchmark] public static void TestCallRoutineWithOneParameter() { for (int x = 0; x < 1000000000; x++) { TestStaticRoutine2(5); } } [Benchmark] public static void TestCallRoutineWithTwoParameters() { for (int x = 0; x < 1000000000; x++) { TestStaticRoutine3(5,7); } } [Benchmark] public static void TestIntegerAddition() { int i = 1; int j = 2; int k = 3; for (int x = 0; x < 1000000000; x++) { i = j + k; } } [Benchmark] public static void TestIntegerSubtraction() { int i = 1; int j = 6; int k = 3; for (int x = 0; x < 1000000000; x++) { i = j - k; } } [Benchmark] public static void TestIntegerMultiplication() { int i = 1; int j = 2; int k = 3; for (int x = 0; x < 1000000000; x++) { i = j * k; } } [Benchmark] public static void TestIntegerDivision() { int i = 1; int j = 6; int k = 3; for (int x = 0; x < 1000000000; x++) { i = j/k; } } [Benchmark] public static void TestFloatingPointDivision() { float i = 1; float j = 6; float k = 3; for (int x = 0; x < 1000000000; x++) { i = j / k; } } [Benchmark] public static void TestFloatingPointSquareRoot() { double x = 1; float y = 6; for (int x2 = 0; x2 < 1000000000; x2++) { x = Math.Sqrt(6); } } [Benchmark] public static void TestFloatingPointSine() { double x = 1; float y = 6; for (int x2 = 0; x2 < 1000000000; x2++) { x = Math.Sin(y); } } [Benchmark] public static void TestFloatingPointLogarithm() { double x = 1; float y = 6; for (int x2 = 0; x2 < 1000000000; x2++) { x = Math.Log(y); } } [Benchmark] public static void TestFloatingPointExp() { double x = 1; float y = 6; for (int x2 = 0; x2 < 1000000000; x2++) { x = Math.Exp(6); } } private static void TestStaticRoutine() { } private static void TestStaticRoutine2(int i) { } private static void TestStaticRoutine3(int i, int j) { } private static class TestStaticClass { } ```
Straight from the source, **[Know what things cost](http://msdn.microsoft.com/en-us/library/ms973852.aspx)**. IIRC Rico Mariani had relative measures as the ones you asked for [on his blog](http://blogs.msdn.com/ricom/default.aspx), I can't find it anymore, though (I know it's in one of thoe twohudnred "dev" bookmarks...)
56,937,577
I'm actually having some troubles optimising my algorithm: ---------------------------------------------------------- I have a disk (centered in 0, with radius 1) filled with triangles (not necessarily of same area/length). There could be a HUGE amount of triangle (let's say from `1k` to **`300k`** triangles) My goal is to find as quick as possible in which triangle a point belongs. The operation **has to be repeated** a large amount of time (around **`10k` times**). For now the algorithm I'm using is: I'm computing the barycentric coordinates of the point in each triangle. If the first coefficient is between 0 and 1, I continue. If it's not, I stop. Then I compute the second coefficient with the same idea, and the third, and I do this for every triangle. I can't think of a way to use the fact that I'm working on a disc (and the fact that I have an Euclidean distance to help me "target" the good triangles directly): If I try to compute the distance from my point to every "center" of triangles : **1)** it's already more operations than what I'm doing when I brute force it with barycentric coordinates **2)** I will have to order a vector containing the Euclidean distances of all triangles to my point. **3)** I have absolutely no guarantee that the closest triangle to my point will be the good triangle. I feel like I'm missing something, and that I could pre-compute, something to help me spot the good "area" before starting the brute force part. The algorithm is already parallelised (using OpenMP): I'm calling the below function on a parallel for. ``` bool Triangle2D::is_in_triangle(Vector2d Point) { double denominator = ((Tri2D(1, 1) - Tri2D(2, 1))*(Tri2D(0, 0) - Tri2D(2, 0)) + (Tri2D(2, 0) - Tri2D(1, 0))*(Tri2D(0, 1) - Tri2D(2, 1))); // Computing the first coefficient double a = ((Tri2D(1, 1) - Tri2D(2, 1))*(Point(0) - Tri2D(2, 0)) + (Tri2D(2, 0) - Tri2D(1, 0))*(Point(1) - Tri2D(2, 1))) / denominator; if (a < 0 || a>1) { return(false); } // Computing the second coefficient double b = ((Tri2D(2, 1) - Tri2D(0, 1))*(Point(0) - Tri2D(2, 0)) + (Tri2D(0, 0) - Tri2D(2, 0))*(Point(1) - Tri2D(2, 1))) / denominator; if (b < 0 || b>1) { return(false); } // Computing the third coefficient double c = 1 - a - b; if (c < 0 || c>1) { return(false); } return(true); } ``` Next step is probably to look at GPU parallelisation, but I need to make sure that the idea behind the code is good enough. For now it takes approximately **`2min30`** for `75k` triangles and `10k` points, but this isn't fast enough. --- **Edit:** `Triangle2D` uses Eigen matrix to store coordinates
2019/07/08
[ "https://Stackoverflow.com/questions/56937577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11755027/" ]
All long-bearded **HPC-professionals**, kindly do permit a bit scholastically elaborated approach here, which may ( in my honest opinion ) become interesting, if not enjoyed by, for our Community Members, that feel themselves a bit more junior than you professionally feel yourselves and who may get interested in a bit deeper look into performance-motivated code-design, performance tweaking and other parallel-code risks and benefits, that you know on your own hard-core HPC-computing experience so well and so deep. Thank you. a) ALGORITHM (as-is) can get ~2X speedup a low-hanging fruit+more surprises yet2come b) OTHER ALGORITHM may get ~40~80X speedup boost due2geometry c) TIPS FOR THE BEST PARALLEL CODE + ULTIMATE PERFORMANCE **GOAL** : A target runtime for **`10k` points** in **`300k` triangles** would be **2-3min** on a computer with an i5 8500, 3GHz, 6core, NVIDIA Quadro P400 (have to try GPU computing, not even sure if it's worth it) [enter image description here](https://i.stack.imgur.com/qgCPt.png) ------------------------------------------------------------------- While this may seem as a long journey, the problem is nice and deserves a bit closer look, so please, bear with me during the flow of utmost-performance motivated thinking. a) ALGORITHM (as-is) ANALYSIS: The as-is use of Barycentric coordinate system is a nice trick, the straight implementation of which costs a bit more than about (20 FLOPs + 16 MEM/REG-I/O-ops) in best case and slightly above (30 FLOPs + 30 MEM/REG-I/O-ops). There are a few polishing touches, that may reduce these execution costs down right by avoiding some expensive and even not important operations from ever taking place: ``` -------------------------------------------------------------------------------------- double denominator = ( ( Tri2D( 1, 1 ) - Tri2D( 2, 1 ) // -------------------------- 2x MEM + OP-1.SUB ) * ( Tri2D( 0, 0 ) //--------------------- + OP-3.MUL - Tri2D( 2, 0 ) //--------------------- 2x MEM + OP-2.SUB ) + ( Tri2D( 2, 0 ) //--------------- + OP-7.ADD - Tri2D( 1, 0 ) //--------------- 2x MEM + OP-4.SUB ) * ( Tri2D( 0, 1 ) //--------- + OP-6.MUL - Tri2D( 2, 1 ) //--------- 2x MEM + OP-5.SUB ) ); // Computing the first coefficient ------------------------------------------------------------------------------------------------------ double a = ( ( Tri2D( 1, 1 ) - Tri2D( 2, 1 ) //-------------------------- 2x MEM + OP-8.SUB ) * ( Point(0) //------------------------ + OP-A.MUL - Tri2D( 2, 0 ) //--------------------- 2x MEM + OP-9.SUB ) + ( Tri2D( 2, 0 ) //--------------- + OP-E.ADD - Tri2D( 1, 0 ) //--------------- 2x MEM + OP-B.SUB ) * ( Point(1) //-------------- + OP-D.MUL - Tri2D( 2, 1 ) //--------- 2x MEM + OP-C.MUL ) ) / denominator; //-------------------------- 1x REG + OP-F.DIV //----------- MAY DEFER THE MOST EXPENSIVE DIVISION UNTIL a third coeff is indeed first needed, if ever------------[3] if (a < 0 || a>1) { // ----------------------------------------------------------------------------- a < 0 ~~ ( sign( a ) * sign( denominator ) ) < 0 return(false); // ------------------------------------------------------------------------------ a > 1 ~~ || a > denominator } // Computing the second coefficient double b = ( ( Tri2D( 2, 1 ) - Tri2D( 0, 1 ) ) //--------- 2x MEM + OP-16.SUB * ( Point(0) - Tri2D( 2, 0 ) ) //--------- 2x MEM + OP-17.SUB + OP-18.MUL + ( Tri2D( 0, 0 ) - Tri2D( 2, 0 ) ) //--------- 2x MEM + OP-19.SUB + OP-22.ADD * ( Point(1) - Tri2D( 2, 1 ) ) //--------- 2x MEM + OP-20.SUB + OP-21.MUL ) / denominator; //-------------------------- 1x REG + OP-23.DIV //---------- MAY DEFER THE MOST EXPENSIVE DIVISION UNTIL a third coeff is indeed first needed, if ever -----------[3] if (b < 0 || b>1) { // ----------------------------------------------------------------------------- b < 0 ~~ ( sign( b ) * sign( denominator ) ) < 0 return(false); // ------------------------------------------------------------------------------ b > 1 ~~ || b > denominator } // Computing the third coefficient double c = 1 - a - b; // ------------------------------------------- 2x REG + OP-24.SUB + OP-25.SUB // 1 -(a - b)/denominator; //--------------------------------------------------------------- MAY DEFER THE MOST EXPENSIVE DIVISION EXECUTED BUT HERE, IFF INDEED FIRST NEEDED <---HERE <----------[3] ``` * repeated re-evaluations, that appear in the original may get explicitly crafted out by manual assign/re-use, yet, there is a chance a good optimising compiler may get these evicted within a use of **`-O3`** enforced optimisation flag. * **[do not hesitate to profile](https://godbolt.org/z/q9SUDw)** even this lowest-hanging fruit, to polish the most expensive parts. [![enter image description here](https://i.stack.imgur.com/g8dnQ.png)](https://i.stack.imgur.com/g8dnQ.png) --- ``` //------------------------------------------------------------------ double Tri2D_11_sub_21 = ( Tri2D( 1, 1 ) - Tri2D( 2, 1 ) ), //====================================================== 2x MEM + OP-a.SUB (REG re-used 2x) Tri2D_20_sub_10 = ( Tri2D( 2, 0 ) - Tri2D( 1, 0 ) ), //====================================================== 2x MEM + OP-b.SUB (REG re-used 2x) Tri2D_00_sub_20 = ( Tri2D( 0, 0 ) - Tri2D( 2, 0 ) ); //====================================================== 2x MEM + OP-c.SUB (REG re-used 1~2x) //----------------------- double denominator = ( ( /* Tri2D( 1, 1 ) - Tri2D( 2, 1 ) // -------------------------- 2x MEM + OP-1.SUB (avoided by re-use) */ Tri2D_11_sub_21 //=========================================== 1x REG + OP-d.MUL ) * ( /* Tri2D( 0, 0 ) //--------------------- + OP-3.MUL - Tri2D( 2, 0 ) //--------------------- 2x MEM + OP-2.SUB (avoided by re-use) */ Tri2D_00_sub_20 //===================================== 1x REG + OP-f.ADD ) + ( /* Tri2D( 2, 0 ) //--------------- + OP-7.ADD - Tri2D( 1, 0 ) //--------------- 2x MEM + OP-4.SUB (avoided by re-use) */ Tri2D_20_sub_10 //=============================== 1x REG + OP-e.MUL ) * ( Tri2D( 0, 1 ) //--------- + OP-6.MUL - Tri2D( 2, 1 ) //--------- 2x MEM + OP-5.SUB ) ); //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ // // Computing the first coefficient ------------------------------------------------------------------------------------------------------ // double enumer_of_a = ( ( /* Tri2D( 1, 1 ) - Tri2D( 2, 1 ) //-------------------------- 2x MEM + OP-8.SUB (avoided by re-use) */ Tri2D_11_sub_21 //=========================================== 1x REG + OP-g.MUL ) * ( Point(0) //------------------------------------------ + OP-i.MUL - Tri2D( 2, 0 ) //--------------------------------------- 2x MEM + OP-h.SUB ) + ( /* Tri2D( 2, 0 ) //--------------- + OP-E.ADD - Tri2D( 1, 0 ) //--------------- 2x MEM + OP-B.SUB (avoided by re-use) */ Tri2D_20_sub_10 //=============================== 1x REG + OP-l.ADD ) * ( Point(1) //-------------------------------- + OP-k.MUL - Tri2D( 2, 1 ) //--------------------------- 2x MEM + OP-j.MUL ) );/*denominator; *///------------------------ 1x REG + OP-F.DIV (avoided by DEFERRAL THE MOST EXPENSIVE DIVISION UNTIL a third coeff is indeed first needed, if ever-----------[3] //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~J.I.T./non-MISRA-C-RET--> // TEST CONDITIONS FOR A CHEAPEST EVER J.I.T./non-MISRA-C-RET--> // if ( enumer_of_a > denominator // in a > 1, THE SIZE DECIDES, the a / denominator > 1, iff enumer_of_a > denominator a rather expensive .FDIV is avoided at all || enumer_of_a * denominator < 0 ) return(false); // in a < 0, THE SIGN DECIDES, not the VALUE matters, so will use a cheaper .FMUL, instead of a rather expensive .FDIV ~~ ( sign( a ) * sign( denominator ) ) < 0 //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ // // Computing the second coefficient // double enumer_of_b = ( ( Tri2D( 2, 1 ) - Tri2D( 0, 1 ) ) //---------------------------------------- 2x MEM + OP-m.SUB * ( Point(0) - Tri2D( 2, 0 ) ) //---------------------------------------- 2x MEM + OP-n.SUB + OP-o.MUL + ( /* Tri2D( 0, 0 ) - Tri2D( 2, 0 ) //--------- 2x MEM + OP-19.SUB + OP-22.ADD (avoided by re-use) */ Tri2D_00_sub_20 //======================================================== 1x REG + OP-p.ADD ) * ( Point(1) - Tri2D( 2, 1 ) ) //---------------------------------------- 2x MEM + OP-r.SUB + OP-q.MUL );/*denominator; *///------------------------ 1x REG + OP-23.DIV (avoided by DEFERRAL THE MOST EXPENSIVE DIVISION UNTIL a third coeff is indeed first needed, if ever-----------[3] //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~J.I.T./non-MISRA-C-RET--> // TEST CONDITIONS FOR A 2nd CHEAPEST J.I.T./non-MISRA-C-RET--> // if ( enumer_of_b > denominator // in b > 1, THE SIZE DECIDES, the a / denominator > 1, iff enumer_of_a > denominator a rather expensive .FDIV is avoided at all || enumer_of_b * denominator < 0 ) return(false); // in b < 0, THE SIGN DECIDES, not the VALUE matters, so will use a cheaper .FMUL, instead of a rather expensive .FDIV ~~ ( sign( a ) * sign( denominator ) ) < 0 //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ // // Computing the third coefficient // double c = 1 - ( ( enumer_of_a - enumer_of_b ) / denominator ); // --------------------------------------------- 3x REG + OP-s.SUB + OP-t.FDIC + OP-u.SUB <----THE MOST EXPENSIVE .FDIV BUT HERE, IFF INDEED FIRST NEEDED <---HERE <------------[3] //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~J.I.T./non-MISRA-C-RET--> // TEST CONDITIONS FOR PRE-FINAL RET J.I.T./non-MISRA-C-RET--> // if ( c < 0 || c > 1 ) return( false ); return( true ); //~~~~~~~~~~~~~~~~~~~ "the-last-resort" RET--> ``` --- b) **OTHER APPROACH** TO THE ALGORITHM: Let's review another approach, that seems both faster and a way cheaper, due to less data and lest instructions and is also promising to have high density, once smart use of vectorised AVX-2 or better AVX-512 vector-instructions will get harnessed per each core : [**ANIMATED, fully-INTERACTIVE** explanation](https://www.desmos.com/calculator/adido1achw) is altogether with analytical problem re-formulation [**here**](https://www.desmos.com/calculator/adido1achw). A triple-test of a **point-to-line** distance (each line being `ax + by + c = 0`) comes at cheap cost of ~ 2 `FMA3` are enough + a sign test (and even better if vector-4-in-1-compact AVX-2 / 8-in-1 AVX-512 **`VFMADD`**-s) While there may be possible to "fast" decide on whether a point makes sense to be tested against a respective triangle, possibly with statically pre-"framing" each triangle in **`polar(R,Theta)`** coordinate space by a static, precomputed tuple of `( R_min, R_max, Theta_min, Theta_max )` and "fast" discriminate each point, if it does not fit inside such a polar-segment. Yet the costs of doing this (data-access pattern costs + the costs of these "fast" instructions) will grow beyond any potentially "saved" instruction-paths, that need not take place (if a point is found outside a polar-segment). Having achieved a range of performance of 24 points-in-triangle tests per a cost of ~9 CPU-instructions per 6 CPU-cores @ 3.0+ GHz, the polar-segment "pre-testing" will suddenly become prohibitively expensive, not speaking about a second order negative effect ( introduced by a way worse cache-hit / cache-miss ratios, given more data is to be stored and read into a "fast"-pre-test ~ +16B per a triangle "framing" polar-segment tuple +8B per point ( with the worst impact on the cache hit/miss-ratio ). That is clearly not good direction for any further move as the performance will get decreased, not increased, which is our global strategy here. [**Intel i5** 8500 CPU](https://ark.intel.com/content/www/us/en/ark/products/129939/intel-core-i5-8500-processor-9m-cache-up-to-4-10-ghz.html) can use but AVX-2, so the most compact use of 8-triangles per CPU-clock tick per core is left for achieving even 2X higher performance, if needed. ``` TRIPLE-"point-above-line"-TEST per POINT per TRIANGLE: --------------------------------------------------------------------------------- PRE-COMPUTE STATIC per TRIANGLE CONSTANTS: LINE_1: C0__L1, C1__L1, C2__L1, bool_L1DistanceMustBePOSITIVE LINE_2: C0__L2, C1__L2, C2__L2, bool_L2DistanceMustBePOSITIVE LINE_3: C0__L3, C1__L3, C2__L3, bool_L3DistanceMustBePOSITIVE TEST per TRIANGLE per POINT (Px,Py) - best executed in an AVX-vectorised fashion LINE_1_______________________________________________________________ C0__L1 ( == pre-calc'd CONST = c1 / sqrt( a1^2 + b1^2 ) ) // Px * C1__L1 ( == pre-calc'd CONST = a1 / sqrt( a1^2 + b1^2 ) ) // OP-1.FMA REG-Px,C1__L1,C0__L1 Py * C2__L1 ( == pre-calc'd CONST = b1 / sqrt( a1^2 + b1^2 ) ) // OP-2.FMA REG-Py,C2__L1, + .GT./.LT. 0 // OP-3.SIG LINE_2_______________________________________________________________ C0__L2 ( == pre-calc'd CONST = c2 / sqrt( a2^2 + b2^2 ) ) // Px * C1__L2 ( == pre-calc'd CONST = a2 / sqrt( a2^2 + b2^2 ) ) // OP-4.FMA REG-Px,C1__L2,C0__L2 Py * C2__L2 ( == pre-calc'd CONST = b2 / sqrt( a2^2 + b2^2 ) ) // OP-5.FMA REG-Py,C2__L2, + .GT./.LT. 0 // OP-6.SIG LINE_3_______________________________________________________________ C0__L3 ( == pre-calc'd CONST = c3 / sqrt( a3^2 + b3^2 ) ) // Px * C1__L3 ( == pre-calc'd CONST = a3 / sqrt( a3^2 + b3^2 ) ) // OP-7.FMA REG-Px,C1__L3,C0__L3 Py * C2__L3 ( == pre-calc'd CONST = b3 / sqrt( a3^2 + b3^2 ) ) // OP-8.FMA REG-Py,C2__L3, + .GT./.LT. 0 // OP-9.SIG ( using AVX-2 intrinsics or inlined assembler will deliver highest performance due to COMPACT 4-in-1 VFMADDs ) ____________________________________________ | __________________________________________triangle A: C1__L1 | | ________________________________________triangle B: C1__L1 | | | ______________________________________triangle C: C1__L1 | | | | ____________________________________triandle D: C1__L1 | | | | | | | | | | ______________________________ | | | | | | ____________________________triangle A: Px | | | | | | | __________________________triangle B: Px | | | | | | | | ________________________triangle C: Px | | | | | | | | | ______________________triandle D: Px | | | | | | | | | | |1|2|3|4| | | | | | | | | | | |1|2|3|4| ________________ | | | | | | | | | | | ______________triangle A: C0__L1 | | | | | | | | | | | | ____________triangle B: C0__L1 | | | | | | | | | | | | | __________triangle C: C0__L1 | | | | | | | | | | | | | | ________triandle D: C0__L1 | | | | | | | | | | | | | | | |1|2|3|4| | | | | | | | | | | | | | | | |1|2|3|4| | | | | | | | | | | | | | | | |1|2|3|4| (__m256d) __builtin_ia32_vfmaddpd256 ( (__v4df )__A, (__v4df )__B, (__v4df )__C ) ~/ per CPU-core @ 3.0 GHz ( for actual uops durations check Agner or Intel CPU documentation ) can perform 4-( point-in-triangle ) PARALLEL-test in just about ~ 9 ASSEMBLY INSTRUCTIONS / per CPU-core @ 3.0 GHz 24-( point-in-triangle ) PARALLEL-test in just about ~ 9 ASSEMBLY INSTRUCTIONS / per CPU using AVX-512 empowered CPU, can use 8-in-1 VFMADDs could perform 8-( point-in-triangle ) PARALLEL-test in just about ~ 9 ASSEMBLY INSTRUCTIONS / per CPU-core @ 3.0 GHz 48-( point-in-triangle ) PARALLEL-test in just about ~ 9 ASSEMBLY INSTRUCTIONS / per CPU ``` --- c) TIPS FOR THE BEST PARALLEL CODE + ULTIMATE PERFORMANCE: **Step -1:** GPU / CUDA costs v/s benefits If your PhD-mentor, professor, boss or Project Manager indeed insists you to develop a GPU-computing c++/CUDA code solution for this very problem, the best next step is to ask for getting any better suited GPU-card for such a task, than the one you posted. Your indicated card, the [**Q400 GPU has just 2 SMX** (48KB L1-cache each)](https://www.techpowerup.com/gpu-specs/quadro-p400.c2934) is not quite fit for a seriously meant parallel CUDA-computing, having about 30X-less processing devices to actually do any SIMD-thread-block computing, not mentioning its small memory and tiny L1 / L2 on-SMX-caches. So, after all CUDA-related design and optimisation efforts, there will be not more, but a single (!) pair of the GPU-SMX `warp32`-wide thread-block executions in the SIMD-threads, so there is no big circus to be expected from this GP107-based device and there are 30+X-better equipped devices for some indeed highly performing parallel-processing available COTS ) **Step 0:** pre-compute and pre-arrange data ( **MAXIMISE cache-line COHERENCY** ): Here, it makes sense to optimise the best macroscoping looping of the algorithm, so that you "benefit" most from cache hits ( i.e. best re-use of "fast" data, pre-fetched already ) So, may test, if it is cache-wise faster to rather distribute the work over N-concurrent-workers, who process disjunct working-blocks of triangles, where they each loop over the smallest memory-area --- all the points ( ~ 10k \* 2 \* 4B ~ 80 kB ), before moving into next triangle in the working-block. Ensuring the row-first array alignment into memory-area is vital ( FORTRAN guys can tell a lot about the costs/benefits of just this trick for an HPC-fast compact/vectorised vector-algebra and matrix-processing ) The benefit? The cached coefficients will be re-used ~ 10k times (at a cost of **`~ 0.5~1.0 [ns]`**, instead of **re-fetching costs of `+ 100 ~ 300 [ns]`** if these would have to be re-read by a RAM memory access). Difference, about **`~ 200X ~ 600X` is worth an effort to best align the workflow sub-ordinated to data-access-patterns and cache-line resources.** Results are atomic - any point will belong to one and only one (non-overlapping) triangles. This simplifies the a priori non-colliding and relatively sparse writes into a resulting vector, into where any detected point-inside-triangle can freely report an index of such triangle found. Using this vector of results for potentially avoiding any re-testing on points, where there has already been performed a match ( index is non-negative ) isnot very efficient, as the costs of re-reading such indication and re-arranging the compact alignment of 4-in-1 or 8-in-1 point-in-triangle tests, would become adversely expensive to potential "savings" of not re-testing an already mapped point. So the `10k` points over a block of **`300k`** triangles may yield a workflow of: a split of some `300k / 6` cores `~ 50k` triangles / 1 core `~ 50k * 10 k` point-in-triangle tests per core **`~ 500M`** point-in-triangle tests per core `@ 3.0+ GHz` **`~ 125M AVX-2`** vector-4-in-1-compact test-executions per-core **`~ 125M`** tests x `10 uops`-instructions `@ 3.0 GHz` ... which is `1.25G uops @ 3.0+ GHz` ... second(s)? Yes, there is a pretty strong motivation to go down here, towards this ultimate performance and direct the further work this way. SO, HERE WE ARE: The principally achievable HPC-target is in a range of a few seconds for 300+k Triangles / 10+k Points on just a 6-core AVX-2 i5 8500 @ 3.0+ GHz Worth an effort, isn't it?
I think you could make an array with boundaries for each triangle: top, bottom, right and left extremes. Then, compare your point to these boundaries. If it falls within one, THEN see if it really is within the triangle. That way, the 99.9% case doesn't involve a double floating-point multiply and a number of additions - just comparisons. The computationally expensive operations are only undertaken if the point is within the rectilinear extremes of the triangle. This could be sped up further yet, by e.g. sorting on e.g. the topmost extreme of the triangles, and using a binary search; and then begin by finding the point that is the highest point that is below your triangle, and then, checking the ones above it. That way, you'd only have to check just over half as many. If there were an upper bound on the height of the extremes of the triangles, you could check far less yet. Note that this latter strategy will make your source code more complex - so it will be a case of determining how much effort you wish to put into the optimization for how much result. The first part seems like it would be fairly easy, and help a lot. The sorted list: more effort for only almost halving your operations. I'd see if the first strategy was enough for you first.
15,315,300
I have a `<div>` with an image as a background. I have it so that whenever someone hovers over the `<div>`, the background image changes to some other image. The problem is, the first time when your mouse hovers over the `<div>`, the background image flickers as it loads and you see no image for few milliseconds. How do I remove this flicker? How do I load the image for the hover before the user actually hovers over the `<div>` so the effect is immediate. My code for changing the `<div>` background is very simple: ``` #someID{ background-image: *image source*; } #someID:hover{ background-image: *Another image source* } ``` I know that there is a solution with putting the two desired images in one image and then play with the background position, but that's not an option here because I always set the background image to be like this: ``` image-size: 100% 100%; ```
2013/03/09
[ "https://Stackoverflow.com/questions/15315300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972768/" ]
Within a window.load() function, * make sure all the images are loaded onto the page. FYI - You probably want to set each image's CSS position to absolute, with a Top:0px and Left:0px, all within a parent div that has a position:relative, with a certain width and height. * set display:none to the ones that should'nt be shown as DC\_ pointed out * use jquery's [hover method](http://api.jquery.com/hover/) or [click method](http://api.jquery.com/click/) to click on the image. Within the method function you choose, fadeOut() the current imag and fadeIn() the image that has a display:none associated to it.
You can place an image tag somewhere in your DOM referencing the image you want to preload and give it a style of `display:none; visibility: hidden;`. You could also try using a JavaScript preloading solution but it wouldn't be as reliable.
72,926
When running a traceroute, should I see any public IP addresses when tracing route from one MPLS point to another MPLS point? So when I do a traceroute from 10.0.0.1 to 10.0.1.1, I see some public IP address in between... On some of the routers I see this, on others I don't, what does this mean?
2009/10/09
[ "https://serverfault.com/questions/72926", "https://serverfault.com", "https://serverfault.com/users/2561/" ]
That depend on your MPLS provider. so there are a patch for the traceroute program, that print the MPLS label using ICMP, if the LSR is configured to affich these labels ( but most of providers don't do). You may test the [NANOG traceroute](ftp://ftp.login.com/pub/software/traceroute/) normalized in RFC 4950
The IPs you see are probably the loopback (that is, "a virtual interface that is the first to become active and the last to disappear on a router, usually used for router ID and for management access") addresses of devices through the MPLS network. I am actually a little bit surprised you see them from your router, that seems to indicate that the MPLS cloud is extended all the way to the CE (customer edge) device.
64,072,259
I've seen other post but I am trying to do this using some of the `<algorithm>` methods. I have a pointer to a map which contains a key to a vector of pointers to BaseElement classes like the following. ``` using ElementV = std::vector<std::shared_ptr<BaseElement>>; using ElementM = std::map<int, ElementV>; using SElementM = std::shared_ptr<ElementM>; SElementM elements; ``` What I am trying to do is concatenate each of the vectors (ElementV) stored as values in the map (ElementM) and populate one large ElementV. I'd like to not have to do deep copies and just access the original elements by their smart pointers (shared\_ptr(BaseElement)) from the allElems vector. The following is wrong, but gives the idea of what I'm trying to do. ``` ElementV allElems; for (auto& index : indices) { allElems = elements->at(index); } ``` I suspect I should be using lambas with std::copy, but have been unable to get something similar to the following to work and I think it's because of iterators. ``` std::copy(allElems.begin(), allElems.end(), [const elements &elems](std::vector<shared_ptr<BaseElement> &val) { elems ...? } ``` Thoughts?
2020/09/25
[ "https://Stackoverflow.com/questions/64072259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1718761/" ]
You can get pairs of keys (first) and values (second) via iteraters of `std::map`, so inserting each vectors via [`std::for_each`](https://en.cppreference.com/w/cpp/algorithm/for_each) is one way. ``` ElementV allElems; std::for_each(elements->begin(), elements->end(), [&allElems](const auto& p) { allElems.insert(allElems.end(), p.second.begin(), p.second.end()); }); ```
You could try this: ``` ElementV allElems; //assuming c++17 compiler for(auto& [ind, elemVectorPtr]: *elements){ //iterate through index, element-vector pointer pair in elements map //copy across all pointers in element-vector into allElems vector std::copy(elemVectorPtr->begin(), elemVectorPtr->end(), std::back_inserter(allElems)); } ``` If you don't have a c++17 compiler, just iterate directly through pairs of items in the map: ``` for(auto& pair : *elements){ std::copy(pair.second->begin(), pair.second->end(), std::back_inserter(allElems)); } ```