INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Redirect when not logged and parametr in link
how do I redirect to 'domain.com/sub' for unlogged users, when the url is without the "one_time_login" parameter? This should not work when a user is trying to login via sub.domain.com/wp-admin. Have no idea. I understand that htaccess cant make this? Thanks for your help! | This should work for what you're looking to achieve;
add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
if ( ! is_user_logged_in() && ! is_page('one_time_login') ) {
wp_redirect( 'domain.com/sub', 301 );
exit;
}
}
This should be added to your theme (or child theme) functions.php file | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect"
} |
Nested Classes with Template
I'm having issues using a nested class with a template. The first snippet is provided, I just have to implement it.
template <typename T>
class a {
public:
class b {
public:
func();
I thought the implementation would look something like this, but it isn't working.
template<typename T>
a<T>::b<T>::func(){} | There's not much wrong with your start. You just need to to tie it together.
template <typename T>
class a {
public:
class b {
public:
void func(); // return type missing
}; // missing
}; // missing
template <typename T>
void a<T>::b ::func() {}
// ^ not <T>
Demo | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c++, class, templates, nested"
} |
How to remove this weird default indentation?
If I do `gg=G` on a file with the following text
- 2018-2019 ICPC Northwestern European Regional Programming Contest (NWERC 2018)
- 2020 ICPC Universidad Nacional de Colombia Programming Contest
- 2018-2019 ICPC Southwestern European Regional Programming Contest (SWERC 2018)
it becomes
- 2018-2019 ICPC Northwestern European Regional Programming Contest (NWERC 2018)
- 2020 ICPC Universidad Nacional de Colombia Programming Contest
- 2018-2019 ICPC Southwestern European Regional Programming Contest (SWERC 2018)
I have executed vim with no configuration files (`vim -u NONE`) and this still happens. | This is a misuse of `=` operator.
Actually, Vim has two builtin "formatting" operators, i.e. `=` and `gq` (there's also `gw` that is simply the same as "internal" `gq`-formatter).
`=` is supposed for use with programming languages. Of course, it could be set up to do anything you like, but it defaults to C. Does it come as surprise? I don't think so.
So I suggest simply to stop using `=` for plain text formatting and switch to `gq` / `gw` instead.
If you still like doing it with `=`, you have to provide non-default values for `indentexpr` or `equalprg`, whichever you choose. | stackexchange-vi | {
"answer_score": 3,
"question_score": 2,
"tags": "indentation"
} |
DateTime parsing of weeks for '30 Dec 2013' is incorrect
`DateTime#parse` on `'Mon, 30 Dec 2013 00:00:00 UTC +00:00'` is wrong for the week. I chose ISO 8601 week-based year and week number `%V` (week number `01..53` of the week-based year).
With format `"%V-%y"`:
DateTime.parse('Mon, 30 Dec 2013 00:00:00 UTC +00:00').strftime "%V-%y"
#⇒ "01-13"
DateTime.parse('Mon, 30 Dec 2013 00:00:00 UTC +00:00').strftime "%W-%y"
#⇒ "52-13"
Date.strptime('01-13', '%V-%y')
#⇒ Tue, 01 Jan 2013
Date.strptime('52-13', '%V-%y')
#⇒ Tue, 01 Jan 2013
`Mon, 30 Dec 2013 00:00:00 UTC +00:00` is not `"01-13"`.
But if I use `"%W"` format, the result is correct (`"52-13"`).
What is it? Or did I make some mistakes? | With week-based week number (`%V`) one should use week-based year (`%g`):
DateTime.parse('Mon, 30 Dec 2013 00:00:00 UTC +00:00').strftime "%V-%g"
#⇒ "01-14" | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ruby, date, datetime"
} |
Why can't I change the view's size of my view controller in Interface Builder?
In addition to view based application template, I made a second view controller. When I open it's XIB in IB, I can't reduce the size of the view. It remains fullscreen. I want this view to contain some buttons only and then place this as a subview on another view. | It's likely because you have some of the "Simulated Interface Elements" turned on (in View Attributes)... probably the Status Bar, which is set to "Gray" by default. Make sure they are all set to "None", and then adjust away.
I run into this frequently myself. | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 3,
"tags": "iphone, interface builder"
} |
Debug a self signed android app? (Need it for facebook integration)
When hitting the "debug"-button in eclipse my App gets signed by a debug key form android which is stored in the file "debug.keystore".
Now I am implementing the Facebook SDK which forces me to use a signed app for the Single SignOn feature. That way I need to generate the hash of my companies keystore and store the one in our facebook developer account.
I know how to sign an app through the wizard in Eclipse (over the AndroidManifest.xml). How to debug such a signed app?
Can I change the debug key somehow and set up our companies key as debug key? Or how should I go? Right now I can get FB working only by signing and installing my app on a device. I already tried to generate a hash of the debug key with no luck... | I do not recommend setting your companies key as your debug key, but you can do that by replacing the Eclipse debug keystore file, named debug.keystore. You can find its location on your OS by reading through this.
A better solution would be to generate the hash of the debug key - follow the instructions given on the official SDK for Android page, and make sure you mention the correct keystore file, and the alias "androiddebugkey". The password is always "android". | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 5,
"tags": "android, debugging, facebook, signing"
} |
Can I omit "one" in the following case?
> Rich people's lives are the most complicated (ones)—and also the most meaningless (ones).
Can I omit both? If not, which one should I keep? | Yes, you can eliminate both _ones_. Your sentence would look like this:
> Rich people's lives are the most complicated — and also the most meaningless.
This reads fluently and looks better than the original on paper.
To make the sentence read better, you could consider removing the _also_ , as @J.R. commented. Doing this will give:
> Rich people's lives are the most complicated — and the most meaningless.
Go minimalism! | stackexchange-english | {
"answer_score": 3,
"question_score": 1,
"tags": "grammar, word usage"
} |
Match two arrays using angular js
I have two arrays.I want to match the values of an arrays using ng_if and else conditions as below:
var a = {'nishant','karan','jyotsna'};
var b = {'nishant','prbh','moh'};
<div ng-repeat="x in a">
<div ng-if="x!=b">
{{x}}
</div>
<div ng-else>
<div ng-repeat="x in b">
{{x}}
</div>
</div>
</div> | I think `ngElse` is not a built-in directive, but you could just use another `ngIf`.
<
<div ng-repeat="x in a">
<div ng-if="b.indexOf(x) !== -1">
{{x}} is in b
</div>
<div ng-if="b.indexOf(x) === -1">
{{x}} is not in b:
<div ng-repeat="x in b">
b: {{x}}
</div>
</div>
<hr/>
</div> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "javascript, angularjs, ionic framework"
} |
How to extract two numbers from input line and tab delimit them?
myString = "Exon 51 100.0 1446231 1446281 NW_003101558.1 1 51 XM_002612573.1 Branchiostoma floridae hypothetical protein, mRNA"
print myString.split('100.0')[1].split(" ")[2]
This is where I got stuck. I would like to get both numbers from the second split ("1446231 1446281"), but I only get the second one.
Ideally i would like "Exon 1446231 1446281" as the output - all tab delimited. Thank you for any help. | Just store the result of the `split()` call, so you can access the elements you need.
Then you can then join those elements together with `join()`:
>>> myString = "Exon 51 100.0 1446231 1446281 NW_003101558.1 1 51
XM_002612573.1 Branchiostoma floridae hypothetical protein, mRNA"
>>> s = myString.split()
>>> print '\t'.join((s[0], s[3], s[4]))
Exon 1446231 1446281
>>>
For more complex scenarios, a single split is probably not sufficient, but you'll get the idea. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "python, string, input, split, line"
} |
write some javascript code in response.write when SqlDataSource1_Deleted
i have a notification j-query plugin .. i taste it in my page (working 100%) but when i want to use it in a event SqlDataSource1_Deleted with the response.write method it does not work
Protected Sub SqlDataSource1_Deleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Deleted
Response.Write("<script type='text/javascript'> showNotification({message: 'This is a sample Success notification', type: 'success' }); </script>")
End Sub | If you use `Response.Write` in a page, you will be putting the code before the HTML document itself. This means that it will run before jQuery or any plugin is loaded. (And also that it may cause the page to be rendered in quirks mode, which would probably break the entire layout.)
Use the `RegisterStartupScript` method to add a script in the page:
Protected Sub SqlDataSource1_Deleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Deleted
Page.ClientScript.RegisterStartupScript(Page.GetType(), "notification", "showNotification({message: 'This is a sample Success notification', type: 'success' });", true)
End Sub | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "asp.net, vb.net, visual studio 2010, events, sqldatasource"
} |
C++ how to draw line chart using WTL?
I am new to C++ and WTL, does WTL provide good API's to display line (stacked area, column) charts? Or do we need to use 3rd party library to integrate the same with our existing C++ code? It would be great if i can some pointers to examples .....i am looking for very basic line 2D chart. The application is written in C++ and use WTL for some of the GUI components .....and platform is windows
Thanks in Advance | WTL provides you with some classes that wrap GDI API and handles, so you can obviously paint variety of charts, you are just going to do it right from scratch. That is, dissecting your client area into chart area, legend, axis and son on. If you were looking for a solution ot use of of the box, WTL does not have anything close. You can certainly integrate third party libraries, ActiveX controls, or even Google Chart Tools hosted by IE ActiveX control on your window, where you pass data synthesizing JS script on runtime. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c++, charts, wtl"
} |
Should the father know about the children or vica versa?
Should the father know about the children or vica versa?
That is, in a situation where I have two kinds of objects (items and categories), each has its own characteristics and fields and we have a relation between them that every item has a category he is in.
I want to ask in two ways about what should happen, in theory and in php + mysql.
Should the categories know about all the items that are in it, or should every item know about its category?
In php + mysql the exact question is should I for every item in its row save its category's id, or should I create a special table for this relation (each row contains a category id and an item id)? | Best practice is the children know about the parents (ex: `parent_id`). The alternative is not scalable, and very taxing to your system. You could easily run a query to FIND the children though - `SELECT * FROM items WHERE item_category = x`. The reason for this is when you add or delete items, the category is not affected. It doesn't become a different category because you assign an item to it or remove an item from it, so it shouldn't care either way which items are assigned to it.
This is different from a tagging setup. In the one-to-many category assignment method, items would fall into a single "category" but might have many "features". Tagging features is a many-to-many relationship and would require the mapping table you mentioned. Assigning parent categories requires only a single "parent" field in the items table. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "php, mysql, theory"
} |
Rotating a set of anges (pitch/yaw/roll) by another set of angles (pitch/yaw/roll)
I want to rotate a set of angles (pitch/yaw/roll) by another set of angles (pitch/yaw/roll). By using Google I only found information about rotating a vector by angles, which is not what I need. Examples: (disregarding signs)
- (0/90/0) rotated by (90/0/0) -> (90/0/90)
- (0/0/90) rotated by (90/0/0) -> (90/90/0)
For simplicity I just created examples with angles of 90°, but I am looking for a method that can also do this with odd angles. What method works for this? Is this possible to do with rotation matrices? | This is a problem that 3D animation software has to deal with all the time, namely when an object's coordinate system is related to another object's coordinate system rather than the global coordinate system. In the general case, there may be arbitrarily many such coordinate systems each adding their own pitch/yaw/roll to each child object.
The solution used by Blender (< is based on Quaternions. Wikipedia explains how quaternions work in this case: < That explanation is perhaps too lengthy to be copied here (though it can be if that's the only way to validly "answer" the question). | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "matrices, trigonometry, 3d"
} |
How to equip and use the golden guns?
I'm in my first playthrough of Max Payne 3 and I can't figure out how to equip the golden guns, once all the pieces have been found. Are those available later, in some sort of "new game+" playthrough ? Or does it have something to do with multiplayer ?
Or it's just some kind of an achievement (but I don't think so, regarding this answer) ? | From what I remember, once all parts are collected, golden guns will automatically replace their regular versions. Try selecting another chapter to play, if you currently don't have the gun which you collected all gold parts of and you would like to try it.
This seems to be supported by posts in this thread at xbox360achievements.org and this one at gamefaqs.com.
Also, check if Golden Guns are enabled at: Main Menu -> Settings -> Gameplay -> Golden Gun Effects On/Off.
In Multiplayer:
> Go to Arsenal then Loadout. Select any Loadout and select any weapon you wish to use. Once selected [press the button for] "modify". In this modify screen the bottom option is called "tint".
Source: <
> The gold paint job is at the bottom of the "attachments" menu for each weapon.
Source: <
In Multiplayer, the golden guns are just cosmetic customization and provide no bonuses (unlike the Single Player golden guns). | stackexchange-gaming | {
"answer_score": 3,
"question_score": 3,
"tags": "max payne 3"
} |
Prove that $G$ is solvable if $AB=BA$ for any subgroups $A$,$B$ of $G$.
Let $G$ be a finite group. Prove that $G$ is solvable if $AB=BA$ for any subgroups $A$,$B$ of $G$.
My attempt:
Since $G$ is finite, so by Jordan-Holder Theorem, $G$ has a composition series, i.e, there exists a sequence of subgroups $N_i$ such that
$1=N_0\le N_1 \le N_2 \le \cdots \le N_k=G$
with $N_i \unlhd N_{i+1}$ and $N_{i+1}/N_i$ is a simple group. In order to prove that $G$ is solvable, I just need to prove $N_{i+1}/N_i$ is abelian. So far I have not used the property of $AB=BA$ for any subgroups $A,B$ of $G$. So I thought of using it in proving $N_{i+1}/N_i$ is abelian. So let $N_{i+1}/N_i=\\{aN_i : a\in N_{i+1}\\}$. I wish to show that $(aN_i)(bN_i)=(bN_i)(aN_i)$ for any $a,b\in N_{i+1}$. However, I am stucked here. Can anyone give me a hint to continue from here?THanks | **Hint:** $AB=BA$ if and only if $AB$ is a subgroup. Thus you know that product of any subgroups is a subgroup. Use induction on $G$. That is why you can say that any proper subgroup of $G$ is solvable.
**Solution:** Actually you can show more. $G$ must be nilpotent.
Assume not. Then there exist $M$ maximal such that $M$ is not normal. Let $M^g\neq M$. Then we must have $MM^g=G$. Thus $g=mn^g\implies g=mg^{-1}ng\implies g=nm\in M\implies M=M^g$. Contradiction. | stackexchange-math | {
"answer_score": 1,
"question_score": 3,
"tags": "group theory, finite groups"
} |
Having a page appear larger when viewed on phones?
having finished a little webpage and giving it a basic layout, I decided to test what it'd look like using a mobile browser. So I installed the Android SDK with emulator, and as it turns out, the couple of elements on the page appear really small. I'd estimate about 80% of the page is currently empty background by default. However, when I zoom, it looks great, because the `width:height` ratio matches the phone's screen. That said, I'd prefer to leave the page unchanged, it just needs to be bigger as a whole.
**Is there a way I can make my page appear zoomed-in on by default?** | Try this:
`<meta name="viewport" content="width=device-width">`
for an initial scale of 1:1, add this:
`<meta name="viewport" content="initial-scale=1.0">` | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "html, css, mobile, zooming, viewport"
} |
C: What will the statement 'return A || 1' return when A >1?
Although I wouldn't have written it myself, what is the expected result of the following statement where `A` (guaranteed to zero or positive integer) is greater than 1?
` return A || 1; `
In many languages, I would expect `A` to be returned, unless the value of `A` is zero, in which case 1 would be.
I don't have my C book to hand, but I note that in reality, the value 1 always seems to be returned. Is this a result of compiler optimisation or given the potential ambiguity of the expression, is it that the return value is non-deterministic? | The standard says
> The `||` operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
See section 6.5.14 of the standard. | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 3,
"tags": "c, objective c"
} |
How to invoke xkbcomp?
When I'm trying to run this `xcbcomp $DISPLAY original.xkb` I'm getting this:
No command 'xcbcomp' found, did you mean:
Command 'xkbcomp' from package 'x11-xkb-utils' (main)
xcbcomp: command not found
How to invoke it ? Or should I make it another way ? I'm trying to emulate numpad on keyboard as described here (I know: that's very different distro): < | Instead, do `xkbcomp $DISPLAY original.xkb` You made a typographical error. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 0,
"tags": "keyboard, xorg, shortcut keys, keyboard layout, xkb"
} |
Reset vmstat statistics without rebooting
Running `vmstat` will give you the average virtual memory usage since last reboot. The `si` and `so` values give the average virtual memory I/O. For example:
root@mymachine# vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 304 300236 244940 967828 0 0 0 1 2 1 0 0 100 0 0
As Ijaz Khan answered, I can how many times I want `vmstat` to run, as well as the increments in between. This is useful in some cases (+1), but I do not want to have to leave `vmstat` running.
I want to be able collect the data, then reset the counters so I can leave it for a while, then come back to get an average of from when I reset the counters to when I next check -- instead of since the last boot. Is that possible? | The memory information isn't averaged; `vmstat` shows the instantaneous memory information as provided in `/proc/meminfo`. So you can use the memory information from `vmstat` without worrying about changes since the last boot.
The values that are accumulated since boot concern the CPU usage, interrupts and context switches, and swap in/out and pages in/out; these are never reset. You can read the raw values from `/proc/stat` and `/proc/vmstat` if you want to be able to calculate your own deltas. For example, `si` is `pswpin` from `/proc/vmstat`, `bi` is `pgpgin` from `/proc/vmstat`. | stackexchange-unix | {
"answer_score": 2,
"question_score": 1,
"tags": "debian, monitoring, virtual memory, statistics, vmstat"
} |
javascript cartesian product of lists
i'd need the cartesian product of two javascript lists.
Example:
let l1 = ['a','e','f'];
let l2 = ['1','3','2'];
let lp = prod(l1, l2);
lp would be
[
['a','1'],
['e','1'],
['f','1'],
['a','3'],
['e','3'],
['f','3'],
['a','2'],
['e','2'],
['f','2']
]
I can easily do it with for/foreach loops, but wonder if someone would have elegant suggestions with map functions. | You can use combination of reduce and map:
console.log(l1.reduce((result, el1) => {
result.push(...l2.map((el2) => [el1, el2]));
return result;
}, [])); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, dictionary, arraylist, cartesian product"
} |
Biased eigenvalue problem
I came across the following "biased eigenvalue problem" when I have tried to solve a quadratic constrained optimization problem.
> $$Ax = \lambda (x+v), $$
where $A \in\mathbb{S}^{n}$ (the set of $n\times n$ positive semidefinite matrices), and $v \in \mathbb{R}^{n}$ a given unit vector.
**My thoughts**
By substituting $y =x+v$ into the problem, we have $$A(y-v) = \lambda y \implies Ay = \lambda y + u,$$ where $u =Av$. Here, $\lambda$ is only multiplied by the vector $y$, but still it is a biased problem.
_How to find the eigenpairs $(x,\lambda)$ or $(y,\lambda)$? Is there a closed form or an algorithm to solve this problem?_
I just need some hints or link for papers. Thanks in advance! | The problem can be written
$$(A-\lambda I)x=\lambda u.$$
In general, $A-\lambda I$ is invertible (unless $\lambda$ is an Eigenvalue of $A$) and the solution
$$x=\lambda (A-\lambda I)^{-1}u$$ holds.
The "trajectory" of the solution is a rational expression in $\lambda$, nothing simple.
With a random $3\times3$ example:
;
async function modalSave() {
await setValChanged(true);// STEP 1
await onEventSave();// This involves saving values to backend (async) STEP 2
}
the onEventSave() async operation relies on valChanged value on previous step and therefore it has to be set to true before onEventSave is invoked. (step 1 has to be completed and its value set to true, before STEP 2 is invoked)
is there anything missing here? | If you are using hooks, there is no `setState` callback function, so you can do it with `useEffect`, like this :
useEffect(() => {
onEventSave();
},[valChanged]);
The above function will be called whenever the `valChanged` is changed | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, reactjs, asynchronous, async await, react context"
} |
Android Asynctask run one by one in order
I am trying to create a lot of asynctask, and run one by on in order. Is it possible? I can't find any solution for this.
onPostExecute and then call a new AsnycTask again is not a good solution for me.
SO what I want:
async1.execute
async2.execute
async3.execute
async1.over->async2.start
async2.over->async3.start | If you use the serial executor (default in API 11 and above), this happens automatically. If you need this to work before API 11, you need to do the classic wait/notify trick (< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "java, android"
} |
The kernel of a continuous linear operator is a closed subspace?
> If $V$ and $W$ are topological vector spaces (and $W$ is finite-dimensional) then a linear operator $L\colon V\to W$ is continuous if and only if the kernel of $L$ is a closed subspace of $V$.
Why is this so? | Assume $W=\mathbb{R}$ for simplicity. If $L$ is not continuous at zero, there is a sequence $\\{v_n\\}$ in $V$ such that $|v_n|=1$ and $|Lv_n| \to +\infty$. Assume that $L \neq 0$, the null map. Then you can fix $z \in V$ such that $Lz=1$. Consider now $w_n=v_n-(Lv_n)z \in V$. Trivially, $Lw_n=0$, so that $w_n \in \ker L$. But $$|w_n| \geq \left| |L v_n| |z| - |v_n| \right| \to +\infty.$$ Hence $\\{w_n\\}$ can't have any convergent subsequence, and $\ker L$ is not closed. This is the proof if $V$ has a norm. In the general case, the reasoning is rather similar, but one needs to know the concept of balanced neighborhood. A precise reference is Theorem 1.18 of Rudin, Functional Analysis. | stackexchange-math | {
"answer_score": 4,
"question_score": 19,
"tags": "functional analysis, topological vector spaces"
} |
UIScrollView dragging affected by UIWindow transform rotation
I'm adding a video out function to my iPad app and have run into a problem with my UIScrollView. To get the proper view orientation on the external monitor, I've rotated the UIWindow based on the current interface orientation (e.g. - mirroredScreenWindow.transform = CGAffineTransformMakeRotation(- M_PI * 0.5);).
The problem I've run into is that the ScrollView dragging seems to be affected by the UIWindow transform. If the UIWindow is rotated 90 degrees, horizontal drags scroll the view vertically and vice versa. Is there any way to correct this? | I got a response from Apple Dev Support that said essentially, "Doing a transform on UIWindow will confuse the internal objects and should never be done."
Looks like I'll just have to create a modified ViewController that lays out all of my UI elements specifically for the format of the external screen, rather than just transforming the view controller that already works correctly on the iPad screen. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, uiscrollview, transform, uiwindow"
} |
Solr Multivalued fields to string
I have a SOLR instance which is fed from a 3rd party application and one of the fields is multivalued and returns like Below
<arr name="site_code">
<str>4A</str>
<str>R3</str>
<str>UK</str>
However another requirment is for the application to display the values as a comma separated list `4A,R3,UK.`
I have tried to create a copyfield from site_code into a field call site_code_csv but it doesnt work. Is there a way this can be done?
thanks
Andy | To get information out of Solr in the format `4A,R3,UK` you can simply change the output format in Solr for your individual query:
Add `wt=csv` (wt is "writer type/response format") to your query.
Documentation: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "solr"
} |
Intersection of a number field with a cyclotomic field
Let $K$ be a number field and $N$ a positive integer. Prove that if the absolute discriminant of $K$ is coprime to $N$, then $K \cap \mathbb{Q}[\zeta_{N}]=\mathbb{Q}.$
This is something that the Childress book on CFT leaves kind of vague when proving Artin's Lemma. I would like to see a proof if possible.
Thanks in advance! | If $L$ is an intermediate extension of $E$ over $F$, and $\Delta_{N/M}$ denotes the discriminant of $N$ over $M$, then $$\Delta_{E/F} = N^{L}_F(\Delta_{E/L})\Delta_{L/F}^{[E:L]},$$ where $N^L_F(\cdot)$ is the norm map from $L$ to $F$.
In particular, the discriminant of $L/F$ divides the discriminant of $E/F$.
Let $L = K\cap\mathbb{Q}(\zeta_N)$. Then the discriminant of $L$ over $\mathbb{Q}$ has to divide the discriminant of $K$, and also has to divide the discriminant of $\mathbb{Q}(\zeta_N)$.
The discriminant of $\mathbb{Q}(\zeta_N)$ is $$(-1)^{\varphi(N)/2}\left(\frac{N^{\varphi(N)}}{\prod\limits_{p|N}p^{\varphi(N)/(p-1)}}\right).$$ In particular, it can only be divisible by primes that divide $N$. | stackexchange-math | {
"answer_score": 6,
"question_score": 5,
"tags": "algebraic number theory"
} |
shell script for below requirement
i have one file named access.log which is always being receiving data from server. so i need to copy the data of access.log file into several files without effecting the data in any files. for example: if i execute the script, need to copy the data into another file (file name should be access_1.log)and access.log file should be truncated. and if i execute the same script 2nd time, the data should be copied to access_2.log file and access.log file should be truncated. so if run the file 10 times then need to created 10 files. i have tried this below script but count values is not increasing in my code.so always getting same file name as access_1.log and data also we changing .
count=1
cp access.log access_$count.log
>access.log
count=`expr $count + 1`
please help me | Here how many times you run it the count value will be retained
LOCATION=/path/to/location
COUNT=`ls $LOCATION/access_*.log | wc -l`
COUNT=`expr $COUNT + 1`
cp $LOCATION/access.log $LOCATION/access_$COUNT.log
>$LOCATION/access.log | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "linux, shell, unix, sh"
} |
How to apply function to multiple datasets train1-train10?
Newbie R question:
I'd like to use the ceiling function to round up the y variable in each of ten training datasets, train1 through train10.
> for (i in 1:10){ x <- get(paste0("train",i)); x$y <- ceiling(x$y) }
The above code runs without error. However when I check the y values of my datasets, I discover they haven't been rounded:
> head(train1$y)
[1] 29561.06 0.00 0.00 4660.24 440.00 924.60
But if I try this:
> head(x$y)
[1] 29562 0 0 4661 772 440
> head(x$Fold)
[1] 10 10 10 10 10 10
it turns out the code is working correctly, but only on the renamed dataset "x" which gets overwritten after each loop, not datasets train1-train10.
What am I doing wrong? | It would be better to keep the datasets in a 'list'. But if you want to update the data objects in the global environment, one option is `list2env`. We get the 'datasets' in a list with `mget`, loop through the 'list' with `lapply` and create a new variable 'y', update the data objects with `list2env`.
list2env(lapply(mget(paste0('train', 1:10)), function(x) {
x$y <- ceiling(x$y)
x}), envir=.GlobalEnv)
Or using `assign`
for(i in 1:10) {
assign(paste0('train', i), `[[<-`(get(paste0('train', i)), 'y',
value= ceiling(get(paste0('train', i))$y)),
envir=.GlobalEnv)}
head(train1,3)
# y
#1 0
#2 1
#3 1
### data
set.seed(24)
list2env(setNames(lapply(1:10, function(i)
data.frame(y= rnorm(5))), paste0('train', 1:10)), envir=.GlobalEnv) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "r, for loop"
} |
how many zookeeper node is suitable?
I know that with more node number ,zookeeper will be more fault tolerate and faster with read but the write performance will be worse.
I wander is there any best node number for a zookeeper cluster. | 3 is suitable for most use-cases, but 5 or 7 would be most fault tolerant
There's no reason to have more than that | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "apache zookeeper"
} |
Windows Console App vs Service, Part II
Windows Console App vs Service
I would like to extend the question at the above post, as the previous answers did a great job of helping me understand the difference between a service and not a service.
The question I have now, is with applications that require to be up 24/7, what security concerns there are with a user that is logged in, vs the service not requiring a user to be logged into the machine. Obviously, if a user walks away without locking, that's an issue (and with redundancy, that's more than one vector of attack), but what other concerns should I be looking at to help my team understand that we're better off using a service for stuff that needs to be up 24/7?
Additional info, the core is on an SS7 network, with some functions migrating to IP (VoIP and mobile, for instance), so the focus of our security concerns are getting wider. | Services usually run as one of "Local System".aspx), "Local Service".aspx), or "Network Service".aspx).
The first of those is quite powerful and has a lot of control over the computer. The other two have _much less_ power than even a limited desktop user. They don't have user credentials. This makes them safer in the event of a security compromise - there's few places they can write to.
If the application is supposed to be running 24/7, there's not really any alternative to running as a service, because otherwise you'd either have to have a human monitoring it or use an autologin with consequent reduced security. | stackexchange-softwareengineering | {
"answer_score": 1,
"question_score": 0,
"tags": "security, windows, operating systems, services"
} |
Editor information as important as the original poster's?
Why is editor information presented so prominently next to the original poster's?
The edits are sometimes as trivial as a capitalization with some spaces inserted, and yet the editor is presented as though he co-authored the question. | Simply because everybody can edit questions (with an approval process for anonymous users and people with low reputation).
When everybody can edit, that also means that the community moderation has to be able to review the edits. It's important for people to check whether an edit actually improved the question, of if it defaced, invalidated, or otherwise strongly changed it.
Making the fact "someone else edited this" obvious helps this community review proccess.
It also has the advantage of very prominently showing to new users that wiki-like editing by "random strangers" is a major part of how the Stack Exchange sites work; this is something that's often unexpected to people coming from "normal" forums. | stackexchange-meta | {
"answer_score": 8,
"question_score": 1,
"tags": "discussion, edits"
} |
How to combine rows based on field value
I have designed the following query
SELECT
v.visitid,
CASE
WHEN vd.DocType = 1 THEN 'y' ELSE 'n'
END as 'FinalReportAttached'
,CASE
WHEN vd.DocType = 13 THEN 'y' ELSE 'n'
END as 'InspectorReportAttached'
,CASE
WHEN vd.DocType = 2 THEN 'y' ELSE 'n'
END as 'Co-ordReportAttached'
FROM Visits v
INNER JOIN VisitDocs vd on vd.VisitID = v.VisitID
WHERE v.VisitID = 79118
!enter image description here
I like to show results in one row. If report is there then 'y' and if not then 'n' .
There is a one to manay relation b/w visit and visitdoc table. Visitdoc can have many different docs for one visit. I need to check if visitdoc has doctype 1,3 or 12 against each visit then say yes otherwise no.
visitID |FinalReport |InspectorReport |Co-ordReport
------------------------------------------------
79118 |n |y |y | You could try this:
SELECT
v.visitid,
CASE
WHEN SUM(CASE WHEN vd.DocType = 1 THEN 1 ELSE 0 END)>0 THEN 'y' ELSE 'n'
END as 'FinalReportAttached'
,CASE
WHEN SUM(CASE WHEN vd.DocType = 13 THEN 1 ELSE 0 END)>0 THEN 'y' ELSE 'n'
END as 'InspectorReportAttached'
,CASE
WHEN SUM(CASE WHEN vd.DocType = 2 THEN 1 ELSE 0 END)>0 THEN 'y' ELSE 'n'
END as 'Co-ordReportAttached'
FROM Visits v
INNER JOIN VisitDocs vd on vd.VisitID = v.VisitID
WHERE v.VisitID = 79118
GROUP BY v.VisitID | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql, sql server 2008"
} |
phonegap : manipulate files system
I curently develop an application for android and ios with phonegap. So I want to create folders and files in the files system of android and ios. How can I check if files exist and create my files in specific folder? And after that, how can I load them? all files I want to create and manipulate are JSON. | In order to achieve your goals you need this Cordova/Phonegap plugin:
<
This plugin supports both Android and iOS platform. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, android, ios, cordova"
} |
Is there a way to declare two spring beans instance from the same class with annotation only?
I usually use the XML Spring configuration (spring-conf.xml) for doing it like this:
<beans>
<context:component-scan base-package="org.company.dept.business" />
...
<bean id="myServiceB2B" class="org.company.dept.business.service.MyService"
p:configLocation="WEB-INF/classes/b2b.properties" />
<bean id="myServiceResidential" class="org.company.dept.business.service.MyService"
p:configLocation="WEB-INF/classes/residential.properties" />
...
</beans>
Because there is only one file (definition) of the class MyService is there a way to instantiate the two beans without using the XML Spring configuration?
I am ok with the XML definition but I am always trying to minimise my XML configuration as much as possible. | In the same way you would use 2 `<bean>` declarations in XML, you use 2 `@Bean` annotated classes in Java configuration.
@Configuration
public class MyConfiguration {
@Bean(name = "firstService")
public MyService myService1() {
return new MyService();
}
@Bean(name = "secondService")
public MyService myService2() {
return new MyService();
}
}
I don't know what the `configLocation` is for, but you can definitely include that in the Java config as well.
The `name` attribute of `@Bean` is equivalent to the `id` attribute of `<bean>`. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 4,
"tags": "java, spring, annotations"
} |
Accessor method object management?
After reading the Memory Management Guide I am trying to get my head around what is happening here My understanding "so far" is ...
- (EngineClass *)engine {
return [[engine retain] autorelease];
}
1. I am returning a pointer to an Engine object.
2. The retain count of the object is incremented to record we are making a new pointer to the object
3. Balance the above retain by specifying an autorelease at some future point.
Am I on the right track?
cheers -gary- | I'm not sure I'd say the retain is "to record we are making a new pointer to the object."
The retain-autorelease pair is there to indicate that there's another object interested in the return value, so it needs to stick around at least that long, but the other object doesn't properly own the return value. Without the retain, if the object performing this method is deallocated immediately afterward, the engine might not have any other owners and would also be deallocated immediately. That's not the expected behavior. Doing it this way causes the object's ownership not to go away until the autorelease pool is drained. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "objective c, memory management"
} |
Angular2 RC5 shared Component between Modules
I'm just updating my `angular2-app` to new `RC5`. I got quite far, and everything seems ok, but now I want to re-organize it into `NgModules` and came across one thing: I used a component ("ComponentA") across multiple other components in different Modules (say ModuleA & ModuleB).
As soon as use it that way, I get an:
> Uncaught Type ComponentA is part of the declarations of 2 modules: ModuleA and ModuleB!
Error.
As far as I see, the only way to get around that is to use a `Shared-Module` with all my common stuff, is that right? Or is there an easier way to share components across Modules?
Thanks in advance :) | You have to make a module for the shared component and import this module where you want to use this component.
As the error messages says a component (or directive, or pipe) can only be listed in `directives` of exactly one module.
If you want to reuse, then you need to add the module that contains it to `@NgModule({imports: [...]})` of the module where you want to use it. | stackexchange-stackoverflow | {
"answer_score": 23,
"question_score": 12,
"tags": "angular"
} |
SQL Replace all values in database, no matter column and table
I am trying to change a specific value, which has no connection to it's column name or table.
For example it can appear in:
column `name` in the table `users`
And also in:
column `hi` in the table `jokes`
There are many more unknown locations. How can I run a loop on all the sql data in my database to change it?
I'm using PHPMyAdmin | As you are saying PHPMyAdmin I suppose you are using MySQL.
See:
* Search for all occurrences of a string in a mysql database
* or Find and replace in entire mysql database.
There's also a PHP script to do this at:
* Search and Replace text in whole MySQL database | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "sql, replace"
} |
Find Those Chews Notations! #6
Here be a hearty return to the original point of this series: retrograde analysis!
Number Of Moves: 12
Checkmater: White
Given Game:
1. ? ?
2. ? ?
3. ? ?
4. ? 0-0
5. ? ?
6. ? ?
7. ? ?
8. Nf6+ Kh8
9. ? ?
10. ? ?
11. Nxf5 ?
12. Ng6#
Cryptic Clue #1: The black king dies a lonely death.
Cryptic Clue #2: No white queens or bishops are allowed.
Cryptic Clue #3: The white rook pawns do not move at all.
Cryptic Clue #4: (Optional): What words awoke the time traveler who came from the blue train?
Task: To use retrograde analysis and give an answer with all of the question marked moves solved, along with reasons for each move and all of the cryptic clues. A simple PGN post shall suffice. A link is optional.
Good luck, and go find those notations! | Since the clue explicitly said:
Cryptic Clue #1: The black king dies a lonely death.
> He got cornered and died alone.
Cryptic Clue #2: No white queens or bishops are allowed.
> (No queen and bishop moves by white.
Cryptic Clue #3: The white rook pawns do not move at all.
> No rook pawn moves by white.
I think the following move set do the job:
> 1\. d4 e5
> 2\. dxe5 Bd6
> 3\. exd6 Ne7
> 4\. Nf3 **O-O**
> 5\. Nc3 f5
> 6\. Nd5 g5
> 7\. dxe7 h5
> 8\. **Nf6+ Kh8**
> 9\. exf8=N g4
> 10\. Nh4 Qe8
> 11\. **Nxf5** Qe7
> 12\. **Ng6#**
Given moves are bolded. | stackexchange-puzzling | {
"answer_score": 2,
"question_score": 2,
"tags": "chess, retrograde analysis"
} |
Cannot access prototype of HTML element in IE
I am trying to fill a textarea in a window opened with `open(link_here)` (on the same domain). It works fine in all browsers except IE/Edge.
Steps to reproduce here on stackoverflow:
var w = open(' // example
// (allow popups and) wait for window to be opened, then:
let input = w.document.getElementsByClassName('f-input js-search-field')[0]
const prototype = Object.getPrototypeOf(input); // returns null on IE/Edge
Any workaround? Thanks | I believe it is a Hierarchy access restriction. Since the element is not in the same `window` as the `Object` you are using, it doesn't have access to the object's information. You will have a somewhat similar problem if you try to append an element created by the main document and try to append it to the iframe document. When attempting this you will get a `HierarchyRequestError`.
Instead of using the main `window`'s `Object` use the iframe `window`'s `Object`:
var prototype = w.window.Object.getPrototypeOf(input);
console.log(prototype); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html, internet explorer, microsoft edge"
} |
Do contributions made to an "involuntary 401(a)" count against the limit for a Roth IRA?
At work I pay into an "involuntary 401(a)" retirement plan. I'd like to also open up a Roth IRA on my own. Do the contributions I make through my work plan count against the $5000/year limit on the Roth? | No, your 401(a) contributions will not count against your Roth IRA limit. Contributing to other IRA accounts can reduce how much you can contribute to a Roth account, but 401(a)/401(k) and other employer sponsored plans do not count against the Roth IRA limit.
The IRS publishes a lot of really good information on this topic, which you can find here. It's pretty long though, so it's best used as a reference. | stackexchange-money | {
"answer_score": 3,
"question_score": 3,
"tags": "united states, roth ira, contribution, limits"
} |
go from work to home on foot / go home from work on foot / come back from work on foot
I know that the first sentence and the second one are used in English. How about the others? Maybe, some examples are grammatically correct, but awkward in English.
> I usually walk home from work.
>
> I usually go home on foot.
> I usually **go from work to home on foot**.
> I usually **go home from work on foot**.
> I usually **come back from work on foot**. | They are all fine (except the last one which is a little clumsy).
As you said in comment, you feel that they have too many words. So go with the shortest one:
> I usually walk home from work.
There's no need to say "walk _back_ home", as this is what "walk home" means, idiomatically. And "walk" is more succinct than "on foot". This really is the most natural way to say what you are trying to. | stackexchange-ell | {
"answer_score": 2,
"question_score": 0,
"tags": "sentence usage"
} |
Changing the StartPoint/EndPoint of a LinearGradient brush in Expression Blend UI
Seems like as really simple thing to do, but I just can't track it down in the help or online.
I know how to change the XAML to set the StartPoint and EndPoint of a LinearGradient brush, but I don't know how you do it using the IDE in Expression Blend - does anyone know the keyboard/mouse actions that you use to do this? | 1. Select the object that you want to modify in the art pane
2. Select the Brush you want to modify in the Brushes properties group
3. Select the Brush Transform tool (it's the arrow that is the 7th from the top) on the left.
4. Drag the arrow head and arrow tail to modify the startpoint and endpoint. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "xaml, expression blend, lineargradientbrush"
} |
Load in `.vimrc` themes and plugins from custom locations
My home folder is loaded dynamically from a a network. I want to keep some configuration files like for vim, in a different location.
I want to do this because I can have the same user on different machines, but each computer can have different settings, in some cases missing for example plugins.
I have a symbolic link from `.vimrc` in home folder to a file in another location.
In `.vimrc` I have added settings for plugins, themes. I don't want to create symlinks also pentru `.vim`, .`viminfo` from home to other location.
How can I set in `.vimrc` the paths for them and plugins ? | Wouldn't this answer work? <
$> env VIMINIT=/home/user/.vimrc VIMRUNTIME=/home/user/.vim/ vim
$> VIMINIT='let $MYVIMRC = expand('\''~user'\'') . '\''/.vimrc'\''|source $MYVIMRC' vim -c 'set runtimepath=~user/.vim,/var/lib/vim/addons,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,/var/lib/vim/addons/after,~user/.vim/after' | stackexchange-unix | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, vim"
} |
Radio Novella about rescuing stranded astronaut
I was listening to the radio recently and happened upon part of what appeared to be a radio novella or short story. It involved attempts to rescue an astronaut named McMillan, who was trapped in orbit.
Details I remember are:
* The astronaut had been trapped for at least 20 days
* The astronaut held the rank of Lieutenant, and some of the story was from the perspective of a General
* While the people on Earth could listen to the astronaut over his comms, the only way he knew they were coming was when they turned all the lights in Kansas City on and off in 2-second intervals to signal him
* At some point in the rescue attempt, the previously assumed 6-hour window between the rescue and the astronaut running out of oxygen is revealed to be only a few minutes
* At least part of the rescue ship is nuclear-powered | I'm going to propose an adaption of "The Cave of Night" by James Gunn. It was adapted as part of the radio series, "X Minus One". There may be other adaptions.
The stranded astronaut is Reverdy L. "Rev" McMillen, III, 1st Lt. (USAF), as detailed in Wikipedia's List of fictional astronauts.
The rescue ship is captained by Frank Pickrell.
The X Minus One adaption is available on archive.org. | stackexchange-scifi | {
"answer_score": 7,
"question_score": 9,
"tags": "story identification"
} |
PostgreSQL user defined type member compare
I have the following table definition:
CREATE TYPE product_limit_type AS (
product_code varchar(5),
limit_type varchar(30),
limit_value numeric(4,0)
);
CREATE TABLE rule_locks (
session_id bigint,
rule_id bigint,
product_limit product_limit_type
);
When I execute the following query:
DELETE FROM rule_locks
WHERE (session_id=session_id_ AND product_limit.product_code=product_code_);
I get this error from the server:
ERROR: missing FROM-clause entry for table "product_limit"
LINE 1: ...FROM rule_locks WHERE (session_id=session_id_ AND product_li...
^
`session_id_` and `product_code_` are pre-initialized variables of corresponding types.
How is it supposed to erase/modify a row, whose cell member variable satisfies given condition? | There should be parentheses around the field's name to access its subfields, as in:
DELETE FROM rule_locks WHERE (session_id=session_id_
AND (product_limit).product_code=product_code_);
See Accessing Composite Types in the documentation. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "postgresql, plpgsql, composite types"
} |
Is it possible to use private project templates with Leiningen
We use S3 wagon private to host our own private Maven repo in AWS S3. I'd like to do the same with a Leiningen project template, but I haven't been able to work out how to tell Leiningen to pull the template from S3 when running `lein new <tmpl> <proj>`. Is this even possible? | It seems this capacity has been added to Leiningen 22 days ago.
See issue1510 on Leiningen's github. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "clojure, amazon s3, leiningen"
} |
How can I make Apple menu shortcut keys work more like Windows?
I recently converted from Windows to Mac, but one thing that I really liked on Windows was how easy it was to traverse the menu bar and the associated submenus with the keys. Effectively, I would push the magic menu button and then type letters corresponding to menu options. With Mac the analog is an awkward button combination followed by repetitively hitting up, down, left, and right.
So, is there any way to make my Mac behave like a Windows computer in this respect? | It works pretty much as you describe Windows.
If you want a better key combo to access the menu bar, you can customize it under `System Prefs > Keyboard > Keyboard Shortcuts > Keyboard & Text Input > Move focus to the menu bar`.
Then type to select which menu you want, hit enter, then type to select the menu item.
Note that most menu items have keyboard shortcuts. These are written next to the menu item, often a single character preceded by the `CMD` key. | stackexchange-apple | {
"answer_score": 3,
"question_score": 4,
"tags": "keyboard, menu bar"
} |
Initialization discards qualifiers from pointer target type
I'm trying to print the list of a singly linked list that I referred to in link text. It works, but I do get the compiler warnings:
> `Initialization discards qualifiers from pointer target type`
(on declaration of start = head) and
> `return discards qualifiers from pointer target type`
(on return statement) in this code:
/* Prints singly linked list and returns head pointer */
LIST *PrintList(const LIST *head)
{
LIST *start = head;
for (; start != NULL; start = start->next)
printf("%15s %d ea\n", head->str, head->count);
return head;
}
I am using XCode. Any thoughts? | It's this part:
LIST *start = head;
The parameter for the function is a pointer to a constant, `const LIST *head`; this means you cannot change what it is pointing to. However, the pointer above is to non-const; you could dereference it and change it.
It needs to be `const` as well:
const LIST *start = head;
The same applies to your return type.
* * *
All the compiler is saying is: "Hey, you said to the caller 'I won't change anything', but you're opening up opportunities for that." | stackexchange-stackoverflow | {
"answer_score": 87,
"question_score": 49,
"tags": "c, linked list"
} |
Order by (chained) column which can be null
I am currently encountering a problem with Hibernate where I create a HQL statement automatically which looks like
FROM table ORDER BY a.b ASC NULLS LAST
My intention was to order all entries by `a.b` and setting all entries where `a` or `b` is `NULL` to the end of the table. Hibernate does not complain about the statement, but just ignores all entries where `a` is `NULL` already. I experimented with setting:
FROM table ORDER BY NULLIF(a.b, NULL) ASC NULLS LAST
and again, Hibernate does not complain but again ignores all entries where `a` is `NULL`.
Thank you for your help! | Thank you for the answer, I found a different solution which was easier to implement. I now create a request as follows:
FROM table ORDER BY a ASC NULLS LAST, a.b ASC NULLS LAST
For me, this works for any dimensions of chains as long as these orders are ok. This is much easier for me to implement since the query is generated automatically. However, thank's for the advice. I tried it and your solution works fine as well but would require me to adjust my overall setup. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 5,
"tags": "hibernate, null, sql order by, hql"
} |
What are "spheres" in Neal Stephenson's "Anathem?"
In "Anathem," the avout (fraa and suur) used "spheres" to do various things. The spheres wered used as a tool to make life comfortable in most cases, but what are they exactly? How should I visualize them? Stephenson didn't really paint a clear picture of it.
**Amazon link to Anathem**
**Google Books preview of Anathem** | It is hard to describe a visual image of the spheres, simply because their forms were so malleable.
> The sphere is a porous membrane. Each pore is a little pump that can move air in or out. Like a self-inflating balloon. The spring constant - the stretchiness - of the membrane is controllable. If you turn the stretchiness way down (that is, make it stiff) and pump in lots of air, becomes a hard little pill.
You can also do the opposite, and make the membrane very stretchy, and or/remove most of the air.
So the sphere can look like anything from a small, hard ball, to a large, floppy disk, plus anything in between (in the passage that follows the above quote, fraa Erasmas makes his sphere into a flat mat, and then inflates it into an air bed between two and three feet in diameter).
In another reference, it can be shrunk to a size that fits easily in the palm of a hand. | stackexchange-scifi | {
"answer_score": 9,
"question_score": 13,
"tags": "anathem"
} |
How to subtract or add date from a variable?
I have a date in the variable `x=20170402`, getting this value from another file.
I want to modify this by adding/subtracting and save to new variable. How can i do this?
ex: if i subtract one day, `y=20170401`; two days, `y=20170331`
and it is GNU based. | With `GNU date` it can be done quite easily with its `-d` switch.
x=20170402
date -d "$x -1 days" "+%Y%m%d"
20170401
and for 2 days
date -d "$x - 2 days" "+%Y%m%d"
20170331 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "bash, shell, date"
} |
$T$-invariant Hamiltonians
If $T$ is time-reversal transformation $t\mapsto -t$, Why do $T$-invariant Bloch Hamiltonians obey $$H(-k) = T H(k) T^{-1}$$ and not $$H(k) = T H(k) T^{-1}$$ Somehow I understand the word "invariant" as being unchanged under a transformation. As the way an operator $O$ on a Hilbert space transforms as $O\mapsto P O P^{-1}$ where $P$ is the transformation, I don't see why it is usually the former and not the latter which you find in literature (for example Hasan and Kane 2010). | It is the total $H = \sum_k H_k$ invariant under time reversal | stackexchange-physics | {
"answer_score": 2,
"question_score": 1,
"tags": "quantum mechanics, solid state physics, symmetry, time reversal symmetry"
} |
preg_replace only replaces first occurrence then skips to next line
Got a problem where preg_replace only replaces the first match it finds then jumps to the next line and skips the remaining parts on the same line that I also want to be replaced.
What I do is that I read a CSS file that sometimes have multiple "url(media/pic.gif)" on a row and replace "media/pic.gif" (the file is then saved as a copy with the replaced parts). The content of the CSS file is put into the variable $resource_content:
$resource_content = preg_replace('#(url\((\'|")?)(.*)((\'|")?\))#i', '${1}'.url::base(FALSE).'${3}'.'${4}', $resource_content);
Does anyone know a solution for why it only replaces the first match per line? | Try:
$resource_content = preg_replace('#(url\((\'|")?)(.*?)((\'|")?\))#i', '${1}'.url::base(FALSE).'${3}'.'${4}', $resource_content);
That will keep the `(.*)` term from matching "too much" content. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "php, regex, preg replace"
} |
Formatting a time as string
I wrote this easy JS timer and i have problem with `if` for minutes, it still writing in first sec 00:01, second sec 000:02...... If you understand me. Please can you help me? Thank you
var sec = 0;
var min = 0;
var time;
function timer() {
sec++;
if (sec < 10) {
sec = "0" + sec;
}
if (min < 10) { //here is problem I think
min = "0" + min;
}
if (sec == 60) {
sec = 0;
min++;
}
if (sec == 5) { //this is just a function test
document.getElementById("myForm").submit();
}
document.getElementById("myTimer").innerHTML = min + ":" + sec;
}
function start() {
time = setInterval("timer()", 1000);
} | Each time your function runs, it adds a zero to the beginning of `min`, which is a global variable. That's why it works the way it does.
You could use a temporary variable for holding the time as string.
var sec = 0;
var min = 0;
var time;
function timer() {
sec++;
var minStr = (min < 10) ? '0' + min : '' + min;
var secStr = (sec < 10) ? '0' + sec : '' + sec;
document.getElementById("myTimer").innerHTML = minStr + ":" + secStr;
}
function start() {
time = setInterval("timer()", 1000);
}
start();
<div id="myTimer"></div> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, timer, setinterval"
} |
Two asymmetric matrices - multiplying
I don't understand why the Wolfram's result of multiplication of matrices
Wolfram said:
$ \begin{vmatrix} \ 0.405875 & 0.496625 & 0.0975\\\ \ 0.395413 & 0.4946 & 0.109988\\\ \ 0.386671 & 0.492879 & 0.12045\ \end{vmatrix} * \begin{vmatrix} \ 1 & 0 & 0 \end{vmatrix} = \begin{vmatrix} \ 0.405875 & 0.395413 & 0.386671 \end{vmatrix} $
But some friends said:
$ \begin{vmatrix} \ 0.405875 & 0.496625 & 0.0975\\\ \ 0.395413 & 0.4946 & 0.109988\\\ \ 0.386671 & 0.492879 & 0.12045\ \end{vmatrix} * \begin{vmatrix} \ 1 & 0 & 0 \end{vmatrix} = \begin{vmatrix} \ 0.405875 & 0.496625 & 0.0975 \end{vmatrix} $
What is right and why? | It is the difference between right multiplication and left multiplication of vector. $$ \begin{pmatrix} 0.405875 & 0.496625 & 0.0975 \\\ 0.395413 & 0.4946 & 0.109988 \\\ 0.386671 & 0.492879 & 0.12045 \end{pmatrix} \begin{pmatrix} 1 \\\ 0 \\\ 0 \end{pmatrix} = \begin{pmatrix} 0.405875 \\\ 0.395413 \\\ 0.386671 \end{pmatrix} $$
$$ \begin{pmatrix} 1 & 0 & 0 \end{pmatrix} \begin{pmatrix} 0.405875 & 0.496625 & 0.0975 \\\ 0.395413 & 0.4946 & 0.109988 \\\ 0.386671 & 0.492879 & 0.12045 \end{pmatrix} = \begin{pmatrix} 0.405875 & 0.496625 & 0.0975 \end{pmatrix} $$ | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "matrices"
} |
Dynamically load dataframe using a for-loop in PySpark
I am trying to dynamically load some data into dataframe in pyspark. I want to pass in a bunch of table names and iteratively load them and name the dataframes as in the list.
Here's what I have tried:
rel_path = 'some/path/'
tables = ['a', 'b', 'c', 'd', 'e', 'f']
for table in candidate_tables:
table_path = rel_path + table + '/*'
table = spark.read.parquet(table_path)
>>> table
I found that I was only able to read the first table (a) and the table name is 'table'. Is it even possible to do it this way or just stick back to loading one by one? | It's not a good practice to create dynamic number of tables in the global environment. The easiest solution is to use a dictionary to hold all your tables:
rel_path = 'some/path/'
names = ['a', 'b', 'c', 'd', 'e', 'f']
tables = {}
for name in names:
table_path = rel_path + name + '/*'
tables[name] = spark.read.parquet(table_path)
Then you can access your table via `table['a'], table['b']` etc. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python 3.x, dataframe, for loop, pyspark"
} |
Connecting to Azure DB from SQL management studio is failing MSSQLSERVER_10060
I'm trying to connect to the sql server that has been created on Azure using SQL management studio, but i'm getting the following error.
 (Microsoft SQL Server, Error: 10060)
