qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
3,701,329
If $\dfrac{z-\alpha}{z+\alpha},(\alpha \in R)$ is a purely imaginary number and $|z|=2$, then find value of $\alpha$. Now I took $\dfrac{z-\alpha}{z+\alpha}=t$ and as t is purely imaginary, and use the fact that $t+ \bar{t}=0$ and obtained the answer $\alpha = \pm2$. But I was wondering that if there is any way to think about the answer more directly using geometry of complex numbers given that $z$ lies on a circle centered at origin having radius $2$.
2020/06/01
[ "https://math.stackexchange.com/questions/3701329", "https://math.stackexchange.com", "https://math.stackexchange.com/users/290994/" ]
Consider the open cover $\{X\}$. This is a finite open cover of every subset of $X$. So your modified notion would apply to every set. --- That said, there is a version of this notion which is nontrivial: what if we bound the sizes of the open sets involved? (Note that this is a fundamentally *metric*, as opposed to *topological*, idea.) Specifically, consider the following property: > > For each $\epsilon>0$ there is a finite cover of $X$ consisting only of open sets with diameter $<\epsilon$. > > > Here the diameter of an open set $U$ is the supremum of the distances between elements of that set:$$diam(U)=\sup\{d(a,b): a,b\in U\}.$$ This is no longer trivial - e.g. $\mathbb{R}$ with the usual metric does *not* have this property. But this is still very different from compactness.
39,884,860
boot(1.4.0) "Pageable" for pagination.It works fine without any issue.But by default the page value starts from "0" but in the front-end the page value starts from "1". So is there any standard approach to increment value instead of manually increment the page number inside the code? ``` public Page<Device> find(DeviceFindCommand deviceFindCommand, Pageable pageable){ //page = 0 //Actual is 0, Expected increment by 1. } ``` Any help should be appreciable. After implementing **Alan** answers having the following issues, 1) Still i am able to access zero page which returns the first page(I don't know this is issue or not but i want to get a better clarity). <http://localhost:8180/api/v1/books/?page=3&size=2> **Response** ``` { "content": [ { "id": "57da9eadbee83fb037a66029", . . . }{ . . . } ], "last": false, "totalElements": 5, "totalPages": 3, "size": 2, "number": 2, //strange always getting 1 less than page number. "sort": null, "first": true, "numberOfElements": 2 } ``` 2) **"number": 2,** in the response always getting one less than the page number.It should return the current page index.
2016/10/05
[ "https://Stackoverflow.com/questions/39884860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3656056/" ]
If you are using Spring Boot 2.X you could switch from `WebMvcConfigurerAdapter` to application properties. There is a set of properties to configure pageable: ``` # DATA WEB (SpringDataWebProperties) spring.data.web.pageable.default-page-size=20 # Default page size. spring.data.web.pageable.max-page-size=2000 # Maximum page size to be accepted. spring.data.web.pageable.one-indexed-parameters=false # Whether to expose and assume 1-based page number indexes. spring.data.web.pageable.page-parameter=page # Page index parameter name. spring.data.web.pageable.prefix= # General prefix to be prepended to the page number and page size parameters. spring.data.web.pageable.qualifier-delimiter=_ # Delimiter to be used between the qualifier and the actual page number and size properties. spring.data.web.pageable.size-parameter=size # Page size parameter name. spring.data.web.sort.sort-parameter=sort # Sort parameter name. ``` But please remember that even if you change the `one-indexed-parameter` the page response (`PageImpl` class) will return results with zero-based page number. It could be a little misleading.
66,991,986
I have one pandas dataframe and one geopandas dataframe. In the Pandas dataframe, I have a column *Points* that contains `shapely.geometry` `Point` objects. The *geometry* column in the geopandas frame has `Polygon` objects. What I would like to do is take a `Point` in the Pandas frame and test to see if it is `within` **any** of the `Polygon` objects in the geopandas frame. In a new column in the pandas frame, I would like the following. If the `Point` is within a given `Polygon` (i.e. `within` call returns `True`), I would like the new column's value at the `Point`'s row to be the value of a different column in the `Polygon`'s row in the geopandas frame. I have a working solution to this problem, but it is not vectorized. Is it possible to vectorize it? Example: ```py import geopandas as gpd import pandas as pd from shapely.geometry import Point, Polygon # Create random frame, geometries are supposed to be mutually exclusive gdf = gpd.GeoDataFrame({'A': [1, 2], 'geometry': [Polygon([(10, 5), (5, 6)]), Polygon([(1,2), (2, 5))]}) # Create random pandas df = pd.DataFrame({'Foo': ['bar', 'Bar'], 'Points': [Point(4, 5), Point(1, 2)]}) # My non-vectorized solution df['new'] = '' for i in df.index: for j in gdf.index: if df.at[i, 'Points'].within(gdf.at[j, 'geometry']): df.at[i, 'new'] = gdf.at[j, 'A'] ``` This works fine, so that `df['new']` will contain whatever is in column `gdf['A']` when the point is within the polygon. I am hoping that there may be a way for me to vectorize this operation.
2021/04/07
[ "https://Stackoverflow.com/questions/66991986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3934100/" ]
You can calculate the Euclidean distance between all the points of the `Points` and `Polygon`. And, wherever the distance is equal to 0, this would give you an intersection point. My approach is below. Note that, I leave the part of getting all the points and the polygon points from your data frames to you. Probably, a function like `pandas.Series.toList` should provide that. ``` import numpy as np from scipy.spatial.distance import cdist polygon = [[10,5],[5,6],[1,2],[2,5]] points = [[4,5],[1,2]] # return distances between all the items of the two arrays distances = cdist(polygon,points) print(distances) ``` ``` [[6. 9.48683298] [1.41421356 5.65685425] [4.24264069 0. ] [2. 3.16227766]] ``` All we have to do now, is to get the index of 0s in the array. As you can see, our intersection point is at the 3rd row and the 2nd column, which is the 3rd item of the polygon or the 2nd item of the points. ``` for i,dist in enumerate(distances.flatten()): if dist==0: intersect_index = np.unravel_index(i,shape=distances.shape) intersect_point = polygon[intersect_index[0]] print(intersect_point) ``` ``` [1,2] ``` This should give you the vectorized form you are looking for.
59,370,781
I built a excel macro using the "Microsoft Outlook 15.0 Object Library" reference, but when I send the file to other people they get this error: "***Can’t find project or library***". This file will be used by a lot of people, so I have to add it from VBA Code. I'm using this code that runs when you open the excel file, which is returning the following error: "***Error in loading DLL***" ``` Private Sub Workbook_Open() Application.VBE.ActiveVBProject.References.AddFromFile "C:\Program Files (x86)\Microsoft Office\Office15\MSOUTL.OLB\" End Sub ``` Do you have any idea why this is happening? Thanks
2019/12/17
[ "https://Stackoverflow.com/questions/59370781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7920914/" ]
If you still want to keep the early binding you could use the GUID in order to add the libray, i.e. ``` Sub AddOL_Ref() Application.VBE.ActiveVBProject.REFERENCES. _ AddFromGuid "{00062FFF-0000-0000-C000-000000000046}", 1, 0 End Sub ``` Advantage of using the GUID is that it is constant and does not change with the version of the program. [Here](https://www.excelcise.org/add-or-remove-object-library-reference-via-vba/) one finds an extened discussion on dis/advantages of early resp. late binding.
4,926,383
I am tring to display all my products within their category, so something like: Category Name1 Product Name1, Product Name2 ... Category Name2 Product Name3, Product Name4 ... I am using oscommerce, So the database structure is not my choice. The database tables I need to use are products\_to\_categories: holds the products\_id and categories\_id products\_description:holds products\_id and products\_name (other info in this table are not important) category\_description: holds the categories\_id and categories\_name I have tried everything and i only can get to echo the products (all together) and categories all together, but I can't get them in a way that all the products within a category sit under the specified name As I said everything I tried resulted in a way that simply echoed all the categories AND THEN all the products I really hope you can help thanks
2011/02/07
[ "https://Stackoverflow.com/questions/4926383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420941/" ]
There are two ways of approaching this, and the idea behind is was already given as an answer here, by Zod. The first way is using category\_description to get **all** categories (whether it's full of products or not), the second way is to only extract categories that are used (i.e., not getting a complete list of categories). I'll go through the first way; getting all categories. Run through category\_description, and get the IDs and category names into an Array. Now, run through that array with `foreach` and grab all product\_ids from products\_to\_categories. (`SELECT products_id FROM products_to_categories WHERE categories_id=[CATEGORY ID GOES HERE]`). Now that you have your product IDs that are associated with the concurrent category, you can run through the products\_description and get their name. Essentially, your code should look like: ``` foreach ($categories as $category) { ...display category name and run code to get product ids... foreach ($products as $product) { ...get product name from products_description... ...display product name... } } ```
5,747,820
How can I change the background color from selected text? Like selecting this question but instead of a blue background and white text, a white background and red, blue, white etc. text. Thanks, VVW
2011/04/21
[ "https://Stackoverflow.com/questions/5747820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665168/" ]
You can use `::selection` CSS to achieve this. Eg: ```css ::selection { background:#fff; color:red; } ```
1,066,784
I am really stuck with this problem, and I cannot come out with a solution. I know that to prove a relation is an equivalence relation we have to prove that it's reflexive, symmetric and transitive, but in this case I don't know how, maybe because I don't much experience (but this exercise should be easy) This is the relation: $S=\{(x,y) \in \mathbb{R}\times \mathbb{R}|x - y \in \mathbb{Q} \}$
2014/12/13
[ "https://math.stackexchange.com/questions/1066784", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
This is Proposition 9.2 on p. 212 of *Elements of Algebraic Coding Theory* by L. R. Vermani. > > **Definiton 9.2** > > > We have shown that linear $[n, 1, n]$, $[n, n- 1, 2]$ and $[n, n, 1]$ codes exist > over any finite field $F$ and these are MDS codes. These are called trivial MDS > codes. > > > **Proposition 9.2** > > > The only binary MDS codes are the trivial codes. > > > ***Proof*** > > > Let $C$ be a binary $[n, k, d]$ MDS code. If $k = 1$, then $C$ is a trivial MDS code and > so we may suppose that $k > 1$. Let $G$ be a generator matrix of $C$ with the first > $k$ columns of $G$ forming the identity matrix. If $n > k + 1$, then $C$ has a column, > say $j$th, of weight less than $k$ and greater than $1$. Suppose that the $i$th entry > of this column is $0$. Then the first $k$ columns of $G$ except the $i$th together > with the $j$th column are linearly dependent. This proves that $C$ cannot be an > MDS code. Hence > > > $$k \le n \le k + 1$$ > > > and $C$ is a trivial MDS code. > > >
373,043
when I open up the terminal and write the command ``` cd Desktop ``` also I have tried ``` cd /Desktop ``` a message appears that no file or directory was found what I suppose to do? I have logged in as a root but still have the same problem any help?
2013/11/08
[ "https://askubuntu.com/questions/373043", "https://askubuntu.com", "https://askubuntu.com/users/212740/" ]
To enter your user's Desktop directory, run `cd ~/Desktop` (the `~` is expanded into your user's home directory). If your Desktop directory doesn't exist, you can create it via `mkdir ~/Desktop`.
49,693,393
I can't find out if the below is possible. I want to run an update statement in one database from another database. I know that I can save a query and run that from the master database but I thought the below would be possible ``` UPDATE tblOne INNER JOIN tblTwo ON tblOne.[TID] = tblTwo.TID SET tblTwo.PC = [tblOne].[PC] from tblOne in 'C:\DB.mdb' ; ``` Any help would be greatly appreciated
2018/04/06
[ "https://Stackoverflow.com/questions/49693393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1342483/" ]
Per the [MSDN Documentation](https://msdn.microsoft.com/en-us/library/bb177907(v=office.12).aspx), the `IN` clause is only compatible when used in conjunction with the `SELECT` statement (i.e. Select queries), `INSERT INTO` statement (i.e. Append queries), or `SELECT INTO` statement (i.e. Make Table queries) - it cannot be used as part of an `UPDATE` statement. I would suggest that you import `tblOne` as a linked table in the database in which you intend to execute your `UPDATE` query - this will also result in improved performance over the use of the `IN` clause. To link the table, select **Access Database** from the **Import** panel of the **External Data** ribbon tab, and then select the **Link** option from the wizard: [![enter image description here](https://i.stack.imgur.com/SNg1a.png)](https://i.stack.imgur.com/SNg1a.png) After the table has been linked, your `UPDATE` statement will become simply: ``` UPDATE tblOne INNER JOIN tblTwo ON tblOne.TID = tblTwo.TID SET tblTwo.PC = tblOne.PC ```
10,838,386
I have this tables `ADDS` (1) ```none +----+--------------+--------------+ | id | name of add | Date | +----+--------------+--------------+ | 1 | Add01 | March 01 | | 2 | Add02 | March 02 | | 3 | Add03 | March 03 | | 4 | Add04 | March 04 | +----+--------------+--------------+ ``` `TYPE OF ADDS` (2) ```none +----+----------+ | id | Add id | +----+----------+ | 21 | 1 | NOTE: Add id of table (2) = id of table (1) | 22 | 2 | | 23 | 3 | | 24 | 4 | +----+----------+ ``` `NAMES OF TYPES` (3) ```none +----+-----------+--------------+ | id | Type id | Name | +----+-----------+--------------+ | 31 | 21 | Text add | | 32 | 22 | Banner | NOTE: Type id of table (3) = id of table (2) | 33 | 23 | Video add | | 34 | 24 | Other | +----+-----------+--------------+ ``` I need a report like this: ```none +--------+-----------+--------------+ | Add id | Add name | Type of add | +--------+-----------+--------------+ | 1 | Add01 | Text add | | 2 | Add02 | Banner | | 3 | Add03 | Video add | | 4 | Add04 | Other | +--------+-----------+--------------+ ``` (`Add id` from table (1), `Add name` from table (1), `Type of add` from table (3)) So far I can do a `SELECT query LEFT JOIN table 1 and 2` but I don't know how to return the value `Name of type` from table 3. How can I do it?
2012/05/31
[ "https://Stackoverflow.com/questions/10838386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428981/" ]
Today is the 31st next month only has 30 days so it would be 7/12 in 1 month from today ``` assuming that today is May 31 2012 date('m Y') == 05 2012 date('m Y', strtotime('+1 month')) == 07 2012 because june has 30 days date('m Y', strtotime('+2 month')) == 07 2012 date('m Y', strtotime('+3 month')) == 08 2012 date('m Y', strtotime('+4 month')) == 10 2012 ``` I would take today's date and find the first day of the month then add a month to that if you are doing something that needs to get each month
5,062,100
I have web pages that may or may not need to do some pre-processing before it can be displayed to the user. What I have done is to display this page with a message (e.g. "please wait ..."), then do an http-equiv refresh **to the same page**. When it refreshes to the same page, the pre-processing is done and the actual content is displayed. Will this harm me in terms of SEO?
2011/02/21
[ "https://Stackoverflow.com/questions/5062100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253976/" ]
It's a hold over from C++ and C before that. In the C context, one of its meanings was for variables that keep their value between invocations. I presume that's where 'static' comes from - it doesn't reset the value (as opposed to a const where the value cannot change)
29,767,059
Chisel generate always blocks with only clock in sensivity list : ``` always @posedge(clk) begin [...] end ``` Is it possible to configure Module to use an asynchronous reset and generate an always block like this ? ``` always @(posedge clk or posedge reset) begin [...] end ```
2015/04/21
[ "https://Stackoverflow.com/questions/29767059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4422957/" ]
Since Chisel 3.2.0, there is support for synchronous, asynchronous, and abstract reset types. Based on the type of reset explicitly specified or inferred, you will get canonical synchronous or asynchronous Verilog output. To try to show this more fully, consider the following `MultiIOModule` which has three resets: * The implicit `reset` input which has an abstract reset type (this is "abstract reset") * The explicit `syncReset` input which has a `Bool` type (this is "synchronous reset") * The explicit `asyncReset` input which has an `AsyncReset` type (this is "asynchronous reset") Using `withReset`, specific reset connections can then be used for different registers in the design: ```scala import chisel3._ import chisel3.stage.ChiselStage class Foo extends MultiIOModule { val syncReset = IO(Input(Bool() )) val asyncReset = IO(Input(AsyncReset())) val in = IO(Input( Bool())) val outAbstract = IO(Output(Bool())) val outSync = IO(Output(Bool())) val outAsync = IO(Output(Bool())) val regAbstract = RegNext(in, init=0.U) val regSync = withReset(syncReset) { RegNext(in, init=0.U) } val regAsync = withReset(asyncReset) { RegNext(in, init=0.U) } outAbstract := regAbstract outSync := regSync outAsync := regAsync } ``` This then produces the following Verilog when compiled with: `(new ChiselStage).emitVerilog(new Foo)`: ``` module Foo( input clock, input reset, input syncReset, input asyncReset, input in, output outAbstract, output outSync, output outAsync ); reg regAbstract; reg regSync; reg regAsync; assign outAbstract = regAbstract; assign outSync = regSync; assign outAsync = regAsync; always @(posedge clock) begin if (reset) begin regAbstract <= 1'h0; end else begin regAbstract <= in; end if (syncReset) begin regSync <= 1'h0; end else begin regSync <= in; end end always @(posedge clock or posedge asyncReset) begin if (asyncReset) begin regAsync <= 1'h0; end else begin regAsync <= in; end end endmodule ``` Note: that in Chisel 3.2 the top-level abstract reset would always be set to synchronous reset. In Chisel 3.3.0, two traits were added: `RequireSyncReset` and `RequireAsyncReset`. These can be used to change the reset type of the register connected to `regAbstract` from synchronous to asynchronous. Recompiling the design with `(new ChiselStage).emitVerilog(new Foo with RequireAsyncReset)`, changes the `regAbstract` logic to ``` always @(posedge clock or posedge reset) begin if (reset) begin regAbstract <= 1'h0; end else begin regAbstract <= in; end end ``` For more information, the [Chisel website has more information on resets](https://www.chisel-lang.org/chisel3/reset.html).
12,894,120
I want to send an SMS, but not using the SmsManager class. I want to do it with the native SMS app which is there on an Android phone. And here is the twist : I do NOT want to launch the native app while doing it. Is there some format of intent which can send an sms directly (given the sms-body and the phone number to send it to) via the native app (without the user having to click 'send'). I googled the same, but all results and responses simply launched the native sms, waiting for user to manually send the SMS. I have seen this being implemented in some apps like 'MightyText' and wish to implement in my app as well. Please help !
2012/10/15
[ "https://Stackoverflow.com/questions/12894120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877972/" ]
Using the SmsManager will send the sms through the system but will not put it in the SMS content provider as was mentioned earlier. Hence any native messaging app will not see it. To do so, you have to add it manually via the SMS content provider AFTER you send the message normally via SmsManager. Here's some sample code to help: ``` ContentValues values = new ContentValues(); values.put("address", "+12345678"); // phone number to send values.put("date", System.currentTimeMillis()+""); values.put("read", "1"); // if you want to mark is as unread set to 0 values.put("type", "2"); // 2 means sent message values.put("body", "This is my message!"); Uri uri = Uri.parse("content://sms/"); Uri rowUri = context.getContentResolver().insert(uri,values); ``` And that's all. After that you'll notice that it's added and the native messaging app displays it normally. Please click "accept" answer if it works out for you.
20,955
My cat, Marty, is a real fraidy cat. He doesn't like most new people, but eventually he'll grow to like them. We recently moved into my grandpa's house a city over from where we used to live. Currently, my cat is hiding under my bed. Usually at night, he'll come out from hiding and come downstairs when he knows it's just me, my sister, my brother and my mom downstairs, but sometimes when he's hungry he'll come out during the day, but only if one of us comes down the stairs with him. He's gotten pretty used to my uncle, he lets him pet him for a while, but he hasn't gotten used to my grandpa. Also at night when we all go to bed he'll follow us upstairs, and he'll always sleep on my bed with me. He's not interested in sleeping on anyone elses bed, even if my sister picks him up and puts him on her bed, he usually just jumps right off and jumps onto my bed. Any help would be appreciated.
2018/07/25
[ "https://pets.stackexchange.com/questions/20955", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/12615/" ]
Two weeks isn't all that long. Our first two cats were incredibly shy (they lived in the wild in a prison, where they had learned to stay quiet and out of sight). It took them *months* to just be out in the open in the living room. We had kept them in a single room for the first two weeks. We then also gave them the hallway, and it took them over a week to actually want to go into the hallway. The same happened when we opened the door to the living room. And for two more months, they would never go downstairs without us, or during the day. Your cat is by itself, getting to meet several new people, and also shy. I would give her a few extra weeks (if not months) before you see full integration into the household.
19,784,868
I'm trying to convert the following MATLAB code to Python and am having trouble finding a solution that works in any reasonable amount of time. ``` M = diag(sum(a)) - a; where = vertcat(in, out); M(where,:) = 0; M(where,where) = 1; ``` Here, a is a sparse matrix and where is a vector (as are in/out). The solution I have using Python is: ``` M = scipy.sparse.diags([degs], [0]) - A where = numpy.hstack((inVs, outVs)).astype(int) M = scipy.sparse.lil_matrix(M) M[where, :] = 0 # This is the slowest line M[where, where] = 1 M = scipy.sparse.csc_matrix(M) ``` But since A is 334863x334863, this takes like three minutes. If anyone has any suggestions on how to make this faster, please contribute them! For comparison, MATLAB does this same step imperceptibly fast. Thanks!
2013/11/05
[ "https://Stackoverflow.com/questions/19784868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2137996/" ]
The solution I use for similar task [attributes to @seberg](https://stackoverflow.com/a/12130287/1265154) and do not convert to `lil` format: ``` import scipy.sparse import numpy import time def csr_row_set_nz_to_val(csr, row, value=0): """Set all nonzero elements (elements currently in the sparsity pattern) to the given value. Useful to set to 0 mostly. """ if not isinstance(csr, scipy.sparse.csr_matrix): raise ValueError('Matrix given must be of CSR format.') csr.data[csr.indptr[row]:csr.indptr[row+1]] = value def csr_rows_set_nz_to_val(csr, rows, value=0): for row in rows: csr_row_set_nz_to_val(csr, row) if value == 0: csr.eliminate_zeros() ``` wrap your evaluations with timing ``` def evaluate(size): degs = [1]*size inVs = list(xrange(1, size, size/25)) outVs = list(xrange(5, size, size/25)) where = numpy.hstack((inVs, outVs)).astype(int) start_time = time.time() A = scipy.sparse.csc_matrix((size, size)) M = scipy.sparse.diags([degs], [0]) - A csr_rows_set_nz_to_val(M, where) return time.time()-start_time ``` and test its performance: ``` >>> print 'elapsed %.5f seconds' % evaluate(334863) elapsed 0.53054 seconds ```
61,069,739
I have a string ``` String mystring = "<html><head><meta name="viewport" content="width=device-width"></head><body><h1><a href="q://d?EN&hello">hello</a></h1> <p> <h3>Alternative forms</h3> <ul><li> <a href="q://d?&hallo">hallo</a></li> <li> <a href="q://d?&hilloa">hilloa</a> (obsolete)</li> <li> <a href="q://d?&hullo">hullo</a> (UK)</li> </ul> <h3>Etymology</h3> <a href="q://d?&Hello">hello</a> (first attested in 1833), from <a href="q://d?&holla">holla</a>, <a href="q://d?&hollo">hollo</a> (attested 1588). This variant of <a href="q://d?&hallo">hallo</a> is often credited to Thomas Edison as a coinage for telephone use, but its appearance in print predates the invention of the telephone by several decades.Ultimately from a variant of Old English <em><a href="q://d?&eala">&#x113;al&#x101;</a></em>, such as <em><a href="q://d?&hela">h&#x113;l&#x101;</a></em>, which was used colloquially in that time similarly to how &quot;hey&quot; or &quot;hi&quot; is used nowadays. Thus, equivalent to a compound of <em><a href="q://d?&hey">hey</a></em> and <em><a href="q://d?&lo">lo</a></em>.Possibly influenced by the lang:goh and lang:osx verb <a href="q://d?&halon">halon</a>, <a href="q://d?&holon">holon</a> (&quot;to bring something, to gather&quot;), akin to English <a href="q://d?&hale">hale</a> or <a href="q://d?&hail">hail</a>. More at {{l/en|hallo}}. <h3>Pronunciation</h3> <ul><li> {{a|UK}} IPA: /h&#x259;&#x2c8;l&#x259;&#x28a;&#x32f;/, /h&#x25b;&#x2c8;l&#x259;&#x28a;&#x32f;/</li> <li> {{a|US}} {{enPR|h&#x115;-l&#x14d;&#x27;|h&#x259;-l&#x14d;&#x27;}}, IPA: /h&#x25b;&#x2c8;lo&#x28a;&#x32f;/, /h&#x259;&#x2c8;lo&#x28a;&#x32f;/</li> <li> {{audio|En-uk-hello.ogg|Audio (UK)|lang=en}}</li> </ul> {|class=&quot;wikitable&quot;! Sense! UK! US|-|{{sense|greeting}}|{{audio|en-uk-hello-1.ogg|Audio (UK)|lang=en}}|{{audio|en-us-hello.ogg|Audio (US)|lang=en}}|-|{{sense|telephone greeting}}|{{audio|en-uk-hello-2.ogg|Audio (UK)|lang=en}}|{{audio|en-us-hello-2.ogg|Audio (US)|lang=en}}|-|{{sense|call for response}}|{{audio|en-uk-hello-3.ogg|Audio (UK)|lang=en}}|{{audio|en-us-hello-3.ogg|Audio (US)|lang=en}}|-|{{sense|sarcastic implication}}|{{audio|en-uk-hello-4.ogg|Audio (UK)|lang=en}}|{{audio|en-us-hello-4.ogg|Audio (US)|lang=en}}|-|{{sense|expressing puzzlement}}|{{audio|en-uk-hello-5.ogg|Audio (UK)|lang=en}}||} <ul><li> {{rhymes|&#x259;&#x28a;|lang=en}}</li> </ul> <h3>Interjection</h3> {en-interj} <ol><li> {{non-gloss definition|A <a href="q://d?&greeting">greeting</a> (<a href="q://d?&salutation">salutation</a>) said when <a href="q://d?&meet">meet</a>ing someone or <a href="q://d?&acknowledge">acknowledging</a> someone&#x2019;s <a href="q://d?&arrival">arrival</a> or <a href="q://d?&presence">presence</a>.}}</li> <ul><li> {{usex|<b>Hello,</b> everyone.|lang=en}}</li> </ul> <li> {{non-gloss definition|A greeting used when <a href="q://d?&answer">answer</a>ing the <a href="q://d?&telephone">telephone</a>.}}</li> <ul><li> {{usex|<b>Hello</b>? How may I help you?|lang=en}}</li> </ul> <li> {{non-gloss definition|A call for <a href="q://d?&response">response</a> if it is not clear if anyone is present or listening, or if a telephone conversation may have been <a href="q://d?&disconnect">disconnect</a>ed.}}</li> <ul><li> {{usex|<b>Hello</b>? Is anyone there?|lang=en}}</li> <li> {{quote-book|year=1913|author={{w|Joseph C. Lincoln}}|chapter=7|title=[http://openlibrary.org/works/OL5535161W Mr. Pratt's Patients]|passage=I made a speaking trumpet of my hands and commenced to whoop &#x201c;Ahoy!&#x201d; and &#x201c;<b>Hello!</b>&#x201d; at the top of my lungs. ... The Colonel woke up, and, after asking what in brimstone was the matter, opened his mouth and roared &#x201c;Hi!&#x201d; and &#x201c;<b>Hello!</b>&#x201d; like the bull of Bashan.}}</li> </ul> <li> {{context|colloquial|lang=en}} {{non-gloss definition|Used <a href="q://d?&sarcastic">sarcastic</a>ally to imply that the person addressed or referred to has done something the speaker or writer considers to be <a href="q://d?&foolish">foolish</a>.}}</li> <ul><li> {{usex|You just tried to start your car with your cell phone. <b>Hello</b>?|lang=en}}</li> </ul> <li> {{non-gloss definition|An expression of <a href="q://d?&puzzlement">puzzlement</a> or <a href="q://d?&discovery">discovery</a>.}}</li> <ul><li> {{usex|<b>Hello</b>! What&#x2019;s going on here?|lang=en}}</li> </ul> </ol> <h4>Usage notes</h4> <ul><li> The greeting <a href="q://d?&hello">hello</a> is among the most generic and neutral in use. It may be heard in nearly all social situations and in nearly all walks of life, and is unlikely to cause offense.</li> </ul> <h4>Quotations</h4> <ul><li> {seeCites}</li> </ul> <h4>Synonyms</h4> <ul><li> {{sense|greeting}}</li> <ul><li> (AU, informal) <a href="q://d?&g%27day">g'day</a>, <a href="q://d?&hey">hey</a>, <a href="q://d?&hi">hi</a>, </li> <li> (UK, informal) <a href="q://d?&hallo">hallo</a>, <a href="q://d?&hi">hi</a>, <a href="q://d?&hiya">hiya</a>, <a href="q://d?&ey+up">ey up</a></li> <li> (US, informal) <a href="q://d?&hallo">hallo</a>, <a href="q://d?&hey">hey</a>, <a href="q://d?&hi">hi</a>, <a href="q://d?&howdy">howdy</a></li> <li> (IE, informal) <a href="q://d?&how%27s+it+going">how's it going</a>, <a href="q://d?&hey">hey</a>, <a href="q://d?&hi">hi</a></li> <li> (SA, informal) <a href="q://d?&howzit">howzit</a></li> <li> (slang) <a href="q://d?&wassup">wassup</a>, <a href="q://d?&what%27s+up">what's up</a>, <a href="q://d?&yo">yo</a>, <a href="q://d?&sup">sup</a></li> </ul> <li> See also </li> </ul> <h4>Antonyms</h4> <ul><li> {{sense|greeting}} <a href="q://d?&bye">bye</a>, <a href="q://d?&goodbye">goodbye</a></li> </ul> <h4>Derived terms</h4> <ul><li> <a href="q://d?&hello+yourself%2C+and+see+how+you+like+it">hello yourself, and see how you like it</a></li> </ul> <h4>See also</h4> <ul><li> <a href="q://d?&%3ACategory%3AGreetings">:Category:Greetings</a></li> <li> {pedialite}</li> </ul> <h3>Noun</h3> {{en-noun|s|helloes}} <ol><li> &quot;<a href="q://d?&hello">Hello</a>!&quot; or an equivalent greeting.</li> <ul><li> {{quote-news|year=2007|date=April 29|author=Stephanie Rosenbloom|title=A Beautiful Day in the Neighborhood|work=New York Times|url=http://www.nytimes.com/2007/04/29/fashion/29condo.html|passage=In many new buildings, though, neighbors are venturing beyond tight-lipped <b>hellos</b> at the mailbox.}}</li> </ul> </ol> <h4>Synonyms</h4> <ul><li> <a href="q://d?&greeting">greeting</a></li> </ul> <h3>Verb</h3> {en-verb} <ol><li> {{context|transitive|lang=en}} To <a href="q://d?&greet">greet</a> with &quot;hello&quot;.</li> <ul><li> <b>2013</b>, Ivan Doig, <em>English Creek</em> (page 139)</li> <ul><li> I had to traipse around somewhat, <b>helloing</b> people and being <b>helloed</b>, before I spotted my mother and my father, sharing shade and a spread blanket with Pete and Marie Reese and Toussaint Rennie near the back of the park.</li> </ul> </ul> </ol> <p> <a href="http://en.wiktionary.org/wiki/hello">http://en.wiktionary.org/wiki/hello</a> </body></html>" ``` --- In **`mystring`** I am trying to remove ``` <h1><a href="q://d?EN&hello">hello</a></h1> ``` **I tried with** : <https://stackoverflow.com/a/32005143/1083093> ... this dosen't work since I am trying to remove only `h1` tags and content between them
2020/04/06
[ "https://Stackoverflow.com/questions/61069739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1083093/" ]
``` public static void main(String[] args) { String mystring = "<html><head><meta name=\"viewport\" content=\"width=device-width\"></head><body><h1><a href=\"q://d?EN&hello\">hello</a></h1>"; System.out.println(removeH1(mystring)); } private static String removeH1(String mystring) { while (mystring.contains("<h1>")) { mystring = mystring.substring(0, mystring.indexOf("<h1>")) + mystring.substring(mystring.indexOf("</h1>") + 5); } return mystring; } ``` Pretty straightforward, you may comment if you have any questions.
48,101,266
I am building an app on Glitch with express js which requires the user to upload multiple files. Here is my code: ```js var express = require('express'); var cors= require('cors'); var bodyParser= require('body-parser'); var contexts= require('./contexts'); var path= require('path'); var fileUpload= require('express-fileupload'); var multer= require('multer'); var upload = multer(); var app = express(); app.use(cors()); app.use(bodyParser.json()); app.use(fileUpload()); app.set('view engine', 'ejs'); app.set('views', 'views'); app.use(express.static('views/')); //here express-fileuploads works fine app.post('/getcontexts', function (req,res) { var context=contexts.get(req.files.file.data.toString()); res.render('rast', {length: context.length, content : context}); }); //this is when I get an empty array app.post('/getrast', upload.array('rastfiles'), function (req, res) { res.json({data: req.files}); }); var listener = app.listen(process.env.PORT, function () { console.log('SERVER STARTED ON PORT ' + listener.address().port); }); ``` and here is the ejs form I use: ```html <form action="/getrast" method="POST" enctype="multipart/form-data"> <label for="rastfiles">Please select your Rast genome files with .txt extension</label> <br> <input type="file" id="file" name="rastfiles" class="inputFile" multiple> <br> <input type="submit" value="Run" id="sub"> </form> ``` I already used express-fileupload to upload a single file and it worked just fine. However, when I use multer to upload multiple files I get and empty array when logging req,files into the console. Any idea why this might be happening? I'd really appreciate any help. Thanks!
2018/01/04
[ "https://Stackoverflow.com/questions/48101266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8371765/" ]
The reason why multer was not working is because express-fileupload was already being used as middleware for file uploading, so commenting out this line: ``` app.use(fileUpload()) ``` fixed the problem for me.
47,466,630
i am developing plugin where i have to update the single record onchanging the select option element , i tried using wordpres codex way ,but i am struck can please anyone help me out here, below is my code ```js function ajaxFunction(str,id) { var payment_selected = str; var id=id; var queryString = '&id_took='+id+'&sel='+payment_selected; var data = { 'action' : 'my_action', 'payment_selected': payment_selected, 'id' : id }; jQuery.post(admin_url("admin-ajax.php"), data, function(response) { jQuery("#status").html(response); }); } ``` ```html /* this is a php file , i used in the plugin where below html form appears */ <?php add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); add_action( 'wp_ajax_my_action', 'my_action' ); function my_action() { global $wpdb; $id_selected = $_POST['payment_selected']; $id = $_POST['id']; $table_name_payment = $wpdb->prefix . "online_booking_system_model"; $result_pay = $wpdb->query($wpdb->prepare("UPDATE $table_name_payment SET payment_status = $id_selected WHERE id=$id")); echo "success"; ?> /* this is the html file */ foreach ($rows as $row) { ?> <table> <td><?php echo $row->payment_status; ?></td> <select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)"> <option value="Payment Due">Payment Due</option> <option value="Payment completed">Payment Completed</option> </select> <?php } ?> <table> <div id="status"></div> ```
2017/11/24
[ "https://Stackoverflow.com/questions/47466630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6737108/" ]
AS it is clear from the html that id and classnames are same for the elements : so you can modify below code as per your requirement (Whether you want to click first , second or third element ) ReadOnlyCollection allelements = driver.FindElement(By.Id("txtSearch")); ``` foreach (IWebElement element in allelements) { //Add logic here whether you want click on first or second or nth element element.Click(); } ```
66,957,425
I need to calculate the mean per group (i.e, per Coordinates) of the sample table below without losing any of the columns (the real table has over 40,000 rows with different states,location coordinates and type) So this: | State | Location Coordinates | Type | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | California | West | Debt | 234 | 56 | 79 | 890 | 24 | 29 | 20 | 24 | 26 | | Nevada | West | Debt | 45 | 54 | 87 | 769 | 54 | 76 | 90 | 87 | 98 | Would become this : | State | Location Coordinates | Type | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | West | West | Debt | 234 | 56 | 79 | 890 | 24 | 29 | 20 | 24 | 26 | When I use aggregate (df <- aggregate(df[,4:length(df)], list(df$Coordinates), mean). It removes the State and City columns. | Location Coordinates | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | West | 235 | 55 | 83 | 843 | 24 | 29 | 20 | 24 | 26 | Debt | 54 | 769 | 76 | 87 | And when I use sqldf it averages the year and becomes this: | State | Location Coordinates | Type | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | West | West | Debt | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 | Any suggestions?
2021/04/05
[ "https://Stackoverflow.com/questions/66957425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14032099/" ]
Use [`Series.dt.time`](https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.time.html): ``` import pandas as pd # sample df = pd.DataFrame({'Time': ['00:00:05', '00:00:10', '00:10:00']}) df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S').dt.time print(type(df.Time[0])) [out]: <class 'datetime.time'> ``` For adding or subtracting `time`, you can do this: ``` pd.Timedelta(df.Time - t1).seconds / 3600.0 ```
823,004
For example, I want the first entry in Column B (B1) to show A5, then B2 shows A10, then B3 shows A15. How would I go about doing this?
2014/10/09
[ "https://superuser.com/questions/823004", "https://superuser.com", "https://superuser.com/users/147795/" ]
For excel you can put this in B1 and drag down ``` =INDEX($A$1:$A$100,5*(ROWS($B$1:B1)-1)) ``` To start with A5 instead of A1, use this ``` =INDEX($A$1:$A$100,5*(ROWS($B$1:B1))) ```
28,949,902
We are receiving an SMTP 4.4.1 connection time out exception every so often when attempting to send mail in C#. So far we have found no pattern as to when the issue occurs, such as the time of day. The exception thrown is: > > System.Net.Mail.SmtpException: Service not available, closing transmission channel. The server response was: 4.4.1 Connection timed out > > > Up to 30 emails at anyone time are sent and 9 times out of 10 all are sent successfully. When we run into the 4.4.1 exception a number of the emails are sent and the remaining 1 or 2 are not. Unfortunately, I don't have access to the clients Exchange server, only the application server where our application is running from. So I'm working with the host on this. The Event Log has been checked on the application server, the only thing found was the following warning from a source McLogEvent: > > Would be blocked by port blocking rule (rule is in warn-only mode) (Anti-virus Standard Protection: Prevent mass mailing worms from sending mail). > > > Has anyone came across this issue before or know of a possible cause?
2015/03/09
[ "https://Stackoverflow.com/questions/28949902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4598265/" ]
You must use a major upgrade if you remove components. See [Changing the Product Code](https://msdn.microsoft.com/en-us/library/aa367850%28v=vs.85%29.aspx) for the list of things that cannot be done with minor upgrades.
421,206
I have a Linux VPS serving data on the internet that has a legitimate Domain name and SSL Certificate ( from GoDaddy.com ). I will refere to this server as "**www.myserver.com**". I also have a local Linux machine ( on my own LAN ) that I want to use to DNS spoof my internet facing Domain name ( www.myserver.com ) to it's own NGINX webserver running on that local machine. I setup DNSMasq on the local machine to spoof that domain to it's local 192.x address and I verified from another machine on the LAN that dig reports the local address. Local server dnsmaq spoof mapping: ``` cat /etc/dnsmasq.d/spoof.hosts 192.168.1.142 www.myserver.com myserver.com ``` Separate machine on LAN shows that spoofed mapping should work: ``` dig +short @192.168.1.142 myserver.com >> 192.168.1.142 ``` My dnsmasq.conf: ``` server=127.0.0.1 listen-address=127.0.0.1 listen-address=192.168.1.142 no-dhcp-interface= no-hosts addn-hosts=/etc/dnsmasq.d/spoof.hosts ``` My spoof.hosts: ``` 192.168.1.142 www.myserver.com myserver.com ``` On the local server, I configured NGINX with resolver to look to localhost for DNS as shown here: ``` http { access_log off; include mime.types; default_type html; sendfile on; keepalive_requests 50; keepalive_timeout 75s; reset_timedout_connection on; server_tokens off; server { listen 8080 default_server; resolver 127.0.0.1 valid=10s; location / { return 302 http://myserver.com/; } } server { listen 80; server_name *.myserver.com; // Various Endpoints } } ``` The problem is that when I visit my local machine 192.168.1.131:8080, it redirects to my **actual** internet facing machine - the **real** domain name on the internet. I want it to redirect to the local spoofed DNS. What am I doing wrong? How can I accomplish this? Thank you. UPDATE: I've tried this as well but no luck: ``` http { access_log off; include mime.types; default_type html; sendfile on; keepalive_requests 50; keepalive_timeout 75s; reset_timedout_connection on; server_tokens off; server { listen 80 default_server; server_name _; resolver 127.0.0.1; return 301 https://myserver.com/$request_uri; } server { listen 443; server_name *.myserver.com; ssl on; ssl_certificate /etc/nginx/ssl/1e17e6d8f94cc4ee.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; ... } } ```
2018/02/01
[ "https://unix.stackexchange.com/questions/421206", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/63801/" ]
When nginx sends a redirect, it simply tells the client to visit the new URL. So now on the client the new hostname is resolved, and as that client is not using the spoofing DNS server, it goes to the real host. Perhaps you want to use nginx in proxy mode, so that nginx is fetching the content from the backend and relaying that on to the client.
46,346,064
I'm trying to define a regex in php to extract words but i didn't succeed... My string is always in this format: "toto=on test=on azerty=on gogo=on" what I would like to do is to get in an array the values toto, test,azerty and gogo. Can someone help ? that's what i tried so far : `/([^\s]|[w]*?=)/`
2017/09/21
[ "https://Stackoverflow.com/questions/46346064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5555681/" ]
It's simple ``` preg_match_all("/(\w*)=/", "toto=on test=on azerty=on gogo=on", $output_array)[1]; ``` It will get all word before "=", the parentheses is for defining a group and put in key "1" , "\w" is for a letter and "\*" is for "many" or You can improve that and use like that ``` preg_match_all("/(\w*)=on/", "toto=on test=on azerty=on gogo=on", $output_array)[1]; ``` So will get only parameters "on", if you have "toto=on test=on azerty=on gogo=on toff=off", the string "toff" dont will appear I like to use this link <http://www.phpliveregex.com/> , so you can try regex and responses in PHP
13,322,107
Hopefully I'll be able to explain this well enough without an example... I have two instances of wonky z-index. Let me explain each: 1) I have a navbar with a dropdown using a css3 slide transition and jquery with positioning to move into place. I set the z-index for the navbar as 100, and the z-index for the dropdown as 90. The navbar has a shadow which I would like go over the drop down menu, but currently wont. Also, the dropdown slides down over the navbar, while it should go under. 2) I have a footer which is basically the same problem above, just inverted. No shadow overlap. Haven't implemented the transition yet, but I'm sure it will do the same thing. Before you answer with the obvious, all the elements in question are positioned. I'm hoping to be able to solve this without having to come up with an example, because this is part of a big project with lots and lots of pieces. Since there's no example, I don't expect the answer to be simple, but maybe you could point me in the right direction? Let me know if you have any questions. Thanks so much! **EDIT** I made a quick sample, posted in the comments. The transition doesn't work but the shadow from the nav isn't covering the dropdown
2012/11/10
[ "https://Stackoverflow.com/questions/13322107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/963475/" ]
1. Add `method: :post` to your `link_to` options. 2. Use a constraint on your route, or check if request is POST with `request.post?`in your controller.
2,697,571
What is the limit of $$\lim\_{x \to \infty} \frac{\sum\_{k=0}^{x} (k+1){e^k}}{x{e^x}}\quad \text{?}$$ I think that it may go to infinity but not sure and i don't know how to solve it.
2018/03/18
[ "https://math.stackexchange.com/questions/2697571", "https://math.stackexchange.com", "https://math.stackexchange.com/users/466808/" ]
The numerator is an arithmetico-geometric series. \begin{align\*} (1-e)\sum\_{k=0}^{x} (k+1){e^k}&=\sum\_{k=0}^{x} (k+1){e^k}-\sum\_{k=0}^{x} (k+1){e^{k+1}}\\ &=\sum\_{k=0}^{x} (k+1){e^k}-\sum\_{k=1}^{x+1} k{e^{k}}\\ &=\sum\_{k=0}^{x} (k+1){e^k}-\sum\_{k=0}^{x} k{e^{k}}-(x+1)e^{x+1}\\ &=\sum\_{k=0}^{x} {e^k}-(x+1)e^{x+1}\\ &=\frac{e^{x+1}-1} {e-1}-(x+1)e^{x+1}\\ \sum\_{k=0}^{x} (k+1){e^k}&=\frac{(x+1)e^{x+1}}{e-1}-\frac{e^{x+1}-1} {(e-1)^2}\\ \frac{1}{xe^x}\sum\_{k=0}^{x} (k+1){e^k}&=\frac{(x+1)e}{x(e-1)}-\frac{e-e^{-x}} {x(e-1)^2}\\ \lim\_{x\to\infty}\frac{1}{xe^x}\sum\_{k=0}^{x} (k+1){e^k}&=\frac{e}{e-1} \end{align\*}
5,661,101
Is it possible to represent an unsigned character array as a string? When I searched for it, I found out that only memset() was able to do this (But character by character). Assuming that is not the correct way, is there a way to do the conversion? Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters. eg: ``` unsigned char data[N]; ... for(i=0;i<N;i++) printf("%x",data[i]); ``` My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing. Thanks!
2011/04/14
[ "https://Stackoverflow.com/questions/5661101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420157/" ]
So, based on your update, are you talking about trying to convert a unsigned char buffer into a hexadecimal interpretation, something like this: ``` #define bufferSize 10 int main() { unsigned char buffer[bufferSize]={1,2,3,4,5,6,7,8,9,10}; char converted[bufferSize*2 + 1]; int i; for(i=0;i<bufferSize;i++) { sprintf(&converted[i*2], "%02X", buffer[i]); /* equivalent using snprintf, notice len field keeps reducing with each pass, to prevent overruns snprintf(&converted[i*2], sizeof(converted)-(i*2),"%02X", buffer[i]); */ } printf("%s\n", converted); return 0; } ``` Which outputs: ``` 0102030405060708090A ```
709,855
Prove that if $H$ is a subgroup of index $2$ in a finite group $G$, then $gH = Hg \; \forall \; g \in G$. I know that $H$ itself is one coset of the subgroup and the other is the compliment of the subgroup, but I don't really understand why the second coset is the compliment. I know that the union of the cosets must be $G$, but how do we know that we can't say, for example, $2H \cup H \equiv G$? Why do we **know** for sure that $H'\cup H$ is $G$? I also know that the number of left and right cosets are identical.
2014/03/12
[ "https://math.stackexchange.com/questions/709855", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80327/" ]
Remember, Langrange's theorem? There was an equivalence relation $a \sim b$ if $a^{-1}b \in H$ So $G\backslash H$ are the equivalence classes induced by $a \sim b$ if $a^{-1}b \in H$ In other words, the cosets represent the different equivalence classes induced by this equivalence relation. What do we know from equivalence classes? They $partition$ $G$, so if $aH$ and $bH$ are two different cosets then $aH \cap bH = \emptyset$ Therfore, if H has index 2 that means that $G\backslash H$ has two cosets. One coset you know is H and the other coset must have $a \in G$ such that $a \notin H$ which is just $H'$ These must also be the right cosets, hence $gH =Hg $ $\forall g \in G$
3,569,212
> > Count the number of arrangements of the $10$ letters ABCDEFGHIJ in which none of the patterns ABE, BED, or HID occur. > > > I thought that the answer would be $\_{10}P\_{10} - (\_{10}P\_{3} + \_{10}P\_{3} + \_{10}P\_{3} - \_{10}P\_{2}$), since we have $\_{10}P\_{10}$ total arrangements, and $\_{10}P\_{3}$ arrangements for ABE, BED, and HID. But we subtracted $BE$ twice, so we need to add it back in: $\_{10}P\_{2}$. Please tell me what is wrong with my reasoning!
2020/03/04
[ "https://math.stackexchange.com/questions/3569212", "https://math.stackexchange.com", "https://math.stackexchange.com/users/742306/" ]
There are $10!$ permutations of the ten distinct letters. From these, we must subtract those arrangements in which the substrings ABE, BED, or HID appear. *Arrangements with a prohibited substring*: We count arrangements in which ABE appears. We have eight objects to arrange: ABE, C, D, F, G, H, I, J. Since the objects are distinct, they can be arranged in $8!$ ways. By symmetry, there are $8!$ arrangements in which BED appears and $8!$ arrangements in which HID appears. Hence, there are $3 \cdot 8!$ arrangements with a prohibited substring. However, if we subtract this amount from the total, we will have subtracted each arrangement in which two prohibited substrings appear twice, once for each way we could designate one of those substrings as the prohibited one. We only want to subtract such arrangements once, so we must add them back. *Arrangements with two prohibited substrings*: Since it is not possible for a permutation of the letters A, B, C, D, E, F, G, H, I, J to contain both BED and HID, this can occur in two ways. Either both ABE and BED appear in the arrangement or both ABE and HID appear in the arrangement. Substrings ABE and BED both appear in the arrangement: This can only occur if the arrangement contains the substring ABED. Then we have seven objects to arrange: ABED, C, F, G, H, I, J. Since the objects are distinct, they can be arranged in $7!$ ways. Substrings ABE and HID both appear in the arrangement: We have six objects to arrange: ABE, HID, C, F, G, H, I, J. Since the objects are distinct, they can be arranged in $6!$ ways. *Arrangements with three prohibited substrings*: Since BED and HID cannot both appear in an arrangement of the letters A, B, C, D, E, F, G, H, I, J, there are no arrangements in which ABE, BED, and HID all appear. Therefore, by the [Inclusion-Exclusion Principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle), the number of arrangements of the letters A, B, C, D, E, F, G, H, I, J in which none of the substrings ABE, BED, and HID appear is $$10! - 3 \cdot 8! + 7! + 6!$$
29,410,408
I have `UIViewController`, inside using `UICollectionViewController` and Single Button, I want to change `UICollectionViewControllerCell` when On Click Button, like Height and Width.
2015/04/02
[ "https://Stackoverflow.com/questions/29410408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4613290/" ]
Referring to [node/readline](https://github.com/joyent/node/blob/master/lib/readline.js) line 313: ``` Interface.prototype.write = function(d, key) { if (this.paused) this.resume(); this.terminal ? this._ttyWrite(d, key) : this._normalWrite(d); }; ``` by calling `rl.write()` you either write to tty or call `_normalWrite()` whose definition follows the block. ``` Interface.prototype._normalWrite = function(b) { // some code // ....... if (newPartContainsEnding) { this._sawReturn = /\r$/.test(string); // got one or more newlines; process into "line" events var lines = string.split(lineEnding); // either '' or (concievably) the unfinished portion of the next line string = lines.pop(); this._line_buffer = string; lines.forEach(function(line) { this._onLine(line); }, this); } else if (string) { // no newlines this time, save what we have for next time this._line_buffer = string; } }; ``` Output is written into `_line_buffer`. line 96: ``` function onend() { if (util.isString(self._line_buffer) && self._line_buffer.length > 0) { self.emit('line', self._line_buffer); } self.close(); } ``` We find, `_line_buffer` is emitted to `line` event eventually. That's why you cannot write output to writeStream. To solve this problem, you can simply open a file using `fs.openSync()`, and `fs.write()` in `rl.on('line', function(line){})` callback. Sample code: ``` var rl = readline.createInterface({ input: fs.createReadStream(temp + '/export.json'), output: process.stdout, terminal: false }); fd = fs.openSync('filename', 'w'); rl.on('line', function(line) { fs.write(fd, line); }); ```
1,049,886
In an ASP.Net MVC 1.0 applicati0n, is it possible to access the application settings (MyProject.Properties.Settings.Default.\*) from inside my View (aspx page)? I've tried but the intellisense and compiler don't like it. It says that it is inaccesible due to the protection level.
2009/06/26
[ "https://Stackoverflow.com/questions/1049886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127488/" ]
Your View should only be responsible for rendering data given to it by the Controller. It's responsibility is for layout. So I would recommend passing the Application data to the view from within your Controller action. Having said that, the technical answer to your question is that ViewPage derives from Page, so you can simply do this: ``` <%= Context.Application["setting"] %> ``` But again, I don't recommend it.
31,571,321
The question's prompt is: > > Write a method that takes an array of numbers. If a pair of numbers in the array sums to zero, return the positions of those two numbers. If no pair of numbers sums to zero, return `nil`. > > > I'm not sure how to approach this problem and what would be the simplest way. Would this involve the .index method? ``` def two_sum(nums) end two_sum([1,3,5,-3]) ```
2015/07/22
[ "https://Stackoverflow.com/questions/31571321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5042162/" ]
As with a lot of things in Ruby, there are a couple different ways of doing this. The "classic" approach to this problem would be to use two nested loops: ``` def two_sum(nums) for i1 in 0...nums.length for i2 in i1...nums.length # Inside this loop, nums[i1] represents one number in the array # and nums[i2] represents a different number. # # If we find that the sum of these numbers is zero... if nums[i1] + nums[i2] == 0 # Then we have our answer return i1, i2 end end end # At this point we've checked every possible combination and haven't # found an answer, so a pair of numbers that sum to zero in that array # must not exist. Return nil. nil end ``` The other approach uses Ruby magic to do the same thing in a somewhat more expressive way: ``` def two_sum(nums) result_pair = nums.each_with_index.to_a.combination(2).find{|n1, n2| n1.first + n2.first == 0} result_pair && result_pair.map(&:last) end ``` The breakdown here is a bit more complex. If you'd like to understand it, I recommend looking at the documentation for these methods on [`Array`](http://ruby-doc.org/core/Array.html) and [`Enumerable`](http://ruby-doc.org/core/Enumerable.html).
64,576,412
To preface, I have reviewed the post [here](https://stackoverflow.com/questions/52908923/check-if-asset-exist-in-flutter), but am still having trouble. I am building a container that is decorated with an image, only if that image exists in the assets/images/ folder. If it does not exist, the container is decorated with a default image instead. The image path is formatted string using a variable, image\_id, that assumes a String response from an API. Here is a code / pseudo-code hybrid of what I'm trying to do... ``` Container( height: 200, width: 300, decoration: BoxDecoration( image: DecorationImage( image: (AssetImage('assets/images/${image_id}.jpg') exists) //pseudo-code here ? AssetImage('assets/images/${image_id}.jpg') : AssetImage('assets/images/default.jpg'), fit: BoxFit.cover, ), ), ); ```
2020/10/28
[ "https://Stackoverflow.com/questions/64576412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11615071/" ]
You should know if the asset exists as you're the responsible for adding those. One option you have is by using: [**FlutterGen**](https://github.com/FlutterGen/flutter_gen) This library will create variables, method, etc for all your assets, if the variable is null, then, there you go. You can also try to get the image like this: ``` final assetImage = Image.asset('path/to/asset.jpg'); ``` and then check if that image is null or not. Even, if you want, you can take that and pre cache your image like this: ``` await precacheImage(assetImage.image, context); ```
8,467,908
I have some utility methods that use `Microsoft.Web.Administration.ServerManager` that I've been having some issues with. Use the following dead simple code for illustration purposes. ``` using(var mgr = new ServerManager()) { foreach(var site in mgr.Sites) { Console.WriteLine(site.Name); } } ``` If I put that code directly in a console application and run it, it will get and list the IIS express websites. If I run that app from an elevated command prompt, it will list the IIS7 websites. A little inconvenient, but so far so good. If instead I put that code in a class library that is referenced and called by the console app, it will ALWAYS list the IIS Express sites, even if the console app is elevated. Google has led me to try the following, with no luck. ``` //This returns IIS express var mgr = new ServerManager(); //This returns IIS express var mgr = ServerManager.OpenRemote(Environment.MachineName); //This throws an exception var mgr = new ServerManager(@"%windir%\system32\inetsrv\config\applicationhost.config"); ``` Evidently I've misunderstood something in the way an "elevated" process runs. Shouldn't everything executing in an elevated process, even code from another dll, be run with elevated rights? Evidently not? Thanks for the help!
2011/12/11
[ "https://Stackoverflow.com/questions/8467908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55142/" ]
Make sure you are adding the reference to the correct Microsoft.Web.Administration, should be v7.0.0.0 that is located under c:\windows\system32\inetsrv\ It looks like you are adding a reference to IIS Express's Microsoft.Web.Administraiton which will give you that behavior
27,212,037
What is the difference between the 2 lines below? They do the same thing so is there any difference ? ``` string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName); string filename = FileUpload1.PostedFile.FileName; ```
2014/11/30
[ "https://Stackoverflow.com/questions/27212037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3994909/" ]
In BASH you can use this utility function: ``` decodeURL() { printf "$(sed 's#^file://##;s/+/ /g;s/%\(..\)/\\x\1/g;' <<< "$@")\n"; } ``` **Then call this function as:** ``` decodeURL 'file:///home/sashoalm/Has%20Spaces.txt' /home/sashoalm/Has Spaces.txt ```
10,741,179
i have some jquery thats expanding/collapsing on click. i would like the first item to be expanded by default but im having trouble with the jquery. i've tried a few different angles to no avail. any help would be much appreciated! <http://jsfiddle.net/trrJp/1/>
2012/05/24
[ "https://Stackoverflow.com/questions/10741179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1211700/" ]
The original poster didn't select an answer I'm going to combine the previous two into one ***super*** answr! :P You can enable word wrapping on all columns on the Spark DataGrid with variableRowHeight: ``` <s:DataGrid variableRowHeight="true"> </s:DataGrid> ``` Or you can enable word wrapping on an individual column by using the word wrap property on the default GridColumn item renderer: ``` <s:GridColumn dataField="fields.description" headerText="Description" > <s:itemRenderer> <fx:Component> <s:DefaultGridItemRenderer wordWrap="true"/> </fx:Component> </s:itemRenderer> </s:GridColumn> ``` Furthermore, in the Grid Column example I'd recommend setting a width if you want to prevent horizontal scroll bars: ``` <s:GridColumn width="{dataGrid.width-column1.width-column3.width}" dataField="fields.description" headerText="Description" > <s:itemRenderer> <fx:Component> <s:DefaultGridItemRenderer wordWrap="true"/> </fx:Component> </s:itemRenderer> </s:GridColumn> ``` I'm finding I have to set both variable row height to true and set the column width to get the behavior I'm looking for.
21,642,329
Let`s say I have the following table ``` +----+-------+ | Id | Value | +----+-------+ | 1 | 2.0 | | 2 | 8.0 | | 3 | 3.0 | | 4 | 9.0 | | 5 | 1.0 | | 6 | 4.0 | | 7 | 2.5 | | 8 | 6.5 | +----+-------+ ``` I want to plot these values, but since my real table has thousands of values, I thought about getting and average for each X rows. Is there any way for me to do so for, ie, each 2 or 4 rows, like below: ``` 2 +-----+------+ | 1-2 | 5.0 | | 3-4 | 6.0 | | 5-6 | 2.5 | | 7-8 | 4.5 | +-----+------+ 4 +-----+------+ | 1-4 | 5.5 | | 5-8 | 3.5 | +-----+------+ ``` Also, is there any way to make this X value dynamic, based on the total number of rows in my table? Something like, if I have 1000 rows, the average will be calculated based on each 200 rows (1000/5), but if I have 20, calculate it based on each 4 rows (20/5). I know how to do that programmatically, but is there any way to do so using pure SQL? EDIT: I need it to work on mysql.
2014/02/08
[ "https://Stackoverflow.com/questions/21642329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278986/" ]
Depending on your DBMS, something like this will work: ``` SELECT ChunkStart = Min(Id), ChunkEnd = Max(Id), Value = Avg(Value) FROM ( SELECT Chunk = NTILE(5) OVER (ORDER BY Id), * FROM YourTable ) AS T GROUP BY Chunk ORDER BY ChunkStart; ``` This creates 5 groups or chunks no matter how many rows there are, as you requested. If you have no windowing functions you can fake it: ``` SELECT ChunkStart = Min(Id), ChunkEnd = Max(Id), Value = Avg(Value) FROM YourTable GROUP BY (Id - 1) / (((SELECT Count(*) FROM YourTable) + 4) / 5) ; ``` I made some assumptions here such as `Id` beginning with 1 and there being no gaps, and that you would want the last group too small instead of too big if things didn't divide evenly. I also assumed integer division would result as in Ms SQL Server.
1,584,983
1. I have an open folder in VSCode, eg `/folders/project1`, this is my workspace. 2. I want to add a file from outside of this folder, eg `/media/files/file1`. I wish there was a VSCode command that displays a file picker that I can select any file on my computer's memory, and that file ends up in a folder opened as workspace. For example: 3. In VSCode select the file `/media/files/file1` and it lands in workspace as `/folders/project1/file1` How to do it? I can't find anything. Of course I know I can do this manually in the file manager, but I want to do it without leaving VSCode.
2020/09/12
[ "https://superuser.com/questions/1584983", "https://superuser.com", "https://superuser.com/users/1050966/" ]
You can use [PowerToys](https://github.com/microsoft/PowerToys) from Microsoft. One of the toys Keyboard Manager is made just for what you are looking for: > > Keyboard Manager allows you to customize the keyboard to be more productive by remapping keys and creating your own keyboard shortcuts. This PowerToy requires Windows 10 1903 (build 18362) or later. > > > To use it, go to the PowerToys settings, select Keyboard Manager, then click Remap Key. [![enter image description here](https://i.stack.imgur.com/o2Pgb.png)](https://i.stack.imgur.com/o2Pgb.png) Select the key that should be remapped plus the key that should take its place. Click `OK`. That's it. [![enter image description here](https://i.stack.imgur.com/0r97Y.png)](https://i.stack.imgur.com/0r97Y.png)
31,428,972
In my .htaccess file: ``` RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L] ``` This is giving me a redirect loop error in Chrome when I visit `mydomain.io`. I have a free SSL certificate set up on CloudFlare, I'm not sure if that could be causing the issue? When I visit `https://mydomain.io` it works fine and comes up with the green lock and https.
2015/07/15
[ "https://Stackoverflow.com/questions/31428972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3040456/" ]
Try this rule instead on [cloudfare](https://support.cloudflare.com/hc/en-us/articles/200170536-How-do-I-redirect-all-visitors-to-HTTPS-SSL-): ``` RewriteEngine On RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,NE,R=302] ```
37,099,617
I'm having difficulties with some recoding (filling in empty cells in R or SPSS) I'm working with a long format data-set (in order to run a multilevel model) where each respondent (ID-variable) has three rows, so three times the same ID number below each other (for three different momemts in time). The problem is that for a second variable (ancestry of respondent) only the first row has a value but the two second rows for each respondent misses that (same) value (0/1). Can any one help? I'm only used to recoding within the same row... below a the data format. ``` ID Ancestry 1003 1 1003 . 1003 . 1004 0 1004 . 1004 . 1005 1 1005 . 1005 . ```
2016/05/08
[ "https://Stackoverflow.com/questions/37099617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5235404/" ]
We can use `na.locf` assuming that `.` implies `NA` values. ``` library(zoo) df1$Ancestry <- na.locf(df1$Ancestry) ``` If the column is non-numeric i.e. have `.` as values, then we need to convert it to numeric so that the `.` coerce to NA and then we apply `na.locf` on it ``` df1$Ancestry <- na.locf(as.numeric(df1$Ancestry)) df1$Ancestry #[1] 1 1 1 0 0 0 1 1 1 ``` If it needs to be grouped by "ID" ``` library(data.table) setDT(df1)[, Ancestry := na.locf(Ancestry), by = ID] ```
11,826,536
I have an AsyncTask which loads Tweets from Twitter. I also have a PullToRefresh ListView... Whenever i pull to refresh it, the listview immediately clears and as soon as the data has been loaded, it's getting filled into the listview. I have other ListViews in my App all with the same stuff (PullToRefresh and Async data loading...). On the other ListViews this does not happen. Only on the Twitter ListView. What am I doing wrong? Here is my Code: ``` public class TwitterDownloader extends AsyncTask<Void, Void, String> { final Handler mHandler = new Handler(); public TwitterDownloader() { } @Override public void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(Void... params) { twitter4j.Twitter twitter = new TwitterFactory().getInstance(); listTweets.clear(); List<twitter4j.Status> statuses = null; try { statuses = twitter.getUserTimeline( MainActivity.TWITTER_USERNAME, new Paging(1, 50)); } catch (TwitterException e) { e.printStackTrace(); Log.e(MainActivity.LOG_TAG, "TwitterException"); } try { for (twitter4j.Status status : statuses) { listTweets.add(status.getText()); } } catch (NullPointerException npe) { } return null; } @Override public void onPostExecute(String unused) { MyCustomAdapter myAdapter = new MyCustomAdapter(myContext, R.layout.row_twitter, listTweets); setListAdapter(myAdapter); getListView().setTextFilterEnabled(true); String lastUpdate = (new SimpleDateFormat( "HH:mm")).format(new Date()); pullToRefreshView.onRefreshComplete(); pullToRefreshView.setLastUpdatedLabel(getString(R.string.last_updated) + ": " + lastUpdate); } ```
2012/08/06
[ "https://Stackoverflow.com/questions/11826536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754730/" ]
I am not sure about this but in `doInBackground` method of AsyncTask, you are doing `listTweets.clear();`. After getting result, you are adding data to it. May be this is causing problems.
80,649
I am working on a physics reserach project for school and I have run into some troubles working Mathematica. I am a fairly inexperienced mathematica user so any help would very much be appreciated. I need to find the roots of the transcendental equation $$\zeta\_n \tan(\zeta) - \sqrt{R^2-\zeta^2\_n}=0$$ and then collect them into a list, $\{\zeta\_n\}$, which I can sum over. FindRoot works but only finds one root at a time. For example $R^2=18$ gives > > FindRoot[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, {zeta, 3}] > > > {zeta -> 3.66808} > From a plot of the function I know there should be two roots for this particular value of $R$, however FindRoot only gives one. > > > I have had no luck with NSolve or Solve either. > > NSolve[xi[zeta, Erg4]- zeta\*Tan[zeta] == 0, zeta] > > > NSolve[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, zeta] > > > Also once I have succeeded in finding all roots how does one put them in an indexed set ${\zeta\_n}$.
2015/04/22
[ "https://mathematica.stackexchange.com/questions/80649", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/27986/" ]
``` With[{maxR = 10}, Manipulate[ expr = Sqrt[R^2 - zeta^2] - zeta Tan[zeta]; zero = zeta /. NSolve[{expr == 0, R^2 - zeta^2 >= 0}, zeta] // Quiet; Column[{ Plot[expr, {zeta, -maxR, maxR}, Exclusions -> {Cos[zeta] == 0}, PlotRange -> {{-maxR, maxR}, {-25, 40}}, Epilog -> {Red, AbsolutePointSize[4], Point[{#, 0} & /@ zero]}, AspectRatio -> 1], zero}, Alignment -> Center], {{R, Sqrt[18]}, 0, maxR, Appearance -> "Labeled"}]] ``` ![enter image description here](https://i.stack.imgur.com/8xcBF.png)
65,126,618
I have monthly data and I want to plot only certain regions, every 24 steps (2 years) or so, how can I find a quick way to plot every 20 steps using a for loop maybe? For example, instead of doing this: ``` #first 24 indices plt.plot(time_months[0:24], monthly[0:24]) plt.xticks(rotation=35) plt.show() #next set of 24 indices plt.plot(time_months[24:48], monthly[24:48]) plt.xticks(rotation=35) plt.show() ``` I tried this: ``` for i in range(monthly.size): plt.plot(time_months[0:i,24]) plt.show() ``` but I get an error: ``` --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-11-db04910853f1> in <module> 4 5 for i in range(monthly.size): ----> 6 plt.plot(time_months[0:24,i]) 7 plt.show() IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed ```
2020/12/03
[ "https://Stackoverflow.com/questions/65126618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14714547/" ]
`pipenv` has no special option for it. But you can use these bash scripts (I made them using the venvs directory `~/.local/share/virtualenvs/` so you should change it if your venvs folder is different) PRINT useless venvs: ==================== ``` for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && echo ${f//\/.project}; done; ``` **PRINT not existing projects paths** that still have corresponding venvs: ``` for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && echo $proj_path; done; ``` **PRINT both** (useless venvs and not existing project folders): ``` for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && echo $proj_path "\n"${f//\/.project} "\n"; done; ``` DELETE useless venvs ==================== ``` for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && rm -rif ${f//\/.project} && echo DELETING ${f//\/.project}; done; ``` Try printing the venvs before deleting! p.s. If your venv folder is not `~/.local/share/virtualenvs/`, make sure to change it to your venv path!
1,897,672
Let $f$ be a separable monic polynomials with integer coefficient. Let $K$ be the splitting field of $f$ over $\mathbb{Q}$, and let $p$ be a prime. What is the relationship between the statements $f$ splits over $\mathbb{F}\_p$ and $p$ is not irreducible in $K$ (there is probably some fancy term for this, like $p$ is inert in $K$?) There are equivalent for the Gaussian Integers, so probably also for any quadratic extension with trivial class group. I suspect they are equivalent, and this is probably extremely well known, but I have asked a couple people with no luck.
2016/08/20
[ "https://math.stackexchange.com/questions/1897672", "https://math.stackexchange.com", "https://math.stackexchange.com/users/116154/" ]
Let $ K = \mathbf Q(\alpha) $ be a number field with ring of integers $ \mathcal O\_K $, where $ \alpha $ is an algebraic integer with minimal polynomial $ \pi(X)$. Dedekind's factorization criterion tells us that if $ p $ is a prime which does not divide the index $ [\mathcal O\_K : \mathbf Z[\alpha]] $, then the way $ \pi(X) $ splits modulo $ p $ is equivalent to the way $ (p) $ splits in $ \mathcal O\_K $, in other words, if we have $$ (p) = \prod\_{i=1}^n \mathfrak p\_i^{e\_i} $$ in $ \mathcal O\_K $ where the inertia degrees of $ \mathfrak p\_i $ are $ f\_i $, then we have $$ \pi(X) \equiv \prod\_{i=1}^n \pi\_i(X)^{e\_i} \pmod{p} $$ where the $ \pi\_i $ are irreducible in $ \mathbf Z/p\mathbf Z[X] $ with $ \deg \pi\_i = f\_i $. This is essentially a consequence of the isomorphisms $$ \mathbf Z[\alpha]/(p) \cong \mathbf Z[X]/(\pi(X), p) \cong \mathbf Z/p \mathbf Z[X]/(\pi(X)) $$ and the fact that you can read off the relevant data from the ring structure alone. As an example of how this fails when the criterion regarding the index is not met, consider $ K = \mathbf Q(\sqrt{5}) $. $ \mathbf Z[\sqrt{5}] $ has index $ 2 $ in $ \mathcal O\_K $, and we have $ x^2 - 5 = (x+1)^2 $ in $ \mathbf Z/2\mathbf Z $, which suggests that $ 2 $ would be a totally ramified prime. However, this is not the case: $ \operatorname{disc} \mathcal O\_K = 5 $, therefore $ 2 $ is not even a ramified prime in $ \mathcal O\_K $. (This is a counterexample to your claim, since $ \mathbf Q(\sqrt{5}) $ is actually the splitting field of $ x^2 - 5 $ over $ \mathbf Q $. Note that $ \mathcal O\_K $ is even a principal ideal domain!)
7,858
My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost. Is anyone doing this and if so, how?
2012/10/18
[ "https://pm.stackexchange.com/questions/7858", "https://pm.stackexchange.com", "https://pm.stackexchange.com/users/4752/" ]
### TL;DR Don't think "time tracking." Think "cycle time" instead. ### Kanban Should Measure Cycle Time Generally, Kanban is not about measuring "activities" at a granular level; it is about measuring cycle time for a pull through the entire system. There is legitimate debate about whether this time should include lead time (e.g. time spent in the ice box) or just time from "started" to "done." Some examples of how lead and cycle times can be measured are: * [Kanban and When Will This Be Done?](https://web.archive.org/web/20160304145123/http://www.dennisstevens.com/2010/06/07/kanban-and-when-will-this-be-done/) * [Kanban Analytics & Metrics: Lead and Cycle Time and Cumulative Flow Diagram](http://kanbantool.com/kanban-analytics-and-metrics) but there may certainly be better explanations out there. The the general idea, though, is that you care about how long it takes and average batch to move from from initialization to a delivered state--regardless of how you choose to measure that. ### Don't Micro-Manage The important thing in Kanban is that you are *not* measuring sub-tasks or work products belows the level of the user story. In other words, if a user story is "embiggen the quux" then it doesn't matter how long it takes to order the quux components, perform the embiggening, or update the quux documentation--unless those are explicit queues in your Kanban process, of course. With Kanban, the question you're asking is "how long does it normally take for a standard-sized story to move through the entire queue and across all defined processes for that queue?" You then use *kaizen* to eliminate waste and reduce cycle time to the maximum extent practical, rather than optimizing individual tasks. When you ask how to track time spent on specific activities, you're trying to optimize parts of a task. This is wrong. Consider the following quote: > > To optimize the whole, you must sub-optimize the parts...First, model the process by breaking it down into between five and nine sub-processes. Visualize each sub-process as an input hopper that sits on top of a black box. Inputs to the queue are dumped on top of the input hopper where they wait their turn. When the black box is ready to process the next item it grabs an input from the bottom of the stack, does whatever it does, and shoves it onto the top of the input hopper of the next sub-process. > > > Lewis, Bob (2012-01-23). Keep the Joint Running: A Manifesto for 21st Century Information Technology (pp. 31-38). IS Survivor Publishing. Kindle Edition. > > > All you (should) care about is the overall efficiency of the entire process chain, not the individual sub-processes. That doesn't mean waste can't exist in a sub-process, but you should spend *zero* time on that level of analysis until and unless it is negatively impacting the cycle time of your macro-process.
8,859,384
Is there such a thing as a 64-bit .dll for the YAJSW Java service wrapper? If so, where do I find it? I know that the Tanuki JSW provides .dll files that go with the .jar files it distributes. So, I am basically wondering if YAJSW has overcome this limitation and I dont need a .dll OR if I need to download one from somewhere? The [YAJSW website](http://yajsw.sourceforge.net/YAJSW%20Configuration%20Parameters.html) mentions the existence of a w86.dll file but provides no information on where to find it or whether you need it or not.
2012/01/14
[ "https://Stackoverflow.com/questions/8859384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118228/" ]
I think you are misunderstanding that reference to "w86.dll". I think it is supposed to be an example of some 3rd party application specific DLL. The text is about how to configure YAJSW to deal with such things. I've never tried to use YAJSW, but the indications from the documentation is that 64 bit is supported for Windows. It should "just work" if you follow the generic instructions. Have you tried that?
18,667,510
I have a bunch of directories that I need to restructure. They're in a format as such: ``` ./1993-02-22 - The Moon - Tallahassee, FL/**files** ./1993-02-23 - The Moon - Tallahassee, FL/**files** ./1993-02-24 - The Moon - Tallahassee, FL/**files** ./1993-02-25 - The Moon - Tallahassee, FL/**files** ./1993-03-01 - The Test - Null, FL/**files** ``` I want to extract the dates from the beginning of each folder. For example, in regex: `([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})` and reformat the directories to `./year/month/day`. So, it should output: ``` ./1993/02/22/**files** ./1993/02/23/**files** ./1993/02/24/**files** ./1993/02/25/**files** ./1993/03/01/**files** ``` How can I go about doing that from a command line?
2013/09/06
[ "https://Stackoverflow.com/questions/18667510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240569/" ]
I understood the question in a different way than [Kent](https://stackoverflow.com/users/164835/kent). I thought that you wanted to create a new tree of directories from each original one and move all files that it contained. You could try following [perl](/questions/tagged/perl "show questions tagged 'perl'") script if that was what you were looking for: ``` perl -MFile::Path=make_path -MFile::Copy=move -e ' for ( grep { -d } @ARGV ) { @date = m/\A(\d{4})-(\d{2})-(\d{2})/; next unless @date; $outdir = join q{/}, @date; make_path( $outdir ); move( $_, $outdir ); } ' * ``` It reads every file from current directory (`*` passed as argument) and does two step filter. The first one is the `grep` for no-directories files and the second one is an undefined `@date` for those that don't begin with it. Then it joins date's components into a path, creates it if doesn't exist and move the old one with all its files to the new one. A test: Here the result of `ls -lR` to show initial state: ``` .: total 24 drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-22 - The Moon - Tallahassee, FL drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-23 - The Moon - Tallahassee, FL drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-24 - The Moon - Tallahassee, FL drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 1993-02-25 - The Moon - Tallahassee, FL drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 1993-03-01 - The Test - Null, FL drwxr-xr-x 2 dcg dcg 4096 sep 7 00:47 dummy_dir -rw-r--r-- 1 dcg dcg 0 sep 7 00:47 dummy_file ./1993-02-22 - The Moon - Tallahassee, FL: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file1 -rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file2 ./1993-02-23 - The Moon - Tallahassee, FL: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file3 ./1993-02-24 - The Moon - Tallahassee, FL: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file4 ./1993-02-25 - The Moon - Tallahassee, FL: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file5 -rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file6 ./1993-03-01 - The Test - Null, FL: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file7 ./dummy_dir: total 0 ``` And after running the previous script note that the base directory only keeps dummy files and the root of the tree created (`1993`). Running the same `ls -lR` yields: ``` .: total 8 drwxr-xr-x 4 dcg dcg 4096 sep 7 00:59 1993 drwxr-xr-x 2 dcg dcg 4096 sep 7 00:47 dummy_dir -rw-r--r-- 1 dcg dcg 0 sep 7 00:47 dummy_file ./1993: total 8 drwxr-xr-x 6 dcg dcg 4096 sep 7 00:59 02 drwxr-xr-x 3 dcg dcg 4096 sep 7 00:59 03 ./1993/02: total 16 drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 22 drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 23 drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 24 drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 25 ./1993/02/22: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file1 -rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file2 ./1993/02/23: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file3 ./1993/02/24: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file4 ./1993/02/25: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file5 -rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file6 ./1993/03: total 4 drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 01 ./1993/03/01: total 0 -rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file7 ./dummy_dir: total 0 ```
106,947
I've been able to add a Google Calendar (CalDAV) account to OS X Calendar (v6, Mountain Lion 10.8.5) without problem, and all my own calendars show up. Is there a way of seeing calendars others have shared with me (these show up under 'Other Calendars' in the Google Calendar website settings)? (Same situation on my iPhone.)
2013/10/26
[ "https://apple.stackexchange.com/questions/106947", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/37070/" ]
Yes, this question is answered by google here: <https://www.google.com/calendar/syncselect> You can click on the link and select shared calendars you wanna sync with your device.
12,859,824
I am parsing through the subviews of a parent view, It has various subviews, all custom classes, of 10 different UIView subclasses. There is just one class which is a normal UIView. Now when I am looping thru, I need to get hold of the UIView subview, isKindOfClass is failing to do so as it returns 1 for all the UIView subclasses as well. Do I have to write a a big if-else construct to check if its an object of any other custom UIView subclass and then in the last else come to a conclusion that its a normal UIView. Or is there a method that tells me exact class of the view ?
2012/10/12
[ "https://Stackoverflow.com/questions/12859824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/961021/" ]
You shoud use : ``` [currentView isMemberOfClass:[UIView class]]; ```
12,523,776
``` #ifndef UNICODE #define UNICODE #endif #include <iostream> #include <Windows.h> #include <queue> using namespace std; void addSomeContent(queue<TCHAR*> &s) { static int counter=0; TCHAR* buffer = new TCHAR[250]; //Allocate memory on heap wsprintf(buffer,TEXT("foo%d"),counter); s.push(buffer); counter++; if(counter < 10) addSomeContent(s); } int main (void) { queue<TCHAR*> strings; addSomeContent(strings); while(!strings.empty()) { wcout<<strings.front()<<endl; strings.pop(); } //Here I want to destroy the "buffer" from the function "addSomeContent" wcout<<TEXT("Memory has been cleaned!\n"); system("pause"); return (0); } ``` If I had deleted the wide char array at the end of the function, I couldn't have processed my queue which references to it. Now, my simple program compiles and works fine, but obviously keeping a garbage in heap isn't considered as a safe programming practice. How to delete the "buffer" just after using it last time?
2012/09/21
[ "https://Stackoverflow.com/questions/12523776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1349442/" ]
You can use a `queue<unique_ptr<TCHAR[]>>` to avoid memory deallocation entirely, or you can simply deallocate the memory before you remove it from the `queue` like so: ``` delete[] strings.front(); strings.pop(); ```
11,736,566
I'm trying to retrieve the month using `date`. ``` $year= 2012; $mon = date( 'F', mktime(0, 0, 0, $month,$year) ); ``` In the above code snippet, `$month` is dynamically incremented. I have used a while loop with `$month++`. But it doesn't give me the correct date. For example, let's say I gave `$month=5` at the beginning, then it's incremented till `$month=12`. Then the output should be something like ``` May June July... ``` but, it's output is: ``` November December January..... ``` why is this? Am I doing anything wrong here?
2012/07/31
[ "https://Stackoverflow.com/questions/11736566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1503607/" ]
You forgot $date parameter. THe correct syntax of mktime is ``` mktime($hour,$minute,$second,$month,$day,$year); ``` so in your example $year will be considered as 'date' try something like ``` mktime(0,0,0,$month,1,$year); ```
1,231,785
I have two .Net applications running on client machine.One is IMSOperations and other is IMSInvoice.Both are windows forms application using C#. What happens is when both of these applications are running,after some time IMSOperations gets automatically closed. What i tried is to find reason of closing by subscribing to main form's Form\_Closing() event.IS there any other way to figure out what's going on and why is that application getting closed.
2009/08/05
[ "https://Stackoverflow.com/questions/1231785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139357/" ]
Might I suggest adding these to make sure no exception is being thrown: You need to add this line to your Main(): ``` AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); ``` and add appropriate handlers to display any exceptions. (ThreadException handles exceptions UI thread exceptions. UnhandledException handles non-UI thread exceptions.)
3,880,339
I have a referenced library, inside there I want to perform a different action if the assembly that references it is in DEBUG/RELEASE mode. Is it possible to switch on the condition that the calling assembly is in DEBUG/RELEASE mode? Is there a way to do this without resorting to something like: ``` bool debug = false; #if DEBUG debug = true; #endif referencedlib.someclass.debug = debug; ``` The referencing assembly will always be the starting point of the application (i.e. web application.
2010/10/07
[ "https://Stackoverflow.com/questions/3880339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28543/" ]
[Google says](http://stevesmithblog.com/blog/determine-whether-an-assembly-was-compiled-in-debug-mode/) it is very simple. You get the information from the [DebuggableAttribute](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggableattribute.aspx) of the assembly in question: ``` IsAssemblyDebugBuild(Assembly.GetCallingAssembly()); private bool IsAssemblyDebugBuild(Assembly assembly) { foreach (var attribute in assembly.GetCustomAttributes(false)) { var debuggableAttribute = attribute as DebuggableAttribute; if(debuggableAttribute != null) { return debuggableAttribute.IsJITTrackingEnabled; } } return false; } ```
54,014,561
I have the following array: var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]; I want to get 15 random numbers from this array, where there can't be duplicates. I have no idea on how to do it. Also, if it'd be easier, I would like to know if there is a way to generate an array with 15 numbers from 1 to 35, with no duplicates, instead of picking them from the array I showed. Thanks in advance!
2019/01/02
[ "https://Stackoverflow.com/questions/54014561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10860157/" ]
If you are just trying to get a number between 1 and 35 then you could do this, ``` Math.floor(Math.random() * 35) + 1 ``` Math.random() returns a number between 0 and 1, multiplying this by 35 gives a number between 0 and 35 (not inclusive) as a float, you then take a floor add 1 to get the desired range. You can then loop over this and use this to populate your array. If you don't want any repeats then I recommend you look at using a `Set` to make sure you don't have any repeats, then just loop until the set has the desired number of values. Sets are documented [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
41,413
My friend asked me for help with an IQ test and after she did it online she came back at me with the ones she couldn't solve. Two of them however, I discovered are the same puzzle type, but no matter how much I look at it, I just can't see the logic in it. We redid the test and this puzzle occurred yet again, so now I have three versions of the same type of sequence written below. > > 19 43 83 233 59 61 283 ? > > > 11 35 75 225 51 53 275 ? > > > 5 29 69 219 45 47 269 ? > > > I get the feeling that this puzzle is easy, yet I just can't see it. [Update] By request, I give the five options for the answer of the top row that I wrote down during the second test. The options are: 800 778 793 58 176. I'm actually leaning towards Jonathan Allan's explanation of a mistake in some data entry for their automated question generation right now, since no one here seems to have solved it yet. Prior to my post here, my friend emailed them asking them about this sequence, so most likely we will know between now and a few days. [Update] Looking at the options again, this puzzle is really really simple. Thank you smriti.
2016/08/25
[ "https://puzzling.stackexchange.com/questions/41413", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/29405/" ]
What these three have in common is that in all of these sequences the addition to the next is in this order: > > 24 40 150 -174 2 222 ? > > > So as these three sequences share the same changing sequence then the changing isn't related to the numbers themselves but the differences between the numbers. Got some hints from @Shimizoki's reasoning, but this might be totally wrong: N1 + 40 = N5 N4 + 50 = N7 This could mean that: N7 + 60 = N8 Because in the next equation: The first in the equation is the number that is three positions further in the sequence. The second number increases with ten. The difference between the first in the equations place in the sequence and the sums number in the sequence increases by one less for each equation. Therefore for the last number in the row for the first sequence would be 283+60=343. This would mean the there are some decoy numbers and we have only deduced the pattern from two cases which makes me doubt that this is the right answer.
23,293,043
Hi I have question about HTML form array and PHP. For example I have name and email but ask 6 times and I want to send this mail. What I should edit to work? thank you! **HTML:** ``` <form method="Post" action="send.php" onSubmit="return validate();"> <?php $amount=6; //amount shows the number of data I want to repeat for( $i = 0; $i < $amount; $i++ ) { ?> <b>Data <?php echo $i+1 ?>º</b> <input type="edit" name="Name[]" size="40"> <input type="edit" name="email[]" size="40"> <br> <?php } ?> <input type="submit" name="Submit" value="send 6 data mail"> </form> ``` **send.php:** ``` <?php require('phpmailer/class.phpmailer.php'); $name= $_POST['name[]']; $email= $_POST['email[]']; $mail = new PHPMailer(); ... $mail->Body = ' Data<br> ' <?php $amount=6; //amount shows the number of data I want to repeat for( $i = 0; $i < $amount; $i++ ) { ?> ' name: '.$name[$i].' email: '.$email[$i]; ... $mail->Send(); ?> ``` should send: ``` Data name: nameinput1 email: emailinput1 name: nameinput2 email: emailinput2 name: nameinput3 email: emailinput3 name: nameinput4 email: emailinput4 name: nameinput5 email: emailinput5 name: nameinput6 email: emailinput6 ```
2014/04/25
[ "https://Stackoverflow.com/questions/23293043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3572757/" ]
I personally prefer to avoid dynamic stuff like ViewBag /ViewData as much as possible to transfer data between action methods and views. Let's build a strongly typed Viewmodel. ``` public class CreateCustomerVM { public string MidName{ get; set; } [Required] public string FirstName{ get; set; } public string Surname{ get; set; } public List<SelectListItem> MidNames { set;get;} public CreateCustomerVM() { MidNames=new List<SelectListItem>(); } } ``` and in your `Create` action method ``` public ActionResult Create() { var vm=new CreateCustomerVM(); vm.MidNames=GetMidNames(); return View(vm); } private List<SelectListItem> GetMidNames() { return new List<SelectListItem> { new SelectListItem { Value="Mr", Text="Mr"}, new SelectListItem { Value="Ms", Text="Ms"}, }; } ``` and in your view, which is strongly typed to our viewmodel ``` @model CreateCustomerVM @using(Html.Beginform()) { <div> Mid name : @Html.DropdownListFor(s=>s.MidName,Model.MidNames) FirstName : @Html.TextBoxFor(s=>s.FirstName) <input type="submit" /> </div> } ``` Now when your form is posted, You will get the selected item value in the `MidName` property of the viewmodel. ``` [HttpPost] public ActionResult Create(CreateCustomerVM customer) { if(ModelState.IsValid) { //read customer.FirstName , customer.MidName // Map it to the properties of your DB entity object // and save it to DB } //Let's reload the MidNames collection again. customer.MidNames=GetMidNames(); return View(customer); } ```
57,575,105
Is there a way to search for multiple conditions in the same column and then count the number of occurrences? For example, I want to figure out how many times a specific combination of values (x and then y, x then w, x then z) occur after one another for each respective person. I tried writing an IF statement but was told that dplyr would be a better route. ``` Dataframe: c1 c2 person1 x person1 y person1 a person1 a person2 x person2 w person1 x person1 z df %>% select(c1, c2) %>% tally(filter(c2 == "x") %>% lead(filter(c2=="y"))) ``` Expected results: a subset that displays the total number of times x then y, x then w, x then z, appear for each person. ``` c1 xy xw xz Person 1 1 0 1 Person 2 0 1 0 ``` R gives me the following error: =============================== ``` Error in UseMethod("filter_") : no applicable methord for 'filter_' applied to an object of class "logical" ```
2019/08/20
[ "https://Stackoverflow.com/questions/57575105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9867193/" ]
``` library(dplyr) c1 = c("person1", "person1", "person1", "person1", "person2", "person2", "person1", "person1") c2 = c("x","y","a","a","x","w","x","z") df = as_tibble(cbind(c1,c2)) df %>% group_by(c1) %>% summarise(xy = sum(c2 == "x" & lead(c2, 1) == "y" ), xw = sum(c2 == "x" & lead(c2, 1) == "w"), xz = sum(c2 == "x" & lead(c2, 1) == "z")) ``` Gives you ``` # A tibble: 2 x 4 c1 xy xw xz <chr> <int> <int> <int> 1 person1 1 0 1 2 person2 0 1 0 ```
17,449,157
Having made the move to C++11, I am now systematically passing my strings by value in my constructors. But now, I realize that it makes it easier to introduce bugs when also using the value in the body of the constructor: ``` class A(std::string val): _val(std::move(val)) { std::cout << val << std::endl; // Bug!!! } ``` What can I do to reduce the chances of getting it wrong?
2013/07/03
[ "https://Stackoverflow.com/questions/17449157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16877/" ]
Name arguments whose purpose is to be moved-from in some distinctive manner, at least within the implementation of the constructor ``` A::A(std::string val_moved_from): _val(std::move(val_moved_from)) { std::cout << val_moved_from << std::endl; // Bug, but obvious } ``` then move from them as early as possible (in the construction list, say). If you have such a long construction list you can miss two uses of `val_moved_from` in it, this doesn't help. An alternative would be to write up a proposal to fix this problem. Say, extend C++ so that the types or scopes of local variables can be changed by operations on them, so `std::safe_move(X)` both moves from `X` and marks `X` as an expired variable, no longer valid to use, for the remainder of its scope. Working out what to do when a variable is half-expired (expired in one branch, but not in another) is an interesting question. Because that is insane, we can instead attack it as a library problem. To a certain limited extent, we can fake those kind of tricks (a variable whose type changes) at run time. This is crude, but gives the idea: ``` template<typename T> struct read_once : std::tr2::optional<T> { template<typename U, typename=typename std::enable_if<std::is_convertible<U&&, T>::value>::type> read_once( U&& u ):std::tr2::optional<T>(std::forward<U>(u)) {} T move() && { Assert( *this ); T retval = std::move(**this); *this = std::tr2::none_t; return retval; } // block operator*? }; ``` ie, write a linear type that can only be read from via `move`, and after that time reading `Assert`s or throws. Then modify your constructor: ``` A::A( read_once<std::string> val ): _val( val.move() ) { std::cout << val << std::endl; // does not compile std::cout << val.move() << std::endl; // compiles, but asserts or throws } ``` with forwarding constructors, you can expose a less ridiculous interface with no `read_once` types, then forward your constructors to your "safe" (possibly `private`) versions with `read_once<>` wrappers around the arguments. If your tests cover all code paths, you'll get nice `Assert`s instead of just empty `std::string`s, even if you go and `move` more than once from your `read_once` variables.
23,395,932
Is it possible to overload = operator of type double? I have the following: ``` double operator=(double a, Length b) { return a = (b.getInches()/12+b.getFeet())*3.2808*0.9144; } ``` It throws the following error: ``` 'double operator=(double, Length)' must be a nonstatic member function ``` What am I doing wrong?
2014/04/30
[ "https://Stackoverflow.com/questions/23395932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1527217/" ]
You cannot overload operators for builtin (integral or floating point) types like `double`, and also you cannot globally overload the `=` operator for *any* type. The `=` operator can only be overloaded as a class member function. See also: [Can I define an operator overload that works with built-in / intrinsic / primitive types?](http://www.parashift.com/c++-faq/intrinsics-and-operator-overloading.html)
57,748,100
When any element with `.mytrigger` is clicked, `.myactive` will be toggled on element with `#mytarget`. I have the following code: ```js var navclick = document.getElementsByClassName("mytrigger"); for (var i = 0; i < navclick.length; i++) { navclick[i].onclick = function() { document.getElementById('mytarget').classList.toggle("myactive"); } } ``` ```css .myactive { background-color: blue; color: white; } ``` ```html <a class="mytrigger">Button</a> <div id="mytarget"><p>Hello</p></div> <a class="mytrigger">Button</a> ``` I need to have multiple triggers and from that this became confusing so I am unable to figure out the correct code. I can't use jquery for this.
2019/09/01
[ "https://Stackoverflow.com/questions/57748100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11282590/" ]
Make as many as elements you want with class ".mytrigger" Just put onclick function as mentioned. I hope this helps:- If not then please clarify your problem **HTML CODE** ``` <a onclick="myFunction()" class="mytrigger">Button</a> <div id="mytarget"><p>Hello</p></div> <a onclick="myFunction()" class="mytrigger">Button</a> ``` **Javascript CODE** ``` function myFunction() { var element = document.getElementById("mytarget"); element.classList.toggle("myactive"); } ```
48,057,433
The following query returns ``` select to_char( trunc(sysdate) - numtoyminterval(level - 1, 'month'), 'mon-yy') as month from dual connect by level <= 12 ``` last 12 months according to today's date(i.e. 2-Jan-18). [![enter image description here](https://i.stack.imgur.com/Sd9ZQ.png)](https://i.stack.imgur.com/Sd9ZQ.png) Say if today's date is 29-DEC-17 it gives oracle sql error: **ORA-01839: date not valid for month specified** (since on subtracting there would be a date in the result as **'29-FEB-17'** which is not possible). So on specific dates this error would pop-up. How do you suggest to overcome this?
2018/01/02
[ "https://Stackoverflow.com/questions/48057433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7906671/" ]
`char` is `signed` on your platform. If you use `unsigned char` for your types for `c2` and `c1` then the implicit promotion to `int` for each term in your expression will have the effect you are after.
22,499,848
I am looking for a way to get the content of the webpage using the url. For instance lets say when you go to www.example.com, you see the text "hello world". I want to get the text hello world in razor c#. In other words, I need a replacement of the following jquery code using c#: ``` $.post("www.example.com",{},function(data){ useme(data); }) ```
2014/03/19
[ "https://Stackoverflow.com/questions/22499848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/991609/" ]
``` var html = Html.Raw(new System.Net.WebClient().DownloadString("http://www.example.com")); ``` `Html.Raw` allows in parsing to HTML while a new instance of `WebClient` can help with directly fetching the string.
61,544,349
*"Do not embed secrets related to authentication in source code"* - [one may hear frequently](https://cloud.google.com/docs/authentication/production#best_practices_for_managing_credentials). Okay, so I use the [Key Management Service](https://cloud.google.com/kms) and [Secret Manager](https://cloud.google.com/secret-manager). But then, **how do I correctly access secrets stored there from Compute Engine's VM and from my local dev environment?** I can think of either: 1. Accessing the secrets using the [default Service Account credentials](https://cloud.google.com/docs/authentication/production#obtaining_credentials_on_compute_engine_kubernetes_engine_app_engine_flexible_environment_and_cloud_functions), but then how do I access the secrets in the local development environment and inside of my local Docker containers (ie. outside the Compute Engine)? 2. Accessing the secrets using a [custom Service Account](https://cloud.google.com/docs/authentication/production#creating_a_service_account), but then I need to store its JSON key somewhere and access it from my code. For that I have two options: 2.1. Store it with the source code, so I have it on dev machine and in the Docker container. But then that goes against the opening statement *"Do not embed secrets ... in source code"*. Bad idea. 2.2. Store it somewhere on my dev machine. But then how do my Docker container accesses it? I could provide the key as Docker secret, but wouldn't that be yet again *"embedding in source code"*? Upon starting the container on my VM I'd need to provide that secret from somewhere, yet again going back to question of how the secret arrives at the VM in the first place. I know that [Application Default Credentials](https://cloud.google.com/docs/authentication/production#finding_credentials_automatically) (ADC) can try to use option 2 and then fallback on option 1 - yet, how do I solve the conflict from option 2? Where should the Service Account credentials reside to be accesible in both my local dev and in a local container - and not *embedded in the source code*?
2020/05/01
[ "https://Stackoverflow.com/questions/61544349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3508719/" ]
I found one way to make this work, (*sortof*): * On local dev env rely on `GOOGLE_APPLICATION_CREDENTIALS` to point to the Service Account credentials manually downloaded from the GCP. * On local Docker container, provide that same file as a secret. My app then searches `/run/secrets/` for it if `GOOGLE_APPLICATION_CREDENTIALS` is not set. * On Compute Engine VM, download that file from a Google Storage bucket (having previously uploaded it). [Given that the default Service Account is used](https://cloud.google.com/docs/authentication/production#obtaining_credentials_on_compute_engine_kubernetes_engine_app_engine_flexible_environment_and_cloud_functions) if no other credential is specified, I'm able to [`gutils cp`](https://cloud.google.com/storage/docs/downloading-objects#gsutil) that file from a bucket. Then provide that downloaded file as a secret to the container. Still, I'm still not sure if that's good from the side of *not embedding in the source code*. It also feels quite manual with all the uploading and downloading the credentials from the bucket. Any hints on how to improve this authentication most welcome.
31,415,188
I have an ASP.NET MVC app written in C#. One of my actions looks like this: ``` [HttpPost] public async Task<ActionResult> Save(int id, MyViewModel viewModel) { viewModel.SaveToDb(); await Backup.Save(viewModel); return View(viewModel); } ``` ... ``` public class Backup { async public static Task Save(IBackup item) { // do stuff } } ``` There is actually a lot going on in the Backup.Save function. In fact, `await Backup.Save(...)` is currently taking 10 seconds. For that reason, I want to run it in the background (asynchronously) and not (a)wait on it. I thought if I just removed the `await` keyword, it would work. However, it does not appear that is the case. How can I run Backup does save asynchronously in the background so that my users can continue using the app without long wait times? Thank you!
2015/07/14
[ "https://Stackoverflow.com/questions/31415188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185425/" ]
See here for a discussion of this: [Can I use threads to carry out long-running jobs on IIS?](https://stackoverflow.com/questions/536681/can-i-use-threads-to-carry-out-long-running-jobs-on-iis) One simple alternative without having to use threads or queues would be to make an additional async call via the client, possibly via Ajax assuming the client is a browser. If you need the view model back immediately, then potentially split this into two methods. One that gets the view model, and then you call a second method that does the save in the background. This should work fine since if you are happy to return right away, you have already implicitly agreed to decoupled the dependency between the two actions. It is a bit of a hack, since the client is now requesting an action it may not need to know or care about.
10,947,628
I want to get distance text from following link. i have used NSXML parsing but unable to get the result. please tell me which xml method should i used for following xml. <http://maps.googleapis.com/maps/api/directions/xml?origin=30.9165904,75.8634752&destination=30.89314000,75.86938000&sensor=true> Thanks to all
2012/06/08
[ "https://Stackoverflow.com/questions/10947628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1314522/" ]
Grid view can be really powerful if used correctly, one of the things you can do is hook onto an event (on data row bound) which will allow you to manipulate each row at a time. ASP.NET is more event driven than PHP, however if you still want to do things the PHP way you could in theory loop through each result. ``` using ( var oConn = new SqlConnection( ConfigurationManager.ConnectionStrings["myConnectionStringNameFromWebConfig"].ConnectionString) ) { oConn.Open(); using (SqlCommand oCmd = oConn.CreateCommand()) { oCmd.CommandType = CommandType.StoredProcedure; oCmd.CommandText = "p_jl_GetThemeForPortal"; oCmd.Parameters.Add(new SqlParameter("@gClientID", clientID)); } using(var oDR = oCmd.ExecuteReader()) { while(oDR.Read()) { string x = (string)oDR["ColumnName"]; int y = (int) oDR["ColumnName2"]; // Do something with the string and int } } } ``` This pattern (by using using statements) ensures your connections are closed at the end of each fetch sequence, so you don't have lots of open DB connections kicking around
27,216,471
I'm trying to create a custom iOS 8 keyboard. I am using Interface Builder to arrange the keyboard layout. I have two NIB files, one for iPhone 6 and one for iPhone 5. There are certain apps that are "scaled" up for the iPhone 6. For these apps, I want to load the iPhone 5 NIB (the iPhone 6 NIB goes off the screen). **Is there any way to determine if the current app running is running on "scaled" mode?** Unfortunately checking UIScreen mainScreen's attributes does not give me a difference between native iPhone 6 app vs scaled iPhone 6 app.
2014/11/30
[ "https://Stackoverflow.com/questions/27216471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/834310/" ]
In scaled app `[UIScreen mainScreen].scale` and `[UIScreen mainScreen].nativeScale` not be the same.
465,531
I have tried right clicking on the file selecting properties and then the permissions tab and setting it to execute. However, when I double click the file it opens in gedit. What do I do?
2014/05/14
[ "https://askubuntu.com/questions/465531", "https://askubuntu.com", "https://askubuntu.com/users/276476/" ]
To run your script by double clicking on its icon, you will need to create a `.desktop` file for it: ``` [Desktop Entry] Name=My script Comment=Test hello world script Exec=/home/user/yourscript.sh Icon=/home/user/youricon.gif Terminal=false Type=Application ``` Save the above as a file on your Desktop with a `.desktop` extension. Change `/home/user/yourscript.sh` and `/home/user/youricon.gif` to the paths of your script and whichever icon you want it ot have respectively and then you'll be able to launch by double clicking it. --- Specifically, for your situation, you need to do: 1. Create a script that runs `mono LOIC.exe`. To do so, create a new text file with these contents: ``` #!/bin/bash mono /home/logan/.loic/LOIC.exe ``` Save this as `/home/locan/run_loic.sh` and then run this command to make it executable (or right click => properties and choose "Allow executing file as program"): ``` chmod +x /home/logan/.loic/LOIC.exe ``` 2. Create a `.desktop` file that launches that script. Create a new text file on your Desktop called `run_loic.desktop` with these contents: ``` [Desktop Entry] Name=Run LOIC Comment=Run LOIC Exec=/home/logan/run_loic.sh Icon= Terminal=false Type=Application ```
45,235,912
In the main window I can set CSS styles for different standard widgets: > > setStyleSheet("QComboBox { background-color: red; } QLabel { background-color: blue; }") > > > These styles will be applied in child widgets with those names. But is it possible to set styles for widgets defined by me in the same fashion? Then this widget should obtain its style by its class name. I can't seem to find corresponding function that would obtain the style sheet by class name. Here is an example. ---custom-widget.h--- ``` #include <QWidget> class MyCustomWidget : public QWidget { Q_OBJECT public: MyCustomWidget(QWidget *parent) : QWidget(parent) { } }; ``` ---main.cpp--- ``` #include <QApplication> #include <QWidget> #include <QLayout> #include <QLabel> #include "custom-widget.h" int main(int argc, char **argv) { QApplication app (argc, argv); QWidget mainWindow; QVBoxLayout mainLayout(&mainWindow); QLabel label("I am a label", &mainWindow); MyCustomWidget customWidget(&mainWindow); mainLayout.addWidget(&label); mainLayout.addWidget(&customWidget); customWidget.setMinimumSize(100, 300); mainWindow.setStyleSheet( "QLabel { background-color: #5ea6e3; }" "MyCustomWidget { background-color: #f00000; }" ); mainWindow.show(); return app.exec(); } ``` ---main.pro--- ``` CONFIG += qt QT += core gui widgets TEMPLATE = app TARGET = main HEADERS = main.h custom-widget.h SOURCES = main.cpp ```
2017/07/21
[ "https://Stackoverflow.com/questions/45235912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7827768/" ]
Yes, styles will work just fine on your own widgets. If you have non-standard properties you want to set, you'll need to declare them using `Q_PROPERTY`. For example: ```c++ class MyWidget : public QWidget { Q_OBJECT Q_PROPERTY(QString extra READ extra WRITE setExtra) //... }; ``` You can then style it: ```css MyWidget { background-color: blue; color: yellow; qproperty-extra: "Some extra text"; } ``` For the widget in your code sample, the background is never drawn. Its constructor needs to be changed to ask Qt to draw the background using the style information: ``` MyCustomWidget(QWidget *parent) : QWidget(parent) { setAttribute(Qt::WA_StyledBackground); } ```
12,929,165
how to create sql server cte from a while loop my loop like this ``` declare @ind as int declare @code as nvarchar set @ind = 0 while @ind < 884 begin select @ind = @ind + 1 --here execute Procedure --and set return value to variable set @code = cast (@ind as nvarchar) end ```
2012/10/17
[ "https://Stackoverflow.com/questions/12929165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743326/" ]
If you need table: ``` ;WITH Sec(Number) AS ( SELECT 0 AS Number UNION ALL SELECT Number + 1 FROM Sec WHERE Number < 884 ) SELECT * FROM Sec OPTION(MAXRECURSION 0) ``` If you need one string: ``` ;WITH Sec(Number) AS ( SELECT 0 AS Number UNION ALL SELECT Number + 1 FROM Sec WHERE Number < 884 ) SELECT STUFF(a.[Str], 1, 1, '') FROM ( SELECT (SELECT ',' + CAST(Number AS NVARCHAR(3)) FROM Sec FOR XML PATH(''), TYPE ).value('.','varchar(max)') AS [Str] ) AS a OPTION(MAXRECURSION 0) ```
67,681,547
I want to set some variables getting they from the values of 5 select elements, the multiselect IDs have the same name that the variable names in the script.... Inside HTML part: ``` <select id="variable1"> <option value="10">10</option> <option value="20">20</option> <option value="50">50</option> </select> <select id="variable2"> <option value="algo1">algo1</option> <option value="algo2">algo2</option> <option value="algo3">algo3</option> </select> <!-- etc --> ``` and in the jQuery script: ``` var variable1; var variable2; var variable3; var variable4; var variable5; $("#variable1, #variable2, #variable3, #variable4, #variable5").change(function(){ var valorAcambiar = $(this).attr('id'); valorAcambiar = $(this).val(); }); ``` So I'm trying this, but doesn't work... I think the problem is that the script is not running the selected strings values from the ID attr of the select elements as variable names for the script, some one could please help me? I mean, I want that "valorAcambiar" takes the name of variable1 (coming from id attr of select element) or any other, to change global variable1 (or any other) value in the script. So I can get variable1 = 20 for example if someone changes variable1 select, or variable2 = algo3 for example if someone changes variable2 select, and this for the 5 multiselect elements. Thanks.
2021/05/25
[ "https://Stackoverflow.com/questions/67681547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10950209/" ]
Use a setInterval and set it to one **second** => `1000` ```js let display = document.getElementById('display') let x = display.textContent; // textContent returns a string value setInterval(()=>{ // lets change the string value into an integer using parseInt() // parseInt would not be needed if the value of x was `typeof` integer already display.textContent = parseInt(x++) }, 1000) ``` ```html <div id="display">2</div> ```
40,827,044
I'm using SQLite's `last_insert_rowid()` to grab the last inserted row ID following a batch insert. Is there any risk of race conditions that could cause this value to not return the last id of the batch insert? For example, is it possible that in between the completion of the insert and the calling of `last_insert_rowid()` some other process may have written to the table again?
2016/11/27
[ "https://Stackoverflow.com/questions/40827044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/411954/" ]
`last_insert_rowid()` returns information about the last insert done in this specific connection; it cannot return a value written by some other process. To ensure that the returned value corresponds to the current state of the database, take advantage of SQLite's [ACID](http://en.wikipedia.org/wiki/ACID) guarantees (here: atomicity): wrap the batch inserts, the `last_insert_rowid()` call, and whatever you're doing with the ID inside a single transaction. In any case, the return value of `last_insert_rowid()` changes only when some insert is done through this connection, so you should never access the same connection from multiple threads, or if you really want to do so, manually serialize entire transactions.
35,555,849
I'm fairly new to Qt and therefor try to find out how things are working. Especially for QTreeView this seems to be quite difficult: the documentation and the example that come from Qt are (at least for me) more or less cryptic. I'd guess one will understand this documentation only when one already knows how it works. So: could someone give an example or an link to an example which is beginner-suitable and demonstrates the usage of QTreeView? Means which demonstrates how to add a node and some child nodes to it? Thanks!
2016/02/22
[ "https://Stackoverflow.com/questions/35555849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1138160/" ]
Maybe [this mini example](http://www.java2s.com/Code/Cpp/Qt/QTreeViewdemoandQStandardItem.htm) can help you. But to understand it you have to grasp the Model-View concept. The idea is that you **don't** add to the view, you add to the model and the view updates itself.
54,662,572
It seems the backward compatibility of SSIS covered from SQL server 2008R2 to SQL server 2017 (since an instance with SQL server 2017 installed can proceed SSIS package with PackageFormatVersion = 3) The question is why do we need to update the SSIS package (.dtsx) Is there any performance boost or other necessaries by updating the SSIS package?
2019/02/13
[ "https://Stackoverflow.com/questions/54662572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3686334/" ]
It is highly recommended to update packages because each new release of SQL Server contains new features, bug fixes, performance improvement. There are many articles describing the features of each release as example: * in SQL Server 2016 package parts was founded which guarantee high re-usability * ODATA components were added later than 2008 R2 You can refer to the following pages for more information: * [SQL Server Integration Services SSIS Versions and Tools](https://www.mssqltips.com/sqlservertutorial/9054/sql-server-integration-services-ssis-versions-and-tools/) * [Stackoverflow - SSIS tag info](https://stackoverflow.com/tags/ssis/info) **Also not that [the support of SQL Server 2008 R2 will end soon](https://blogs.msdn.microsoft.com/sqlreleaseservices/end-of-mainstream-support-for-sql-server-2008-and-sql-server-2008-r2/)** *(July 9, 2019)*
15,202,513
I am trying to calculate the monthly payment of a loan and it always comes out wrong. The formula is as follows where i is interest ``` ((1 + i)^months / (1 + i)^months - 1) * principal * i ``` Assuming that annual interest rate and principal is an invisible floating point, can you tell me what's wrong with my formula? ``` double calculatePaymentAmount(int annualInterestRate, int loanSize, int numberOfPayments; { double monthlyInterest = annualInterestRate / 1200.0; return ( pow(1 + monthlyInterest, numberOfPayments) / (pow(1 + monthlyInterest, numberOfPayments) - 1) ) * (loanSize / 100) * monthlyInterest; } ``` For example: an interest rate of 1.25 and a loan size of 250 for 12 months gives 22.27 instead of 20.97. Thank you in advance. Edit 1: Changed monthly interest to annualInterestRate / 1200
2013/03/04
[ "https://Stackoverflow.com/questions/15202513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892641/" ]
If you didn't, `john.property` would be undefined.
22,912,327
I have the following PHP code to resize an image (i know this image will be a png so no need for checking...) ``` // The file //$filename = $_POST['original']; $filename = 'planets.png'; // Set a maximum height and width $width = 200; $height = 200; // Content type header('Content-Type: image/png'); // Get new dimensions list($width_orig, $height_orig) = getimagesize($filename); $ratio_orig = $width_orig/$height_orig; if ($width/$height > $ratio_orig) { $width = $height*$ratio_orig; } else { $height = $width/$ratio_orig; } // Resample $image_p = imagecreatetruecolor($width, $height); imagecreatefrompng($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Output imagepng($image_p); ``` However, I would like to be able to return this to my page via ajax... see the code below: ``` <div data-img-src="planets.png"></div> <script type="text/javascript"> $("div[data-img-src]").each( function() { $.ajax({ type: "POST", url: "/image-resize.php", data: { original: $(this).attr("data-img-src") }, dataType: "html", success: function(result) { $(this).append(result); } }); }); </script> ``` Any ideas what I need to do to make this work?? **EDIT!** Alternatively, is this an acceptable way to achieve the same desired result? ``` $("div[data-img-src]").each( function() { $(this).append("<img src='/image-resize.php?original="+$(this).attr("data-img-src")+"' />"); // COUPLED WITH $_GET... in the php }); ```
2014/04/07
[ "https://Stackoverflow.com/questions/22912327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457148/" ]
Basically you need index for the `cell` which has to be deleted when delete is pressed. you can set the `tag` property and when button is pressed you can check the tag propery of the button which is sending event. see below code, ``` UIButton *removeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; removeButton.tag = indexPath.row; removeButton.frame = CGRectMake(200.0f, 5.0f, 75.0f, 30.0f); [removeButton setTitle:@"Remove" forState:UIControlStateNormal]; removeButton.tintColor = [UIColor colorWithRed:0.667 green:0.667 blue:0.667 alpha:1]; /*#aaaaaa*/ removeButton.titleLabel.font = [UIFont systemFontOfSize:15]; [cell addSubview:removeButton]; [removeButton addTarget:self action:@selector(removeItem:) forControlEvents:UIControlEventTouchUpInside]; -(void) removeItem:(id) sender { UIButton *button = (UIButton*)sender; int index = button.tag; } ```
34,713,996
I have this code: ``` <?php echo $form->fileField($model, 'avatar_url', array('style' => 'display:none')) ?> <a href="#" class="thumbnail" style="width: 96px" id="avatar"> <?php if (empty($model->avatar_url)) { ?> <img data-src="holder.js/96x96" id="avatar-img"> <?php } else { ?> <img src="<?= Yii::app()->baseUrl . $model->avatar_url ?>" id="avatar-img"> <?php } ?> ``` When I replace `<?php` to `<?` , the code does not work and the browser shows an error. > > PHP notice Undefined variable: class > > > Maybe I missed an extension in PHP?
2016/01/11
[ "https://Stackoverflow.com/questions/34713996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3750963/" ]
Sounds like you need to enable `short_open_tag` in your php.ini. Find the line `short_open_tag` in your php.ini and set the value to `1`: ``` short_open_tag = 1 ``` After you make the change, restart your web server. Read more here: <http://php.net/manual/en/ini.core.php#ini.short-open-tag> > > **short\_open\_tag** > > > Tells PHP whether the short form (`<? ?>`) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use `<?xml ?>` inline. Otherwise, you can print it with PHP, for example: `<?php echo '<?xml version="1.0"?>'; ?>`. Also, if disabled, you must use the long form of the PHP open tag (`<?php ?>`). > > >
59,080,359
I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5 Where distinct numbers are separated by a space(s). Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5].
2019/11/28
[ "https://Stackoverflow.com/questions/59080359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448955/" ]
I'm not sure what you mean by "not in a data structure", that doesn't make much sense. But assuming you have a string, then `numpy` even provides a utility method for this: ``` >>> import numpy as np >>> data = '1 1.5 120202.4343 58 -2442.5' >>> np.fromstring(data, sep=' ') array([ 1.00000000e+00, 1.50000000e+00, 1.20202434e+05, 5.80000000e+01, -2.44250000e+03]) ```
17,706,823
I need create an Email List. For each Folder, I need get all email from owners. But, I have an error in listRequest.Email = reader["Email"].ToList(); The error is in "ToList()", I'm declaring namespace System.Collections.Generic but don't resolves. ``` public class ListRequest { public List<string> Email { get; set; } public string FolderAccess { get; set; } } public List<ListRequest> PreencheValores(SqlDataReader reader) { var lista = new List<ListRequest>(); while (reader.Read()) { var listRequest = new ListRequest(); listRequest.Email = reader["Email"].ToList(); listRequest.FolderAccess = reader["FolderAccess"].ToString(); lista.Add(listRequest); } return lista; } ```
2013/07/17
[ "https://Stackoverflow.com/questions/17706823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2456471/" ]
Below statement is not valid. ``` listRequest.Email = reader["Email"].ToList(); ``` Using SqlDataReader you can read only single element but not list like what you did to retrieve folder access. ``` listRequest.FolderAccess = reader["FolderAccess"].ToString(); ``` One thing you could do is retrieve email addresses as comma separated values and then split them. Also consider using string[] instead of List ``` public class ListRequest { public string[] Email { get; set; } public string FolderAccess { get; set; } } public List<ListRequest> PreencheValores(SqlDataReader reader) { var lista = new List<ListRequest>(); while (reader.Read()) { var listRequest = new ListRequest(); if(reader["Email"] != null) listRequest.Email = reader["Email"].ToString().Split(','); if(reader["FolderAccess"] != null) listRequest.FolderAccess = reader["FolderAccess"].ToString(); lista.Add(listRequest); } return lista; } ```
27,651,730
I have the following string example: ``` [14:48:51.690] LOGON error group: 103 ``` I get many different from them. The only thing is, that the beginning is always the same expect the date (always in brackets) and name of `LOGON`. I want to remove thi in front. How can I achieve this efficiently? Regex? Splitting and remove from array? The only thing I want to have finally is ``` error group: 103 ```
2014/12/26
[ "https://Stackoverflow.com/questions/27651730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2257374/" ]
You can split the string based on regex `\[\d{1,2}:\d{1,2}:\d{1,2}\.\d{1,3}\]\s*\w*\s*` ``` import java.util.regex.Pattern; public class T { public static void main(String[] args) { String s = "[14:48:51.690] LOGON error group: 103"; String[] split = s.split("\\[\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}\\]\\s*\\w*\\s*"); System.out.println(split[1]); } } ``` Output ``` error group: 103 ```
643,022
I wanted to write a script to add some tools to my VPS or VMS and I write something like that ``` # Edit sudoers echo -e "${GREEN}Configure sudoers...${NOCOLOR}" echo echo '# Allow user to use sudo without passwd' >> /etc/sudoers echo '$USER ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers ``` this script run as Sudo and i test echo $USER in Sudo is the user name, not root I mean I'm kind of new so I did not know that and write this but when I test it I'm getting error `permission error` i don't know what to do I did some search but can't find anything
2021/04/01
[ "https://unix.stackexchange.com/questions/643022", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/464537/" ]
I have three things to point out there. One, you should really use `visudo` to edit the `/etc/sudoers` file, even if you set `$EDITOR` to a script that echoes that content. The other is that it is sub-optimal to let any user run any command without a password. Finally, `$USER` will equal root, so that will be pointless. If you really want to do that, make a separate script that has this in it: ``` echo '# Allow user to use sudo without a password' >> $1 echo "$PERSON ALL=\(ALL\) NOPASSWD:ALL" >> $1 ``` Second, make yet another script that runs your main script like this: ``` sudo "env PERSON=$USER /your/script/here" ``` That should tidy it up a bit, because you can be sure that the whole script is being run as root, and `visudo` keeps backups in case you screw up the sudoers file.
489,035
It is a simple exercise to prove using mathematical induction that if a natural number n > 1 is not divisible by 2, then n can be written as m + m + 1 for some natural number m. (Depending on your definition of odd number, this can either be stated as "every number is even or odd", or as "every odd number is one greater than an even number". My question is, can this be proven without induction? In other words, can this be proven in Robinson arithmetic? If not, what is example of a nonstandard model of Robinson arithmetic that doesn't have this property? The reason I'm asking this is that the proof of the irrationality of the square root of 2 is usually presented with only one use of induction (or an equivalent technique). But the proof depends on the fact if k^2 is even, then k is even, and that fact in turn depends on the fact that the square of a number not divisible by 2 is a number not divisible by 2. And that fact is, as far as I can tell, is a result of the proposition above. (I'm open to correction on that point.) So if that proposition depended on induction, then the proof that sqrt(2) is irrational would depend on two applications of induction. (The reason that the ancient Greeks wouldn't have been aware of this is that Euclid implicitly assumes the proposition above, when he defines an odd number as "that which is not divisible into two equal parts, or that which differs by a unit from an even number".) Any help would greatly appreciated. Thank You in Advance.
2013/09/10
[ "https://math.stackexchange.com/questions/489035", "https://math.stackexchange.com", "https://math.stackexchange.com/users/71829/" ]
Take $M = \{P = a\_nx^n + \ldots + a\_0 \in \Bbb Z[x] / a\_n > 0 \}$, with the usual addition and multiplication on polynomials. Interprete $S(P)$ as $P(X)+1$. Then $M$ is a model of Robinson arithmetic, but there are long strings of "not-even" numbers, such as $X,X+1,X+2,\ldots$. So in this model, it is false that if $n$ is not even then $n+1$ is even. If you define "$n$ is odd" as "$\exists k / n= k+k+1$", then it is false that every number is even or odd. However, it is still true in $M$ that addition is associative and commutative, and so if $n$ is odd then $n+1$ is even, and if $n$ is even, then $n+1$ is odd. (you will need a stranger model for this to fail) --- If you want a model in which $a^2-2b^2 = 0$ has a solution, you can pick $M = \{ P \in \Bbb Z[X,Y]/(X^2-2Y^2) / \lim\_{y \to \infty} P(\sqrt 2 y,y) = + \infty$ or $P \in \Bbb N \}$
37,770,930
I have a JSON file and need to get the parameter ' fulltext ' , but I'm new to JSON and do not know how to retrieve it in Java . Could someone explain to me how caught this value fulltext ? Here a piece of the file in JSON. ``` { "head": { "vars": [ "author" , "title" , "paper" , "fulltext" ] } , "results": { "bindings": [ { "author": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/person/richard-scheines" } , "title": { "type": "literal" , "value": "Discovering Prerequisite Relationships among Knowledge Components" } , "paper": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492" } , "fulltext": { "type": "literal" , "value": "GET TEXT" } } , ```
2016/06/12
[ "https://Stackoverflow.com/questions/37770930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6363322/" ]
Json library download from here **jar** dowonload form [here](http://central.maven.org/maven2/org/json/json/20160212/json-20160212.jar) Add this code in **JSonParsing.java** ``` import org.json.*; public class JSonParsing { public static void main(String[] args){ String source = "{\n" + " \"head\": {\n" + " \"vars\": [ \"author\" , \"title\" , \"paper\" , \"fulltext\" ]\n" + " } ,\n" + " \"results\": {\n" + " \"bindings\": [\n" + " {\n" + " \"author\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/person/richard-scheines\" } ,\n" + " \"title\": { \"type\": \"literal\" , \"value\": \"Discovering Prerequisite Relationships among Knowledge Components\" } ,\n" + " \"paper\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492\" } ,\n" + " \"fulltext\": { \"type\": \"literal\" , \"value\": \"GET TEXT\" }\n" + " }\n" + " ]\n" + " }\n" + "}\n" + ""; JSONObject main = new JSONObject(source); JSONObject results = main.getJSONObject("results"); JSONArray bindings = results.getJSONArray("bindings"); JSONObject firstObject = bindings.getJSONObject(0); JSONObject fulltextOfFirstObject = firstObject.getJSONObject("fulltext"); String type = fulltextOfFirstObject.getString("type"); String value = fulltextOfFirstObject.getString("value"); System.out.println("Type :"+ type+"\nValue :"+value); } } ``` NOTE: In JSON **`{}`** represents jsonObject and `[]` represents jsonArray.
19,250
Can the [psychology](http://en.wikipedia.org/wiki/Psychology) of a middle-aged person alter their immune health? I have read about the different types of linkage between nervous system and immune system. Can someone outline the general facts about what is understood about this?
2014/06/22
[ "https://biology.stackexchange.com/questions/19250", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/8101/" ]
I'm not sure what you mean by psychology exactly, but assuming you are referring to a persons mental state there is a known link between stress and immunity. This link occurs through neuro-endocrine pathways. The central nervous system and endocrine (hormonal) systems are linked through the hypothalamus, a key controller of hormone release in the central nervous system. In a state of stress our central nervous system reacts by increasing the release of hormones such as the steroid cortisol and catacholamines such as adrenaline (a.k.a epinephrine in USA). We know that steroids have an effect of dampening down the immune system (in fact steroids are often used for this intentionally in the case of autoimmune conditions for example). Thus based on this we have a scenario where stress can lead to increase in cortisol (and other hormones) which in turn can have an effect on your immunity. The effect to which this impacts on your life is then further dependent on your psychology and social support. More generally, the links between illness and psychology are integrated together in what is called the biopsychosocial model of illness. I suggest you look this up to gain a more in depth understanding of this complicated issue.
25,103
In WC3 TFT when you're doing ladder, you can view a lot of statistics online, e.g: <http://classic.battle.net/war3/ladder/w3xp-player-stats.aspx?Gateway=Azeroth&PlayerName=Jorgie> I've been trying to find the similar information for SC2 but the most I can see is a basic match history and the # of wins, am I missing something? It would be nice to view a detailed statistical information about your profile. Thanks!
2011/06/22
[ "https://gaming.stackexchange.com/questions/25103", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/1789/" ]
[SC2 Ranks](http://sc2ranks.com) has a match history, and can also show win percentage by map, but I believe they skim off the Battle.Net API, so it won't be any more than Blizzard provides in the first place. If you want more information about *your own* matches, [SC2 Gears](https://sites.google.com/site/sc2gears/) can look through all your past replays and give you much more information. What it can do is too extensive to list here, check out their [features page](https://sites.google.com/site/sc2gears/features/replay-analyzer).
192,976
I have a similar problem to [this post](https://stackoverflow.com/questions/174535/google-maps-overlays). I need to display up to 1000 polygons on an embedded Google map. The polygons are in a SQL database, and I can render each one as a single KML file on the fly using a custom HttpHandler (in ASP.NET), like this <http://alpha.foresttransparency.org/concession.1.kml> . Even on my (very fast) development machine, it takes a while to load up even a couple dozen shapes. So two questions, really: 1. What would be a good strategy for rendering these as markers instead of overlays once I'm beyond a certain zoom level? 2. Is there a publicly available algorithm for simplifying a polygon (reducing the number of points) so that I'm not showing more points than make sense at a certain zoom level?
2008/10/10
[ "https://Stackoverflow.com/questions/192976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
For your second question: you need the [Douglas-Peucker Generalization Algorithm](http://everything2.com/index.pl?node_id=859282)
19,343,518
I have an edittext for which I want to set below background![enter image description here](https://i.stack.imgur.com/xgiFQ.png) but when I set this as background it stretches itself to fit in whole EditText like below image.![enter image description here](https://i.stack.imgur.com/70GuR.png) and below is my code for xml file for editext ``` <LinearLayout android:id="@+id/footer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:visibility="visible" > <EditText android:id="@+id/comment" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:hint="@string/add_your_comment" android:imeOptions="actionDone" android:padding="5dp" android:background="@drawable/bg_search_field" android:scrollHorizontally="true" android:singleLine="true" /> <ImageView android:id="@+id/post_comment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="5dp" android:layout_marginRight="@dimen/fifteen_dp" android:src="@drawable/tick_selection" /> </LinearLayout> ``` How can I set the background correctly?
2013/10/13
[ "https://Stackoverflow.com/questions/19343518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1109493/" ]
Ok So issue resolved simply by using nine patch image i have got from actionBarsherlock library which is using it for it's search view.
57,433,195
Unable to locate image hyperlink on my profile. Tried using `xpath`, `css locator` but nothing worked. 1. `driver.findElement(By.cssSelector("//img[contains(@src,'https://d3ejdag3om7lbm.cloudfront.net/assets/img/Default User.png')]")).click();` 2. `driver.findElement(By.xpath("//span[@class='user_name']")).click();` 3. `driver.findElement(By.cssSelector("span[class='user_name']")).click();` Selenium fails to find the element. [enter image description here](https://i.stack.imgur.com/xOo1t.png)
2019/08/09
[ "https://Stackoverflow.com/questions/57433195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11908159/" ]
Converting my comments to answer to help out future visitors to easily find a quick solution. ``` Options +FollowSymlinks -MultiViews RewriteEngine On # redirect to https RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # pass query parameter to a php file internally RewriteRule ^services/([\w-]+)/?$ services.php?param=$1 [L,NC,QSA] # handle .php extension RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^([^.]+)/?$ $1.php [L] ```
50,505,805
Recently finished putting together a React project that fetches News Articles and displays them. Recently deployed to Heroku and have found that only Chrome on Desktop seems to run it. Safari and Firefox both give me the same error when I look in the Javascript console.[Javascript error](https://i.stack.imgur.com/RKPfj.png) Link to heroku applicatio - <https://calm-bastion-47290.herokuapp.com/>? **Server set up** ``` const express = require("express"); const mongoose = require("mongoose"); const bodyParser = require("body-parser"); const passport = require("passport"); const path = require("path"); const users = require("./routes/api/users"); const profile = require("./routes/api/profile"); const app = express(); // Body Parser Middleware app.use(express.urlencoded({ extended: false })); app.use(express.json()); // DB config const db = require("./config/keys").mongoURI; //mongodb database url connection // connect to mongodb mongoose .connect(db) .then(() => console.log("MongoDB Connected")) .catch(err => console.log(err)); //passport Middleware app.use(passport.initialize()); //passport config require("./config/passport")(passport); //use routes app.use("/api/users", users); app.use("/api/profile", profile); // Server static assets if in production if (process.env.NODE_ENV === "production") { // Set static folder app.use(express.static("client/build")); app.get("*", (req, res) => { res.sendFile(path.resolve(__dirname, "client", "build", "index.html")); }); } const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Server running on port ${port}`)); ``` I don't think there is anything wrong with my code as it runs perfectly locally and chrome handles it just fine. Any obvious reason why Safari, Firefox and any browser on mobile simply fails to render any part of my web application?
2018/05/24
[ "https://Stackoverflow.com/questions/50505805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9839752/" ]
Just had the same issue. Make sure you take out the redux development tools before deploying. In your store.js file include the following to not use the "redux devtools" in production. ``` if(process.env.NODE_ENV === 'production') { store = createStore(rootReducer, initialState, compose( applyMiddleware(...middleware) )); } else { store = createStore(rootReducer, initialState, compose( applyMiddleware(...middleware), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() )); } ``` The idea is to only include REDUX\_DEVTOOLS while in development. In production this should not be used, because then only browsers with the redux devtool extension will be able to view the page.
14,496,831
This is the code I am using to get string coming through a SBJson parsing: ``` NSMutableArray *abc=[jsonData valueForKey:@"items"]; NSString *imgStr=(NSString *)[abc valueForKey:@"image"]; NSLog(@"%@",imgStr); ``` here abc is `NSMutableArray` and the exception it is throwing is ``` > -[__NSArrayI stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance ```
2013/01/24
[ "https://Stackoverflow.com/questions/14496831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1983242/" ]
In the first line you declare `abc` to be an `NSMutableArray` In the second line you attempt to access it as an `NSDictionary`. In your case (and I am guessing here), I expect you have an array of items, and each item is a dictionary with an "image" key. So to get your first item you might use ``` NSDictionary* firstItem = [abc objectAtIndex:0]; ``` Then you can extract your image from that: ~~NSString \*imgStr=(NSString \*)[firstItem valueForKey:@"image"];~~1 ``` NSString *imgStr = [abc objectForKey:@"image"]; ``` 1 see comment from @Stig
54,207,983
I'm trying to make a program that does the following: As command line arguments it receives paths to FIFO files. It is supposed to monitor those FIFOs using the `epoll` API. Through the FIFOs it is guaranteed that only float numbers will be sent. The output of the program should be the sum of numbers send through each FIFO (the program stops when the write side closes all files). Before I start with the actual code, here's a macro and a function you'll be seeing throughout the entire program: ``` #define iAssert(cond, msg) crash(cond, msg, __LINE__) void crash(bool cond, char * msg, int line){ if(!cond){ perror(msg); fprintf(stderr, "at line %d\n", line); exit(EXIT_FAILURE); } } ``` It's just a simple asserting mechanism, irrelevant for the problem itself. Anyway, first I fetch the number of FIFOs passed through command line arguments and create an `epoll` file descriptor: ``` int numFifos = argc - 1; int epollFileDesc = epoll_create(1); iAssert(-1 != epollFileDesc, "epoll_create"); ``` Then I create an array of fifo file descriptors and an array of sums, which in the following loop I initialize to zero. ``` int * fifoFileDescriptors = malloc(numFifos * sizeof(int)); iAssert(NULL != fifoFileDescriptors, "malloc1"); float * localSums = malloc(numFifos * sizeof(float)); iAssert(NULL != localSums, "malloc 2"); ``` So far so good, I think. The following loop, apart from initializing the array of sums, opens FIFOs, fills the previous array of file descriptors and registers events. ``` for(int i = 0; i<numFifos; i++){ localSums[i] = 0.f; int thisFd = open(argv[i+1], O_RDONLY | O_NONBLOCK); iAssert(-1 != thisFd, "open"); fifoFileDescriptors[i] = thisFd; FILE * thisFs = fdopen(thisFd, "r"); iAssert(NULL != thisFs, "fdopen"); DataPass registerThis; registerThis.fifoIndex = i; registerThis.file = thisFs; struct epoll_event thisEvent; thisEvent.events = 0; thisEvent.events |= EPOLLIN; thisEvent.data.ptr = (void *)&registerThis; iAssert(-1 != epoll_ctl(epollFileDesc, EPOLL_CTL_ADD, thisFd, &thisEvent), "epoll_ctl"); } ``` The DataPass structure looks like this: ``` typedef struct{ int fifoIndex; FILE * file; }DataPass; ``` What I want is, as you can see, is to receive file streams instead of file descriptors because they're easier to read from. Apart from that I keep the index of the FIFO so I know which one is it. After this I monitor for changes: ``` int nOpen = numFifos; struct epoll_event events[MAX_EVENTS]; while(nOpen){ int active = epoll_wait(epollFileDesc, events, MAX_EVENTS, -1); iAssert(-1 != active, "epoll_wait"); for(int i = 0; i<active; i++){ struct epoll_event thisEvent = events[i]; if(thisEvent.events & EPOLLIN){ DataPass * thisData = (DataPass *)thisEvent.data.ptr; //fifo with index thisData->fifoIndex has sent a message float x; while(1 == fscanf(thisData->file, "%f", &x)){ localSums[thisData->fifoIndex] += x; } }else if (thisEvent.events & (EPOLLERR | EPOLLHUP)){ //need to close this connection DataPass * thisData = (DataPass *)thisEvent.data.ptr; iAssert(-1 != epoll_ctl(epollFileDesc, EPOLL_CTL_DEL, fifoFileDescriptors[thisData->fifoIndex], NULL), "epoll_ctl del"); fclose(thisData->file); close(fifoFileDescriptors[thisData->fifoIndex]); nOpen--; } } } ``` The `MAX_EVENTS` macro is defined to be 4. After running this (and using a side program to make the fifos and send values through them) I get a segmentation fault which I've managed to track down to the `fscanf` part. Even though I've tracked it down I still have no idea why it's causing it. Any ideas? Thanks.
2019/01/14
[ "https://Stackoverflow.com/questions/54207983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8873813/" ]
You are invoking undefined behavior by saving a pointer to a local variable past the validity of the stack in which it exists ``` for(int i = 0; i<numFifos; i++){ DataPass registerThis; registerThis.file = thisFs; thisEvent.data.ptr = (void *)&registerThis; } ``` Don't export pointers to local variables and try to use them when they no longer exist. Allocate your storage in a more long-lived way.
53,755,508
I would like to run multiple Hive queries, preferably in parallel rather than sequentially, and store the output of each query into a csv file. For example, `query1` output in `csv1`, `query2` output in `csv2`, etc. I would be running these queries after leaving work with the goal of having output to analyze during the next business day. I am interested in using a bash shell script because then I'd be able to set-up a `cron` task to run it at a specific time of day. I know how to store the results of a HiveQL query in a CSV file, one query at a time. I do that with something like the following: ``` hive -e "SELECT * FROM db.table;" " | tr "\t" "," > example.csv; ``` The problem with the above is that I have to monitor when the process finishes and manually start the next query. I also know how to run multiple queries, in sequence, like so: ``` hive -f hivequeries.hql ``` Is there a way to combine these two methods? Is there a smarter way to achieve my goals? Code answers are preferred since I do not know bash well enough to write it from scratch. This question is a variant of another question: [How do I output the results of a HiveQL query to CSV?](https://stackoverflow.com/questions/18129581/how-do-i-output-the-results-of-a-hiveql-query-to-csv)
2018/12/13
[ "https://Stackoverflow.com/questions/53755508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2205916/" ]
You can run and monitor parallel jobs in a shell script: ``` #!/bin/bash #Run parallel processes and wait for their completion #Add loop here or add more calls hive -e "SELECT * FROM db.table1;" | tr "\t" "," > example1.csv & hive -e "SELECT * FROM db.table2;" | tr "\t" "," > example2.csv & hive -e "SELECT * FROM db.table3;" | tr "\t" "," > example3.csv & #Note the ampersand in above commands says to create parallel process #You can wrap hive call in a function an do some logging in it, etc #And call a function as parallel process in the same way #Modify this script to fit your needs #Now wait for all processes to complete #Failed processes count FAILED=0 for job in `jobs -p` do echo "job=$job" wait $job || let "FAILED+=1" done #Final status check if [ "$FAILED" != "0" ]; then echo "Execution FAILED! ($FAILED)" #Do something here, log or send messege, etc exit 1 fi #Normal exit #Do something else here exit 0 ``` There are other ways (using XARGS, GNU parallel) to run parallel processes in shell and a lot of resources on it. Read also <https://www.slashroot.in/how-run-multiple-commands-parallel-linux> and <https://thoughtsimproved.wordpress.com/2015/05/18/parellel-processing-in-bash/>
231,859
I am working with a library that has a base class Base, and three class descending from it Destination, Amenity and Landmarks. The Base class looks something like this ``` public class Base { public Integer id; public String externalId; public Base() { } public int getId() { return this.id; } public String getExternalId() { return this.externalId != null ? this.externalId : ""; } } ``` The children classes look like this ``` public class Destination extends Base implements Parcelable { private String name; private String description; private Point[] points public String getName() { return this.name; } public String getDescription() { return this.description; } public Point[] getPoints(){ return this.points; } } ``` The important thing to note here is that the three child classes have the points property and the getPoints getter for accessing it. If it was my implementation, I would bring the points field into the base class to avoid replicating multiple times in the child classes but like I said, it's a library and I cannot modify the source. While working with the library I have ran into a situation where I have had to use the `instanceof` function multiple times and since this is considered a code smell, I'd like to know if there is a better way of going about it. The situation I'm describing happens when I try to get one of the child objects when a point item is specidied, the code looks like this right now ``` public static <T> T getCurrentMapObjectWithPoint(Point point, T [] bases){ T base = null; for(T model: bases){ Point[] points = getpointsArrayFromMapObject(model); for(Point currentpoint: points){ if(currentpoint.id.equals(point.id)){ return base; } } } return base; } private static <T> point[] getpointsArrayFromMapObject(T base){ if(base instanceof Amenity ){ return ((Amenity) base).getpoints(); } else if(base instanceof Destination){ return ((Destination) base).getpoints(); } else if (base instanceof LandMark){ return ((LandMark) base).getpoints(); } return new point[]{}; } ``` So simply put, given a `Point` and list of map items(`T[] base` - which means and array of either Amenity, Destination or Landmark) I'm trying to figure out which Amenity, Destination or LandMark the point belongs to which means I have to go throgh the list of map items and for each item, go through the points for that item and whenever the point id is equal to the id of the point given at the start I break out of the loop and return the current map item. Is there a better way of doing this without using `instanceof` multiple times?
2019/11/05
[ "https://codereview.stackexchange.com/questions/231859", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/212659/" ]
Create a class that extends `Base` that has the `points` field and have your 3 classes extend that class. Your improved method would look like this: (Note: you should give it a better name) ``` private static <T> point[] getpointsArrayFromMapObject(T base){ if(base instanceof MyBase ){ return ((MyBase) base).getpoints(); } return new point[]{}; } ``` However It looks like these methods only relate to the type `Base`. If so you can change your generic to extend from it: ``` private static <T extends MyBase> point[] getpointsArrayFromMapObject(T base) { return base.getpoints(); } ``` You should note it does not matter if each class implements its own `getPoints` method. The correct method will be executed based on the type of Object passed. This is known as `polymorphism`. At which point, there is no need for an additional method: ``` public static <T extends Base> T getCurrentMapObjectWithPoint(Point point, T [] bases){ T base = null; for(T model: bases){ Point[] points = base.getPoints(); for(Point currentpoint: points){ if(currentpoint.id.equals(point.id)){ return base; } } } return base; } ```
201,832
Okay so I am part of two Mage the Awakening 2ed campaigns and the two GM's disagree on the rules for prime sight. What they disagree on is if prime sight is able to see if a mage have active spells. The rule stats: "... and the presence (if not the composition) of any awakened spell ...". One of the GMs interpret this as being able to see the spells active in another mages pattern while the other believe it only applies to the spells on objects. Therefore if someone, as an example, has nightvision active (forces dot one spell) another mage with prime sight turned on would or would not be able to see this. Which interpretation is correct?
2022/10/03
[ "https://rpg.stackexchange.com/questions/201832", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/43898/" ]
**Yes, a mage with prime sight active would be able to see that another mage has a spell active on themselves** The rules are on page 91. In my opinion, the part you quoted already answers the question. Someone with active prime sight would would at least be able to see that there was an awakened spell affecting the target, even if it was a spell the mage cast on themselves. I believe expanding the quote removes all reasonable doubt: > > Prime Sight highlights anything the mage can use as a Yantra, and the > presence (if not the composition) of any Awakened spell or Attainment > effect. > > > Note the discussion of seeing attainment effects. While there are definitely exceptions, particularly if you allow in some of the older 1e stuff as expanded material, most attainments only affect the mage and are **generally** harder to detect and with less chance of side effects than spells. If prime sight shows attainments, it makes sense for it to show spells affecting the mage.
41,596,491
If I remove the part `$this->upload->do_upload('filefoto')` my data is saved into the database, but the image file is not saved to the folder path. [enter link description here](http://pastebin.com/hHQgt1ap) Copied from pastebin ``` public function tambahanggota() { $this->load->library('upload'); $nmfile = "file_".time(); $config['upload_path'] = './assets/uploads/'; $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; $config['max_size'] = '3072'; $config['max_width'] = '5000'; $config['max_height'] = '5000'; $config['file_name'] = $nmfile; $this->upload->initialize($config); if($_FILES['filefoto']['tmp_name']) { if ($this->upload->do_upload('filefoto')) { $gbr = $this->upload->data(); $data = array( 'nm_gbr' =>$gbr['file_name'] ); $res = $this->M_tambahdata->tambahdata("anggota",$data); $config2['image_library'] = 'gd2'; $config2['source_image'] = $this->upload->upload_path.$this->upload->file_name; $config2['new_image'] = './assets/hasil_resize/'; $config2['maintain_ratio'] = TRUE; $config2['width'] = 100; $config2['height'] = 100; $this->load->library('image_lib',$config2); if ($res>=1) { echo "<script>alert('Data berhasil disimpan')</script>"; echo "<script>window.location='".base_url()."dataanggota'</script>"; } else{ $this->session->set_flashdata('pesan', 'Maaf, ulangi data gagal di inputkan.'); redirect('dashboard/index'); } } } } ``` How can I upload my images?
2017/01/11
[ "https://Stackoverflow.com/questions/41596491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6752036/" ]
on a shared server hosting you may need to provide the **complete relative path** to your upload folder. Also make sure you have all permissions to write a file to that directory! you can use on a localhost environment ``` $config['upload_path'] = './assets/upload'; ``` but on a shared hosting, you'll need to get more specific, normally something like ``` $config['upload_path'] = '/home/yourserver/public_html/assets/upload'; ``` You can find this upload\_path, e.g. in your accounts cPanel main page on the left column or might want to call your provider's helpdesk for more info on the correct path.
9,219,010
I have a child layer that I'm adding to the scene which contains a menu, it is initialized like so: ``` - (id) init { if((self=[super init])) { CGSize winSize = [[CCDirector sharedDirector] winSize]; CCMenuItemImage* attackButton = [CCMenuItemImage itemFromNormalImage:@"btnAttack.png" selectedImage:@"btnAttack.png" target: self selector:@selector(attack)]; CCMenu* menu = [CCMenu menuWithItems:attackButton, nil]; menu.position = ccp(winSize.width-80,winSize.height-140); [menu alignItemsHorizontally]; [self addChild:menu]; } return self; } ``` This crashes with a SIGABRT error unless I change the target: to 'nil'. Why is this not working and how can I fix it?
2012/02/09
[ "https://Stackoverflow.com/questions/9219010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/744306/" ]
I would follow the native API of your tablet. Your tablet's vendor has very well described SDK including several [`examples`](http://www.wacomeng.com/windows/index.html) (in Visual C++). What you are specifically looking for is [`the eraser detection`](http://www.wacomeng.com/windows/docs/Wintab_v140.htm#_Toc275759917)
8,034,657
I have a moveable and closable jquery pop-up notification box. It works well aside from the fact that it pops up every time the page is loaded. What method would I need to implement to allow a user to permanently (or at least semi permanently) close the pop-up box? If I need to use cookies how would I tie a cookie to a specific action like closing the div?
2011/11/07
[ "https://Stackoverflow.com/questions/8034657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709066/" ]
yes you can use cookies. when user click on the close button you can write it to the cookies. and when page load, if cookie is not available display the popup
2,123,395
I've noticed an annoying peculiarity in PHP (running 5.2.11). If one page includes another page (and both contain their own variables and functions), both pages are aware of each others' variables. However, their functions seem to be aware of no variables at all (except those declared within the function). **My question:** Why does that happen? How do I make it *not* happen, or what's a better way to go about this? An example of what I'm describing follows. Main page: ``` <?php $myvar = "myvar."; include('page2.php'); echo "Main script says: $somevar and $myvar\n"; doStuff(); doMoreStuff(); function doStuff() { echo "Main function says: $somevar and $myvar\n"; } echo "The end."; ?> ``` page2.php: ``` <?php $somevar = "Success!"; echo "Included script says: $somevar and $myvar\n"; function doMoreStuff() { echo "Included function says: $somevar and $myvar\n"; } ?> ``` The output: `Included script says: Success! and myvar. Main script says: Success! and myvar. Main function says: and Included function says: and The end.` Both pages output the variables just fine. Their functions do not. WRYYYYYY
2010/01/23
[ "https://Stackoverflow.com/questions/2123395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254830/" ]
You need to use `global` before using outside-defined variables in a function scope: ``` function doStuff() { global $somevar, $myvar; echo "Main function says: $somevar and $myvar\n"; } ``` More detailed explanation provided at: <http://us.php.net/manual/en/language.variables.scope.php> As comments & other answers pointed out accurately, globals *can be evil*. Check out this article explaining just why: <http://my.opera.com/zomg/blog/2007/08/30/globals-are-evil>
26,510,679
After reading these two posts: * [++someVariable Vs. someVariable++ in Javascript](https://stackoverflow.com/questions/3469885/somevariable-vs-somevariable-in-javascript) * <http://community.sitepoint.com/t/variable-vs-variable/6371> I am still confused on the following code: ``` var num = 0; num++ // returns 0 ++num // returns 1 ``` Why dose `num++` return 0? I understand that it assigns first, then adds one, ***but I still don't understand why it doesn't display the 1.*** ``` var num = 0; num++ // returns 0 num // returns 1 ``` I am really confused with the following example: **Example:** ``` var num = 0; num++ // assigns then increments // So if it assigns the num = 0, then increments to 1, Where is one being //stored? Is it assigned anywhere? ``` Or does it assign the expression. (I imagine the expression is this: num = num + 1;) This is probably my best guess but it still isn't 100% clear to me, I still don't understand why num++ displays/returns 0 instead of having the expression being evaluated and returning 1.
2014/10/22
[ "https://Stackoverflow.com/questions/26510679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6475188/" ]
Maybe looking at the specification helps. [Postfix increment operator](http://www.ecma-international.org/ecma-262/5.1/#sec-11.3.1) (`num++`) -------------------------------------------------------------------------------------------------- > > The production *PostfixExpression : LeftHandSideExpression [no LineTerminator here] ++* is evaluated as follows: > > > **1.** Let *lhs* be the result of evaluating *LeftHandSideExpression*. > > > That simply means we are looking at what's before the `++`, e.g. `num` in `num++`. > > **2.** Throw a `SyntaxError` exception if the following conditions are all true: [left out for brevity] > > > This step makes sure that `lhs` really refers to a variable. The postfix operator only works on variables, using e.g. a literal, `1++`, would be a syntax error. > > **3.** Let *oldValue* be [ToNumber](http://www.ecma-international.org/ecma-262/5.1/#sec-9.3)([GetValue](http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1)(*lhs*)). > > > Get the value of the variable represented by *lhs* and store it in `oldValue`. Imagine it to be something like `var oldValue = num;`. If `num = 0` then `oldValue = 0` as well. > > **4.** Let *newValue* be the result of adding the value 1 to *oldValue*, using the same rules as for the + operator (see [11.6.3](http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.3)). > > > Simply add 1 to `oldValue` and store the result in `newValue`. Something like `newValue = oldValue + 1`. In our case `newValue` would be `1`. > > **5.** Call [PutValue](http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.2)(*lhs*, *newValue*). > > > This assigns the new value to *lhs* again. The equivalent is `num = newValue;`. So `num` is `1` now. > > **6.** Return *oldValue*. > > > Return the value of `oldValue` which is still `0`. So again, in pseudo JavaScript code, `num++` is equivalent to: ``` var oldValue = num; // remember current value var newValue = oldValue + 1; // add one to current value num = newValue; // sore new value return oldValue; // return old value ``` --- [Prefix increment operator](http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.4) (++num) ----------------------------------------------------------------------------------------------- The algorithm is exactly the same as for the postfix operator, with one difference: In the last step, `newValue` is returned instead of `oldValue`: > > 6. Return *newValue*. > > >
33,359,268
"Modify the car-painting example so that the car is painted with your favorite color if you have one; otherwise it is painted w/ the color of your garage (if the color is known); otherwise it is painted red." Car-painting example: car.color = favoriteColor || "black"; **How or what do I need to do to make my script work?** ``` car.color = favoriteColor || "red"; if (car.color = favoriteColor ){ alert("your car is " + favoriteColor); } else if (car.color = garageColor){ alert("your car is " + garageColor); } else { car.color = "red"; } ```
2015/10/27
[ "https://Stackoverflow.com/questions/33359268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4115586/" ]
**This is the correct answer to your question:** See my comments to get a better understanding of how this works. ``` if (favoriteColor) { car.color = favoriteColor; // If you have a favorite color, choose the favorite color. } else if (garageColor) { car.color = garageColor; // If the garage color is known, choose the garage color. } else { car.color = 'red'; // Otherwise, choose the color 'red'. } alert('Your car is: ' + car.color); ``` **[Try it Online!](https://jsfiddle.net/jem6wp11/9/)** **Related Question (for further insight):** <https://softwareengineering.stackexchange.com/q/289475> **Alternative Method:** As another possibility, you can write a [conditional (ternary) operation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) to compact all of the logic into a single statement. ``` alert('Your car is: ' + (car.color = favoriteColor ? favoriteColor : garageColor ? garageColor : 'red')); ```
2,730,865
Background: * I have a short list of strings. * The number of strings is not always the same, but are nearly always of the order of a “handful” * In our database will store these strings in a 2nd normalised table * These strings are **never** changed once they are written to the database. We wish to be able to match on these strings quickly in a query without the performance hit of doing lots of joins. So I am thinking of storing a hash code of all these strings in the main table and including it in our index, so the joins are only processed by the database when the hash code matches. So how do I get a good hashcode? I could: * Xor the hash codes of all the string together * Xor with multiply the result after each string (say by 31) * Cat all the string together then get the hashcode * Some other way So what do people think? --- In the end I just concatenate the strings and compute the hashcode for the concatenation, as it is simple and worked well enough. *(If you care we are using .NET and SqlServer)* --- **Bug!, Bug!** [Quoting from Guidelines and rules for GetHashCode](http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/) by Eric Lippert > > The documentation for > System.String.GetHashCode notes > specifically that two identical > strings can have different hash codes > in different versions of the CLR, and > in fact they do. Don't store string > hashes in databases and expect them to > be the same forever, because they > won't be. > > > So String.GetHashcode() should not be used for this.
2010/04/28
[ "https://Stackoverflow.com/questions/2730865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57159/" ]
Standard java practise, is to simply write ``` final int prime = 31; int result = 1; for( String s : strings ) { result = result * prime + s.hashCode(); } // result is the hashcode. ```
57,278,351
I built my bot using Direct Line and authentication works there. But when I deployed my bot to MS Teams, pressing the sign in button does nothing at all. I used the following code: ``` AddDialog(new OAuthPrompt( nameof(OAuthPrompt), new OAuthPromptSettings { ConnectionName = ConnectionName, Text = " Welcome! Please Sign In.", Title = "Sign In", Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5), }) ); ``` I tried looking up documentation, but it seems they're using a different framework, or the v3 bot framework. How can I make OAuth work in web and ms teams? I'm using Bot Framework v4.
2019/07/30
[ "https://Stackoverflow.com/questions/57278351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1404347/" ]
How are you testing the Teams app? Did you side-load it into your Teams environment? When you are using Azure Bot Service for Authentication in Teams, you need [to whitelist the domain in your Bot Manifest](https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/authentication/auth-oauth-card#getting-started-with-oauthcard-in-teams). This requirement applies to bots built with the v3 and v4 SDK. You could use [App Studio](https://learn.microsoft.com/en-us/microsoftteams/platform/get-started/get-started-app-studio) to add `token.botframework.com` to the `validDomains` section of the [manifest file](https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/apps/apps-package). (or you can build the manifest file manually)