I have enabled the client IP in the SQL server firewall settings.
Please let me know if anything else need to be taken cared. Thank you | To resolve this error, try one of the following actions:
* Make sure that you have configured the firewall on the computer to allow this instance of SQL Server to accept connections. That is, If you are trying to connect from within a corporate network, outbound traffic over port 1433 may not be allowed by your network's firewall. If so, you cannot connect to your Azure SQL Database server unless your IT department opens port 1433. On the Azure Side, you also need to check if the NSG (associated with that subnet the Azure SQL server sitting in) allows the client IP with the specific port 1433.
* Add the client IP in the SQL server firewall settings if you enable a server-level firewall.
* Telnet the current IP of your Azure SQL Database server with the port to verify the network connection. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 9,
"tags": "sql server, azure"
} |
Como adicionar uma foreign key em uma tabela já criada
Sou iniciante em mysql e não consigo adicionar uma fk em uma tabela que criei. Tenho duas tabelas (pessoa, objeto) e desejo criar uma 'fk_pessoa' em objeto que receba o valor do atributo 'id' de pessoa. As tabelas já estão configuradas para usar a engine InnoDB. Tenho digitado o seguinte:
ALTER TABLE objeto ADD CONSTRAINT fk_pessoa FOREIGN KEY(id) REFERENCES pessoa (id);
Então me retorna isso:
> ERROR 1072 (42000): Key column 'id' doesn't exist in table
Tentei seguir o padrão desse vídeo: < "Creating Tables in MySQL 5 with Foreign Keys"
e também tentei seguir o exemplo do devmedia <
Minha tabela objeto está assim:
id_objeto int(4) PRIMARY KEY auto_increment
fk_pessoa int(4) NOT NULL
Minha tabela pessoa está assim:
id int(4) PRIMARY KEY auto_increment
Desde já agradeço | Resolvido - A primary key da tabela 'pessoa' estava como 'unsigned' então houve uma incompatibilidade de tipo de dados. Porém pude sanar muitas dúvidas a respeito de chave-estrangeira, então agradeço profundamente! | stackexchange-pt_stackoverflow | {
"answer_score": 6,
"question_score": 7,
"tags": "mysql, chave estrangeira"
} |
Search engine on top of Nexus maven repository manager
We use Nexus as our maven repository manager, and while it does have a built in search/browse capabilities, it can be a little clunky to use. Is there a way to put an external search engine on top of the Nexus repository, such as the one the maven central repository uses (< so it's a little easier to search/browse? Or is that a custom search engine for the Maven central repo only? | The search for Central is custom. What is the problem with the search in Nexus you are having?
In the extreme case you can implement your own indexer in a custom Nexus plugin and extend the search to work with it.
Or if you really want to create your own user interface you can access all the information from Nexus via the REST API and write your own search app. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "maven, search, repository, nexus"
} |
Table ordering Cucumber Capybara
I'm writing some tests for a web app, I'm still pretty new to this Cucumber Capybara.
I've got a table of data on screen which can be ordered ascending/descending by clicking on the column header.
I've created a hash out of the headers using:
table_head = find('#clickable-rows > thead')
headers = Hash.new(table_head)
In total there are seven headers on the table, I'd like to click on any of them by referencing the index (0 - 6).
I've tried
find(headers[0]).click
All of the other click commands referencing the header in that way and I keep getting the error:
Selenium::WebDriver::Error::InvalidSelectorError: invalid selector: An invalid or illegal selector was specified
I'm clearly missing a trick here, does anyone have a solution or better way to do this? I thought hashing would be the most suitable.
Thanks | `headers` is not likely what you expect. Unless I am missing something, it will be an empty `Hash`. Given you just want to click one of the column headers by index, you just need to locate the element and click it. There should not be a need to create a `Hash`.
Assuming that the clickable part of the column headers are links, the following returns all of the header elements:
column_headers = all('#clickable-rows > thead a')
You can then click one based on its position:
column_headers[0].click | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "cucumber, capybara"
} |
show div only on POST requests via ajax global events
i have ajax global events to show overlay on every ajax hit on document, it look somthing like:
$(document).ajaxSend(function (e, jqXHR) {
//show the loading div here
$('#DivProgressBar').show(); //if ajax is Post only
});
$(document).ajaxComplete(function (e, jqXHR) {
//remove the div here
$('#DivProgressBar').hide(); //if ajax is Post only
});
Now i want that this overlay should only work for post requests only and not for get requests. Can i modify my current jquery code to achive this?
Thanks. | jQuery(element).ajaxComplete(function(event, request, settings) {
alert(settings.type);
});
Found that in this answer: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, ajax"
} |
Number of ways to form committee of 5 people
I am trying to solve the following problem on combinations:
> You wish to select five persons from seven men and six women to form a committee that includes at least three men.
>
> a. In how many ways can you form the committee?
>
> b. If you randomly choose five persons to form the committee, what is the probability that you will get a committee with at least three men?
My attempt:
a) Number of ways = $ C(7,3) * C(10,2) = 1575 $
b) Sample space = $ C(13,5) = 1287 $
Now the working for (b) looks pretty strange because the probability will be $ \frac{1575}{1287} > 1 $ which is definitely incorrect. Can anyone please advise me what is wrong here? | (a) is incorrect, because you count some selections of men twice. For example, picking the first five men is counted in:
* I first pick the first three men, then the fourth and fifth
* I first pick men 1,2,4, then 3,5
* I first pick 1,2,5, then 3,4
and so on. So, basically, in your solution to (a), you made a distinction between "men chosen as one of the first three" and "men chosen as one of the final two", a distinction that doesn't really exist.
So your answer for (a) is not correct. I suggest just summing the numbers for a commitee with _exactly_ three, four or five men. | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "probability, combinations"
} |
Composite Attribute
Is there any way of making a composite attribute in C# to provide equivalent metadata at compile time?
E.g, change:
[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("MyProgId")]
[MyMefExport("MyProgId")]
public class MyClass
{
}
To:
[MyCompositeAttribute("MyProgId")]
public class MyClass
{
} | Attributes in and of themselves are meaningless. It is the code that enumerates the attributes attached to a class that may change its operation.
If you control the code that understands the attribute, you could create a composite attribute and act as though multiple separate attributes were applied.
That being said, I doubt you control ProgId nor the C# compiler that interprets it... | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 6,
"tags": "c#, .net, reflection, attributes"
} |
Zipping arrays with every n-th element
Is there a way to use `zip` in such a way that 2 arrays will be zipped with spaces between n-elements such as:
a = [1,2,3,4,5,6,7,8,9,10]
b = ["x","y","z"]
n = 3
the result will be
res = [[1,"x"],2,3,[4,"y"],5,6,[7,"z"],8,9,10] # note that 10 is alone and b is not cycled | I'd write:
res = a.each_slice(n).zip(b).flat_map do |xs, y|
y ? [[xs.first, y], *xs.drop(1)] : xs
end
#=> [[1, "x"], 2, 3, [4, "y"], 5, 6, [7, "z"], 8, 9, 10] | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "ruby, arrays"
} |
How to limit the mysql records on the basis of a column value?
I want to limit the records on the basis of usernames(column) in my table i.e if my limit is 5 then fetch all the records of the first 5 usernames only. There can be multiple records for any usernames. I also want to be able to use the concept of offset so that next time I can fetch other 5 records. | See the following :
SELECT * FROM table
WHERE username IN (SELECT DISTINCT username FROM table ORDER BY username LIMIT 5 OFFSET 0)
Then later with offset :
SELECT * FROM table
WHERE username IN (SELECT DISTINCT username FROM table ORDER BY username LIMIT 5 OFFSET 5)
etc.
Of course you could add an order by for the main query like "ORDER BY username" if you want to sort the final results. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, sql, database"
} |
Contar elementos na tela
Gostaria de saber se há a possibilidade de eu contar os elementos na tela, por exemplo uma função que listasse a quantidade de `<li>` dispostos na minha página web.
Como eu poderia fazer isto? E como funcionaria está função? | Podes fazer isso assim:
function contar(what){
return document.querySelectorAll(what).length;
}
Por exemplo nesta página usando `contar('li')` dá 92. Com esta função podes passar um seletor de CSS como `ul li.nome` que também funciona.
Exemplo: < | stackexchange-pt_stackoverflow | {
"answer_score": 10,
"question_score": 9,
"tags": "javascript, html, aplicação web"
} |
How to remove the cancel button from the billing address edit form?
As per the title, how do I remove the cancel button from the billing address edit form ?
The button is highlighted on the screenshot attached bellow.
 to boot automatically to the GRUB menu without requiring me to hold **Option** and select the "Windows" partition at each boot. Since there is actually no Windows installation on my computer, I can't access the Boot Camp Assistant to tell OS X to boot to the Windows partition by default. | In OS X there is the Startup Drive section in System Preferences. Ideally you should be able to select Ubuntu as the default drive there. I wasn't able to, I just set refit to only show up for one second in the config file (not difficult to do). I only see refit for a split second so it doesn't really bother me.
Also if you only want to use GRUB, I'm assuming you still want access to OS X. Without chainloading GRUB you can't boot directly into OS X from the grub menu. The option is there but it won't work properly, so that's another reason to see refit for a second at bootup. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 0,
"tags": "grub2, macbook, refit"
} |
Problem with hired freelance editor
I am not a native English speaker and hired an editor to correct the style of a book that is being published. However, this editor didn't work in the final version of the manuscript I sent but rather on an old draft I had sent for a quotation. Additionally, the returned manuscript had many added typos (at least 20 in one chapter).
Since the editing was done it an old version, it is now completely useless to me. How should I handle this? Should I pay for work that wasn't even what I requested?
Is it normal for an editor leave typos and expect for a proofreader to fix them? | I would talk to them about it. Just be friendly. Let them know that the wrong file was edited. See what they have to say. Were both files sent in the same email / however you sent it? If it wasn't clear which was to be edited, that may be on you. If you were very clear about which was to be edited, they might offer to look at it again. Could just be a simple mistake. Give them the chance to offer a second look.
'Light editing' usually is for content editing. It looks at a broader picture. e.g. Does the narrative flow? Are there plot inconsistencies? Does each chapter have a purpose? Did you start off with a character and then forget about them halfway through?
Proofreading is a separate style of editing and is often charged separately by editors. They will focus on the grammar, spelling, spacing, etc. When you get a contract for this service, they usually won't make notes / corrections to your content. | stackexchange-writers | {
"answer_score": 1,
"question_score": 2,
"tags": "publishing, editing"
} |
proving that $89 \mid 2^{44}-1$
i tried to prove that $2^{44} \equiv 1\pmod{89}$.
I noticed that by Fermat's little theorem $2^{88} \equiv 2^{44}\cdot 2^{44} \equiv 1\pmod{89}$ which means that $2^{44}$ is the inverse of itself $\rightarrow 2^{44} \equiv 1 \pmod{89}$ or $2^{44}\equiv 88 \pmod{89}$.
how can I rule out the second option? | You have $2^{11}= 2048 \equiv 1 \pmod {89} $. Hence, $$2^{44}=(2^{11})^4 \equiv 1 \pmod {89} $$ | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "elementary number theory, modular arithmetic"
} |
How to create one uwsgi log file per day?
I use uwsgi with the parameter --daemonize /logs/uwsgi.log
This file is however becoming large and I would like to split it into smaller pieces. One per day would be preferable. I have done that for nginx where it was easy to specify the log file name using date variables. Is it possible to do the same for uwsgi?
Something like:
[uwsgi]
daemonize=/logs/uwsgi-$year-$month-$day.log
Or is there another way to get the same result, without too much involvement of other processes? | uWSGI by itself can only "split by size", with the --log-maxsize option.
Time-based approaches are using classic logrotate or apache rotatelogs (< that you can combine with uWSGI logpipe plugin.
Finally you can have an nginx like behaviour triggering a reload at midnight of the uWSGI instance (you can even use the embedded cron facility):
[uwsgi]
daemonize = /logs/uwsgi-@(exec://date +%%Y-%%m-%%d).log
log-reopen = true | stackexchange-stackoverflow | {
"answer_score": 20,
"question_score": 11,
"tags": "logging, uwsgi, log rotation"
} |
Can one partially serialize an object using Protobuf-net?
I would like to be able to update objects by serializing/deserializing only the field that changed. I am using the nongeneric version of the serializer since I don't know the type at compile. At runtime, I do have the type though.
Locally I want to do something like:
var existingObject.SomeField = 10;
// Say I only want to serialize field B
byte[] serializedField = SerializeField(existingObject, "SomeField")
Remotely I would deserialize and create a new object:
Merge(serializedField, existingObject);
There does not seem to be a way to do this using the NonGeneric interface? | You have a couple of options there.
If your type internally knows what has changed, you can use the same pattern as XmlSerializer (IIRC), I.e.
[ProtoMember(12)]
public string Foo {get;set;}
public bool ShouldSerializeFoo() {
return ... true if Foo is dirty
}
Second option would be to create the model on the fly, and only tell it about the members that are changed. However, since by default this would cause (over time) lots of dynamic code to be generated, so you might want to set AutoCompile to fse for that case.
A third option would be to serialize manually via ProtoWriter. This probably needs more protobuf know-how than is desirable. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "protobuf net"
} |
A problem on four kissing circles (Descartes Theorem)
Two circles $C_1$ and $C_2$ with radius $r_1$ and $r_2$ touching each other externally and both touching circle $C_3$ with radius $r_1+r_2$ internally. If another circle with radius $r_3$ touches all three circles such that $r_1, r_2, r_3$ are in $A.P.$ and $r_1\gt r_2 \gt r_3$ find $$\frac{r_1}{r_2}$$
I tried applying the Descartes' theorem but the equation so formed seemed to be nearly unsolvable. Any new method or improvement in the method of Descartes theorem is appreciated. | Say $r_1 = k r_2$, so $r_3 = (2-k) r_2$. Observe first that the centres of $C_1$, $C_2$ and $C_3$ lie on a straight line, by considering the radii of each, so our diagram looks like this, where $D$ is the centre of $C_3$ r_2$, and $CD= r_1 + r_2 - r_1 = r_2$. In particular, we know every length inside the triangle in terms of $r_2 $and $k$. Apply Stewart's Theorem and cancel $r_2^3$ to give $(k+1)k + (2k-1)^2 (k+1) = 4k + (3-k)^2$, which simplifies to $k^3 = 2$, so $k = \sqrt[3]{2} = \frac{r_1}{r_2}$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "geometry, trigonometry, algebraic geometry, euclidean geometry, circles"
} |
Swift - accessing nil does not crash
I noticed a strange behavior in swift. The following code will print "Not found" as one would expect.
import Cocoa
var array = [["one":"1"]]
for element in array {
if let check = element["two"] {
print(check)
} else {
print("Not found")
}
}
Slightly changing the code to
import Cocoa
var array : [AnyObject]?
array = [["one":"1"]]
for element in array! {
if let check = element["two"] {
print(check)
} else {
print("Not found")
}
}
will print "nil" - that's not what I was expecting as I thought in swift a nil is a "not set" and not a printable object.
Is there something i'm missing? Thanks! | In the second case, you're actually creating a nested optional, which is generally not a good idea (it only leads to confusion, and I don't know why the compiler allows it frankly). If you put in the line:
let foo = element["two"]
and inspect `foo`'s type, you'll see that it is `AnyObject?!`. So it's an optional with no value wrapped in an optional. This has the effect of making your `if/let` statement unwrap the first optional to give you a second optional, which is `nil`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "arrays, swift, cocoa, null"
} |
C++11 compiler error when using decltype(var) followed by internal type of "var"
I'm using Visual C++ 2010, and here's my code snippet:
std::set<int> s;
decltype(s)::value_type param = 0;
I got the following error message, anyone can help me?
> error C2039: 'value_type' : is not a member of '`global namespace''
> error C2146: syntax error : missing ';' before identifier 'param' | This is a Visual Studio bug that was raised last year on Connect. It is issue 757545 ("Cannot use decltype before scope operator").
The issue has a workaround listed alongside it that is effectively the same as @iammillind's, except it uses `std::identity` that was removed from `<functional>` shortly prior to the publication of C++11, for whatever reason. (`std::common_type` with one template parameter is equivalent; `std::remove_reference` is the same in some cases.) | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 9,
"tags": "c++, visual studio 2010, c++11, compiler errors, decltype"
} |
How to create a mat from bits in opencv for java?
can somebody explain how to create a binary mat with values from a bitstring?
For example, I want to create my Mat from bitstrings `11110000`and `01010101`, so I have a mat object with 2 rows and 1 colum.
For this I initialize the mat-object with `Mat mat = new Mat(2,1,CvType.CV_8UC1);`
Can I convert these strings to a byte array and use `mat.put(0,0,bytearray)` or is there something else that I must conside?
Later I want to use this approach to create my own `binary descriptor` that can compare wth other descriptors, extracted by `ÒRB`. With `norm(descA,descB,NORM_HAMMING)`
thank you and best regards | You can use `Byte.parseByte()` with a `radix` of 2 e.g `byte b = Byte.parseByte(str, 2);` to first convert it to `byte` and then create a byte array and then covert it to `Mat` object as below:
Mat mat = Imgcodecs.imdecode(new MatOfByte(byteArray), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "java, opencv, feature descriptor"
} |
Reading UTF-8 characters from console
I'm trying to read UTF-8 encoded polish characters from console for my c++ application. I'm sure that console uses this code page (checked in properties). What I have already tried:
* Using cin - instead of "zażółć" I read "za\0\0\0\0"
* Using wcin - instead of "zażółć" - same result as with cin
* Using scanf - instead of 'zażółć\0' I read 'za\0\0\0\0\0'
* Using wscanf - same result as with scanf
* Using getchar to read characters one by one - same result as with scanf
On the beginning of the main function I have following lines:
setlocale(LC_ALL, "PL_pl.UTF-8");
SetConsoleOutputCP(CP_UTF8);
SetConsoleCP(CP_UTF8);
I would be really greatful for help. | Here is the trick I use for UTF-8 support. The result is multibyte string which could be then used elsewhere:
#include <cstdio>
#include <windows.h>
#define MAX_INPUT_LENGTH 255
int main()
{
SetConsoleOutputCP(CP_UTF8);
SetConsoleCP(CP_UTF8);
wchar_t wstr[MAX_INPUT_LENGTH];
char mb_str[MAX_INPUT_LENGTH * 3 + 1];
unsigned long read;
void *con = GetStdHandle(STD_INPUT_HANDLE);
ReadConsole(con, wstr, MAX_INPUT_LENGTH, &read, NULL);
int size = WideCharToMultiByte(CP_UTF8, 0, wstr, read, mb_str, sizeof(mb_str), NULL, NULL);
mb_str[size] = 0;
std::printf("ENTERED: %s\n", mb_str);
return 0;
}
Should look like this:
 * (2/4) * (1/3) * 1 = 0.1$$
(first pick three non-special ones, then there is only special ones left). With the same logic, the probability of observing $2$ special balls would be
$$(3/5) * (2/4) * (2/3) * (1/2) = 0.1$$
which doesn't make sense to me (first pick two non-special, then two special). I don't see why the probability could be the same for observing $1$ or $2$ special ones.
How do I solve this problem? | Here, the number of special balls you draw, say $X$, is distributed according to hypergeometric distribution. And, according to its PMF definition, we have $$P(X=k)=\frac{{m\choose k}{n-m\choose p-k}}{{n \choose p}}$$
In the denominator, you count all possible $p$ drawings, and in the numerator you count all possible $k$ special drawings from $m$ balls together with the remaining $p-k$ possible non-special drawings from the remaining $n-m$ balls. | stackexchange-stats | {
"answer_score": 1,
"question_score": 3,
"tags": "probability, distributions, combinatorics, hypergeometric distribution"
} |
Embed custom SSDL in EF dll
As part of a project I'm working on we have a requirement to support Sql Server and Sql Server Compact. Now as it's only the two, I don't mind creating a custom ssdl generated via a T4 template from the default Sql Server one, which works fine. However, this does involve passing round the created file and referencing the path to it.
When it comes to deployment I'd like to embed that custom ssdl file into the dll directly, and preferably access it as you would with a standard ssdl, e.g. have res://*/Model.SqlServerCe.ssdl or something similar in a connection string.
I've tried messing around with the VS build actions and had a bit of a google but can't seem to find anything relevant to embedding custom extra metadata files into a single dll. Is this something anyone's come across before or know hows to do?
Thanks in advance. | Turns out I was being a bit silly, setting the ssdl to embed in the build actions, you can then access the embed resource via its fully qualified name, e.g. `res://*/<dll namespace>.Model.SqlServerCe.ssdl`, which I managed to find from doing a call Assembly.GetManifestResourceNames(). Obvious if you think about it, doh.
Thanks to Ladislav for making me look a little more closely. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, entity framework, dll, embed"
} |
Series Summation to calculate algorithm complexity
I have an algorithm, and I need to calculate its complexity. I'm close to the answer but I have a little math problem: what is the summation formula of the series
½(n4+n3) where the pattern of n is 1, 2, 4, 8, ... so the series becomes:
½(14+13) + ½(24+23) + ½(44+43) + ½(84+83) + ... | It might help to express n as 2^k for k=0,1,2...
Substitute that into your original formula to get terms of the form (16^k + 8^k)/2.
You can break this up into two separate sums (one with base 16 and one with base 8), each of which is a geometric series.
S1 = 1/2(16^0 + 16^1 + 16^2 + ...)
S2 = 1/2(8^0 + 8^1 + 8^2 + ...)
The J-th partial sum of a geometric series is a(1-r^J)/(1-r) where a is the initial value and r the ratio between successive terms. For S1, a=1/2, r=16. For S2, a=1/2, r=8.
Multiply it out and I believe you will find that the sum of the first J terms is O(16^J). | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "algorithm, math, complexity theory"
} |
How can I copy text from xfce4 terminal emulator to the clipboard?
I want to be able to select certain text with mouse to copy and paste it to the commandline. The "select" and "paste from clipboard/primary selection" part works, but I am unable to copy the selection to the clipboard (verified with `xsel`).
So far I have tried:
* selection (I think it had been working some time ago),
* `Ctrl`+`Shift`+`C`
* RMB/Copy
* Edit/Copy
I use Ubuntu server 14.04.4 and xfce4-terminal 0.6.3
MMB, Shift-Insert and `Ctrl`+`Shift`+`V` works when I populate the clipboard from elsewhere.
The answers to the 4 years old question Why can't I copy text from the Ubuntu Terminal? were not helpful. | You can use `clipman` to sync selections and paste it anywhere using the middle click of your mouse. Just, select some text, open the terminal, and press the middle click. You can play with the options to adjust it to your preferences. To install clipman, use:
sudo apt-get install xfce4-clipman
Or, if you prefer, install the complete set of utilities for XFCE, using:
sudo apt-get install xfce4-goodies | stackexchange-askubuntu | {
"answer_score": 9,
"question_score": 10,
"tags": "command line, xfce, clipboard, copy, xfce4 terminal"
} |
Suppress compiler warnings using aspnet_compiler at the command line
Is there a switch to suppress specific compiler warnings when using the aspnet_compiler.exe warnings at the command line?
I've tried fixing the errors myself, rather than ignoring them - they are for events that are defined by never used. I simply commented out the events, but this caused other problems! It's as if they are used but the compiler doesn't recognise that (which seems unlikely).
I'm calling the compiler from the command line, and I'm using Visual Web Developer Express, which does not have the detailed build options in the Project Properties Build dialog that can be found in the full version of Visual Studio. | In the end I used
#pragma warning disable [warning no]
some code that triggers a warning
#pragma warning enable [warning no]
in my code, as per < This works fine and although needs entering once for each compiler warning, it seems to be the best fit. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "c#, .net, aspnet compiler"
} |
Using Capybara w/ Selenium, how would I click a table row?
Would simply like to know if there's an alternative to click_link / click_button that can be used with any element as some of my clickable elements are not standard html clickables such as tr elements, but they still contain href attributes.
Javascript enabled. | Use Javascript then:
page.execute_script("$('whatever_you_want').click()"); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "ruby on rails, selenium, capybara"
} |
How to achieve split look of the Android Honeycomb Gmail app?
I have searched quite extensively throught stackoverflow but unfortunately found no conclusive answer to my question.
I simply wish to achieve the look of the view positioning similar to the Gmail app on Honeycomb tablets (check the picture)
<
In my case there would be a list of employees on the left side and, after clicking on one of them, data about them would appear on the right side of the screen as in the Gmail app. Both views would preferably be scrollable.
From which angle should I be approaching this?
UPDATE: After googling the issue for a bit I think Fragments may be the key. Am I right? | You're right, fragments are the key.
If you create a layout containing two LinearLayouts in the horizontal alignment, you can fill these with two seperate `Fragments`, creating the look you're looking for.
For an example check this example from the SDK. It also contains a list which opens an image in the other fragment when you select an item in the list. Of course you can also use this to show an employee as you want. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, listview, layout, gmail, android 3.0 honeycomb"
} |
How to change the ipython notebook format?
I want to change ipython notebook font type and color theme . How can I do that ? | I invite you to read this and follow the links to next post that show you how to make a theme selector for dev version. There are also a few links on interesting theme for the notebook, as well as explanation at what won't work in next release.
In short, use `custom.css` in your profile if you have a recent enough version. Other methods will be deprecated soon enough. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "ipython"
} |
When to use Map and when to use Array/List?
I am quite new to flutter and in my tutorial I've learnt to use Maps and Arrays. I know that a Map is pretty much an array but things are identified by a key. When should I be using Maps and when should I be using Arrays? Can you please provide some real examples? Thank you very much! | When you want to store data in key and values then used Map. eg. contact list. In that, you can store a person's name as a key and phone no as a value.
The array used for only similar data types. we can not store data of multiple data types in the array. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "arrays, flutter, dictionary, dart"
} |
Where can I find a comparison between TFS and VSTS Reporting abilities?
I've read that TFS supports SSRS and VSTS supports Power BI but I have not found any meaningful comparison on the actual reports or their usefulness. Nor about which might have different or better dashboards. Anyone know of any? | A quick Google search shows up with this link for Dashboards and reports for VSTS and TFS. Shows Power BI, SSRS reports, and indicates which ones are exclusive to the platforms.
<
As for usefulness, that all depends on your organization and is a bit subjective because of how each org uses reports. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "reporting services, tfs, azure devops"
} |
Gcd of two number divides each other
(a) Prove that $\operatorname{gcd}(a, b) | \operatorname{gcd}\left(3 a+b, a^{3}\right)$
Since say $d = gcd(a,b)$ then $d|a$ and $d|b$ this will imply $d|(3a+b)$ and $d|a^3$ and therfore $d$ is divisor of those two.But how to show it is greatest common divisor. | One of the basic properties of $e = \gcd(f,g)$ is that if $d \mid f$ and $d \mid g$, then $d$ is a common divisor, so it must also divide the greatest common divisor, i.e., $d \mid e$. As shown in the answer of if $p\mid a$ and $p\mid b$ then $p\mid \gcd(a,b)$, its definition #$1$ uses this explicitly, with a second definition being provable using Bezout's lemma (basically, if $d = \gcd(a,b)$, then $ax + by = d$ for some integers $x,y$, so if $e \mid a$ and $e \mid b$, then $e \mid ax + by = d$). You can also use the Fundamental theorem of arithmetic to show this using prime factorizations, but I won't go into details about that here.
With this concept, you've basically proven what you're asking to show, i.e., with $d = \gcd(a,b)$, then $d \mid 3a + b$ and $d \mid a^3$, so $\gcd(a,b) \mid \gcd(3a + b, a^3)$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "number theory, elementary number theory, gcd and lcm"
} |
Switching from PHP to Rails Need Help translating URL shortener
Previous developers used source code from this website to create a URL shortener. I am essentially tasked with translating this piece of code into ruby:
function getIDFromShortenedURL1 ($string, $base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
$length = strlen($base);
$size = strlen($string) - 1;
$string = str_split($string);
$out = strpos($base, array_pop($string));
foreach($string as $i => $char)
{
$out += strpos($base, $char) * pow($length, $size - $i);
}
return $out;
}
I am new to ruby and any help would be much appreciated :) | Here's what basically amounts to a direct port of the PHP code.
def getIDFromShortenedURL1(string, base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
length = base.length # $length = strlen($base);
size = string.length - 1 # $size = strlen($string) - 1;
string = string.split '' # $string = str_split($string);
out = base.index string.pop # $out = strpos($base, array_pop($string));
string.each_with_index do |char, i| # foreach($string as $i => $char);
# $out += strpos($base, $char) * pow($length, $size - $i);
out << base.index(char) * (length ** (size - i))
end
out # return $out;
end
The code an the results of a very basic test (to make sure the functionality is equal) can be found at < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "php, ruby on rails, ruby, url shortener"
} |
How do I customize my kits between matches?
It doesn't seem like it's possible to customize your kit, except for when you are playing or in the main menu (i.e. not between matches). Or am I missing something? | It's currently impossible to change any settings outside of a match. This includes kits.
However it's a highly requested feature to let us customize kits on Battlelog, and a DICE employee has stated that they're going to look into it, however that doesn't mean it's going to happen. | stackexchange-gaming | {
"answer_score": 9,
"question_score": 4,
"tags": "battlefield 3"
} |
Substitute to MenuCompat.setShowAsAction() on Android
While searching for a way to show an option in the ActionBar and still be compatible with Honey I came across the MenuCompat.setShowAsAction() method from the compatibility library (< but it is deprecated and I can't find a substitute in the library to do the same thing. Any Ideas?
Thanks In Advance | If you read the JavaDocs for `setShowAsAction()` on `MenuCompat` at the page you linked to above, you will find your answer:
> Use MenuItemCompat.setShowAsAction(MenuItem, int) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "android, android actionbar, compatibility"
} |
Why does Utf8Helper::setCollatorLanguage always return false?
enter image description hereWhy does the fuction `Utf8Helper::setCollatorLanguage` in arangodb sdk always return false?
It is at fault ERROR ERROR in the Collator: : createInstance < > : U_FILE_ACCESS_ERRORAnd It's lead to failed to initialise ICU; ICU_DATA= "F:\\\work_lc\\\arangodb-2.6\\\Build32\\\bin\\\\..\\\\\\\share\\\arangodb\\\";This project where to copy from others, it can be used, but i'm not,I just wonder what configuration file not produced | You need to make shure, ICU is able to load its locale database.
See our cookbook regarding windows compilation how to achieve this.
Please note that ArangoDB 2.6 is way out of date, and you should work with a more recent version.
More recent versions will also provide better error messages in such situations via the windows event log. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "arangodb"
} |
Show that the following function is primitive recursive
Let $f$ be a function defined by \begin{array}{l} f(0)=1;\quad f(1)=2;\quad f(2)=3;\quad f(n)=0 \mbox{, for $n>2$} \end{array}
How to show that $f$ is primitive recursive? | > **Proposition.** Let $g(x)$ be a primitive recursive function and $f(x) = g(x)$ for all but finitely many values of $x$. Then $f(x)$ is also a primitive recursive function.
_Proof._ Let $\\{a_1, \dots, a_n\\}$ be the set $\\{x \mid f(x) \neq g(x)\\}$. Let $b_i = f(a_i), i = 1,\dots, n$. Then we can define $f(x)$ using $g(x)$ and other primitive recursive functions and substitution: $$f(x) = g(x)\cdot\mbox{sg}\left(|x-a_1|\cdot\ \dots\ \cdot |x-a_n|\right) + \sum_{i = 1}^n b_i\cdot\overline{\mbox{sg}}|x - a_i|,$$ where $$\mbox{sg}(x) = \begin{cases} 1, & \text{if } x \neq 0,\\\ 0, & \text{if } x = 0. \end{cases} \qquad \overline{\mbox{sg}}(x) = 1\ \dot{-}\ \mbox{sg}(x),$$ $$|x - y| = (x\ \dot{-}\ y) + (y\ \dot{-}\ x), \qquad x\ \dot{-}\ y = \max(x - y, 0).$$
Now apply this proposition with $g(x) \equiv 0$ and $\\{a_1, a_2, a_3\\} = \\{0, 1, 2\\}$ | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "computer science, computability"
} |
bar plot with stack and beside in r
Using base R I want to create a plot like this with two groups, one beside and other on the top.

green <- c(4,7,8)
blue <- c(4,7,2)
dark <- data.frame(brown=brown, green=green, blue=blue)
barplot( as.matrix(t(dark)), col = c("brown", "green", "blue"), beside = TRUE)
brownL <- c(3,1,2)
greenL <- c(2,2,4)
blueL <- c(3,2,1)
light <- data.frame(brownL =brownL, greenL =greenL, blueL =blueL)
barplot( as.matrix(t(light)), col = c("pink", "lightgreen", "lightblue"), add=TRUE)
Is there base R solution for this ? | Try this:
barplot( as.matrix(t(dark)), col = c("brown", "green", "blue"), beside = TRUE)
barplot( as.matrix(t(light)),col = c("pink", "lightgreen", "lightblue"), beside = TRUE, add=TRUE) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "r, bar chart"
} |
Rebuilding historical builds through TFS with version numbers
I have automatic build numbering setup, based on build date/name, using approach proposed by John Robbins from Wintellect described here. So the version/resource file is automatically created on build time but not checked-in.
I wonder how to approach a problem of rebuilding historical versions (based on labels) and having the original build number/name in them. Is it possible to detect 'GetVersion' parameter of MSBuild and try to recreate the original build name from it?
Is it a sane approach anyway? What alternatives do you see? | It's not easy to build a specific changeset (though possible, if you pass the changeset number into your build script and modify the "Get Latest" portion of the build).
However, one easier way of handling this is to create a branch of your code. You can branch at a specific date or changeset, which will create a copy of code from that point in time. Your build scripts can then be pointed at this code.
With respect to your versioning problem: you may find that the only sensible way to do this is to hardcode the required version number. My understanding of your version numbering strategy is that it doesn't relate to anything you can derive from the source (such as the changeset number, date, or file content), and it isn't checked in - so re-calculating it will be pretty complicated! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "tfs, msbuild"
} |
Is there a minimum spacing planted trees need to grow?
Does this game use the New Leaf rules? | No, it's not quite like New Leaf but back to that in a sec.
Yes, you need space all around the tree/sapling, as in it can't be up against a building, right next to the slope to the beach, or even on that peninsula jutting out to the right on the island. A tree that cannot grow in that spot will just remain a stunted sapling.
A good way to test whether a tree can grow in that spot is to dig up a sapling from elsewhere and try to plant it in the target spot (rather than planting the seed or fruit). The hole won't let you plant the sapling if it's a bad location.
But back to that New Leaf stuff, the weird issue of tree spacing (in which the tree in the middle of a group of trees wouldn't grow) has been resolved:
 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "android, ffmpeg, h.264, hevc"
} |
Is it possible to do ?view=q with javascript insteat of php?
<?php $view = $_REQUEST["view"];
$default_header="index-home.php";
switch ($view) {
case "voorwaarden":
include("index-voorwaarden.php");
break;
default:
include($default_header);
}
?>
Is there anyway to do this with javascript or jquery and ajax, so that the link won't change but goes to a different page like test.com and show home and when you click a link it stays on test.com but with completely different content
Thanks, Sake | here is the function to get or you can visit this question How can I get query string values in JavaScript?
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, php, jquery, html, ajax"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.