qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
6,734,128 | I am working on a script that develops certain strings of alphanumeric characters, separated by a dash `-`. I need to test the string to see if there are any sets of characters (the characters that lie in between the dashes) that are the same. If they are, I need to consolidate them. The repeating chars would always occur at the front in my case.
```
Examples:
KRS-KRS-454-L
would become:
KRS-454-L
DERP-DERP-545-P
would become:
DERP-545-P
``` | 2011/07/18 | [
"https://Stackoverflow.com/questions/6734128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36545/"
] | ```
<?php
$s = 'KRS-KRS-454-L';
echo preg_replace('/^(\w+)-(?=\1)/', '', $s);
?>
// KRS-454-L
```
This uses a *positive lookahead* `(?=...)` to check for repeated strings.
Note that `\w` also contains the underscore. If you want to limit to alphanumeric characters only, use `[a-zA-Z0-9]`.
Also, I've anchored with `^` as you've mentioned: *"The repeating chars would always occur at the front [...]"* | Use this regex `((?:[A-Z-])+)\1{1}` and replaced the matched string by $1.
`\1` is used in connection with `{1}` in the above regex. It will look for repeating instance of characters. |
2,328,287 | User has html-form, then user fills all field and data transferred to PHP script.
How do would data send, but not refresh html page? | 2010/02/24 | [
"https://Stackoverflow.com/questions/2328287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278221/"
] | `setTimeout` is the answer.
```
$(div).html('<script...> setTimeout(function() { window.location = url; },10); </script>');
```
Doesn't have this problem. It must have something to do with the way jQuery executes inline scripts (by creating a `script` tag in the `head` element). | You could use `window.location.assign(URL)`. |
9,876,732 | Let's say I have a table like:
```
Persons
FirstName varchar(50)
LastName varchar(50)
EmailAddress varchar(200)
```
Now, let's say I have a google like search box; in other words just one textbox with a search button.
Normally we do something like:
```
declare @searchTerm varchar(50)
set @searchTerm = 'tom'
select *
from Persons
where (FirstName = @searchTerm)
or (LastName = @searchTerm)
or (EmailAddress = @searchTerm)
```
What I'd like to do is be able to pass both the first and last name (for example) into the @searchTerm variable, but my brain just doesn't want to build that query. ;)
For example:
```
declare @searchTerm varchar(50)
set @searchTerm = 'tom smith'
select *
from Persons
where ????
```
The idea is to return all records where 'tom' OR 'smith' appear in those fields. | 2012/03/26 | [
"https://Stackoverflow.com/questions/9876732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2424/"
] | This is a really complex topic that has many subtle performance implications. You really need to read these excellent articles by Erland Sommarskog:
[Dynamic Search Conditions in T-SQL](http://www.sommarskog.se/dyn-search.html)
[The Curse and Blessings of Dynamic SQL](http://www.sommarskog.se/dynamic_sql.html)
Since there is no "one size fits all" query approach for this, there are subtle performance implications in how you do this. If you would like to go beyond just making the query return the proper answer, no matter how slow it is, look at this article: [Dynamic Search Conditions in T-SQL by Erland Sommarskog](http://www.sommarskog.se/dyn-search.html). It covers every method and gives PROs and Cons of each method in great detail.
If you can determine a min and a max possible range for your search column, and the search column is NOT NULL, then you can do better than the (@Search IS NULL OR Col=@Search), [see this area of the above linked article](http://www.sommarskog.se/dyn-search-2005.html#Umachandar). However you should read the entire article, there are so many variations that depend on your situation, you really need to learn multiple approaches and when to use them.
if you want to search on multiple terms within a single string parameter, you need to split that string.
You need to create a split function. This is how a split function can be used:
```
SELECT
*
FROM YourTable y
INNER JOIN dbo.yourSplitFunction(@Parameter) s ON y.ID=s.Value
```
[I prefer the number table approach to split a string in TSQL](http://www.sommarskog.se/arrays-in-sql-2005.html#tblnum) but there are numerous ways to split strings in SQL Server, see the previous link, which explains the PROs and CONs of each.
For the Numbers Table method to work, you need to do this one time table setup, which will create a table `Numbers` that contains rows from 1 to 10,000:
```
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
INTO Numbers
FROM sys.objects s1
CROSS JOIN sys.objects s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)
```
Once the Numbers table is set up, create this split function:
```
CREATE FUNCTION [dbo].[FN_ListToTable]
(
@SplitOn char(1) --REQUIRED, the character to split the @List string on
,@List varchar(8000)--REQUIRED, the list to split apart
)
RETURNS TABLE
AS
RETURN
(
----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT @SplitOn + @List + @SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = @SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''
);
GO
```
You can now easily split a CSV string into a table and join on it:
```
select * from dbo.FN_ListToTable(',','1,2,3,,,4,5,6777,,,')
```
OUTPUT:
```
ListValue
-----------------------
1
2
3
4
5
6777
(6 row(s) affected)
```
Your can use the multiple search criteria string like this:
```
DECLARE @Persons table (FirstName varchar(50) , LastName varchar(50), EmailAddress varchar(200) )
INSERT INTO @Persons VALUES ('aaa','bbb','ccc@ddd.eee')
INSERT INTO @Persons VALUES ('xxx','yyy','zzz@abbba.zzz')
INSERT INTO @Persons VALUES ('aaa','yyy','zzz@zzz.zzz')
INSERT INTO @Persons VALUES ('111','222','333@444.555')
declare @searchTerm varchar(50)
set @searchTerm = 'aaa bbb'
--this should use an index on FirstName and LastName if they exist, no index usage on EmailAddress
select
p.* --<<"*" isn't good, only list the columns you need
FROM @Persons p
INNER JOIN dbo.FN_ListToTable(' ',@searchTerm) b on p.FirstName=b.Listvalue
UNION
select
p.* --<<"*" isn't good, only list the columns you need
FROM @Persons p
INNER JOIN dbo.FN_ListToTable(' ',@searchTerm) b on p.LastName=b.Listvalue
UNION
select
p.* --<<"*" isn't good, only list the columns you need
FROM @Persons p
INNER JOIN dbo.FN_ListToTable(' ',@searchTerm) b on p.EmailAddress like '%'+b.Listvalue+'%'
```
OUTPUT:
```
FirstName LastName EmailAddress
---------- ---------- -------------------------
aaa bbb ccc@ddd.eee
aaa yyy zzz@zzz.zzz
xxx yyy zzz@abbba.zzz
(3 row(s) affected)
```
this method will work for any number of parameters:
```
aaa
aaa
aaa bbb
aaa bbb
aaa bbb eee
aaa bbb eee ddd
aaa bbb eee
``` | You could try something like this:
```
DECLARE
@searchTerm VARCHAR(100),
@FirstName VARCHAR(100),
@LastName VARCHAR(100)
SET
@searchTerm = 'tom smith'
SELECT
@FirstName = '%' + SUBSTRING(@searchTerm, 1, CHARINDEX(' ', @searchTerm) - 1) + '%',
@LastName = '%' + SUBSTRING(@searchTerm, CHARINDEX(' ', @searchTerm) + 1, LEN(@searchTerm)) + '%'
SELECT *
FROM
Persons
WHERE
FirstName LIKE @FirstName
OR LastName LIKE @FirstName
OR EmailAddress LIKE @FirstName
OR FirstName LIKE @LastName
OR LastName LIKE @LastName
OR EmailAddress LIKE @LastName
``` |
3,705,307 | From a cucumber feature file when I go to 'Run features' Im getting the error below in the popup box that appears.
How do I fix this?
---
/Library/Ruby/Site/1.8/rubygems/custom\_require.rb:31:in `gem_original_require': no such file to load -- /Users/evolve/Projects/i9/Tornelo/.bundle/environment (LoadError) from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in`require' from /Users/evolve/Library/Application Support/TextMate/Bundles/Cucumber.tmbundle/Support/lib/cucumber/mate/../mate.rb:10 from /Users/evolve/Library/Application Support/TextMate/Bundles/Cucumber.tmbundle/Support/lib/cucumber/mate/feature\_helper.rb:1:in `require' from /Users/evolve/Library/Application Support/TextMate/Bundles/Cucumber.tmbundle/Support/lib/cucumber/mate/feature_helper.rb:1 from /tmp/cucumber-906.rb:2:in`require' from /tmp/cucumber-906.rb:2 | 2010/09/14 | [
"https://Stackoverflow.com/questions/3705307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172651/"
] | This has happened to me since I loaded rvm and gone through the steps listed under packages for textmate.
Now, when I 'run feature' for a cucumber feature from within textmate I get an error '.bundle/environment no such file to load'.
I don't have a .bundle/environment.rb so I created an empty one and the feature gets run but the environment.rb file gets deleted every time! (Making me very keen to see this fixed!)
If you have any feedback to add to your post I'd be very interested to hear it.
Since I posted this, I've reloaded the Textmate cucumber bundle and the problem has gone away.
Beware though - the installation instructions are incorrect - they should read
```
mkdir -p ~/Library/Application\ Support/TextMate/Bundles/
cd ~/Library/Application\ Support/TextMate/Bundles
rm -rf Cucumber.tmbundle
git clone http://github.com/drnic/cucumber-tmbundle Cucumber.tmbundle
osascript -e 'tell app "TextMate" to reload bundles'
```
You don't need the 'rm -rf Cucumber.tmbundle' line if this is a first install.
No editing of files needed!
You will be able to update from within textmate once you have done this. | I had the same problem and solved it by following these steps :
```
> mate ~/Library/Application\ Support/TextMate/Bundles/Cucumber.tmbundle/Support/lib/cucumber/mate.rb
```
Comment or Remove line 20 (or whatever line the error message says) :
```
> #require 'spec'
``` |
20,222,504 | I am trying to make a local validation. Every combination you enter in editText1 (for example abc) should be converted to numbers (a=1, b=2, c=3). The text in editText2 should match abc converted to numbers (123). If this is true: start the new activity. else: display a 'login failed' textview.
```
public class Login extends Activity {
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.login);
setContentView(R.layout.home_login);
Button btn = (Button) findViewById(R.id.loginButton2);
EditText email_text = (EditText) findViewById(R.id.editText1);
EditText code_text = (EditText) findViewById(R.id.editText2);
final String userEmail = email_text.getText().toString();
final String userCode = code_text.getText().toString();
String x = "";
for (int i = 0; i <= 2; i++) {
x += getNumber(userEmail.charAt(i));
}
final int validCode = Integer.parseInt(x);
btn.setOnClickListener(new OnClickListener() {
@SuppressLint("ResourceAsColor")
@Override
public void onClick(View v) {
if (userCode.equals(validCode)) {
Intent intent = new Intent(Login.this, Home.class);
startActivity(intent);
} else {
TextView view = (TextView) findViewById(R.id.loginfailed);
view.setVisibility(View.VISIBLE);
editText2.setText("");
}
}
});
}
private int getNumber(Character c) {
return "abdcefghijklmnopqrstuvwxyz".indexOf(c) + 1;
}
```
However, when I run my app it crashes immediately and the following error raises:
```
FATAL EXCEPTION:main
java.lang.RuntimeException: Unable to start activity ComponentInfo {...}:
java.lang.StringIndexOutOfBoundsException: length=0; index=0
```
how do i fix this?? | 2013/11/26 | [
"https://Stackoverflow.com/questions/20222504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2989346/"
] | If you want a 9-length array:
```
Array.apply(null, {length: 9}).map(function() {return 0;})
```
If you want a X-length array:
```
Array.apply(null, {length: X}).map(function() {return 0;})
```
If you have an array and want to rewrite its values:
```
var arr=[54,53,6,7,88,76]
arr=arr.map(function() {return 0;})
```
You can fill the array with anything you want, just by changing the value at **return** inside the **function** inside **.map**:
```
Array.apply(null, {length: 9}).map(function() {return "a string";})
Array.apply(null, {length: 9}).map(function() {return Math.random();})
Array.apply(null, {length: 9}).map(function() {return NaN;})
Array.apply(null, {length: 9}).map(function() {return null;})
Array.apply(null, {length: 9}).map(function() {return true;})
Array.apply(null, {length: 9}).map(function() {return;})
```
The last one will fill the array with **undefined** | One way could use recursion.
```
function fillArray(l, a) {
a = a || [];
if (0 < l) {
l -= 1;
a[l] = 0;
return fillArray(l, a);
}
return a;
}
```
I had also posted a more classic option:
```
function fillArray(l) {
var a;
for (a = []; 0 < l; l-=1, a[l]=0);
return a;
}
``` |
29,502,874 | The app I'm working on has a credit response object with a Boolean "approved" field. I'm trying to log out this value in Objective C, but since there is no format specifier for Booleans, I have to resort to the following:
```
NSLog("%s", [response approved] ? @"TRUE" : @"FALSE");
```
While it's not possible, I would prefer to do something like the following:
```
NSLog("%b", [response approved]);
```
...where "%b" is the format specifier for a boolean value.
After doing some research, it seems the unanimous [consensus](https://stackoverflow.com/questions/6752082/is-there-a-format-specifier-that-works-with-boolean-values) is that neither C nor Objective-C has the equivalent of a "%b" specifier, and most devs end up rolling their own (something like option #1 above).
Obviously Dennis Ritchie & Co. knew what they were doing when they wrote C, and I doubt this missing format specifier was an accident. I'm curious to know the rationale behind this decision, so I can explain it to my team (who are also curious).
**EDIT:**
Some answers below have suggested it might be a localization issue, i.e. "TRUE" and "FALSE" are too English-specific. But wouldn't this be a dilemma that all languages face? i.e. not just C and Objective-C? Java and Ruby, among others, are able to implement "True" and "False" boolean values. Not sure why the authors of these langs didn't similarly punt on this choice.
In addition, if localization were the problem, I would expect it to affect other facets of the language as well. Take protected keywords, for instance. C uses English keywords like "include", "define", "return", "void", etc., and these keywords are arguably more difficult for non-English speakers to parse than keywords like "true" or "false". | 2015/04/07 | [
"https://Stackoverflow.com/questions/29502874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2143275/"
] | What should the formatter display? 0 & 1? TRUE & FALSE? YES & NO? -1 and 1? What about other languages?
There's no good consistently right answer so they punted it to the app developer, for whom it'll be a clearer (and still simple) choice. | In C early days, there was no numeric `printf()` specifier for `char`, `short` either as there was little need for it. Now there is `"%hhd"` and `"%hd"`. Any type narrower than `int/unsigned` was promoted.
Today, in C, `_Bool` type maybe printed with `"%d"`.
```
#include <stdio.h>
int main(void) {
_Bool some_bool = 2;
printf("%d\n", some_bool); // prints 1 (or 0 when false)
return 0;
}
```
The missing link in C is its lack of a format specifier to *scan* into a `_Bool`. This leads to various solutions like the following which are not satisfactory with input like "T" or "false".
```
_Bool some_bool;
int temp;
scanf("%d", &temp);
some_bool = temp;
``` |
29,427 | As far as I can see, there is no `GL_PIXEL_UNPACK_BUFFER`. Also, the OpenGL ES 2.0 specification (and as far as I know, no iOS device currently supports OpenGL ES > 2.0) states that `glMapBufferOES()` can only use `GL_ARRAY_BUFFER` as a target, yet `glTexImage2D()` and `glTexSubImage2D()` only seem to use PBOs if `GL_PIXEL_UNPACK_BUFFER` is bound.
The [OpenGL documentation for `glBindBuffer()`](http://www.opengl.org/sdk/docs/man/xhtml/glBindBuffer.xml) also states that:
>
> `GL_PIXEL_PACK_BUFFER` and `GL_PIXEL_UNPACK_BUFFER` are available only if the GL version is **2.1 or greater**.
>
>
>
So, can I use PBOs for textures? Am I missing something obvious? | 2012/05/22 | [
"https://gamedev.stackexchange.com/questions/29427",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/11982/"
] | OpenGL ES doesn't have pixel buffer objects. So you can not use them there. | [OpenGL](http://www.opengl.org/registry/) and [OpenGL ES](http://www.khronos.org/registry/gles/), despite the similar names, are two *different* specifications. They may have similarly named functions, but there will be semantic differences between what these functions do. And of course, there will be differences in what features they support.
PBOs are not supported on ES (except for ES 3.0, which recently came out but isn't widely supported yet), regardless of version. There isn't even an extension for it. Also, you should probably read up on [what PBOs actually do](http://www.opengl.org/wiki/Pixel_Buffer_Object); they don't do what you think they do. |
12,386 | Imagine you have a m x n grid which is initially colored white. you can fill in a cell with black color if and only if there are no immediately neighboring black cells (no black cells to the left/right/top/bottom). If you keep on filling cells you will eventually run out of legal cells to fill.
An example configuration is shown below. The green patterned ones are the only legally available spaces.

What is the minimum number of black cells you can fill in the grid till you have no more cells you can legally fill? What is the best strategy to get this minimum? | 2015/04/18 | [
"https://puzzling.stackexchange.com/questions/12386",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/11592/"
] | This is the *independent domination number* of the grid graph, that is, the smallest subset $S$ of nodes, no two adjacent, for which every node is in $S$ or adjacent to a node in $S$. The square version $m=n$ is in the [OEIS](http://oeis.org/A321684), and the linked paper "Independent Domination of Grids" gives the complete results for all $m \times n$. | One fill for larger boards is a pattern like the movement of a knight - I'm on mobile but I'll explain it as well as I can.
```
..X.
X...
...X
.X..
```
This patter repeats in a 4x4 square - for larger boards, it is nearly optimal. |
554,713 | I'm using Snort 2.9 on windows server 2008 R2 x64, with a very simple configuration that goes like this:
```
# Entire content of Snort.conf:
alert tcp any any -> any any (sid:5000000; content:"_secret_"; msg:"TRIGGERED";)
# command line:
snort.exe -c etc/Snort.conf -l etc/log -A console
```
Using my browser, I send the string "\_secret\_" in the url to my server (where Snort is located). Example: `http://myserver.com/index.php?_secret_`
Snort receives it and throws an alert, it works, no problem ! But when I try something like this :
```
<?php // (index.php)
header('XTest: _secret_'); // header
echo '_secret_'; // data
?>
```
If I just request `http://myserver.com/index.php`, it does not work or detect anything from the outgoing traffic even though the php file is sending the same string both in headers and in data, with no compression/encoding or whatsoever. (I checked using Wireshark)
This looks to me like a Snort problem. No matter what I do it only detects receiving packets. Did anyone ever face this sort of problems with Snort ? Any idea how to fix it ? | 2013/11/13 | [
"https://serverfault.com/questions/554713",
"https://serverfault.com",
"https://serverfault.com/users/143159/"
] | After 6 painfull hours of trying everything, I finally fixed it !
Just needed to add `-k none` to the command line.
For some reason, in my desktop pc it works without the `-k none` parametre. If someone care to explain what is going on, that would be very helpfull. Thanks. | Sometimes the snaplen (*-P*) might be also an issue. Increase the value (default is the size of the MTU) and you will get a lot of more data. |
1,709,833 | This is a problem from a real analysis book. The book gives a hint: Consider $g(x)=\arctan f(x)$. However, I don't think it makes any difference. I try to find an injection form $E$ into a countable set. But I've got completely no idea, and wondered if the statement was wrong. | 2016/03/23 | [
"https://math.stackexchange.com/questions/1709833",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/219963/"
] | Hint: Assume that $E = \{x : \lim\_{y\to x} f(y) = \infty\}$ is uncountable. For $n\in \mathbb N,$ let $E\_n = \{x\in E: f(x) < n\}.$ Show that some $E\_{n}$ is uncountable, hence some point of this $E\_{n}$ is a limit point of $E\_n.$ | Here is some further commentary:
1. **Does the hint help at all**? (After all, the elegant and brief answer by @zhw did not need it.) Sometimes hints can seem rather oblique. In this case
the hint evidently intends the student to reduce the problem to one that is already solved. The composition $ g(x)=\arctan f(x)$ converts the unbounded situation to a bounded one so that the limit is finite at each point of the set $E$.
So in fact all one needs to realize is that for every $x\in E$ the limit $\lim\_{y\to x} g(x)$
exists and is different from $g(x)$. That means that the set $E$ contains only removable discontinuities of the function
$g$ and consequently, by a theorem (evidently already proved in the source textbook), is countable.
2. **Is this problem interesting**? By that I mean does it really reveal anything about the structure of real functions in general, or is it just some textbook problem that pushes the student to apply some theorem or technique.
If we view it from a more general point of view we can learn quite a bit more about real functions and limits.
If
$f:\mathbb R\to\mathbb R$ is an
arbitrary function one defines a number $$r\in \overline{\mathbb R}=\mathbb R \cup \{\infty\} \cup \{-\infty\}$$
to be a *right cluster value* of $f$ at $x$ if there is at least
one sequence $x\_n\searrow x$ for which $f(x\_n)\to r$. The set of all right cluster values at $x$ is denoted $\Lambda\_f^+(x)$. It is a nonempty closed set (i.e., closed in $\overline{\mathbb R}$.)
The left cluster set at $x$ is similarly defined and notated as
$\Lambda\_f{}^-(x)$.
>
> **Theorem** (W. H. Young 1908) If $f:\mathbb R\to\mathbb R$ is an arbitrary function then the sets $$E^+= \left\{x\in \mathbb R:
> f(x)\not\in \Lambda\_f^+(x)\right\} \ \ and \ \ E^-= \left\{x\in
> \mathbb R: f(x)\not\in \Lambda\_f{}^{-}(x)\right\} $$ are countable.
>
>
>
The problem posed here is a very special case of this in which
$\Lambda\_f^+(x)=\Lambda\_f{}^-(x)=\{\infty\}$ at each point of the given set $E$.
The proof is not hard, using ordinary and familiar techniques at this level. For each point $x\in E^+$ there are integers $m$ and $n$ so that whenever $x<z<x+\frac1n$ one has $$|f(z)-f(x)|>\frac1m.$$ Let $E\_{mn}$ be the set of all points $x\in E^+$ that have this property for $m$ and $n$. Evidently
the union of the family of sets $\{E\_{mn}\}$ is all of $E^+$.
Now just observe that if $u$, $v\in E\_{mn}$ with $0<v-u<\frac1n$ then $|f(v)-f(u)|>\frac1m$. Conclude that $E\_{mn}$ must be countable and so also must be $E^+$.
This analysis using cluster values shows that questions of this type are not really about limits themselves. Young didn't use this language and, in fact, his theorem was overlooked for some time and rediscovered later when cluster sets were introduced in this and other settings. |
4,127,553 | So for this problem I need to use the fact that $\frac {1-r^2}{1-2r\cos\theta+r^2}$=$1+2\sum\_{n=1}^{\infty} r^n\cos n\theta$.
I replaced the term in the integral but i ended up getting $\sum\_{n=1}^{\infty} r^n+2$ as my final answer. Im not sure if I got it right and i need to reframe it to get $\frac {2(1+r^2)}{1-r^2}$ or my answer is completely wrong.
Thanks for the help. | 2021/05/05 | [
"https://math.stackexchange.com/questions/4127553",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/489246/"
] | A much simpler way is to note that $$\int\_{0}^{\pi}\frac{dx}{a+b\cos x} =\frac{\pi} {\sqrt{a^2-b^2}}, a>|b|$$ and differentiate it with respect to $a$ to get $$\int\_{0}^{\pi}\frac{dx}{(a+b\cos x) ^2}=\frac{\pi a} {(a^2-b^2)^{3/2}}$$ Putting $a=1+r^2,b=-2r$ and noting that $$a^2-b^2=(1-r^2)^2$$ we can see that $$\int\_{0}^{\pi}\frac{dx}{(1-2r\cos x+r^2)^2}=\frac{\pi(1+r^2)}{(1-r^2)^3}$$ which is equivalent to your result in question.
The integral at the beginning of this answer is evaluated by using non-obvious substitution $$(a+b\cos x) (a-b\cos t) =a^2-b^2$$
---
Your own approach should lead to $$\int\_{0}^{\pi}\left(\frac{1-r^2}{1-2r\cos x+r^2}\right)^2\,dx=\pi+4\sum\_{n=1}^{\infty}r^{2n}\int\_{0}^{\pi}\cos^2 nx\, dx$$ which equals $$\pi+2\pi\sum\_{n=1}^{\infty}r^{2n}=\frac{\pi(1+r^2)}{1-r^2}$$ Note that while squaring you also get terms like $\cos mx\cos nx$ but their integral vanishes so I have ommitted these in the above calculation.
Also $x$ has been used in place of $\theta$ to reduce typing effort. | You have reduced the problem to evaluating
$$
\frac{1}{\pi}\int\_{-\pi}^{\pi}\left(1+2\sum\_{n=1}^{\infty}r^n\cos(n\theta)\right)^2d\theta.
$$
The terms $1,\cos(\theta),\cos(2\theta),\cdots$ are mutually orthogonal on $[-\pi,\pi]$, which further reduces the above to
$$
\frac{1}{\pi}\left(\int\_{-\pi}^{\pi}1d\theta+4\sum\_{n=1}^{\infty}r^{2n}\int\_{-\pi}^{\pi}\cos^2(n\theta)d\theta\right) \\
= 2+\frac{4}{\pi}\sum\_{n=1}^{\infty}r^{2n}\pi \\
=2+4r^{2}\sum\_{n=0}^{\infty}(r^2)^n \\
=2+4r^{2}\frac{1}{1-r^2} \\
=2\frac{1+r^2}{1-r^2}.
$$
And that checks with your answer. |
8,250,898 | I have reached a point in my web application where we are ready to go live and the thought occurred to me to put in some way of catching application errors users hit and forwarding them on to the appropriate support.
At the moment the site currently catches any errors and redirects to an error page. It also catches all the data a support person should need to fix the bug. What we want it to do is provide functionality for the user to send the error details for to a support person somehow.
Ways that we have thought of so far include:
* Simply printing the error on the page as text for the user to copy.
* Providing a button to copy the error onto a clipboard for them to paste into an email.
* Providing a help form for the user to fill in which will send the error on.
* Providing a 'send error' button that simply forwards the error onto an configured or user-entered email address.
* Storing the error details in a database table on page load for a support person to then view.
None of these stand out to me as super clean or intuitive. Has anyone come up with a unique and clean way to handle this kind of situation?
**NB: I am looking for a solution to handle reporting generated errors in the system, not a solution for user feedback.** | 2011/11/24 | [
"https://Stackoverflow.com/questions/8250898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155586/"
] | If you're displaying all the information the user needs, why not just log it in a database or send an email to support? That way you don't have to worry the user with the fact that you have bugs. Send them to your "Sorry, but please try that again later" page... | You could take a look at plugging in [UserVoice](http://uservoice.com/). It's great for capturing user feedback and easy to set up. |
62,569,356 | Yet again JetBrains managed to implement an "ungoogleable" feature.
Does anyone know what this "R with pencil" icon means?
[](https://i.stack.imgur.com/Bc0VA.png) | 2020/06/25 | [
"https://Stackoverflow.com/questions/62569356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1280511/"
] | If you hover over the icon there is an explanation text:
[](https://i.stack.imgur.com/nuLhE.png)
which means that this action will run [Rename](https://www.jetbrains.com/help/go/rename-refactorings.html#invoke-rename-refactoring) refactoring for the changed name of the symbol.
See [IntelliJ IDEA 2020.1 EAP4: In-place Rename and Change Signature](https://blog.jetbrains.com/idea/2020/02/intellij-idea-2020-1-eap4/) related blog post about it.
If there are no usages of this variable the Rename action (and icon) is dimmed and a bit different text is displayed (that nothing needs to be updated at this point):
[](https://i.stack.imgur.com/VjZJF.png) | I don't know what the "R" exactly stands for, but it's used to **r**eflect [signature changes](https://www.jetbrains.com/help/idea/change-signature.html) and so for **r**efactoring methods. |
51,694,629 | I've got a query that outputs the contents of an SQL table. At the end of every row, I've got a button, that contains the ID of that specific row:
```
<button name='delButton' type='submit' class='delete' value='".$row["id"]."'>Delete Account</button>
```
So, the problem that I encounter is when I try to use $\_POST["delButton"] to get the ID of that row, it shows as being NULL.
```
var_dump($_POST["delButton"]);
``` | 2018/08/05 | [
"https://Stackoverflow.com/questions/51694629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7317593/"
] | If you (as indicated in the comments) don't want to create a function that you need to pass 6 arguments, then you *could* use a lambda like this:
```
const auto do_something = [&] { /* do stuff with captured reference variables */ };
if (conditionA) {
// some code here
if (conditionB) {
// stuff
} else {
do_something();
}
} else {
do_something();
}
``` | You can wrap it up into cthulhu loop and use `break`:
```
for(;;) // executed only once
{
if (conditionA)
{
//some code here
if(conditionB)
{
// some more code here
break; // for(;;)
}
}
//do something
break; // for(;;)
}
``` |
31,764 | I am wondering when I should use "*des*" and "*les*". I know the grammatical point about using "*articles definis*" but I see different sentences on the Internet which made me confused.
Example:
>
> *Comment confire des légumes ?*
>
>
> *Braiser des légumes.*
>
>
> *Cuisinez les légumes.*
>
>
> *Comment blanchir les légumes ?*
>
>
>
Is it correct to say:
>
> *Je prépare des légumes frais pour cette salade ?*
>
>
> | 2018/09/24 | [
"https://french.stackexchange.com/questions/31764",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17645/"
] | "Je mange **des** légumes." means : I eat vegetables. You don't know which are the vegetables. It is "**indéfini**".
"Je mange **les** légumes" would be equivalent to : I eat *the* vegetables. You know that you eat these vegetables. It is "**défini**".
Example : Je mange des légumes tous les jours. Mais aujourd'hui, j'ai mangé les légumes du jardin. | This question was already asked a couple of times, [here](https://french.stackexchange.com/questions/13333/when-are-les-des-etc-used-or-not-used?rq=1) and [here](https://french.stackexchange.com/questions/19750/correct-use-of-les-and-des?rq=1) for example, although no answer was accepted.
Both *des* and *les* can be used in your sentences.
>
> *Comment xxxx des légumes ?*
>
>
>
means
>
> How to xxxx vegetables ? (any kind of them)
>
>
>
while
>
> *Comment xxxx les légumes ?*
>
>
>
means
>
> How to xxxx the vegetables ?
>
>
>
with *xxxx* being one of the verbs of your examples (*confire, braiser, cuisiner, blanchir, préparer...*).
Here the meaning might be identical to the previous form, when **the** vegetables is representing "the vegetables in general" but it might also means "the vegetables that we are talking about, the vegetables I need to cook". The context should help figuring out which meaning is intended.
In the last sentence:
>
> *Je prépare des légumes frais pour cette salade*
>
>
>
You tell you are using some fresh vegetables to make this salad while in:
>
> *Je prépare les légumes frais pour cette salade*
>
>
>
you tell you use the fresh vegetables (all the ones that are already here) to make the salad. |
663,418 | I wish to set up Postfix to use an external relay depending on the destination hostname, ie:
* If destination hostname is \*.outlook.com, use relay some\_smtp.example.com
* If any other destination hostname, use local relay
**What I mean by destination hostname is the hostname obtained from MX record.** If the recipient domain has MX record `microsoft-com.mail.protection.outlook.com`, then use a different relay
I know it is possible to specify a relay depending on the sender address (using `sender_dependent_relayhost_maps`), but it's impractical in my situation.
The goal is to use a different relay for finicky destination hosts: maybe Mandrill, or another Postfix installation. | 2015/01/29 | [
"https://serverfault.com/questions/663418",
"https://serverfault.com",
"https://serverfault.com/users/147144/"
] | [Arul's answer](https://serverfault.com/a/663435/218590) was perfect for transport based on recipient domain. However, bencaue you refer to MX record hostname instead recipient domain, the answer was non-applicable.
One solution is using `check_recipient_mx_access`. Snippet from [official docs](http://www.postfix.org/postconf.5.html#check_recipient_mx_access)
>
> **check\_recipient\_mx\_access *type:table***
>
>
>
> >
> > Search the **specified access(5) database for the MX hosts for the RCPT TO domain**, and execute the corresponding action. Note: a result of "OK" is not allowed for safety reasons. Instead, use DUNNO in order to exclude specific hosts from blacklists. This feature is available in Postfix 2.1 and later.
> >
> >
> >
>
>
>
For your case, just put `check_recipient_mx_access hash:/etc/postfix/finickydestination` in appropriate place `smtpd_*_restriction`. In that file put the hostname
```
# /etc/postfix/finickydestination
.outlook.com FILTER smtp:[some_smtp.example.com]
```
Don't forget to postmap the file and execute postfix reload.
Reference(s):
* [Postfix patch announcement](http://archives.neohapsis.com/archives/postfix/2003-09/1616.html) regarding [VeriSign site finder](http://en.wikipedia.org/wiki/Site_Finder)
* [Another people which has same problem](http://marc.info/?l=postfix-users&m=121920465018833&w=2) | As commented above: "For your case, just put check\_recipient\_mx\_access hash:/etc/postfix/finickydestination in appropriate place smtpd\_\*\_restriction. In that file put the hostname"
smtpd\_sender\_restrictions is not the appropriate place, as at the point in the smtp transaction, postfix does not know who the receiver is.
Also if you had any more FILTER statements, such as spam/virus scanning, it would override that FILTER statement, if they happened after smtpd\_sender\_restrictions. |
8,227,809 | I use grails with a legacy database, all hibernate classes and their mappings are packaged in a jar file and reside in the grails lib folder. Querying/updating/inserting with GORM works ok.
Now I would like to add some mappings, let's say I want to add the mapping:
```
id column:'person_id'
```
Is there any way to do this ? | 2011/11/22 | [
"https://Stackoverflow.com/questions/8227809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/868975/"
] | It worked for me on iPad when I listen to
`MPMoviePlayerWillExitFullscreenNotification`.
```
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doneButtonClick:)
name:MPMoviePlayerWillExitFullscreenNotification
object:nil];
```
And selector method:
```
-(void)doneButtonClick:(NSNotification*)aNotification{
NSNumber *reason = [notification.userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
if ([reason intValue] == MPMovieFinishReasonUserExited) {
// Your done button action here
}
}
``` | check for a enum inside notification userInfo dictionary
```
NSNumber *reason = [notification.userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
if ([reason intValue] == MPMovieFinishReasonUserExited) {
// done button clicked!
}
```
**Selected answer has since integrated my response. Please refer above.** |
45,456,591 | I'm using php dir() function to get files from directory and loop through it.
```
$d = dir('path');
while($file = $d->read()) {
/* code here */
}
```
But this returns false and gives
>
> Call to member function read() on null
>
>
>
But that directory exists and files are there.
Also, Is there any alternative to my above code? | 2017/08/02 | [
"https://Stackoverflow.com/questions/45456591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3719167/"
] | You can try this:
```
$dir = new DirectoryIterator(dirname('path'));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
```
Source: [PHP script to loop through all of the files in a directory?](https://stackoverflow.com/questions/4202175/php-script-to-loop-through-all-of-the-files-in-a-directory) | Please check your file path if your path is right. Then please try this code this may help you. Thanks
```
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
``` |
12,524,322 | I have a java file containing more than one class, out of which one is public. If main method is inside a non-public class. I can't run that java file. Why is that? and there is no compilation error as well. If so, how can I use that main method? | 2012/09/21 | [
"https://Stackoverflow.com/questions/12524322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/953140/"
] | Have a look at this code:
**Super.java**
```
public class Super{ }
class Sub{
public static void main(String[] s){
System.out.println("Hello");
}
}
```
In order to print `Hello` you can compile and run the program as:

**How this works?**
The compiler generates separate `.class` file for every class in your program. So, instead of calling the `main()` of non-public class from the public class's `main()` you can print the output as shown above.
**Note:** As the convention says, you must put a `public class` in separate file `<class_name>.java`. And do not put more than one class in a single file (except if they are inner class) because if you would like to import them or use them with other classes then it will cause problem. | It is a compile-time error if a top level type declaration contains any one of the following access modifiers: protected, private, or static.This [link](http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.6) may be helpful. |
28,872,399 | in c++ reference i read "Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions."
my doubt is if it is sequential then how it can take constant time to delete and insert a node.Any way we have to traverse sequentially to reach that node . Deleting node depends on its position | 2015/03/05 | [
"https://Stackoverflow.com/questions/28872399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3107268/"
] | O(1) referst to the complexity for inserting/erasing nodes provided you *already have a handle (in the form of an iterator) to that node*. Obtaining an iterator to the *i*th element of a list given an iterator to the first one is O(N).
This is quite often overlooked when judging the relative merits of `std::list` vs. say, `std::vector`. But note that both inserting and erasing elements return iterators that can be used for further insert/erase operations. | Because the list is not sorted. If you look closely, the actual function for putting elements in the list is `list::insert(hint, element)` (<http://www.cplusplus.com/reference/list/list/insert/>). I.e. for every insertion, the place where the element is added is already known, thus constant time.
E.g. `list::push_front(element)` is short for `insert(begin(), element)`. |
1,395,361 | I am converting some code from C to C++ in MS dev studio under win32. In the old code I was doing some high speed timings using QueryPerformanceCounter() and did a few manipulations on the \_\_int64 values obtained, in particular a minus and a divide. But now under C++ I am forced to use LARGE\_INTEGER because that's what QueryPerformanceCounter() returns. But now on the lines where I try and do some simple maths on the values I get an error:
error C2676: binary '-' : 'LARGE\_INTEGER' does not define this operator or a conversion to a type acceptable to the predefined operator
I tried to cast the variables to \_\_int64 but then get:
error C2440: 'type cast' : cannot convert from 'LARGE\_INTEGER' to '\_\_int64'
How do I resolve this?
Thanks, | 2009/09/08 | [
"https://Stackoverflow.com/questions/1395361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169774/"
] | LARGE\_INTEGER is a union of a 64-bit integer and a pair of 32-bit integers. If you want to perform 64-bit arithmetic on one you need to select the 64-bit int from inside the union.
```
LARGE_INTEGER a = { 0 };
LARGE_INTEGER b = { 0 };
__int64 c = a.QuadPart - b.QuadPart;
``` | `LARGE_INTEGER` is a union, [documented here](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-large_integer-r1). You probably want a `QuadPart` member. |
13,822,353 | Windows 7 32 bit, IIS 7.5.760016385
I created a DLL in Visual Basic 6.0 and trying to use it from within classic ASP code:
```
set obj = Server.CreateObject("a.b")
```
I get the following error:
>
> 006 ASP 0178
>
> Server.CreateObject Access Error
>
> The call to Server.CreateObject failed while checking permissions. Access is denied to this object.
>
> err.number = -2147024891
>
>
>
I have tried creating the iusr\_cmpname user and giving rights to it in the Default website and virtual directory of this ASP page. I have REGSVR32'd the dll's.
I have gone to "Turn Windows features on and off" and selected IIS/World Wide Web Services/Application Development Features then CHECKED off ASP, ASP.net, ISAPI extensions, and ISAPI filers.
I have followed many leads in different Newsgroups but I can get past this problem.
We tried this last year, a year and 1/2 ago and had the same problem. Since we couldn't conquer this problem, we went back to Windows NT. We never had this problem on NT.
Now we are trying again to get past this so we can move to Windows 7 again. It seems that many people had this problem but any solution they found and have posted, don't seem to be what I need.
Any help will be appreciated. Thank you. | 2012/12/11 | [
"https://Stackoverflow.com/questions/13822353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894838/"
] | This page suggests that the problem may be the access rights assigned to the VB runtime. Try assigning everyone read and execute permissions on Msvbvm60.dll.
<http://support.microsoft.com/kb/278013> | Another approach that might work, is to install the DLL as DCOM application on dcomcnfg. It will run under different credentials. |
332,261 | I'm looking for something that's catchy and succinct. 'Exploit' is a good word for 'take advantage of' but it doesn't take into account someone's psychological weaknesses.
example sentences:
>
> "By taking advantage of her substance abuse in order to get sex, he was \_\_\_\_\_\_\_\_\_ her."
>
>
>
or
>
> "She took advantage of his bad memory by repeatedly getting him to wash the dishes more often than not. She was \_\_\_\_\_\_\_\_\_ him."
>
>
> | 2016/06/12 | [
"https://english.stackexchange.com/questions/332261",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | **gaslight**
.
[Oxford dictionaries](http://www.oxforddictionaries.com/us/definition/american_english/gaslight)
>
> verb: Manipulate (someone) by psychological means into questioning their own sanity:
>
>
>
.
[dictionary.com definition](http://www.dictionary.com/browse/gaslight)
>
> 4. to cause (a person) to doubt his or her sanity through the use of psychological manipulation:
>
>
>
.
I think that's the closest I'm gonna get to what I want.. | Exploit seems like the proper word to me. |
24,025,423 | Let an object contain color and size, and a list like
`l = [<'GREEN', 1>, <'BLUE', 1>, <'BLUE', 2>, <'BLUE', 3>, <'RED', 4>, <'RED', 4>, <'GREEN', 5>]`
Each element is an instance of the object which contains color and size (not tuples). I've represented them in non-conventional way.
I want to eliminate elements from l only if the color of the previous element is the same. So l should be
`l = [<'GREEN', 1>, <'BLUE', 1>, <'RED', 4>, <'GREEN', 5>]`
List comprehensions or iterating directly on the list won't work, since I won't have access to previous element...
I know I can create a second list and only add to it if it's a "new" color, but I wanted to do it in-place if possible. | 2014/06/03 | [
"https://Stackoverflow.com/questions/24025423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105486/"
] | The cleanest way to iterate through sequence in a context of previous element is [with\_prev](http://funcy.readthedocs.org/en/latest/seqs.html#with_prev) function from [funcy](https://github.com/Suor/funcy) library:
```
from funcy import with_prev
[x for x, prev in with_prev(l)
if prev and x.color != prev.color]
```
(I assume here you have a `color` attribute on your objects). | I have tested and confirmed that the following code will work. Partially inspired by the other posts here.
```
l = ["red","red","green","blue","green","green"]
k = 1
while k < len(l):
if l[k-1]==l[k]:
del l[k]
k = k + 1
else:
k = k + 1
for x in range(len(l)):
print l[x]
```
Output:
```
red
green
blue
green
``` |
70,957,589 | I am writing a micro-library instead of using jQuery. I need only 3-4 methods ( for DOM traversal, Adding Eventlisteners etc). So I decided to write them myself instead of bloating the site with jQuery.
Here is the snippet from the code:
`lib.js`
```js
window.twentyFourJS = (function() {
let elements;
const Constructor = function(selector) {
elements = document.querySelectorAll(selector);
this.elements = elements;
};
Constructor.prototype.addClass = function(className) {
elements.forEach( item => item.classList.add(className));
return this;
};
Constructor.prototype.on = function(event, callback, useCapture = false){
elements.forEach((element) => {
element.addEventListener(event, callback, useCapture);
});
return this;
}
const initFunction = function(selector){
return new Constructor(selector);
}
return initFunction;
})(twentyFourJS);
```
`script.js`
```js
(function($){
$('.tab-menu li a').on('click', function(event) {
console.log('I am clicked'); // This works
this.addClass('MyClass'); // This does NOT work (as expected)
// I want to be able to do this
$(this).addClass('MyClass');
event.preventDefault();
});
})(twentyFourJS);
```
Basically I want to be able to use `$(this)` like we use it in jQuery.
`this.addClass('MyClass')` and `$(this).addClass('MyClass')` won't work and this is the expected behaviour.
As per my understanding `this` is referring to the plain HTML element. So it does not have access to any Constructor methods. it won't work.
And I have not written any code that will wrap element in Constructor object in `$(this)`. I will have to do some changes to my `Constructor` so that I can access the Constructor functions using `$(this)`. What are those changes/addition to it?
Kindly recommend only Vanilla JS ways instead of libraries. | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1633812/"
] | in your constructor you need to see what you have and handle it in different ways.
```
const Constructor = function(selector) {
if (typeof selector === 'string') {
elements = document.querySelectorAll(selector);
} else {
// need some sort of check to see if collection or single element
// This could be improved since it could fail when someone would add a length property/attribute
elements = selector.length ? selector : [selector];
}
this.elements = elements;
};
``` | All you really need to do is make sure your `Constructor` argument can distinguish between a string selector being passed in, and an object.
```
const Constructor = function(selector) {
if(typeof selector == "string"){
elements = document.querySelectorAll(selector);
this.elements = elements;
}
else{
this.elements = selector;
}
};
```
You can go further than this, but at a very minimum for the example given that works.
Live example below:
```js
window.twentyFourJS = (function() {
let elements;
const Constructor = function(selector) {
if(typeof selector == "string"){
elements = document.querySelectorAll(selector);
this.elements = elements;
}
else{
this.elements = selector;
}
};
Constructor.prototype.addClass = function(className) {
elements.forEach( item => item.classList.add(className));
return this;
};
Constructor.prototype.on = function(event, callback, useCapture = false){
elements.forEach((element) => {
element.addEventListener(event, callback, useCapture);
});
return this;
}
const initFunction = function(selector){
return new Constructor(selector);
}
return initFunction;
})();
(function($){
$('.btn').on('click', function(event) {
console.log('I am clicked'); // This works
// I want to be able to do this
$(this).addClass('MyClass');
event.preventDefault();
});
})(twentyFourJS);
```
```css
.MyClass{
background-color:red
}
```
```html
<button class="btn">Click me</btn>
``` |
151,298 | **I was wondering if there was a .NET-compatible CLR that was implemented using the CLI** (common language infrastructure), e.g., using .NET itself, or at least if there were any resources that would help with building one.
Basically, something like a .NET program that loads assemblies as MemoryStreams, parses the bytecode, constructs the types, and executes the instructions. Optionally, it can JIT-compile to standard IL using Reflection.Emit or however.
**I don't want to *compile* a .NET language to be run by the original CLR. I want a CLR that's *written* in a .NET language** (not unmanaged C++ or C as it usually is) **and *runs* CIL.** If done right, it should be able to run itself.
Any thoughts on using Mono.Cecil for this kind of thing? | 2008/09/30 | [
"https://Stackoverflow.com/questions/151298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659/"
] | I am not aware of one, but ideas frm JVM running on JVM should be helpful.
* [Jikes RVM](http://jikesrvm.org/)
* [Maxine VM](http://maxine.dev.java.net/) | Look at the System.Reflection.Emit namespace, specifically the ILGenerator class.
You can emit IL on the fly.
<http://msdn.microsoft.com/en-us/library/system.reflection.emit.ilgenerator_members.aspx> |
15,258,708 | I am trying to write a program that accepts a phone number in the format `XXX-XXX-XXXX` and translates any letters in the entry to their corresponding numbers.
Now I have this, and it will allow you to reenter the correct number if its not correct to start, but then it translates the original number entered. how do i fix this?
```
def main():
phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
validNumber(phone_number)
translateNumber(phone_number)
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
phone_number=input('Please enter a valid phone number: ')
return phone_number
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return phone_number
return phone_number
def translateNumber(phone_number):
s=""
for char in phone_number:
if char is '1':
x1='1'
s= s + x1
elif char is '-':
x2='-'
s= s + x2
elif char in 'ABCabc':
x3='2'
s= s + x3
elif char in 'DEFdef':
x4='3'
s= s + x4
elif char in 'GHIghi':
x5='4'
s= s + x5
elif char in 'JKLjkl':
x6='5'
s= s + x6
elif char in 'MNOmno':
x7='6'
s= s + x7
elif char in 'PQRSpqrs':
x8='7'
s= s + x8
elif char in 'TUVtuv':
x9='8'
s= s + x9
elif char in 'WXYZwxyz':
x10='9'
s= s + x10
print(s)
``` | 2013/03/06 | [
"https://Stackoverflow.com/questions/15258708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2084066/"
] | If you don't want to use regular expressions: You can use `isalnum` to check if something is a number or letter. You can access the `n`th character in a string using `mystr[n]` so, you could try:
```
def validNumber(phone_number):
if len(phone_number) != 12:
return False
for i in range(12):
if i in [3,7]:
if phone_number[i] != '-':
return False
elif not phone_number[i].isalnum():
return False
return True
```
To see what `phone_number[i]` is doing, try this:
```
for i in range(len(phone_number)):
print i, phone_number[i]
```
Using `enumerate`:
```
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
return False
elif not c.isalnum():
return False
return True
```
---
Once you have it working, you should use it later (inside of `main`) like:
```
def main():
phone_number = '' # an invalid number to initiate while loop
while not validNumber(phone_number):
phone_number = input('Please enter a phone number in the format XXX-XXX-XXXX: ')
translated_number = translateNumber(phone_number)
``` | 1. You should use a regex to match the text.
2. the string module has a `translate` function that will replace most of your logic
code example below. note how i cast everything into lowercase to simplify the regex and translation.
```
import string
import re
RE_phone = re.compile("^[a-z0-9]{3}-[a-z0-9]{3}-[a-z0-9]{4}$")
map_in = 'abcdefghijklmnprstuvwxyz'
map_out = '222333444555667778889999'
mapped = string.maketrans( map_in , map_out )
def main():
while True:
phone_number= raw_input('Please enter a phone number in the format XXX-XXX-XXXX: ')
phone_number = phone_number.lower()
if RE_phone.match(phone_number):
break
print "Error. Please try again"
print translateNumber(phone_number)
def translateNumber(phone_number):
return phone_number.translate( mapped )
main()
``` |
313,297 | I'm trying to come up with a simple and efficient way to create a smooth surface which intersects a number of given "sample" points.
For any X,Y point on the surface, I identify up to 4 sample points in each of the 4 directions (the next higher and lower points on the X, and then the Y axes). Given this point, I want a way to compute a Z value that interpolates between the 4 sample points.
Of course the algorithm, given the X, Y position of any of the 4 sample points, should output the Z value for that point. Note also that there may be less than 4 sample points.
I guess some function of the Z values for the 4 sample points, somehow inversely biased by the distance to the sample point, but I can't figure out how to do this.
Anyone got any ideas about a simple way to do this? | 2008/11/24 | [
"https://Stackoverflow.com/questions/313297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16050/"
] | You can do this by constructing patches from Catmull-Rom splines. These splines will hit each of the control points and they are continuous in the first derivative (though not the second). I also find them to be extremely easy to work with. The math is straightforward and they behave intuitively with slight changes in the control points.
At the highest level, you'll need 16 points per patch (at the edge of your dataset, you can use the corner and edge points twice in the same spline).
First, you'll need to interpolate across the points *p[i][j]* in each row in your 4x4 matrix to create a set of four intermediate control points *q[i]*. Here's a rough ASCII sketch of what I mean.
```
p00 p01 q0 p02 p03
p10 p11 q1 p12 p13
p20 p21 q2 p22 p23
p30 p31 q3 p32 p33
```
Now you can interpolate between each of those four intermediate control points to find a final splined point on your surface.
[Here is a construction of the Catmull-Rom spline](http://www.cs.cmu.edu/~462/projects/assn2/assn2/catmullRom.pdf) across four points. In this example, you are interpolating between points *p[i-1]* and *p[i]*, using control points on either side *p[i-2]* and *p[i+1]*. *u* is the interpolation factor ranging from zero to one. *τ* is defined as the tension on the spline and will affect how tightly your splined surface conforms to your control points.
```
| 0 1 0 0 | | p[i−2] |
|−τ 0 τ 0 | | p[i−1] |
p(u) = 1 u u2 u3 | 2τ τ−3 3−2τ −τ | | p[i] |
|−τ 2−τ τ−2 τ | | p[i+1] |
```
NOTE: it's not immediately obvious how to lay this out in Stackoverflow's gui but *u2* and *u3* are supposed to represent *u squared* and *u cubed*, respectively. | Use catmull-rom patches |
56,799,028 | the script in the loop detects the height of all divs, and then sets the highest value for all to make them div the same in height - specifically, the title. The script reads the height correctly from the first one, but not from the others, so it sets the height value according to the first div. In the chrome debugger at (this), I always see a different height value, but the function still takes the original one.
```js
$(function() {
var maxh = 0;
var maxhnew = 0;
$('.entry-header').map(function() {
var testVar = $('#test2').height();
var idname = 0;
var idname = $(this).attr("class");
var maxhnew = $('.'+ idname ).height();
if(maxh < $('.'+ idname ).height()) {
maxh = $('.'+ idname ).height();
}
var maxhnew = 0;
});
$('.entry-header').map(function() {
var idname = $(this).attr("class");
$('.'+ idname ).height(maxh);
});
});
```
```html
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="items-row sppb-row row-0 row clearfix">
<div class="col-sm-4">
<article class="bt-inner item column-1 item-featured" itemprop="blogPost" itemscope="" itemtype="http://schema.org/BlogPosting">
<div class="entry-image intro-image"> </div>
<div class="entry-header"id="test1">
<h2 itemprop="name">one row title</h2>
</div>
<div class="autoreadmore"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </div>
</article>
</div>
<div class="col-sm-4">
<article class="bt-inner item column-2 item-featured" itemprop="blogPost" itemscope="" itemtype="http://schema.org/BlogPosting">
<div class="entry-image intro-image"> </div>
<div class="entry-header" id="test2">
<h2 itemprop="name">one row title, one row title, one row title</h2>
</div>
<div class="autoreadmore"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </div>
</article>
<!-- end item -->
</div>
<!-- end col-sm-* -->
<div class="col-sm-4">
<article class="bt-inner item column-3 item-featured" itemprop="blogPost" itemscope="" itemtype="http://schema.org/BlogPosting">
<div class="entry-image intro-image"> </div>
<div class="entry-header" id="test3">
<h2 itemprop="name">one row title 2</h2>
</div>
<div class="autoreadmore">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </article>
</div>
</div>
</body>
``` | 2019/06/27 | [
"https://Stackoverflow.com/questions/56799028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9263356/"
] | bump, for whoever is having this issue. The problem is still there.I got around it by using this in my styling:
```
mapArea:{
height:'70vh',
width:'100%',
"& div:first-child ":{
height:'100%',
width:'100%',
}
},
``` | your problem is that child div is position absolute, while the parent has width auto, auto width will adjust to it's relative content width. try to set width: 100% instead of auto on
```
<div style={{gridArea: '2 / 5 / 3 / 6'}}>
<MapContainer containerStyle={{width: '100%', height: 'auto'}} />
</div>
```
or to flex 1
```
<div style={{gridArea: '2 / 5 / 3 / 6'}}>
<MapContainer containerStyle={{flex: 1, height: 'auto'}} />
</div>
``` |
3,751 | Why does the Plutus script need be provided in the transaction?
My understanding is that a script address is just a hash of the script. In order to spend a UTxO from a script address the spending transaction needs to include the script. The validator will check if the attached script's hash matches the script address and then execute the script to check if the input is allowed to be spent.
So the script needs to be known to whoever wants to spend a UTxo from a script address. The actual script can be attached to the UTxO when it is created on the script address so you can know what script needs to be used to unlock the funds. However, you still need to provide the script in the spending transaction.
This means that any time a UTxO from a smart contract address is spent, the transaction needs to include the script. If the script was stored separately on the address, then a spending transaction would only need to *point* to that script instead of spamming the blockchain with duplicate data. What am I missing here? | 2021/09/13 | [
"https://cardano.stackexchange.com/questions/3751",
"https://cardano.stackexchange.com",
"https://cardano.stackexchange.com/users/780/"
] | An update on one part of the question that hasn't been addressable till now
>
> If the script was stored separately on the address, then a spending
> transaction would only need to point to that script instead of
> spamming the blockchain with duplicate data. What am I missing here?
>
>
>
Well, this is exactly what a new Cardano Improvement Proposals called CIP-33 (Reference scripts) seems to be rooting for.
From the [CIP-33 proposal](https://cips.cardano.org/cips/cip33)
>
> We propose to allow scripts ("reference scripts") to be attached to
> outputs, and to allow reference scripts to be used to satisfy script
> requirements during validation, rather than requiring the spending
> transaction to do so. This will allow transactions using common
> scripts to be much smaller.
>
>
>
at the end it summarizes as below:
>
> The key idea of this proposal is stop sending frequently-used scripts
> to the chain every time they are used, but rather make them available
> in a persistent way on-chain.
>
>
>
So fingers crossed, if this makes it into some future release, we will have enormous reduction in size of transactions and a lot more transactions would fit in into a block.
UPDATE: The Vasil hard fork is happening on mainnet on 22 Sep 2022 (already available on testnet)
Other CIPs of interest :
1. [CIP32 - Inline Datums](https://github.com/cardano-foundation/CIPs/pull/160)
2. [CIP31 - Reference Inputs](https://github.com/cardano-foundation/CIPs/pull/159) | >
> If the script was stored separately on the address, then a spending transaction would only need to point to that script instead of spamming the blockchain with duplicate data.
>
>
>
It's true that you could minimalize the size of transactions gossiped around the network by storing the script on-chain, but there are other resources to consider. Storage on the blockchain is very expensive because everything on there is permanent. Once something is added, it will need to be included every time someone builds a node for all eternity (with the exception of pruned networks).
I think in a world where we stream Netflix at 4K, including the script in the transaction seems like a negligible cost to me. The payoff might not be there for the busiest dApps, but seems like a safer bet for a vast majority of junk on the chain. |
28,052,924 | I think this image explains it all. I have a subclass of UIView that I've entered into the class field. I'm trying to connect ibOutlets between the storyboard and class implementation. It's not giving me an error, but it's not working either. Is this another xcode bug, or am I expecting this to work in a way that it won't?
 | 2015/01/20 | [
"https://Stackoverflow.com/questions/28052924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2471333/"
] | Here is a solution:
1) Type an IBOutlet **by hands** in your header file, *example*:
```
@property (strong, nonatomic) IBOutlet ProgressBarElementView *targetProgressElement;
```
2) Drag the pin **from the code** to the *element* in document outline zone
[](https://i.stack.imgur.com/qI1rm.png) | To overcome XCode stubborness, especially when you need to hook up different enums from `UIControlEvent` than `UIControlEventTouchUpInside`, I'd rather use code directly from within the custom view class:
*SWIFT*
```
button.addTarget(self, action:#selector(ClassName.handleRegister(sender:)),
for: .touchDragExit)
```
*OBJECTIVE-C*
```
[self.button addTarget:self
action: @selector(buttonTouchDragExitAction:)
forControlEvents:UIControlEventTouchDragExit];
```
One might include such code in `awakeFromNib` or `viewDidLoad` or where it best suits. |
14,910,724 | if I have this:
(I already declared the variables)
```
random1 = new Random();
Console.WriteLine(random1.Next(1, 100));
Console.WriteLine(random1.Next(1, 100));
```
When I have that, it'll generate a different number for every time I call console.writeline, so this would generate ex. 10, 55 and if you do it again 20,60 so basically random numbers each time, good.
But when I add this:
```
random2 = new Random();
Console.WriteLine(random1.Next(1, 100));
Console.WriteLine(random1.Next(1, 100));
Console.WriteLine(random2.Next(1, 100));
Console.WriteLine(random2.Next(1, 100));
```
Random1 will generate the same numbers as random! So it will be ex. 5,54,5,54 and if i do it again 70,34,70,34. But it's random2 is a new object so why is it generating the same numbers as random1??
Another example:
If I have class like this
```
class RandomNumber
{
Random random = new Random();
public int getrandomnumber { get { return random.Next(1, 5); } }
}
```
After doing this
```
randomnumberobject = new RandomNumber();
randomnumberobject2 = new RandomNumber();
Console.WriteLine(randomnumberobject.getrandomnumber);
Console.WriteLine(randomnumberobject2.getrandomnumber);
```
They'll generate a random number, but both of them will generate the exact same random number. So first time i'd get this 5,5 second time this 3,3 and so on.
But if I change the class to this
```
class RandomNumber
{
Random random;
public int getrandomnumber { get { return random.Next(1, 5); } }
public RandomNumber(Random random) { this.random = random; }
}
```
And do this instead
```
random = new Random();
randomnumberobject = new RandomNumber(random);
randomnumberobject2 = new RandomNumber(random);
Console.WriteLine(randomnumberobject.getrandomnumber);
Console.WriteLine(randomnumberobject2.getrandomnumber);
```
Suddenly, they both generate different random numbers! So why does this happen? What's the reason? Keep in mind, I'm still kind of a beginner. | 2013/02/16 | [
"https://Stackoverflow.com/questions/14910724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2053323/"
] | What you see is "by design" - i.e. it happens because of how the class is implemented... the algorithm it uses needs a "seed" (kind of a starting state) which in this case is based on the clock... as documented on [MSDN](http://msdn.microsoft.com/en-us/library/system.random.aspx):
>
> The random number generation starts from a seed value. If the same
> seed is used repeatedly, the same series of numbers is generated. One
> way to produce different sequences is to make the seed value
> time-dependent, thereby producing a different series with each new
> instance of Random. By default, the parameterless constructor of the
> Random class uses the system clock to generate its seed value, while
> its parameterized constructor can take an Int32 value based on the
> number of ticks in the current time. However, because the clock has
> finite resolution, using the parameterless constructor to create
> different Random objects in close succession creates random number
> generators that produce identical sequences of random numbers. The
> following example illustrates that two Random objects that are
> instantiated in close succession generate an identical series of
> random numbers.
>
>
>
This means basically that if two `Random` objects are created at nearly the same time using the parameterless constructor they will produce the same sequence of random numbers since they have been initialized with the same "starting state" based on the clock. | Random number generation works based on a seed value in most of the programming languages. This seed is usually taken from a current time value. So if you declare the two Random objects close to each other, most likely they will obtain the same seed from the CLR. That's why they will generate the same numbers.
When you use the same instance, the first two numbers will already come from the random sequence, so the next two won't be the same.
Use the explicit seed in such situations (the constructor of Random which is overloaded with an int value). |
14,714,877 | I downloaded and extracted Crypto++ in C:\cryptopp. I used Visual Studio Express 2012 to build all the projects inside (as instructed in readme), and everything was built successfully. Then I made a test project in some other folder and added cryptolib as a dependency. After that, I added the include path so I can easily include all the headers. When I tried to compile, I got an error about unresolved symbols.
To remedy that, I added `C:\cryptopp\Win32\Output\Debug\cryptlib.lib` to link additional dependencies. Now I get this error:
```
Error 1 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(cryptlib.obj) CryptoTest
Error 2 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(iterhash.obj) CryptoTest
Error 3 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(sha.obj) CryptoTest
Error 4 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(pch.obj) CryptoTest
Error 5 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(misc.obj) CryptoTest
Error 6 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(queue.obj) CryptoTest
Error 7 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(algparam.obj) CryptoTest
Error 8 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(filters.obj) CryptoTest
Error 9 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(fips140.obj) CryptoTest
Error 10 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(cpu.obj) CryptoTest
Error 11 error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in program.obj C:\Data\Work\C++ VS\CryptoTest\CryptoTest\cryptlib.lib(mqueue.obj) CryptoTest
```
I also get:
```
Error 12 error LNK2005: "public: __thiscall std::_Container_base12::_Container_base12(void)" (??0_Container_base12@std@@QAE@XZ) already defined in cryptlib.lib(cryptlib.obj) C:\Data\Work\C++ VS\CryptoTest\CryptoTest\msvcprtd.lib(MSVCP110D.dll) CryptoTest
Error 13 error LNK2005: "public: __thiscall std::_Container_base12::~_Container_base12(void)" (??1_Container_base12@std@@QAE@XZ) already defined in cryptlib.lib(cryptlib.obj) C:\Data\Work\C++ VS\CryptoTest\CryptoTest\msvcprtd.lib(MSVCP110D.dll) CryptoTest
Error 14 error LNK2005: "public: void __thiscall std::_Container_base12::_Orphan_all(void)" (?_Orphan_all@_Container_base12@std@@QAEXXZ) already defined in cryptlib.lib(cryptlib.obj) C:\Data\Work\C++ VS\CryptoTest\CryptoTest\msvcprtd.lib(MSVCP110D.dll) CryptoTest
Error 15 error LNK2005: "public: __thiscall std::locale::id::id(unsigned int)" (??0id@locale@std@@QAE@I@Z) already defined in cryptlib.lib(iterhash.obj) C:\Data\Work\C++ VS\CryptoTest\CryptoTest\msvcprtd.lib(MSVCP110D.dll) CryptoTest
Warning 16 warning LNK4098: defaultlib 'LIBCMTD' conflicts with use of other libs; use /NODEFAULTLIB:library C:\Data\Work\C++ VS\CryptoTest\CryptoTest\LINK CryptoTest
Error 17 error LNK1169: one or more multiply defined symbols found C:\Data\Work\C++ VS\CryptoTest\Debug\CryptoTest.exe 1 1 CryptoTest
```
The code I tried to compile was simple (I got this from another site):
```
#include <iostream>
#include <string>
#include "sha.h"
#include "hex.h"
using namespace std;
string SHA256(string data) {
byte const* pbData = (byte*) data.data();
unsigned int nDataLen = data.size();
byte abDigest[32];
CryptoPP::SHA256().CalculateDigest(abDigest, pbData, nDataLen);
return string((char*)abDigest);
}
int main(void) {
return 0;
}
```
Any ideas how to fix this? I really only need SHA-256 right now, nothing else.
I am using Windows 7 64 bit, and I downloaded VS C++ today, so it should be the newest version. | 2013/02/05 | [
"https://Stackoverflow.com/questions/14714877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2007674/"
] | (This is already answered in comments, but since it lacks an actual *answer*, I'm writing this.)
This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are *using different versions of the CRT (the C RunTime library.)*
To correct this error, you need to go into your `Project Properties` (and/or those of the libraries you are using,) then into `C/C++`, then `Code Generation`, and check the value of `Runtime Library`; this should be exactly the same for *all* the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)
There are currently four options for this setting:
1. Multithreaded Debug
2. Multithreaded Debug DLL
3. Multithreaded Release
4. Multithreaded Release DLL
Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug *DLL*" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.
Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.
For (some) more information, you can see these (linked from a comment above):
1. [Linker Tools Warning LNK4098](http://msdn.microsoft.com/en-us/library/6wtdswk0%28v=vs.110%29.aspx) on MSDN
2. [/MD, /ML, /MT, /LD (Use Run-Time Library)](http://msdn.microsoft.com/en-us/library/2kzt1wy3%28v=vs.110%29.aspx) on MSDN
3. [Build errors with VC11 Beta - mixing MTd libs with MDd exes fail to link](https://bugzilla.mozilla.org/show_bug.cgi?id=732124) on Bugzilla@Mozilla
**UPDATE**: (This is in response to a comment that asks for the reason that this much care must be taken.)
If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless *great* care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)
The most important part of the problem is this: *having the same idea about the size of objects on either side of a function call*.
Consider for example that the above two pieces of code are called `A` and `B`. A is *compiled* against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a `FILE` object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)
Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)
The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.
All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)
This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.
What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it! | I had this problem along with mismatch in ITERATOR\_DEBUG\_LEVEL.
As a sunday-evening problem after all seemed ok and good to go, I was put out for some time.
Working in de VS2017 IDE (Solution Explorer) I had recently added/copied a sourcefile reference to my project (ctrl-drag) from another project. Looking into properties->C/C++/Preprocessor - **at source file level, not project level** - I noticed that in a Release configuration \_DEBUG was specified instead of NDEBUG for this source file.
Which was all the change needed to get rid of the problem. |
4,139 | I've got a somewhat obfuscated javascript file with multiple variables named `a##########`, where `#` stands for a single `0-9` digit. Each such identifier may or may not be unique.
I was substituting these manually, using `:%s/<c-r>k/f#/g`, where `k` was the register I put one of these identifiers and `#` was a number I was incrementing manually.
This soon proved quite slow and tedious, as well as error-prone, so I decided to do them all at once, automatically. I tried the help files and online and came up with this (after I'd named the first 30 occurrences manually):
`let: counter = 31 | g/a\d\{10\}/s//\="f".counter/ | let counter = counter + 1`
This worked, except instead of running each substitution globally, it ran it for each match individually, thus distorting the meaning of the identifiers (e.g. where there would be `a234789453` 5 times, it would give me `f1`, `f2` etc. for each match, instead of replacing all instances of the same match with the same text).
So I ran the same, placing the regex in `s`'s call and using the `g` flag for `s` and got the same results, whether I made these modifications to the original command alone or separately. Then I tried:
`let: counter = 31 | %s/a\d\{10\}/\="f".counter/ | let counter = counter + 1`
Which resulted in *all* occurences of the pattern being replaced by `f31`, regardless of the `g` flag or not.
Clearly, the issue is that I need to run `%s/__match__/\="f".counter/g` for each match specifically, but I can't seem to find a way to explain this to vim.
**Is there a way to run a global substitute for each unique match of a regex?** | 2015/08/02 | [
"https://vi.stackexchange.com/questions/4139",
"https://vi.stackexchange.com",
"https://vi.stackexchange.com/users/1275/"
] | Although I think John's answer is quite good, I thought of a different way to achieve this. It still requires a custom function, but it is a little bit simpler.
The idea is to create an incrementer object that keeps track of the individual variable IDs. To do this, we define a dictionary with an incrementer function (you can add this for example to your vimrc):
```
let g:incrementer = {
\ 'n' : 31,
\ 'ids' : {},
\ }
function! g:incrementer.increment(id)
if !has_key(self.ids, a:id)
let self.ids[a:id] = self.n
let self.n += 1
endif
return 'f' . self.ids[a:id]
endfunction
```
With the above code loaded, you can perform the substitution similar to how you tried it yourself:
```
:%s/a\d\{10\}/\=g:incrementer.increment(submatch(1))/g
``` | Many linux distributions offer a Vim with Perl support. If this is the case we can use `:perl perl-command` and `:perldo perl-command`:
```
:perldo $c=31
:perldo s/a(\d{10})/$m{$1} ||= $c++; "f$m{$1}" /ge
```
(untested)
The solution presented is in fact very similar to the question...
* `:perldo perl-command` executes perl-command for the range (def: all lines)
* if "perl-command" modifies the default string, the line gets modified. Perl's `s/regExp/str/` is very similar to vim's s///...
* but "eval" option: `s/RegExp/perl-exp/e` is nice and powerful: it substitutes by `eval-in-perl(perl-exp)`, in our case:
+ for all occurences of `a\d{10}`
+ define a new number if we have a new case: `$m{number} = $n{number} || $c++`
+ replace by `fNUMBER`
* RegExp (following the question) is "a" followed by 10 digits (`\d{10}`) |
31,390,105 | Is it possible to do something only if a Jasmine test fails? Juxtaposed with `afterEach()` which executes after an `it()` regardless of outcome, I'm looking for some way to execute code only after an `it()` has a failed expectation.
This question is not Angular-specific, but in my scenario I am testing an Angular service which outputs debug messages using `$log`. I don't want to clutter my console for tests that are successful, but only show the additional information for failing tests.
```
describe("MyService", function() {
var MyService, $log;
beforeEach(function() {
inject(function (_MyService_, _$log_) {
MyService = _MyService_;
$log = _$log_;
});
});
afterEach(function () {
if (/* test failed */) {
//console.log($log.debug.logs);
}
});
it("should output debug logs when this fails", function() {
//do something with MyService that would put a message in $log
expect(false).toBe(true);
});
});
```
I'm running Jasmine 2.2.0.
Edit: [here](http://jsfiddle.net/dimmreaper/Lfvhjdjh/)'s a very simple fiddle which shows the Jasmine 1.3 `jasmine.getEnv().currentSpec` solution no longer working. | 2015/07/13 | [
"https://Stackoverflow.com/questions/31390105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123195/"
] | Here's a hack to re-enable `jasmine.getEnv().currentSpec` in Jasmine 2 (sort of, `result` isn't the full `spec` object, but contains `id`, `description`, `fullName`, `failedExpectations`, and `passedExpectations`):
```
jasmine.getEnv().addReporter({
specStarted(result) {
jasmine.getEnv().currentSpec = result;
},
specDone() {
jasmine.getEnv().currentSpec = null;
}
});
``` | I wanted to do something similar on jasmine 2.5.2 (having custom logger object which would print out only when test fails, without having to do it manually).
Struggled quite a bit to make it work generically through beforeEach/afterEach, finally I caved in to an uglier solution
```
// logger print on fail
function collectSpecs(suite: jasmine.Suite): jasmine.Spec[] {
const result: jasmine.Spec[] = [];
const process = [suite];
while (process.length) {
const suite = process.pop();
const children = <jasmine.SuiteOrSpec[]> <any> suite.children; // wrong jasmine typing
children.forEach(item => {
switch (item.constructor.name) {
case "Suite":
process.push(<jasmine.Suite>item);
break;
case "Spec":
result.push(<jasmine.Spec>item);
break;
}
});
}
return result;
}
function findSpec(specId: string): jasmine.Spec {
const rootSuite: jasmine.Suite = jasmine.getEnv()["topSuite"]();
return collectSpecs(rootSuite)
.filter(s => `${s.id}` === specId)[0]; // wrong jasmine typing on id
}
const loggerSpecProperty = "logger";
function createReporter(): jasmine.CustomReporter {
return {
specDone: (result: jasmine.CustomReporterResult) => {
const spec = findSpec(result.id);
if (result.failedExpectations.length) {
const logger: modLog.MemoryLogger = spec[loggerSpecProperty];
if (logger) {
console.log(`\nfailed spec logger:\n${logger.lines.join("\n")}`);
}
}
delete spec[loggerSpecProperty];
}
};
}
export function registerReporter(): void {
jasmine.getEnv().addReporter(createReporter());
}
function createLogger(): modLog.MemoryLogger {
return new modLog.MemoryLogger(modLog.LogLevel.debug);
}
interface IItCallback {
(done?: Function): void;
}
interface IItFunctionTyping {
(name: string, callback: IItCallback): void;
}
interface IItFunction {
(name: string, callback: IItCallback): jasmine.Spec;
}
// bad typings on it/xit/fit, actually returns Spec but is typed as void
export function lit(fnIt: IItFunctionTyping, name: string, callback: IItCallback): jasmine.Spec {
function inner(spec: jasmine.Spec, done?: Function) {
const log = createLogger();
this.log = log;
spec[loggerSpecProperty] = log;
callback.call(this, done);
}
const itFunc = <IItFunction> (fnIt || it);
if (callback.length) {
const spec = itFunc(name, function (done) {
inner.call(this, spec, done);
});
return spec;
} else {
const spec = itFunc(name, function () {
inner.call(this, spec);
});
return spec;
}
}
```
some unneccessary type mumbo jumbo there due to @types/jasmine obscuring some details of the actual implementation (I suppose it's on purpose, typing version matches the jasmine package version), but I also wanted to practice my TypeScript
passing "it" function to still allow for xit/fit when needed
modLog is my logger module, override this to suite your needs
usage:
instead of
```
it("should do something", function (done) {
done();
});
```
use
```
lit(it, "should do something", function (done) {
this.log.debug("test");
fail("test output");
done();
});
```
(not very well documented but I think you can get the picture)
it would be much nicer if there was a way for customReporter to access the spec context
(then again this all is basically only for debugging purposes, you could as well add console.log to specific test when it fails and you're struggling with the details, but it was interesting excercise in getting to know jasmine a bit more) |
9,675,668 | Hey I have this code that sends an email with some data sent by a form:
```
<?php
if (isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email ($str) {
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if ($_POST['name'] != '' && $_POST['email'] != '' && $_POST['tel'] != '' && valid_email($_POST['email']) == TRUE && strlen($_POST['comment']) > 1) {
$to = preg_replace("([\r\n])", "", $_POST['receiver']);
$from = preg_replace("([\r\n])", "", $_POST['name']);
$subject = 'Online Message';
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) || preg_match($match, $from) || preg_match($match, $message) || preg_match($match, $subject)) {
die("Header injection detected.");
}
$headers = "From: \"".$_POST['name']."\" <".$_POST['email'].">\n";
$headers .= "Reply-to: ".$_POST['email']."\r\n";
if (mail($to, $subject, $message, $headers)) {
echo 1; //SUCCESS
} else {
echo 2; //FAILURE - server failure
}
} else {
echo 3; //FAILURE - not valid email
}
} else {
die("Direct access not allowed!");
}
```
I want to add the `$_POST['tel']` to the `$message` variable so in the body of the email I can get the message plus the telephone that people type into the form. In the first part of the code I think I made the telephone input obligatory.
I tried doing `$message = $_POST['comment'] && $_POST['tel'];` but the only thing I recieve is a `1` in the body of the mail that is the first number of the telephone entered. | 2012/03/12 | [
"https://Stackoverflow.com/questions/9675668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If this is for a first time java class, my guess is he is looking for these 2 cases:
```
//the one you have, using a precreated array
double[] myArray = {1.1, 2.2, 3.3}
xMethod(myarray);
//and putting it all together
xMethod(new double[]{1.1, 2.2, 3.3});
```
Basically illustrating you can make an array to pass, or simply create one in the call.
Just a guess though | static methods are not bound to the construction of the class.
The method above can be called either by constructing the class or just by using the namespace:
```
Classname myclass = new Classname();
myclass.xMethod(myarray);
```
or you could just do:
```
Classname.xMethod(myarray);
```
as you see, you don't have to construct the class in order to use the method. On the other hands, the static method can't access non-static members of the class.
I guess that's what the question meant by 2 different ways... |
12,559,254 | ```
List userProcessedCountCol = new ArrayList();
while (iResultSet1.next()) {
afRealTimeIssuance afRealTimeIssuance = new afRealTimeIssuance();
Integer i = 0;
afRealTimeIssuance.setSub_channel(iResultSet1.getString(++i));
afRealTimeIssuance.setAgent_names(iResultSet1.getString(++i));
afRealTimeIssuance.setFtd(iResultSet1.getDouble(++i));
afRealTimeIssuance.setMtd(iResultSet1.getDouble(++i));
afRealTimeIssuance.setQtd(iResultSet1.getDouble(++i));
userProcessedCountCol.add(afRealTimeIssuance);
}
```
where afRealTimeIssuance is `ActionForm`
Using the above snippet I get something like below output
```
1 A 100
2 B 200
3 C 300
4 D 400
```
But I want to rearrange the output as
```
2 B 200
4 D 400
3 C 300
1 A 100
```
In short I want to rearrange the rows as I want.How to arrange the resultset data based on one particular value.Please guide | 2012/09/24 | [
"https://Stackoverflow.com/questions/12559254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142496/"
] | you can act as at two levels here:
* Database level
* Java level
At the database level the only way to manipulate the order of results to be returned is using ''ORDER BY ASC/DESC'' in your sql query. Note, that you can't rely on any other way to get the ordered results from the database.
At the java level you can store your objects like this:
- use a sortable collection. Make your action form comparable or implement a comparator that
allows to sort elements as you wish.
Then your can use [This method](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29) to get the ordered collection by your own criteria.
You can consider also using [TreeSet](http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html) instead of ArrayList
This data structure will allow you to just add the data and given the comparator that you've defined in advance it will be always sorted. The addition has a logarithmic complexity though, so its up to you to decide.
Hope this helps | The ResultSet cannot be rearranged manually (only with sql) . What you can rearrange is your data structure that you hold your Objects
You can use an ArrayList of your row Objects and insert each row in the **position** you would like.
Lets say in your example, in the while loop:
```
userProcessedCountCol.add(index, element);
``` |
40,226,373 | Creating a sub-theme in Drupal 7's `page.tpl.php` and needing to pull the value (plain text) from `field_EXAMPLE` from a custom content type outside of where the rest of the content would normal be.
```
<!-- Adding $title as normal-->
<?php print render($title_prefix); ?>
<?php if (!empty($title)): ?>
<h1><?php print $title; ?></h1>
<?php endif; ?>
<?php print render($title_suffix); ?>
<!-- THE ISSUE: Adding field_EXAMPLE -->
<h2> <?php print render($field_EXAMPLE;);?> </h2>
...
<!-- Where the rest of the content loads by default -->
<div><?php print render($page['content']); ?></div>
```
Would `field_get_items` work?
```
function field_get_items($entity_type, $entity, $field_name, $langcode = NULL) {
$langcode = field_language($entity_type, $entity, $field_name, $langcode);
return isset($entity->{$field_EXAMPLE}[$langcode]) ? $entity->{$field_name}[$langcode] : FALSE;
}
```
Or this?
```
$node = node_load($nid);
$node->field_EXAMPLE[$node->language][0]['value'];
```
Do I put this in `page.tpl.php`?
Tried them but no dice. -Novice
Here is var\_dump(get\_defined\_vars());
```
["field_thestring"]=>
array(1) {
["und"]=>
array(1) {
[0]=>
array(3) {
["value"]=>
string(44) "This is a string of text please refer to me "
["format"]=>
NULL
["safe_value"]=>
string(44) "This is a string of text please refer to me "
}
}
}
``` | 2016/10/24 | [
"https://Stackoverflow.com/questions/40226373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2887660/"
] | Lets assume that you created a field called `field_thestring` that you want to render for a content type `article`'s page at a location outside of `THEME`'s outside of where page's content renders.
Step 1. Copy the theme's page.tpl.php. and rename it `page--article.tpl.php`.
Step 2. In `page.var.php`,
```
function THEME_preprocess_page(&$variables) {
// To activate page--article.tpl.php
if (isset($variables['node']->type)) {
$nodetype = $variables['node']->type;
$variables['theme_hook_suggestions'][] = 'page__' . $nodetype;
}
// Prevent errors on other pages
if ($node = menu_get_object()) {
if ( !empty($node) && $node->type == 'article') {
$fields = field_get_items('node', $node, 'field_thestring');
$index = 0;
$output = field_view_value('node', $node, 'field_thestring', $fields[$index]);
$variables['thestring'] = $output;
}
else{
$variables['thestring'] = 'Angry Russian: How this error?';
}
}
}
```
Step 3. In `page--article.tpl.php` add `<?php print render($thestring); ?>`
Initially, I wanted to require all content types to have another field since all Content Types has a Title. Determined it wasn't a great idea for further development.
[Source](https://drupal.stackexchange.com/questions/20192/how-do-i-render-a-field-value-including-its-format) | You can use a preprocess to add value into $variables passed to template
<https://api.drupal.org/api/drupal/includes%21theme.inc/function/template_preprocess_page/7.x>
In template.php :
```
MYTHEMENAME_preprocess_page(&variable){
$values = current(field_get_items('node', $variable['node'],'field_machine_name'));
$variable['myvar'] = $values['value'];
}
```
In your template.tpl.php
```
echo $myvar; // contains your value
``` |
203,626 | I got a call from my company and I heard as follows:
```
Sorry, we are going to have to let you go now.
```
Can anyone tell me what does this means. | 2014/10/21 | [
"https://english.stackexchange.com/questions/203626",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/63650/"
] | "Let you go" means "fire you".
"We have to let you go" implies that they don't like to fire you. But they are in a situation that they have no other choice.
By adding "We are going to" they are saying that this situation will happen in [probably close] future. | The phrasing is the grown-ups' equivalent of getting your girlfriend to dump you so that you don't have to dump her.
We're *going to have to let you go*; in other words:
>
> We are no longer able to compel you to stay, so if you were to walk out the door and never come back, we'd simply wring our hands in despair and try to muddle through somehow. The door, by the way, is conveniently situated just over there...
>
>
> |
15,274,710 | Quick question. I am binning a variable in a number of different ways for exploratory data analysis. Let's say I have a variable called `var` in data.frame `df`.
```
df$var<-c(1,2,8,9,4,5,6,3,6,9,3,4,5,6,7,8,9,2,3,4,6,1,2,3,7,8,9,0)
```
So far, I've employed the following approaches (code below):
```
#Divide into quartiles
df$var_quartile <- with(df, cut(var, breaks=quantile(var, probs=seq(0,1, by=.25)), include.lowest=TRUE))
# Values of var_quartile
> [0,3],[0,3],(7.25,9],(7.25,9],(3,5],(3,5],(5,7.25],[0,3],(5,7.25],(7.25,9],[0,3],(3,5],(3,5],(5,7.25],(5,7.25],(7.25,9],(7.25,9],[0,3],[0,3],(3,5],(5,7.25],[0,3],[0,3],[0,3]
#Bin into increments of 2
df$var_bin<- cut(df[['var']],2, include.lowest=TRUE, labels=1:2)
# Values of var_bin
> 1 1 2 2 1 2 2 1 2 2 1 1 2 2 2 2 2 1 1 1 2 1 1 1 2 2 2 1
```
The last thing that I'd like to do is bin the variable into sections of 10 observations after it has been sorted in chronological order. This is an identical approach to splitting after finding the median (counting up to the middle observation), only I want to count in 10-observation increments.
Using my example, this would split `var` into the following sections:
```
0,1,1,2,2,2,3,3,3,3
4,4,4,5,5,6,6,6,6,7
7,8,8,8,9,9,9
```
**N.B. -- I need to run this operation in very large datasets (usually 3-6 million observations in wide form).**
How do I do this? Thanks! | 2013/03/07 | [
"https://Stackoverflow.com/questions/15274710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515626/"
] | `cut_number()` from **ggplot2** is designed to cut a numeric vector into intervals containing equal numbers of points. In your case, you might use it like so:
```
library(ggplot2)
split(var, cut_number(var, n=3, labels=1:3))
# $`1`
# [1] 1 2 3 3 2 3 1 2 3 0
#
# $`2`
# [1] 4 5 6 6 4 5 6 4 6
#
# $`3`
# [1] 8 9 9 7 8 9 7 8 9
``` | This should do it.
```
df$var_bin<- cut(df[['var']], breaks = Size(df$var/10),
include.lowest=TRUE, labels=1:10)
``` |
4,022,887 | I recently came across Pytables and find it to be very cool. It is clear that they are superior to a csv format for very large data sets. I am running some simulations using python. The output is not so large, say 200 columns and 2000 rows.
If someone has experience with both, can you suggest which format would be more convenient in the long run for such data sets that are not very large. Pytables has data manipulation capabilities and browsing of the data with Vitables, but the browser does not have as much functionality as, say Excel, which can be used for CSV. Similarly, do you find one better than the other for importing and exporting data, if working mainly in python? Is one more convenient in terms of file organization? Any comments on issues such as these would be helpful.
Thanks. | 2010/10/26 | [
"https://Stackoverflow.com/questions/4022887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/316357/"
] | Have you considered Numpy arrays?
PyTables are wonderful when your data is too large to fit in memory, but a
200x2000 matrix of 8 byte floats only requires about 3MB of memory. So I think
PyTables may be overkill.
You can save numpy arrays to files using `np.savetxt` or `np.savez` (for compression), and can read them from files with `np.loadtxt` or `np.load`.
If you have many such arrays to store on disk, then I'd suggest using a database instead of numpy `.npz` files. By the way, to store a 200x2000 matrix in a database, you only need 3 table columns: row, col, value:
```
import sqlite3
import numpy as np
db = sqlite3.connect(':memory:')
cursor = db.cursor()
cursor.execute('''CREATE TABLE foo
(row INTEGER,
col INTEGER,
value FLOAT,
PRIMARY KEY (row,col))''')
ROWS=4
COLUMNS=6
matrix = np.random.random((ROWS,COLUMNS))
print(matrix)
# [[ 0.87050721 0.22395398 0.19473001 0.14597821 0.02363803 0.20299432]
# [ 0.11744885 0.61332597 0.19860043 0.91995295 0.84857095 0.53863863]
# [ 0.80123759 0.52689885 0.05861043 0.71784406 0.20222138 0.63094807]
# [ 0.01309897 0.45391578 0.04950273 0.93040381 0.41150517 0.66263562]]
# Store matrix in table foo
cursor.executemany('INSERT INTO foo(row, col, value) VALUES (?,?,?) ',
((r,c,value) for r,row in enumerate(matrix)
for c,value in enumerate(row)))
# Retrieve matrix from table foo
cursor.execute('SELECT value FROM foo ORDER BY row,col')
data=zip(*cursor.fetchall())[0]
matrix2 = np.fromiter(data,dtype=np.float).reshape((ROWS,COLUMNS))
print(matrix2)
# [[ 0.87050721 0.22395398 0.19473001 0.14597821 0.02363803 0.20299432]
# [ 0.11744885 0.61332597 0.19860043 0.91995295 0.84857095 0.53863863]
# [ 0.80123759 0.52689885 0.05861043 0.71784406 0.20222138 0.63094807]
# [ 0.01309897 0.45391578 0.04950273 0.93040381 0.41150517 0.66263562]]
```
If you have many such 200x2000 matrices, you just need one more table column to specify which matrix. | One big plus for PyTables is the storage of metadata, like variables etc.
If you run the simulations more often with different parameters you the store the results as an array entry in the h5 file.
We use it to store measurement data + experiment scripts to get the data so it is all self contained.
BTW: If you need to look quickly into a hdf5 file you can use HDFView. It's a Java app for free from the HDFGroup. It's easy to install. |
20,270,871 | I have a file with questions and answers on the same line, I want to seperate them and append them to their own empty list but keep getting this error:
`builtins.ValueError: need more than 1 value to unpack`
```
questions_list = []
answers_list = []
questions_file=open('qanda.txt','r')
for line in questions_file:
line=line.strip()
questions,answers =line.split(':')
questions_list.append(questions)
answers_list.append(answers)
``` | 2013/11/28 | [
"https://Stackoverflow.com/questions/20270871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3046660/"
] | This is probably because when you're doing the splitting, there is no `:`, so the function just returns one argument, and not 2. This is probably caused by the last line, meaning that you're last line has nothing but empty spaces. Like so:
```
>>> a = ' '
>>> a = a.strip()
>>> a
''
>>> a.split(':')
['']
```
As you can see, the list returned from `.split` is just a single empty string. So, just to show you a demo, this is a sample file:
>
>
> ```
> a: b
> c: d
> e: f
>
> g: h
>
> ```
>
>
We try to use the following script (`val.txt` is the name of the above file):
```
with open('val.txt', 'r') as v:
for line in v:
a, b = line.split(':')
print a, b
```
And this gives us:
```
Traceback (most recent call last):
a b
c d
File "C:/Nafiul Stuff/Python/testingZone/28_11_13/val.py", line 3, in <module>
a, b = line.split(':')
e f
ValueError: need more than 1 value to unpack
```
When trying to look at this through a debugger, the variable `line` becomes `\n`, and you can't split that.
However, a simple logical ammendment, would correct this problem:
```
with open('val.txt', 'r') as v:
for line in v:
if ':' in line:
a, b = line.strip().split(':')
print a, b
``` | The reason why this happens could be a few, as already covered in the other answers. Empty line, or maybe a line only have a question and no colon. If you want to parse the lines even if they don't have the colon (for example if some lines only have the question), you can change your split to the following:
```
questions, answers, garbage = (line+'::').split(':', maxsplit=2)
```
This way, the values for `questions` and `answers` will be filled if they are there, and will be empty it the original file doesn't have them. For all intents and purposes, ignore the variable `garbage`. |
33,139,852 | Ok I'm trying to add these columns to that table but it says I have a syntax error, Please let me know whats wrong
```
ALTER TABLE equipomulti ADD
marca VARCHAR(45) NULL ,
serie VARCHAR(45) NULL ,
modelo VARCHAR(45) NULL ,
fechaAd DATE NULL ,
costo DOUBLE NULL ,
observacion VARCHAR(500) NULL ;
``` | 2015/10/15 | [
"https://Stackoverflow.com/questions/33139852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5315275/"
] | **UPDATE:**
Retrofit2.0 has now own [converter-scalars](https://github.com/square/retrofit/tree/master/retrofit-converters/scalars) module for `String` and primitives (and their boxed).
```
com.squareup.retrofit2:converter-scalars
```
---
You can write custom `Converter` and Retrofit repository has a own `String` Converter implementation sample: [ToStringConverterFactory](https://github.com/square/retrofit/blob/07d1f3de5e0eb11fb537464bd14fdbacfc9e55a7/retrofit/src/test/java/retrofit/ToStringConverterFactory.java)
```
class ToStringConverterFactory extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
if (String.class.equals(type)) {
return new Converter<ResponseBody, String>() {
@Override public String convert(ResponseBody value) throws IOException {
return value.string();
}
};
}
return null;
}
@Override public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
if (String.class.equals(type)) {
return new Converter<String, RequestBody>() {
@Override public RequestBody convert(String value) throws IOException {
return RequestBody.create(MEDIA_TYPE, value);
}
};
}
return null;
}
}
```
and related issue are tracked [here](https://github.com/square/retrofit/issues/1151). | Basically you will need to write a custom [Converter](http://square.github.io/retrofit/javadoc/index.html)
Something like this
```
public final class StringConverterFactory extends Converter.Factory {
public static StringConverterFactory create(){
return new StringConverterFactory();
}
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
return new ConfigurationServiceConverter();
}
final class ConfigurationServiceConverter implements Converter<ResponseBody, String>{
@Override
public String convert(ResponseBody value) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(value.byteStream()));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
return total.toString();
}
}
}
```
and add this using addConverterFactory |
15,409,833 | I have implemented in app billing on an Android application and although it works ok with the testing constants, it breaks on real products.
I have uploaded the application as a draft on Google Play, created and published products, installed the exact same application on the device (included the right base64EncodedPublicKey) and used the right test account (the primary account on the device & the one i did set on my developer account)
The flow is that I get on the Google Play Activity where I can see the product and its details, I press buy, introduce the test account password, it gets out of the activity, receive the congratulation message and
>
> Signature verification failed for product(response:-1003:Purchase
> signature verification failed)
>
>
>
The item is actually purchased (it appears on Google Checkout and on a 2nd buying atempt it says "Item already owned"). Also I have used only the TriviaDrive example code from Google.
Any suggestions are very helpful. Thank you! | 2013/03/14 | [
"https://Stackoverflow.com/questions/15409833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597810/"
] | In the In App Billing documentation there is a section called [Initiate your connection to Google Play](http://developer.android.com/training/in-app-billing/preparing-iab-app.html#Connect).
It tells you that you would need a base64 encoded Public Key to instantiate your IabHelper. You can get this code from the Google Play Developer Console. Login into the console, click apps and then go to the "Services and API" tab.
```
IabHelper mHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
String base64EncodedPublicKey;
// compute your public key and store it in base64EncodedPublicKey
mHelper = new IabHelper(this, base64EncodedPublicKey);
}
```
Please consider the security recommendations suggested in the documentation:
>
> Security Recommendation: It is highly recommended that you do not
> hard-code the exact public license key string value as provided by
> Google Play. Instead, you can construct the whole public license key
> string at runtime from substrings, or retrieve it from an encrypted
> store, before passing it to the constructor. This approach makes it
> more difficult for malicious third-parties to modify the public
> license key string in your APK file.
>
>
> | I had this problem with my subscriptions because I haven't set the "itemType"
```
mHelper.launchPurchaseFlow(this,
SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS,
RC_REQUEST, mPurchaseFinishedListener, payload);
``` |
22,523,900 | Assume that I have some div elements like these:
```
<div class="mystyle-10">Padding 10px</div>
<div class="mystyle-20">Padding 20px</div>
<div class="mystyle-30">Padding 30px</div>
```
Is it possible to create a class or something like :
```
.mystyle-*{padding: *px; margin-left: *px; border: *px solid red; }
```
that will replace the \* with the value we set for the div's class?
Thanks in advance! | 2014/03/20 | [
"https://Stackoverflow.com/questions/22523900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/566603/"
] | Assuming the above xml is named button\_view.xml
```
View view = LayoutInflater.from(context).inflate(R.layout.button_view);
Button button = (Button) view.findViewById(R.id.BtnRating1);
```
This way you can inflate directly from xml | I gave you code how to create a button on dynamic time, you can set all property which you want for this button.
```
Button myButton = new Button(this);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.BtnRating1);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
``` |
42,228,016 | I know that this code is not good and maybe it's stupid question but can anybody explain me why it works in this way?
I have this simple class
```
public class Customer
{
public string Name { get; set; }
}
```
And I have next method with Action delegate
```
private Customer GetCustomer(Action<Customer> action)
{
var model = new Customer { Name = "Name 1" };
action?.Invoke(model);
return model;
}
```
Then I execute this method with delegate and write into console model.Name
```
var model = GetCustomer(c => c = new Customer { Name = "Name 2" });
Console.WriteLine(model.Name);
```
I expected to get "Name 2". But I get "Name 1" - which is value of the class defined inside method. I understand that to get what I want - I could write code in this way:
```
var model = GetCustomer(c => c.Name = "Name 2");
Console.WriteLine(model.Name);
```
And everything will be ok. But why my first implementation doesn't work?
I would be thankful a lot if somebody explain me this. | 2017/02/14 | [
"https://Stackoverflow.com/questions/42228016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3473079/"
] | `c` in your lambda is only assigning to the parameter, its not assinging it back to `model` in `GetCustomer`. | In your lambda expression, you are just saying that `c` and `model` are pointing to the same reference. And then you are changing the reference of `c`. At the end `model` is still referencing to the previous instance. This is the equivalent code of what you are trying to do:
```
var model = new Customer { Name = "Name 1" };
var c = model;
c = new Customer { Name = "Name 2" };
```
But, `model.Name` is still `Name1`.
You can change your code as if you want to change one of hte properties:
```
var model = GetCustomer(c => c.Name = "Name2");
Console.WriteLine(model.Name);
``` |
46,909 | There are a few philosophers who still push the “perverted faculty argument” to prove that contraception, homosexual acts and masturbation are immoral. This argument is based on classic natural law, which is itself based on a metaphysics that assumes essentialism and teleology (broadly Aristotelian).
Because of that, it's usually not taken seriously anymore. It would still be interesting to find out if such arguments even fail at a **late** stage, when a lot of heavy lifting has already been done (that is, the opponent has granted all the relevant metaphysical foundations).
One version is the 40-page article by Edward Feser: *[In Defense of the Perverted Faculty Argument](https://drive.google.com/file/d/0B4SjM0oabZazWC1SRmN0WXVpYkE/view)* (please read *at least* the twelve pages of part IV. before answering, thank you).
He states his key premise (full argument on page 403f) as:
>
> Where some faculty *F* is natural to a rational agent *A* and by nature exists for the sake of some end *E* (and exists in *A* precisely *so that* *A* might pursue *E*), then it is *metaphysically impossible* for it to be good for *A* to use *F* in a manner contrary to *E*.
>
>
>
Since he doesn't want to condemn chewing gum as immoral, he grants that using a faculty *F* for an end “other than” *E* is morally neutral.
>
> Hence examples like chewing gum (which is merely other than, rather than contrary to, the natural end of our digestive faculties) […] simply miss the point of the argument.
>
>
>
But chewing gum looks *strikingly* parallel to masturbation. It even [decreases appetite](http://www.sciencedirect.com/science/article/pii/S0031938415300317), like masturbation temporarily reduces sexual tension. The digestive system prepares for food, but no food is taken. The reproductive system of a solitary masturbating woman prepares for heterosexual intercourse (or so claims Feser), but in the end, no man has sex with her.
So to finally get to the question:
In the article, is the differentiation between “contrary to” and “other than” really meaningful? If yes, then how exactly should we understand it? If not, can you go into more details how and why the reasoning here became fallacious?
PS: I'm genuinely just trying to *understand* how people manage to reach such strange conclusions – no intentions to make this an “am I right?” post. | 2017/10/31 | [
"https://philosophy.stackexchange.com/questions/46909",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/18903/"
] | There is absolutely no empirical evidence that masturbation, anal, oral sex or homosexual sex diminishes the faculty to procreate. It could even be argued that, by releasing sexual impulse in a contraceptive fashion, it can help people who are already parents to keep their offspring at a sustainable quantity, securing the long term survival of the human species, which is after all the very goal of procreation. So that is teleology for you.
Given that procreation abilities are not diminished, it can't be argued that those sexual behaviors are "contrary" to the goal of reproduction in anyway, even granting the teleological premise. They are at worst leasurly use of a natural faculty, at best, as demonstrated above, a useful complement to the goal of reproduction.
Therefore, the distinction between chewing gum and masturbation looks very much like special pleading. "Masturbation I dislike, so not ok. But if I follow my logic a lot of other popular behaviors will be forbidden as well, and that will alienate support for my position. So, they are ok, because reasons." | The perverted faculty argument says that it is perverted to use the given faculty in a manner whereby it circumvents its intended end. What Edward Feser fails to explain is that it is not the sex that prevents the conception of children after i get my vasectomy. It's the method of contraception. Further the intended purpose of sex is pleasure. If you are achieving that without perversions such as homosexuality or such you are achieving the intended purpose of sex. I would venture to say that the true perversion is what happens when a child is conceived and carried to term. Honestly if there has been a time in recent history outside of primitive cultures where it would be sane to want a child I haven't heard of it. |
20,174,542 | I couldn't find the ".NET CLR Memory" counter category programmatically (in c#), as in [this](https://stackoverflow.com/q/4705698/738851) question. Running as admin solved the issue.
But why do I need to do this? Is there an alternative? I want readonly access, to see GC generation collections inside my app for profiling purposes. Preferably without having to run the app with admin privileges.
**Edit:**
* I can see the Memory performance counters in the Performance Monitor tool, without running as Admin
* Without running as Admin, I can get a shortened (but not empty) list of performance counter categories programmatically, but this doesn't include the one I'm interested in.
* Our corporate setup is a bit crazy: I have admin privileges, but am not a member of the local admins group. I do have the privileges to add myself, but every 30 minutes or so some automated process removes me. Don't know if this affects anything
* Adding myself to the Performance Monitor Users group had no effect (unless I need to reboot first) | 2013/11/24 | [
"https://Stackoverflow.com/questions/20174542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738851/"
] | You only need to be in group *Performance Monitor Users*. Simply adding your non admin user to that group should fix the problem. | Performance counters are a security hazard. One of the common attack techniques is to observe the execution of secured code. A very common mistake in such code is it not having constant execution time, taking inappropriate shortcuts when a password is invalid for example. This can greatly reduce the number of brute force attack attempts.
In spirit, it will certainly look like you want to bypass your company's security policy. Be wary of mistrusting sys admins, they tend to take this seriously and won't hesitate to report violations. It is certainly best to talk to one of them instead of trying to hack around it. You could look at Perfmon.exe's security demands with SysInternals' Process Explorer. I see a mandatory demand for the built-in "Performance Log Users" group, sounds relevant. |
12,203,272 | i am trying to improve my jQuery skills and therefore i write a own lightbox.
But there is one thing which drives me crazy. How can i animate a div like the other lightboxes. Starting in the middle and spread out to each side. I am helpless.
Is that possible with that special easing properties, which are provided by jQuery?
[Here is jsFiddle to inspect.](http://jsfiddle.net/x5A42/5)
```
$('#clickme').click(function() {
$('#book').animate({
width: 'toggle',
height: 'toggle'
}, {
duration: 5000,
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
complete: function() {
$(this).after('<div>Animation complete.</div>');
}
});
});
```
I hope someone can help me :) | 2012/08/30 | [
"https://Stackoverflow.com/questions/12203272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/787999/"
] | You can also animate the top and left position of the div to give the effect of resizing relative to the center of the element.
**[jsFiddle example](http://jsfiddle.net/j08691/x5A42/14/)**
```
$('#clickme').click(function() {
$('#lightbox').fadeIn();
$('#lightbox').animate({
width: 500,
height: 250,
top:5,
left:10
});
});
``` | replace this, jquery.
Will close your opened div as well.
Thanks 'j08691' for the help.
`$('#clickme').click(function() {
$('#lightbox').fadeIn();
$('#lightbox').animate({
width: 500,
height: 250,
top:5,
left:10
});});`
`$('#lightbox').click(function() {
$('#lightbox').animate({
width: 0,
height: 0,
top:0,
left:0,
}).fadeOut();
});` |
16,010 | I know it is referring to Shanghai, and Baidu has a handy explanation of its origins [here](http://baike.baidu.com/subview/1353406/10221125.htm), but how would you translate it? "The Mystic Capital"? "The Devilish Capital"?
In the theme of 帝都 to describe Beijing as the "The Imperial capital" etc. | 2015/09/19 | [
"https://chinese.stackexchange.com/questions/16010",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/11057/"
] | Why not "Mordor"... I have always believed this is the only correct transl(iter)ation. | Strictly on its own and without any contextual reference, 魔都, can only mean "Devil / Evil City" and calling it a "Metropolis" makes no semantic difference.
Since the author 村松梢風, Muramatsu Shōfu, is Japanese, then the Japanese translation for 魔都 should carry the intended meaning; and as I found out, 魔都 is "Mazu" which means "Magic City"
But WiKi says, "In his 1924 novel Mato (“Demon City”, 1924), he portrayed the dichotomy of Shanghai – a modern, beautiful, civilized façade, hiding a darker side populated by all manner of criminals and vice"
So there you have it. Pick the one meaning that suits your idea of Shanghai, now and in 1924, assuming you were alive in Shanghai then. |
14,178,814 | I have a database with a little over 300 rows.
For various reasons I only want to search 21 rows at a time for specific terms and at different starting index points.
I am querying for 'banned commercials' in a column called `search_terms`.
When I use the query below it searches all 300 rows 'banned commercials' instead of just 21 rows.
```
SELECT `rating_score`
FROM archived_videos
WHERE search_terms='banned commercials'
ORDER BY `rating_score` DESC
LIMIT 0,21
``` | 2013/01/06 | [
"https://Stackoverflow.com/questions/14178814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422657/"
] | Try using this
```
SELECT rating_score FROM archived_videos WHERE search_terms='banned commercials' ORDER BY rating_score DESC LIMIT 21
```
Limiting it specifying 21 will limit the results to first 21 | I take it from your question that you want to search a block of 21 rows, not limit the result set to 21 rows. The LIMIT clause limits the results, not the set of records being searched. To limit records, you need to add something to your where clause. What this is depends on the contents of your table. If you had a sequence column that numbered the rows from 1 to 300, you could say "where sequence>= 1 and sequence < 21", and adjust the numbers as appropriate.
Another way to do it is to add a select clause:
```
select iif (search_terms="banned", 1, 0) as flag
into temp_table
from archived_videos
limit 21
select * from temp_table where flag = 1
```
You might be able to combine these two selects into one using a subselect. |
12,349,829 | My Sql table is similar like below
```
Code Value ID
A 100 1
A 200 2
A 300 3
B 200 1
B 500 2
B 600 3
C 800 1
C 700 2
C 200 3
```
How I can write query in sql server 2008 to get values in below format.
```
ID A B C
1 100 200 800
2 200 500 700
3 300 600 200
``` | 2012/09/10 | [
"https://Stackoverflow.com/questions/12349829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597933/"
] | Use PIVOT
```
select ID,[A],[B],[C]
from your_table T
PIVOT (MAX(Value) FOR Code in ([A],[B],[C]) )P
```
IF the number if Codes are not fixed you could use **dynamic pivot**
```
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Code)
from your_table
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ID, ' + @cols + '
from your_table
pivot
(
MAX([Value])
for Code in (' + @cols + ')
) p '
print(@query)
execute(@query)
``` | The answer is [PIVOT](http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx)
```
DECLARE @t TABLE (Code varchar(10), Value int, Id int)
INSERT INTO @t VALUES
('A',100,1),
('A',200,2),
('A',300,3),
('B',200,1),
('B',500,2),
('B',600,3),
('C',800,1),
('C',700,2),
('C',200,3);
SELECT ID,[A],[B],[C]
FROM @t
PIVOT (SUM(Value) FOR Code IN ([A],[B],[C]))P
```
**Result**
```
ID A B C
1 100 200 800
2 200 500 700
3 300 600 200
``` |
6,454,631 | I know in jQuery, `$(callback)` is the same as `jQuery(callback)` which has the same effect as `$(document).ready()`.
How about
```
jQuery(function($) {
});
```
Can some one explain to me what does this kind of function mean?
What does it do?
what is the difference between this one and `$(callback)`??
what is the difference between this one and `$(function())`?? | 2011/06/23 | [
"https://Stackoverflow.com/questions/6454631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/740018/"
] | * `$(function())` is a syntax error.
* `$()` creates an empty jQuery object.
* `$(document).ready(function() { ... })` executes the given function when the DOM is ready
* `$(function() { ... })` is a shortcut for the same thing
* `jQuery(function($) { ... })` does so, too, but it also makes `$` available inside the function no matter what it's set to outside. | So I was corrected on this and if you read the first comment it gives some context.
```
jQuery(function() {
// Document Ready
});
(function($) {
// Now with more closure!
})(jQuery);
```
I'm not 100% sure but I think this just passes the jQuery object into the closure. I'll do some digging on the google to see if I am right or wrong and will update accordingly.
EDIT:
I'm pretty much right, but here it is straight from their website:
<http://docs.jquery.com/Plugins/Authoring>
"Where's my awesome dollar sign that I know and love? It's still there, however to make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution." |
85,946 | I started the game with more city-states than the game can handle and therefore was able to pick up a lot of free labor from city-state settlers who were just standing there doing nothing.
I glossed over warnings that I am making the coalition of city states angry at me. Now, right after saving a game I attacked a city state that I want to have tactically, but more than half the rest declared permanent war on me. Is there a way for me to bully, trick, or otherwise convince Dublin to declare war on me so that it is an act of aggression on their part? Or do I have to wait for another civilization (which is also a target for me soon) to make friends/allies with Dublin and declare war on the Washington?
That may be more trouble than it is worth. My preferable strategy at this point would be to take Dublin as a bridge into my next biggest rivals - and I would not feel a need to take any other city states the rest of the game (although they don't know that). | 2012/09/27 | [
"https://gaming.stackexchange.com/questions/85946",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/33608/"
] | There are only three situations where a city state will declare war on an actual civilization:
1. You're too aggresive towards city-states, and many of them band together and declare permanent war against you.
2. They're allied with someone you're at war with.
3. You declare war on them enough times that they alone go to permanent war with you.
Unfortunately, there isn't any way to provoke just Dublin to declare war on you, without you already being the aggressor.
I see your options as just attacking Dublin anyway, ignoring Dublin and sending your troops through their territory, or making Dublin your ally. If you can afford to make Dublin your ally, that could be a good approach as they would help you with the war. If you ignore them and use their territory, they'll hate you but they won't do anything about it. | As far as I know, a single city state will never declare war on you unless they are allied with a larger civilization with whom you are at war. |
53,176,287 | I want to web scrape this site 'http://mbsweblist.fsco.gov.on.ca/agents.aspx'. I have last names of a list of agents. Upon searching using last name it returns license id which is a hyperlink which takes you to another page with their licensing information such as expiry date.
This is the code I have so far. But it only searches for 1 name at a time. How do I search and retrieve License Number and Date of Expiry for lets say a 1000 names?
```
import requests
from bs4 import BeautifulSoup
def get_result_page_ontario(name):
r = requests.post("http://mbsweblist.fsco.gov.on.ca/agents.aspx",
data={
'ctl00$ctl00$MainPlaceHolder$Content4$bkmbname:': 'crossley',
'_EVENTTARGET': '',
'__EVENTARGUMENT': '',
'__LASTFOCUS': '',
'__VIEWSTATE': '/wEPDwULLTEwMzk1Nzk2NDAPZBYCZg9kFgJmD2QWBAIBD2QWAgIBDxYCHgRUZXh0BcUHPGxpbmsgcmVsPSdzdHlsZXNoZWV0JyBocmVmPSdodHRwOi8vd3d3LmZzY28uZ292Lm9uLmNhLy9TdHlsZSBMaWJyYXJ5L0ZTQ08vSW50ZXJuZXQvQ1NTL21hc3Rlci5jc3MnIHR5cGU9J3RleHQvY3NzJyBtZWRpYT0nc2NyZWVuJyAvPjxsaW5rIHJlbD0nc3R5bGVzaGVldCcgaHJlZj0naHR0cDovL3d3dy5mc2NvLmdvdi5vbi5jYS8vU3R5bGUgTGlicmFyeS9GU0NPL0ludGVybmV0L0NTUy9jaGFuZ2VtZS5jc3MnIHR5cGU9J3RleHQvY3NzJyBtZWRpYT0nc2NyZWVuJy8+PCEtLVtpZiBsdGUgSUUgNl0+PGxpbmsgcmVsPSdzdHlsZXNoZWV0JyBocmVmPSdodHRwOi8vd3d3LmZzY28uZ292Lm9uLmNhLy9TdHlsZSBMaWJyYXJ5L0ZTQ08vSW50ZXJuZXQvQ1NTL2llNi5jc3MnIHR5cGU9J3RleHQvY3NzJyBtZWRpYT0nc2NyZWVuJyAvPiA8IVtlbmRpZl0tLT48bGluayByZWw9J3N0eWxlc2hlZXQnIGhyZWY9J2h0dHA6Ly93d3cuZnNjby5nb3Yub24uY2EvL1N0eWxlIExpYnJhcnkvRlNDTy9JbnRlcm5ldC9DU1MvcHJpbnQuY3NzJyB0eXBlPSd0ZXh0L2NzcycgbWVkaWE9J3ByaW50JyAvPjxsaW5rIHJlbD0nc3R5bGVzaGVldCcgaHJlZj0naHR0cDovL3d3dy5mc2NvLmdvdi5vbi5jYS8vU3R5bGUgTGlicmFyeS9GU0NPL0ludGVybmV0L0NTUy9tb2JpbGUuY3NzJyB0eXBlPSd0ZXh0L2NzcycgbWVkaWE9J2hhbmRoZWxkJyAvPjxsaW5rIHJlbD0nc3R5bGVzaGVldCcgaHJlZj0naHR0cDovL3d3dy5mc2NvLmdvdi5vbi5jYS8vU3R5bGUgTGlicmFyeS9GU0NPL0ludGVybmV0L0NTUy9GU0NPQ3VzdG9tLmNzcycgdHlwZT0ndGV4dC9jc3MnIG1lZGlhPSdzY3JlZW4nIC8+PGxpbmsgcmVsPSdzdHlsZXNoZWV0JyBocmVmPSdodHRwOi8vd3d3LmZzY28uZ292Lm9uLmNhLy9TdHlsZSBMaWJyYXJ5L0ZTQ08vSW50ZXJuZXQvQ1NTL2dlbmVyYWwuY3NzJyB0eXBlPSd0ZXh0L2NzcycgbWVkaWE9J3NjcmVlbicgLz5kAgMPZBYKAgkPFgIeBGhyZWYFHmh0dHA6Ly93d3cuZnNjby5nb3Yub24uY2EvL2VuLxYCAgEPDxYCHghJbWFnZVVybAVKaHR0cDovL3d3dy5mc2NvLmdvdi5vbi5jYS8vU3R5bGUgTGlicmFyeS9GU0NPL0ludGVybmV0L0ltYWdlcy9GU0NPbG9nby5naWZkZAILD2QWCAIBDxYCHwEFHmh0dHA6Ly93d3cuZnNjby5nb3Yub24uY2EvL2VuL2QCAw8WAh8BBTZodHRwOi8vd3d3LmZzY28uZ292Lm9uLmNhLy9lbi9BYm91dC9QYWdlcy9kZWZhdWx0LmFzcHhkAgUPFgIfAQU8aHR0cDovL3d3dy5mc2NvLmdvdi5vbi5jYS8vZW4vQWJvdXQvUGFnZXMvZGVmYXVsdC5hc3B4I3N1cGVyZAIHDxYCHwEFPmh0dHA6Ly93d3cuZnNjby5nb3Yub24uY2EvL2VuL0Fib3V0L2NvbnRhY3QvUGFnZXMvZGVmYXVsdC5hc3B4ZAIPD2QWAgIBD2QWAgIBD2QWCgICD2QWAgIBD2QWAmYPEGRkFgFmZAIDD2QWAgIBD2QWAmYPDxYEHglCYWNrQ29sb3IKpAEeBF8hU0ICCGRkAgUPZBYEZg8PFgIfAAUXQWdlbnQvQnJva2VyIExhc3QgTmFtZTpkZAIBD2QWAmYPDxYEHwMKpAEfBAIIZGQCBg9kFgICAQ9kFgJmDw8WBB8DCqQBHwQCCGRkAgcPZBYCAgEPZBYCZg8QDxYEHgdDaGVja2VkaB4HRW5hYmxlZGhkZGRkAhMPFgIfAQU+aHR0cDovL3d3dy5mc2NvLmdvdi5vbi5jYS8vZW4vQWJvdXQvY29udGFjdC9QYWdlcy9kZWZhdWx0LmFzcHhkAhUPFgIfAQUjaHR0cDovL3d3dy5mc2NvLmdvdi5vbi5jYS8vZW4vSGVscC9kZHbfkxqmdOpuM/SlhkyMUMPoqe7xpqvhLZfOLed46aNe',
'__VIEWSTATEGENERATOR': '160FAD78',
'__EVENTVALIDATION': '/wEdAA7Q4cvANrpN5o7qvL/AjrRj3ieM1gYOLXKttt+dfEvWRlC30MDmLdG0SqBLRp4Edr0smFtAlmZS0w2+VR/uBTUgaQpcj9uHtwyf+rB2XgM9KzV/VOD8+NmupvzRtXx7cILCclsqUAusKL6yu6LPJYCYN93eHCeJb+Wv6Dc0KUw/tN8+BEUTySkHJ91vQ/nzu4CsVp8wE0Bpab2MDGOxbDBR3HNdVeUhWlxmX6SwVRp9GtD5VgtZgtwF9KTW5gMitXmBcXMJkDk9iOnoeSz/z5VWv/AwskRm5Qo6YdBnxt7SdQEcL98iN0RCUjhr/FmBpke28iIjJEQtlWEoAG7jfIg+',
'ctl00$ctl00$MainPlaceHolder$Content4$searchoption': 'Agents or Broker',
'ctl00$ctl00$MainPlaceHolder$Content4$bkmbno': '',
'ctl00$ctl00$MainPlaceHolder$Content4$bkmbname': name,
'ctl00$ctl00$MainPlaceHolder$Content4$agbkcity': '',
'ctl00$ctl00$MainPlaceHolder$Content4$srButton': 'Search',
'ctl00$ctl00$hLocal': 'en',
'ctl00$ctl00$hIsWide': '0'
})
return r.text
def parse_result_page_ontario(page):
soup = BeautifulSoup(page, 'html.parser')
allA = soup.find_all('a', href=True)
licenses = []
for a in allA:
if('ShowLicence.aspx' in a['href']):
licenses.append(a.text)
return licenses
def parse_license_page_ontario(license):
r = requests.get("http://mbsweblist.fsco.gov.on.ca/ShowLicence.aspx?" +
license + "~")
soup = BeautifulSoup(r.text, 'html.parser')
return soup.find("span", {"id":
"MainPlaceHolder_Content4_cragexpiry"}).text
name = 'crossley'
page = get_result_page_ontario(name)
licenses = parse_result_page_ontario(page)
for l in licenses:
print(l)
print(parse_license_page_ontario(l))
``` | 2018/11/06 | [
"https://Stackoverflow.com/questions/53176287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7798197/"
] | If you're using a native array of arrays of `int`, you can't force-feed it to a function expecting a pointer to a sequence of pointers. All of those hard casts are a clear-and-present indicator you're doing something wrong. Whoever told you `int[N][M]` is synonymous with `int**` was lying; they're not.
Most toolchain vendors support VLAs (variable length arrays) in C in automatic variable locations, including function arguments. The only requirement is the size must precede the array in the argument list:
```
#include <stdio.h>
void transpose(size_t siz, int mat[][siz])
{
for(size_t i= 0; i< siz; ++i)
{
for(size_t j = i ; j< siz; ++j)
{
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
}
void printMat(size_t siz, int const arr[][siz])
{
for(size_t i=0; i<siz; ++i)
{
for (size_t j=0; j<siz; ++j)
printf("%d| ", arr[i][j]);
fputc('\n',stdout);
}
}
int main()
{
int arr[][3] = {{1,2,3},{4,5,6},{7,8,9}};
printMat(3, arr);
transpose(3, arr);
printMat(3,arr);
return 0;
}
```
**Output**
```
1| 2| 3|
4| 5| 6|
7| 8| 9|
1| 4| 7|
2| 5| 8|
3| 6| 9|
```
[See it live](https://ideone.com/BCqmpa). | So, I was thinking about how the 2D array is set in the memory, the col are needed to let the compiler know how many ints (in this case) to skip over between the rows, but in fact A 2D array is simply set as a regular array in the memory, a continuous block of memory.
So- if I want to "move" between the rows I can simply calculate the offset myself. For example- the element mat[1,0] is set in the mat[col\_num\*1 +0] if I ask the compiler to look at mat as an ordinary int array.
The reason I wanted to set my function this way is that I wanted this function to work without having to #define col 3, or set it as a literal int the function definition (int mat[][3]). keeping in mind the int mat[][3] I declared in main will have to be casted into (int\*)mat when calling the function, this works:
```
void TransposeOfD2Array(int* mat, size_t col)
{
int i = 0;
int j = 0;
for(i= 0; i< col; ++i)
{
for(j = i ; j< col; ++j)
{
int temp = mat[(col*i)+j];
mat[(col*i)+j] = mat[(col*j)+i];
mat[(col*j)+i] = temp;
}
}
}
void printMat(int* arr, int size)
{
int i = 0;
for(i = 0 ; i< size*size ;++i)
{
printf("%d| ", arr[i]);
if((1+i)%size == 0)
{
printf("\n");
}
}
}
int main()
{
int mat[][3] = {{0,1,2},{3,4,5},{6,7,8}};
TransposeOfD2Array((int*)mat, 3);
printMat((int*)mat, 3);
return 0;
}
``` |
59,172,338 | Notepad++ works with Scintilla lexer to recognize switches in language within a .php file somehow. It seems to default to HTML and recognizes `<?php ... ?>`, and `<script type="text/javascript">...</script>` as delimiters for embedded PHP and javascript languages and thus applies the correct syntax highlighting and code completion.
Question: is it possible to get it to do the same for SQL, perhaps with the heredoc delimiters such as `<<<sql ... sql`?
I searched the web and notepad++ forums without success. UDLs work on the content of a file based on its extension, which doesn't help because I'm specifically looking for code *embedded* in .php files. I also tried digging in the files in Notepad's ProgramData folder but couldn't find anything defining the language switching delimiters.
The Notepad plugins for SQL all want to format the entire content of the file as sql, so that doesn't help either, I just want it to work with the *embedded* sections only. In fact, I'd rather find a solution that works without plugins.
Edit: sample code as requested
```
<p>Some html code here</p>
<?php
$value1 = 1234;
$sql = <<<sql
select * from table1
where column1 = $value1
sql;
$rows = mysqli->query($sql);
?>
<script type="text/javascript">
var results = <?php echo queryToJSresults($rows);?>;
</script>
```
Everything is syntax highlighted correctly in Notepad++. Want I want is to syntax highlight the bit between `<<<sql` and `sql` using the language SQL. Currently it is sees it (rightly so) as a string literal, same as a quoted string. | 2019/12/04 | [
"https://Stackoverflow.com/questions/59172338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2318559/"
] | In past I was thinking about something similar, but I gave up, as Notepad++ has no API or configuration for different language in another language format.
See search results for `<?php` in the source code:
<https://github.com/notepad-plus-plus/notepad-plus-plus/search?l=C%2B%2B&q=%22%3C%3Fphp%22>
After a couple of another searches I found out:
- PHP has no proper lexer, it highlights only basic things like strings (i.e. something enclosed in single/double quotes, heredoc, nowdoc, ...), variables (i.e. something with `$` sign), keywords, ... you get the point.
See <https://github.com/notepad-plus-plus/notepad-plus-plus/blob/f02d166081fd5fcf7af14be1174910b2ec4f5656/PowerEditor/src/langs.model.xml> for heredoc definition.
- SQL/MySQL has a proper lexer
Based on this quick research you can not rewrite/generate the php rules to fully support SQL or any other lexer in it by only editing the rules files.
The only possibility is dig into the Notepad++ code directly (or an extension). Then find a ways how to:
1. find a string part in PHP
2. how to pass the string part to the SQL lexer and use it as a highligter for that part
I hope I helped you. If you will discover an easy way I will be very glad and you can even submit a PR for it to parse SQL in PHP heredoc/nowdoc. | My solution until NotePad++ and/or Scintilla developers come up with an enhancement is to copy the sql-code into a new tab and select SQL as the language.
For those who would like to do the same, here is a macro to do that. Paste this into your shortcuts.xml file found in the folder where you set NPP+ to store your configuration files (%appdata%\notepad++ on windows by default). Select the sql-code then press the shortcut key `Ctrl``~` (you can change that to suit your needs).
```
<Macro name="SQL view" Ctrl="yes" Alt="no" Shift="no" Key="192">
<Action type="0" message="2178" wParam="0" lParam="0" sParam=""/>
<Action type="0" message="2025" wParam="0" lParam="0" sParam=""/>
<Action type="0" message="2422" wParam="0" lParam="0" sParam=""/>
<Action type="0" message="2325" wParam="0" lParam="0" sParam=""/>
<Action type="2" message="0" wParam="41001" lParam="0" sParam=""/>
<Action type="0" message="2179" wParam="0" lParam="0" sParam=""/>
<Action type="2" message="0" wParam="46020" lParam="0" sParam=""/>
</Macro>
``` |
5,258 | In the workplace environment, I don’t think it is productive to dwell on what happened or keep score on who did what to whom.
In English I would summarize my motto as:
>
> Ever Forward
>
>
>
Now I am looking for an appropriate Latin equivalent, i.e., a phrase that conveys:
1. The past is behind me and does not matter too much.
2. Today is a new day, and things are good. A non-defeatist point of view.
3. We can accomplish great things by focusing on the future and not dwelling on the past.
I found [similar discussion on another Latin site](http://latindiscussion.com/forum/latin/always-moving-forward-without-fear.18082/). Maybe it helps. | 2017/09/16 | [
"https://latin.stackexchange.com/questions/5258",
"https://latin.stackexchange.com",
"https://latin.stackexchange.com/users/1997/"
] | A common motto is *semper prorsum*, "always forward." You can find examples of this [all over Google](https://books.google.com/books?id=G2ghAQAAMAAJ&pg=PA249&dq=%22semper+prorsum%22#v=onepage&q=%22semper%20prorsum%22&f=false), and is used as a way of expressing the necessity of marching forward. "Always forward, never backward" is what the link is saying in Latin—double down and don't retreat. *Semper prorsus* is a less common but still valid alternative.
If it's not too cheesy, I'd also suggest just a simple *Excelsior!*. This has now entered the common parlance as a way of saying "Onward & Upward," which I think gets to the heart of what you're intending to convey. | "Duc in altum !" coming from the Holy Scriptures (Luke, 5,4): *dixit (Jesus) ad Simonem duc in altum et laxate retia vestra in capturam* : Launch out into the deep, and let down your nets for a draught.\* |
189,183 | How do I disable the password lock on my My book 1 TB, I want to so I may use it directly with my xbox 360, since it won't pick it up on my pc list. | 2010/09/16 | [
"https://superuser.com/questions/189183",
"https://superuser.com",
"https://superuser.com/users/49469/"
] | Your question is not clear, has the password been set, and you forgot it?
<http://community.wdc.com/t5/External-Drives-for-Mac/WD-My-Book-1TB-locked-out/td-p/6860> states the following:
>
> 1. Unplug and plug in Drive again.
> 2. You will be prompted to type in password.
> 3. Type five wrong password.
> 4. After 5th time, you will be prompted with screen to check off and
> give your drive storage back in
> exchange of giving up data. **\* There
> is no way to get password back (no
> exception; not even from WD)\***
>
>
>
Or look for the user guide here
<http://support.wdc.com/product/download.asp?level1=1&lang=en> | This came to the front page, so I'll reply, but the OP probably wiped it already.
See if you had installed anything from a CD **originally** to enable this password set-up. You should summon the same program to seek the option to change the known password to an empty one. If you don't remember the original password, then you will have to clean-wipe it.
My best guess is that the PC list means your "My Computer" list of disks. If it used to just be there originally and *suddenly disappeared*, you have a disk problem totally unrelated to passwords. Then I would recommend running the original CD's recovery programs (or use the Moab's links and download anything that looks useful for your exact WD model.) |
12,319,204 | How many times is Reactive Extensions supposed to evaluate its various operators?
I have the following test code:
```
var seconds = Observable
.Interval(TimeSpan.FromSeconds(5))
.Do(_ => Console.WriteLine("{0} Generated Data", DateTime.Now.ToLongTimeString()));
var split = seconds
.Do(_ => Console.WriteLine("{0} Split/Branch received Data", DateTime.Now.ToLongTimeString()));
var merged = seconds
.Merge(split)
.Do(_ => Console.WriteLine("{0} Received Merged data", DateTime.Now.ToLongTimeString()));
var pipeline = merged.Subscribe();
```
I expect this to write "Generated Data" once every five seconds. It then hands off that data to both the 'split' stream which writes "Split/Branch received Data", and to the 'merged' stream which writes "Received Merged data". Last, because the 'merged' stream is also receiving from the 'split' stream, it receives the data second time and writes "Received Merged data" a second time. (The order it writes some of them in is not particularly relevant)
But the output I am getting is this:
```
8:29:56 AM Generated Data
8:29:56 AM Generated Data
8:29:56 AM Split/Branch received Data
8:29:56 AM Received Merged data
8:29:56 AM Received Merged data
8:30:01 AM Generated Data
8:30:01 AM Generated Data
8:30:01 AM Split/Branch received Data
8:30:01 AM Received Merged data
8:30:01 AM Received Merged data
```
It is writing "Generaged Data" twice. To my understanding, The number of downstream observers that are subscribed to the "seconds" IObservable should not affect the number of times that "Generated Data" writes (which should be ONCE), but it does. Why?
*NOTE* I am using the stable release v1.0 SP1 of reactive extensions in a .Net Framework 3.5 environment. | 2012/09/07 | [
"https://Stackoverflow.com/questions/12319204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/447885/"
] | Presumably, they choose that approach to allow each subscriber to get its values at the same interval from their initial subscription. Consider how your alternate Interval would work:
```
0s - First subscriber subscribes
5s - Value: 0
8s - Second subscriber subscribes
10s - Value: 1
15s - Value: 2
17s - Unsubscribe both
```
What you end up with is something like this:
```
First -----0----1----2-|
Second --1----2-|
```
In this case, the two observers have **noticeably** different results depending on whether or not there is any other observer already attached. As it is implemented, `Interval` gives the same experience to each subscriber regardless of order or past subscribers.
All that said, you can "convert" `Interval` to the behavior you describe by adding `.Publish().RefCount()` when creating the `seconds` observable. | Although it seems like it might be nice sometimes if sequences were multicasted at every step, if it were that way it wouldn't allow you to have the rich composition that Rx allows for.
To think of it another way,
`IObservable` is the push-based dual of `IEnumerable`.
`IEnumerable` has the property of lazy evaluation - the values aren't computed until you start moving through the `Enumerator`. Rx sequences are composed lazily and finally a Subscribe() (the Observable equivalent of For-Each) realises the sequence.
This way you can stop the pipeline at all stages simply by un-subscribing from the last stage, allowing you to have fire and forget behavior without going through the nightmare of managing individual subscriptions. |
275,208 | I'm using a [Matsusada HV Power supply](https://www.matsusada.com/product/psel/hvps1/handy/000034/) up to 20 kV. The manual mentioned that the ground terminal of the chassis should be connected to earth. And I had a few questions
1. What are the best, or at least acceptable, ways to make this connection. Would it be OK to connect it to the earth ground in the power outlet? If so, is there some sort of adapter or tool that makes it safe to access the earth ground from the power outlet? I'm wary of poking around outlets.
2. Is there a reason why the user manual instructs the users to make the earth ground connection? Doesn't the instrument have access to earth ground through the power outlet via the AC power cord? The only reason I can think of is that they don't trust all buildings to be connected properly.
Thanks | 2016/12/15 | [
"https://electronics.stackexchange.com/questions/275208",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/133364/"
] | I agree with @ThePhoton overall. The earth pin in the IEC connector should be an extremely low resistance path to the chassis ground stud. Any other arrangement would be irresponsible, dangerous, and probably illegal. How you connect the supplemental earth depends on your lab setup. A permanent, sealed mechanical bond (nut, bolt, and washers) between cleaned surfaces (buffed and cleaned with alcohol) is ideal. That level of rigor is probably not necessary in this application. The scenario @ThePhoton described *will* happen somewhere eventually, but it's still an unlikely event. If your power supply is sitting on a shelf and not moving, there is about zero probability that the IEC connector will fall out.
For short term use, the earth pin of a socket is safe to use because it connects to the dirt outside. (Unless your building is heinously, illegally, dangerously miswired) Just stay away from the live and neutral. Put some insulating tape over those sockets. The screws that hold outlet cover plates on typically screw into the junction box, which is earthed. I'm not convinced that's a highly reliable connection, but you could try using that screw to attach a ring terminal connector to earth via the junction box. If you're going to install the power supply permanently or semi-permanently, you need to know with confidence that that connection is robust. | The Japanese have several (at least two) different mains power distribution systems -- one at 60 Hz and one at 50 Hz. This [wiki page](https://en.wikipedia.org/wiki/Mains_electricity) says the boundary between the two regions contains four back-to-back high-voltage direct-current (HVDC) substations to interconnect these two power grids.
These systems are grounded using a [Terra-Terra](https://en.wikipedia.org/wiki/Earthing_system#TT_network) grounding approach and often, but not always, with an entrance GFCI at each customer site.
I suspect this separate ground lug may be present to deal with power distribution systems similar to those found in Japan.
Why don't you contact Matsusada and just ask an appropriate engineer there? I'm pretty sure you will get a meaningful reply from them.
---
As a separate note, I think it's very unlikely the power inlet will be a danger when the plug is removed. But given the voltages involved, that's something else I'd test (even after properly attaching to the grounding lug, if appropriate.) I'd want to know if there is any possibility of accident due to pulling the plug out of the wall and touching any of the exposed, presented contacts. And it's simple to test. Worth doing, just in case. |
6,406,930 | I have read this post: [what happens to NSLog info when running on a device?](https://stackoverflow.com/questions/5318342/what-happens-to-nslog-info-when-running-on-a-device)
...but wondering if NSLog is a problem when distributing the app such as filling up the memory or something? I am only interested to see it when i test the consistency of my input data to the database.
The reason is that I have NSLog to control when i load the data into my database in the simulator. I could remove it when i upload but it would be good if i do not need to? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6406930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/418332/"
] | You should remove it. For example if you log contents of a UITableViewCell (in `-tableView:cellForRowAtIndexPath:`), it can make a big difference in performance, especially on slower hardware.
Use a macro to keep NSLog output in Debug mode, but remove it from Release mode. An example can be found on the following site: <http://iphoneincubator.com/blog/debugging/the-evolution-of-a-replacement-for-nslog> | There only real reason to remove your NSLog entries is to save on memory consumption by running unnecessary code, but unless you're consistenly adding data, it shouldn't be too much of an issue.
Furthermore, if a user has an issue such as app crash, etc. NSlogs can be submitted which the dev can read to work out the reason for the crash. If you're loading the NSlog with a great deal of unnecessary data, it can be troublesome at a later date if you need to go through said log to find a user's issue in order to fix the issue.
Ultimately, I wouldn't worry too much about removing them. That's my 2 cents anyhow. |
23,890,361 | I need to write a script where one can type their name (via input) and the script has to check if the name has the right format (no numbers, no Capslock, starting with the capital letter). This is what i have so far:
```
import re
def inputName():
name = input("Enter your name: ")
if re.search('^[A-Z]{1}\w[a-z]+',name):
print("ok")
else:
print('not ok')
inputName()
```
I've also tried [^\d] and \D and [^0-9] but it still doesnt work correctly. When I enter "A8hkjh" it returns "not ok", nut when I type "Ahj8k" it returns "ok", even though there is a digit in the string.
How can I make the script check the whole string? | 2014/05/27 | [
"https://Stackoverflow.com/questions/23890361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3652491/"
] | `\w` matches letters as well as digits and underscores. Also, don't forget to [anchor](http://www.regular-expressions.info/anchors.html) the regex to the end of the string, otherwise it will succeed on a partial match. For example, on `"Ab1"`, the substring `"Ab"` is matched by your regex if you don't use the `$` anchor:
```
re.search('^[A-Z][a-z]+$',name)
```
should fix this. | ```
import re
username = "john"
result = re.search(r'.*?(?!.*?(\d|[A-Z]))', username)
if result.groups()[0] is None:
print "{} passed validation".format(username)
```
The regex: `.*?(?!.*?(\d|[A-Z]))` will match anything as long as it has no digits or capital letters in it, as requested. |
36,267,507 | I am trying to animate with CSS the a line through on a bit of text, but it's not actually animating, just going from hidden to displayed. Can anyone advise if what I'm trying is actually possible? If not, is there another way to achieve this?
HTML:
```
<div>
The text in the span <span class="strike">is what I want to strike out</span>.
</div>
```
CSS:
```
@keyframes strike{
from{text-decoration: none;}
to{text-decoration: line-through;}
}
.strike{
-webkit-animation-name: strike; /* Chrome, Safari, Opera */
-webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
animation-name: strike;
animation-duration: 4s;
animation-timing-function: linear;
animation-iteration-count: 1;
animation-fill-mode: forwards;
}
``` | 2016/03/28 | [
"https://Stackoverflow.com/questions/36267507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149614/"
] | You can use a pseudo like this
*Note (thanks to [Phlame](https://stackoverflow.com/questions/36267507/is-it-possible-to-animate-a-css-line-through-text-decoration/36267849?noredirect=1#comment114475894_36267849)), this left-to-right animation won't work if the line to strike breaks in to a second line. For that one need to use yet another pseudo element and some script to position the two properly. Or use some other animation effect, e.g. like the one suggested in [Oriol's answer](https://stackoverflow.com/a/36268164/2827823).*
```css
@keyframes strike{
0% { width : 0; }
100% { width: 100%; }
}
.strike {
position: relative;
}
.strike::after {
content: ' ';
position: absolute;
top: 50%;
left: 0;
width: 100%;
height: 1px;
background: black;
animation-name: strike;
animation-duration: 4s;
animation-timing-function: linear;
animation-iteration-count: 1;
animation-fill-mode: forwards;
}
```
```html
<div>
The text in the span <span class="strike">is what I want to strike out</span>.
</div>
``` | Here's a variation on the [accepted](https://stackoverflow.com/a/36267849/8112776) answer, using an image to provide an animated "scribble" strike-through.
```css
html {
font-family: Helvetica;
font-size: 24px;
}
.strike { position:relative; }
.strike::after {
content:' ';
position:absolute;
top:50%; left:-3%;
width:0; height:10px;
opacity:80%;
transform:translateY(-50%);
background:repeat-x url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAKAQMAAAByjsdvAAAABlBMVEUAAADdMzNrjRuKAAAAAXRSTlMAQObYZgAAADdJREFUCNdj+MMABP8ZGCQY/h9g+MHw/AHzDwbGD+w/GBhq6h8wMNj/b2BgkP8HVMMPUsn+gQEAsTkQNRVnI4cAAAAASUVORK5CYII=);
animation: strike 2s linear .3s 1 forwards;
}
@keyframes strike { to { width: 106%; } }
```
```html
This thing and <span class="strike">this thing and</span> this thing.
``` |
1,616,293 | Given the following code, how do I use the variable divs created by the first jQuery selector, without rerunning it on the line where I add the class?
So, given this:
```
var divs = $("div.searchhit");
```
// more code here using divs.length
divs.removeClass("selected");
$("div.searchhit:eq(0)").addClass("selected");
How do I get the last line to look like this:
```
divs(":eq(0)").addClass("selected");
``` | 2009/10/23 | [
"https://Stackoverflow.com/questions/1616293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17891/"
] | Just use the [`eq()` method](http://docs.jquery.com/Traversing/eq#index):
```
divs.eq(0).addClass('selected');
``` | Please read the jQuery documentation. This is well covered.
That was a bit terse of me. Here small explanation:
`jQuery(query)` is the primary filter which searches from the root of the DOM. Subsequent queries run on the resultant object start on that set. If no expanding operations are performed (say, looking at children within a previously matched node) then the resulting query can contain at most as many elements as the previous query. |
8,022,699 | I would like to know how can I manually insert some php code inside a cck node (in Drupal).
The thing is that I have this stuff:
```
$output .= '<br>';
$mor = _pitch_detalle($cid, $previamente, $luego);
if (sizeof($mor) > 0){
$output .= theme('pitch', $mor);
}
return $output;
```
This stuff shows some information that changes from day to day, and each time the users view the page, the information changes.
I want the user to see an unmodified version of that code, the same information that existed when the user created the page.
As the user **cannot edit** the page, I think that ist´s pretty safe to say that **if I enter that code inside a field, it will remain unchanged. Is that assumption correct?**
How could I do that?
Thanks for your help!!!
Rosamunda | 2011/11/05 | [
"https://Stackoverflow.com/questions/8022699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892490/"
] | `$.validator.setDefaults` doesn't work for unobtrusive validation as the validator is initialized internally.
To change the settings on forms that use unobtrusive validation you can do the following:
```
var validator = $("form").data("validator");
if (validator) {
validator.settings.onkeyup = false; // disable validation on keyup
}
``` | Don't know how to set it to a specific field, but you could try this to disable keyup validation (for all fields):
```
$.validator.setDefaults({
onkeyup: false
})
```
See
* [MVC 3 specifying validation trigger for Remote validation](https://stackoverflow.com/questions/4798855/mvc-3-specifying-validation-trigger-for-remote-validation/5444452#5444452)
* [ASP.NET Remote Validation only on blur?](https://stackoverflow.com/questions/5407652/asp-net-remote-validation-only-on-blur/5408735#5408735) |
18,046,776 | I use a javascript song countdown on my radio website.
At every 10 seconds, the countdown lags (skipping 1 one more seconds), because of an ajax call to check if there's a new song:
```
function getcursong(){
var result = null;
var scriptUrl = "get_current_song.php";
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
```
Looking in the console, I see that the `GET` call takes about 2 seconds.
`get_current_song.php` uses `curl` to get the current song from the icecast server.
Is there something I can do to prevent the countdown from lagging because of those ajax calls?
Below is `get_current_song.php`.
```
<?php
require('config.php');
$current_song = getStreamInfo();
function url_get_contents($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_TIMEOUT,2);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
function getStreamInfo(){
$str = url_get_contents(SERVER.'/status.xsl?mount='.MOUNT);
if(preg_match_all('/<td\s[^>]*class=\"streamdata\">(.*)<\/td>/isU', $str, $match)){
$x = explode(" * ",$match[1][9]);
return $x[1];
}
}
?>
<?php
echo $current_song;
?>
``` | 2013/08/04 | [
"https://Stackoverflow.com/questions/18046776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1904386/"
] | I assume that `async: false` is hijacking your countdown function. Do you need it to be false? | ```
function ()
{
var result = null;
var scriptUrl = "get_current_song.php";
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: true, // NEEDED TO BE TRUE
success: function(data) { // on success, I get the data
song = $('#song').html();
if (data != song && data != ""){
setTimeout(function (){ $('#nowplaying').load('nowplaying.php'); }, 5000); // pourquoi fadeIn("slow"); ?!?
}
}
});
}, 10000);
``` |
319,306 | I've just installed an SSL certificate for our domain, and now when I try to browse to the site using https I get a connection reset error in FF and chrome both locally and from a client. I can still access the site without SSL (using http).
If it makes any difference I have another SSL certificate installed for a different website, but it is bound to a different IP.
We are running IIS7 on Win2K8
EDIT: For the site that is not working with https: I cannot access this site via it's IP address either. The only way I can access it is by regular http and using the domain name. | 2011/10/07 | [
"https://serverfault.com/questions/319306",
"https://serverfault.com",
"https://serverfault.com/users/93735/"
] | Oh god embarrasing. So it turns out that I had set the correct SSL binding but in the binding I had actually forgotten to select the certificate that I had installed. So it was just sitting there as not selected. This was causing a whole bunch of chaos but now my ports all appear open and I can browse the site via IP and domain name. | Sometimes the use of `SelfSSL.exe` will lead to this problem, try to re-run the command `selfssl.exe /N:CN=localhost /K:1024 /V:365 /S:{your site id} /P:443` |
7,726,513 | I know how to sort an array that has two columns:
```
Arrays.sort(myarray, new Comparator<String[]>() {
@Override
public int compare(String[] entry1, String[] entry2) {
String time1 = entry1[0];
String time2 = entry2[0];
return time2.compareTo(time1);
}
});
```
This sorts the arrray by the first column.
But what if I have more columns? E.g.
```
myarray[0][0]= +3620205252
myarray[0][1]= 32534
myarray[0][2]= Franco Nera
myarray[0][3]= 183
myarray[1][0]= +3658300234
myarray[1][1]= 4334
myarray[1][2]= Judy Moira
myarray[1][3]= 28
```
etc..
I want to sort this e.g. by the second column, or the fourth column...
I can try to work this out by creating a new array[1st+3rd+4th column][2nd column] and then sort it with the above solution, then take the elements apart, but that is too circumstantial. | 2011/10/11 | [
"https://Stackoverflow.com/questions/7726513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571648/"
] | You have to walk the two arrays until you find an index where the elements differ and the return the comparison of the strings at that index. It is basically the same idea that is used in comparing strings.
```
for(int i=0;i<Math.min(entry1.length,entry2.length);i++){
String x=entry1[i], y=entry2[i];
int diff=x.compareTo(y);
if (diff!=0) return diff;
}
if (entry1.length==entry2.length) return 0;
else return entry1.length-entry2.length;
```
The code above also handles the case where the arrays might not have the same number of columns. | I think the easiest way is to use a temporary array of strings since you have array of strings -
Sample array:
```
String array[][][] = {
{
{"Hello", "World"},
{"Apple", "Orange"}
},
{
{"Zebra", "Cow"},
{"Cat", "Ball"}
},
{
{"Elephant", "Whale"},
{"Lion", "Monkey"}
}
};
```
Temporary array of strings:
```
String[] tempArray = new String[array.length * array[0].length * array[0][0].length];
```
Fill the temporary array:
```
int tempIndex = 0;
for(int i=0; i<array.length; i++) {
for(int j=0; j<array[i].length; j++) {
for(int k=0; k<array[i][j].length; k++) {
System.out.println("array[" + i + "][" + j + "][" + k + "]: " + array[i][j][k]);
tempArray[tempIndex++] = array[i][j][k];
}
}
}
```
That also prints -
```
array[0][0][0]: Hello
array[0][0][1]: World
array[0][1][0]: Apple
array[0][1][1]: Orange
array[1][0][0]: Zebra
array[1][0][1]: Cow
array[1][1][0]: Cat
array[1][1][1]: Ball
array[2][0][0]: Elephant
array[2][0][1]: Whale
array[2][1][0]: Lion
array[2][1][1]: Monkey
```
Now, sort the temp array -
```
Arrays.sort(tempArray);
```
Fill the original array with sorted values -
```
tempIndex = 0;
for(int i=0; i<array.length; i++) {
for(int j=0; j<array[i].length; j++) {
for(int k=0; k<array[i][j].length; k++) {
array[i][j][k] = tempArray[tempIndex++];
}
}
}
```
Now the if you print the elements of the original array again, it should print -
```
array[0][0][0]: Apple
array[0][0][1]: Ball
array[0][1][0]: Cat
array[0][1][1]: Cow
array[1][0][0]: Elephant
array[1][0][1]: Hello
array[1][1][0]: Lion
array[1][1][1]: Monkey
array[2][0][0]: Orange
array[2][0][1]: Whale
array[2][1][0]: World
array[2][1][1]: Zebra
``` |
18,279,238 | I want to insert an image in a div, but i have problems: the image overflows outside the div!! O.O
(sorry for my english)
thats' the code HTML
```
<div class='immagine2'><img src='http://farm4.staticflickr.com/3822/9522792825_c68706706d_o.jpg'></div>
```
and CSS...
```
div.immagine2 {
position:relative;
width:500px;
height:410px;
margin: 30px 30px 30px auto;
}
div.immagine2 img {
float:left;
position:absolute;
left:50%;
top:50%;
margin-left:-155px;
margin-top:-75px;
}
```
And [here](https://thimble.webmaker.org/project/8979/edit) the link.
what's wrong?
IMPORTANT!!! : i want that image has flow left, cause i want to add text on the right! | 2013/08/16 | [
"https://Stackoverflow.com/questions/18279238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2659836/"
] | Add the `overflow: hidden` to the following id:
```
div.immagine2 {
overflow:hidden;
...
}
```
This will effectively prevent any content extending beyond the div from displaying on the page. Hope it helps!! | Add the background-image to your CSS (As a commentor mentioned this is ineffective if you wish to use different images ).
```
background-image: url(../images/picture.jpg)
```
You can play around with numerous background settings in the CSS.
```
background-size: 100%;
```
If you are using px you can specify the size the image should occupy.
```
background-size: 30px 40px;
``` |
38,487,479 | I have tried to create a sample program using Node.js, following instructions from <https://developers.google.com/google-apps/activity/v1/quickstart/nodejs>
I throws an error saying **cannot read property 'client\_secret' of undefined** when trying to run it.
Looking for your valuable suggestions.
Thanks in advance. | 2016/07/20 | [
"https://Stackoverflow.com/questions/38487479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4559107/"
] | Since there is no key named "installed", it's parsing it to be `undefined`.
In `credentials.json` change the key "web" to "installed". Probably the docs need to change from Google's side.
Before
------
[](https://i.stack.imgur.com/H6f20.png)
After
-----
[](https://i.stack.imgur.com/4Ydnu.png) | Your `client_secret.json` file needs to have the line below:
```
"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"]
```
instead of the lines like below:
```
"javascript_origins":
[
"http://localhost:8080",
"http://localhost:1453",
"http://127.0.0.1:1453",
"http://localhost"
]
```
Also you may want to change chain head in `client_secret.json` from `web` to `installed`, or vise versa. |
15,712,567 | I have a UINavigationController in my AppDelegate with a RootViewController that has a UITableView. On startup, the status bar changes its color to the color of the navigation bar. When I colored my navigation bar to orange, this is what the status bar is looking like:

It seems that my navigation bar is shifted to the top a little bit. It appears that the navigation controller does not recognize the status bar. How can I fix this issue?
The only thing I have in my app is an AppDelegate and an empty RootViewController. My `application:didFinishLaunchingWithOptions` is:
```
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
RootViewController *rootViewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
[navigationController.navigationBar setTintColor:[UIColor orangeColor]];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
return YES;
```
My IB file for RootViewController just has an empty view.
Nothing unusual. I'm pretty experienced with iOS and that's how I've been doing it every single time. I have no idea what is different this time.
Could someone please advise me? Thanks | 2013/03/29 | [
"https://Stackoverflow.com/questions/15712567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680441/"
] | Set your status-bar-style towards `UIStatusBarStyleBlackOpaque` and you should get a solid black bar.
To do that, use `setStatusBarStyle:animated:` on your applications' instance:
```
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque
animated:NO];
``` | Add this code:
```
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
```
This will make your status bar black again.
You should add it **after** changing the color of your navigation bar. |
26,514,014 | I've tried searching around for an answer, but have not succeeded in doing so.
I want to pass the text in one of the UILabel's the cell holds. I am not entirely sure on how to do this. I am trying to pass the content of one of the UILabels into the swipeTableViewCell didTriggerRightUtilityWithIndex function, as I am using SWTableViewCell.
The table is populated with items from a mysql table.
This is my current UITableViewCell function:
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableItem";
if([taskArray valueForKey:@"TaskData"] != [NSNull null])
{
GroupDataTableViewCell *cell = (GroupDataTableViewCell*)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
// Add utility buttons
NSMutableArray *rightUtilityButtons = [NSMutableArray new];
[rightUtilityButtons sw_addUtilityButtonWithColor:
[UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
title:@"Les mer"];
cell.rightUtilityButtons = rightUtilityButtons;
cell.delegate = self;
if (cell == nil) {
//cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableItem" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *item = [taskArray objectAtIndex:indexPath.row];
if([item objectForKey:@"TaskID"] != [NSNull null])
cell.numberTextField.text = [item objectForKey:@"TaskID"];
if([item objectForKey:@"Title"] != [NSNull null])
cell.titleTextField.text = [item objectForKey:@"Title"];
if([item objectForKey:@"Description"] != [NSNull null])
cell.descriptionTextField.text = [item objectForKey:@"Description"];
if([[selfArray valueForKey:@"CheckStat"] isEqualToString:@"(null)"])
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
else if([[selfArray valueForKey:@"CheckStat"] length] == 0)
{
if ([[item objectForKey:@"CheckStat"] containsString:@"1"])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
}
else
{
for(int i = 0; i < [[[selfArray valueForKey:@"CheckStat"] componentsSeparatedByString:@","] count]; i++)
{
NSString *checkedNumStr = [[[selfArray valueForKey:@"CheckStat"] componentsSeparatedByString:@","] objectAtIndex:i];
//if (i >= [taskArray count] || [checkedNumStr intValue] >= [taskArray count])
//break;
if ([checkedNumStr intValue] == indexPath.row + 1)
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
return cell;
}
else
return nil;
}
```
I want to send the cell.descriptionField.text from there to this code, when the rightUtilityButton is activated:
```
- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index {
switch (index) {
case 0:
{
// More button is pressed
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Bookmark" message:@"Description" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alertView show];
[cell hideUtilityButtonsAnimated:YES];
break;
}
case 1:
default:
break;
}
}
```
So, I want the cell.descriptionTextField.text from the first snippet into the second snippet. I am not entirely sure on how to do this, as I am not good with tablecells. I want the cell.descriptionTextField.text from the first snippet to show up in the alertView as the description. | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4171026/"
] | Save your [item objectForKey:@"Description"] into an NSMutableArray previously created, if you order your cells with the same order as the nsmutablearray, you could access this value into your wanted function like this:
```
- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index {
switch (index) {
case 0:
{
// More button is pressed
NSString *desc = [myarray objectAtIndex:index];
// Use your string wherever you want
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Bookmark" message:@"Description" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alertView show];
[cell hideUtilityButtonsAnimated:YES];
break;
}
case 1:
default:
break;
}
}
``` | Do not store information in cell object rather than that use datasource to store information.
using index you can get the respective information that was stored in label
In your case you are storing description in label which can be later retrieved as follows
```
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
NSDictionary *item = [taskArray objectAtIndex:index;
//Do something with the item
}
``` |
19,929,267 | I was wondering if there's a way to use [Mosh](http://mosh.mit.edu/) on windows without Cygwin?
I need to be able to put it on my USB drive and copy it over to a windows computer and be able to Mosh into one of my servers. Otherwise, is there a way to use Cygwin and have it portable? I did get mosh working under windows via Cygwin, but that meant I had to add an environment path to the windows computer, which, on the windows computer that I'm working on doesn't allow you to change that, since I don't have admin privileges. | 2013/11/12 | [
"https://Stackoverflow.com/questions/19929267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2683453/"
] | [MobaXTerm](http://mobaxterm.mobatek.net/download-home-edition.html) is portable and supports Mosh.
It works quite well. I spent all day using it on a very dodgy connection and it worked like a charm.
Just get the most recent version and from the Session menu select Mosh. It did does not support IPv6 (at least in [Version 9.2 (2016-09-18)](https://mobaxterm.mobatek.net/download-home-edition.html)):
>
> Bugfix: Mosh sessions are forced to IPv4 only (IPv6 is not yet supported by Mosh client/server)
>
>
>
But it might work now, since [Version 10.4](https://blog.mobatek.net/post/mobaxterm-new-release-10.4/) (untested):
>
> We also improved MobaXterm behavior and fixed issues with multi-monitors, **IPv6 connections**, mouse scrolling and keyboard shortcuts.
>
>
> | I have noticed that a new version of MobaXterm has been released (version 7.1) and includes an intergrated Mosh session.
So, you dot not need anymore need plugin for that.
They said that it is "experimental", but I have tested it, and it is working quite well. |
21,263,379 | I'm using asp.net. I have a table in a repeater. I keep the ID's of the items in the repeater in an hiddenfield in the last column of the table with an edit hyperlink, and when it's clicked the user is redirected to the edit page of the item, which has a url like `/ItemEdit.aspx?ItemID=236`
Now, my problem is, instead of using an edit button, I want the user to be redirected to the edit page when he/she clicks on anywhere on the row. I've added an onclick event to the `<tr>` tag, and it works when I put static links. However as my hiddenfield is in a `<td>` tag, I cannot reach the value of the ID of the item. My code is something like:
```
<tr onclick="var itemID=document.getElementById('hdnItemID').value; location.href='ItemEdit.aspx?ItemID='+itemID;">
<td>Some stuff about the item</td>
<td>Some other stuff about the item </td>
<td><asp:HiddenField ID="hdnItemID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "ItemID")%>' /></td>
</tr>
```
And as expected, browser has no idea what `hdnItemID` is. How to solve this problem? Where to add the hiddenfield and how to get the value of it? | 2014/01/21 | [
"https://Stackoverflow.com/questions/21263379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2814738/"
] | Thanks to Ardesco and Robbie, I came up with the following solution:
```
private String RequiredSystemNameXpath = "//td[contains(text(),'xxxxx')]";
private WebElement prepareWebElementWithDynamicXpath (String xpathValue, String substitutionValue ) {
return driver.findElement(By.xpath(xpathValue.replace("xxxxx", substitutionValue)));
}
public void deleteSystem (String systemName) {
WebElement RequiredSystemName = prepareWebElementWithDynamicXpath(RequiredSystemNameXpath, systemName);
RequiredSystemName.click();
}
``` | You can't do that, Annotations are constant values stored in the class file. You can't compute them at runtime.
See [Can the annotation variables be determined at runtime?](https://stackoverflow.com/questions/5743167/can-the-annotation-variables-be-determined-at-runtime) |
1,050,720 | It amazes me that JavaScript's Date object does not implement an add function of any kind.
I simply want a function that can do this:
```
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// How do I implement this?
}
```
I would simply like some pointers in a direction.
* Do I need to do string parsing?
* Can I use setTime?
* How about milliseconds?
Like this:
```
new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?
```
This seems really hackish though - and does it even work? | 2009/06/26 | [
"https://Stackoverflow.com/questions/1050720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111934/"
] | If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
```js
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
``` | A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
```
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
```
Your output would be: 2019-04-03T16:58 |
487,196 | I'm an illustrator and need some idiom help (obviously visualizing but using existing idioms or metaphors can help). The article I'm illustrating for is about teachers quitting their jobs within 5 years as it's very overwhelming and they're often not prepared enough. There's too much they have to do at once, making late hours and not being able to keep their minds off of work, feeling overexhausted. What are some idioms that fit with this situation?
Thanks! | 2019/02/25 | [
"https://english.stackexchange.com/questions/487196",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/337799/"
] | They could be "**pooped out**". It fits your description.
<https://idioms.thefreedictionary.com/pooped+out> | I'd say they've been **run ragged**. Gives a nice visual to the situation you've described.
*Running someone ragged* is defined by Merriam-Webster as *making someone very tired*.
An example in the wild from a horoscope:
*If there's one thing in the whole world you need it's peace. Unfortunately a boss, child or loving partner seems intent on **running you ragged** with one job after another. Try to make time to put your feet up and switch off but don't be grouchy if you find it's all work and no play!* |
35,064,187 | I'm using bootstrap to make a website for all devices. This website contains a row that is solely devoted to an image carousel. The code for this carousel is below.
```
<div class="row" id="imageCarouselRow">
<div class="col-md-12" id="imageCarouselColumn">
<div id="imageCarousel" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#imageCarousel" data-slide-to="0" class="active"></li>
<li data-target="#imageCarousel" data-slide-to="1"></li>
<li data-target="#imageCarousel" data-slide-to="2"></li>
<li data-target="#imageCarousel" data-slide-to="3"></li>
<li data-target="#imageCarousel" data-slide-to="4"></li>
</ol>
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="Image link" class="img-responisve" alt="Caption">
</div>
<div class="item">
<img src="Image Link" class="img-responsive" alt="Caption">
</div>
<div class="item">
<img src="Image Link" class="img-responsive" alt="Caption">
</div>
<div class="item">
<img src="Image Link" class="img-responsive" alt="Caption">
</div>
<div class="item">
<img src="Image Link" class="img-responsive" alt="Caption">
</div>
</div>
</div>
</div>
</div>
```
As you can see it contains 5 different images (the real links are included in the actual code) all of which I've given the 'img-responsive' class so the images can be scaled to different devices.
My problem is that the image carousel does not take up the entire row, but I still want it to be the only thing on the row. I also want it to be centralised. Additionally, on desktops since the carousel is the size of the entire row images will transition in from the very edge of the screen which I do not want, I only want the image to transition in from the edge of the previous image (i.e the carousel is no bigger than the size of the individual images)
Each individual image is 1025px by 424px by default.
The only way I have managed to accomplish this so far is by making the imageCarousel class have a size in px or em in an external stylesheet and give it a margin property of 0 auto that looks like this below:
```
#imageCarousel{
width: 1025px;
height: 424px;
margin: 0 auto;
}
```
I've also set the size in em's. The problem is if I do this the size is static which stops bootstrap from scaling the site to different device sizes and when the browser window is rescaled.
Any solutions to this problem? | 2016/01/28 | [
"https://Stackoverflow.com/questions/35064187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4346886/"
] | Looking at your SQL query:
```
INSERT INTO users(username, password, namn) VALUES :username, :password, :name
spelling? -----^ ^------ parentheses ------^
```
The spelling one is mostly a guess, but at the very least the parentheses are a good idea. So maybe you meant this?:
```
INSERT INTO users(username, password, name) VALUES (:username, :password, :name)
```
Also, as a side note, *never* store user passwords *in plain text*. This is very irresponsible handling of user data. PHP has a lot of [built-in functionality](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to assist in properly obscuring user passwords behind a one-way hash. (As well as [a compatibility pack](https://github.com/ircmaxell/password_compat) for older PHP versions.) | enclose the variables in single quotes because these are string and strings cannot be directly inserted in database. e.g
```
INSERT INTO talbe_name (col1,col2) VALUES ('string1','string2');
```
also draw `{}` around variables inside the string in php code e.g
```
<?php
$str = "Value={$variable}";
?>
``` |
34,290 | The classification of finite simple groups, whether it be viewed as finished, or as a work in progress, is (or will be) without doubt an enormous achievement. It clearly sheds a great deal of light on the structure of finite groups. However, as with the classification of simple Lie algebras, one might expect this to have a significant impact outside of the immediate subject. So what are some of the known, or expected, applications to the classification outside of finite group theory?
---
NB:
* this question was significantly edited by other users soon after being posted (Aug 2 '10). The few critical comments below were actually addressed before the question was edited and improved.
* To anyone who has doubts about the proof, please see [Aschbacher's *Notices* paper "The status of the classification of the finite simple groups"](https://www.ams.org//notices/200407/fea-aschbacher.pdf)
and please rather don't debate that particular matter here. | 2010/08/02 | [
"https://mathoverflow.net/questions/34290",
"https://mathoverflow.net",
"https://mathoverflow.net/users/9558/"
] | There are all kinds of applications of CFSG within the rest of algebra. I am afraid they are too numerous to list here. Let me mention [Lubotsky and Segal - Subgroup growth](https://books.google.com/books?id=654LRcD4538C) which I personally find very interesting, and which has a number of such results. On the other hand, if you read it carefully, you will see that many applications of CFSG also follow from a (weaker but readable) result by Larsen & Pink ([Finite subgroups of algebraic groups](https://doi.org/10.1090/S0894-0347-2011-00695-4), 1998).
Let me turn and give another answer. If you study currently best bound due to Babai & Luks, on the complexity of [graph isomorphism](https://en.wikipedia.org/wiki/Graph_isomorphism_problem), you will also see that it is based on CFSG, although again on a relatively easy looking consequence of it. Although most experts would say that this problem is strongly connected to group theory, as stated, it lies outside of algebra. Hope you find this example convincing enough. | Maybe it is difficult to say what is strictly "outside" of finite group theory. However, to add to Igor's answers, I can suggest that you look at the work of Bob Guralnick and various collaborators. Among the interesting results which use the classification is the proof by Fried, Guralnick and Saxl in [Schur covers and Carlitz's conjecture](https://doi.org/10.1007/BF02808112) of a 1966 conjecture of Carlitz. Let $f(x)$ be a polynomial with coefficients in the finite field $\mathbb F\_q$. Then $f$ is called "exceptional" if, for infinitely many finite extensions $K$ of $\mathbb F\_q$, the induced function $f:K\to K$ is a permutation. The conjecture of Carlitz was that if $q$ is odd and $f$ is exceptional then $f$ has odd degree.
There is also a large body of work saying that the structure, both as an abstract group and as a permutation group, of the monodromy group of a finite branched covering of connected Riemann surfaces is controlled by the genus of the covering surface. For example, the Guralnick–Thompson Conjecture (now a theorem, with the final piece of the proof due to Frohardt and Magaard, in [Composition factors and monodromy groups](https://doi.org/10.2307/3062099)) says that if we bound the genus of the covering surface, we can obtain only finitely many nonalternating, noncyclic groups as composition factors of the monodromy group. I don't think anyone knows how to prove results of this nature without the classification. |
758 | I made some sorbet at the weekend, and realised just when we were due to serve that I had forgot to take it out of the freezer to soften, and so it was rock hard.
What is the best way to bring it to a usable temperature quickly? We chucked it in the microwave and then hacked it with a spatula, but ended up with a lumpy texture as many parts were still very frozen. Any ideas to avoid a repeat in the future would be appreciated. | 2010/07/12 | [
"https://cooking.stackexchange.com/questions/758",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/210/"
] | Don't. Ice cream is hard. It melts slowly. Instead, focus on scooping.
Get the largest spoon you have, or ideally, an ice cream scoop. Fill up a cup with boiling water, or as hot as your faucet will get it. Dip spoon/scoop in the water. Scoop. Dip. Scoop. Shake off excess water as you go.
Like a hot spoon through ice cream. | When you go to the kitchen to get your ice cream, don't tell the guests what you're doing. After you take it out, announce dinner. That way, you can eat dinner while the ice cream defrosts. Check on it when everyone has finished, then tell them you have dessert. Now you can give them ice cream. |
5,358,468 | >
> **Possible Duplicate:**
>
> [text-overflow:ellipsis in Firefox 4?](https://stackoverflow.com/questions/4927257/text-overflowellipsis-in-firefox-4)
>
>
>
I have the same issue mentioned in [Truncating long strings with CSS: feasible yet?](https://stackoverflow.com/questions/802175/truncating-long-strings-with-css-feasible-yet). It's been nearly two years since that post, and Firefox still ignores the `text-overflow: ellipsis;` property.
My current solution is to truncate long strings in PHP like so:
```
if(strlen($some_string) > 30)
$some_string = substr($some_string,0,30)."...";
```
That more or less works, but it doesn't look as nice or as accurate as `text-overflow: ellipsis;` in browsers that support it. The actual width of thirty characters varies since I'm not using a monospace font. The XML fix and jQuery plugins posted in the other thread appear to no longer work in Firefox either.
Is there currently a way to do this in CSS that is browser independent? If not, is there a way to measure the width of a string given a font and font size in PHP so that I might more accurately place my ellipsis? | 2011/03/18 | [
"https://Stackoverflow.com/questions/5358468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364123/"
] | Blueprint css has default colours for heading tags. (see [screen.css](https://github.com/joshuaclayton/blueprint-css/blob/master/blueprint/screen.css))
You need to specify:
```
#left-sidebar h2, #left-sidebar h4,
#right-sidebar h2, #right-sidebar h4 { color: white; }
``` | the header tags need their own CSS Class.
```
h2, h4{
color:white;
}
```
should do the trick |
359,236 | For the last month or so, I've been attempting to get jetbrains-toolbox to work. It used to work (and is how I installed IntelliJ IDEA and Gogland.) When I went to update the IDEA
I'm currently using Arch. Here are the things I have tried.
1. Loading jetbrains-toolbox from within Sway.
2. Reinstalling jetbrains-toolbox from the aur.
3. Reinstalling jetbrains-toolbox from the Jetbrains website.
4. Launching it with --disable-gpu
5. Clearing ~/.local/share/JetBrains/Toolbox
6. Googling all messages that I get.
7. Loading jetbrains-toolbox in different DEs. I tried GNOME, KDE, and i3.
The settings file (~/local/share/JetBrains/Toolbox/.settings.json), even after being cleared by action number 5, is able to regenerate, so I assume that there is something, somewhere on my filesystem that it isn't going away. This is what I think might be causing the problems. I have verified that the settings file was deleted by looking at Thunar's trash folder. However, doing a search for my email address (contained in the settings file) from ripgrep did not turn up anything relevant.
These are the commands I ran:
1. `cd ~/
sudo rg --hidden "MY_EMAIL_HERE" >> ~/Desktop/home_search.txt`
2. `cd /usr/
sudo rg --hidden "MY_EMAIL_HERE" >> ~/Desktop/home_search.txt`
The only relevant results of this were: `.local/share/JetBrains/Toolbox/.settings.json: "email": "MY_EMAIL_HERE",
.local/share/Trash/files/Toolbox/.settings.json: "email": "MY_EMAIL_HERE",`
I'm not exactly proficient with Linux, but I've been asking around for help with this for a while. If you have any advice, please have patience with me. I might be a bit stupid.
When I run it from the terminal, this is the message that shows up:
`john@john ~/D/jetbrains-toolbox-1.2.2314> ./jetbrains-toolbox
[0415/155414:WARNING:resource_bundle.cc(311)] locale_file_path.empty() for locale`
This is a message that will show up occasionally *through a system tray notification* (it does not use my notification daemon):
`failed to find application to url: share/jetbrains-toolbox/jetbrains-toolbox`
Maybe I need some folder in /usr/share or ~/.local/share named jetbrains-toolbox? I *do not* have that folder in either location.
These are two log files. One is from executing ToolBox and leaving it open for a bit. Another is from uninstalling ToolBox from the aur and deleting ~/.local/share/JetBrains/Toolbox and leaving it open for a bit. They have been labeled appropriately. <https://gist.github.com/gonzalezjo/4cf09eb4b7ad849df5557fd297a7061c>
When I open ToolBox, I'm greeted with a black screen. After about 15 seconds, it becomes white. Here's an imgur gallery showcasing this. [http://imgur.com/a/JS08D](https://imgur.com/a/JS08D)
(Note: I don't have enough reputation to include these as separate images while still including a link to the logs. Sorry about that :\)
From the moment the black screen shows to the moment it becomes white, I've timed it down to an average of 13.7 seconds using a stopwatch app on my phone and three trials. From the moment I type ./jetbrains-toolbox to the moment it becomes white, it's an average of about 16.1 seconds. Again, three trials.
My CPU is a Haswell i7 (i7-4790k) and my GPU is Pascal (Nvidia's GTX 1050). I think it's possible that this could be graphics driver or X related (or both? I am clueless here.) based off of a scary experience upgrading drivers prevented me from entering a DE. That experience was resolved after xorg (or something like that?) and the `nvidia` package were reinstalled.
According to nvidia-smi, my driver version is:
`NVIDIA-SMI 378.13 Driver Version: 378.13`
I've tried to provide all the information I can, but if anything else is needed, I'm happy to provide. | 2017/04/15 | [
"https://unix.stackexchange.com/questions/359236",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/227119/"
] | Just launch with `--disable-seccomp-filter-sandbox` and it should work.
I found it in <https://bbs.archlinux.org/viewtopic.php?id=229859> | So I spent about a month struggling with packages and downloads everywhere, with tons of googling, asking around etc., to no avail. I made this post and within about an hour, messing around in my file manager, completely clueless, I somehow managed to fix this. Welp. Sorry... Here's exactly what I did. Hurray for desperation, I guess?
1. Install the `jetbrains-toolbox` package from the AUR.
2. Go to `/opt/JetBrains/Toolbox` (found by looking at the `PKGBUILD`)
3. Navigate to `/opt/JetBrains/Toolbox/bin/` to find `jetbrains-toolbox`, an executable. I copied this to a folder I made in documents named `ToolboxResearch/`.
(Run `mkdir -p ~/Documents/ToolboxResearch/Extracted`, then run `cp /opt/JetBrains/Toolbox/bin/jetbrains-toolbox ~/Documents/ToolboxResearch`).
4. Navigate to `~/Documents/ToolboxResearch`
5. Extract it using Ark to the `Extracted` folder.
6. You should have a file hierarchy that looks like so: `~/Documents/ToolboxResearch/Extracted/jetbrains-toolbox/`. I copied this from the file path bar of Thunar, my file manager of choice, so if I made a mistake anywhere up to this point, you can rest assured that this part is correct.
7. To avoid confusing myself with `/usr/` and `usr/`, I ran `mv ~/Documents/ToolboxResearch/Extracted/jetbrains-toolbox/usr ~/Documents/ToolboxResearch/Extracted/jetbrains-toolbox/store`.
8. I edited `~/Documents/ToolboxResearch/Extracted/jetbrains-toolbox/Jetbrains Toolbox` to have these contents:
```
Type=Application
Name=JetBrains Toolbox
Exec=/home/john/Documents/ToolboxResearch/Extracted/jetbrains-toolbox/store/bin/jetbrains-toolbox %u
Icon=/store/share/jetbrains-toolbox/toolbox.svg
StartupNotify=false
Terminal=true
MimeType=x-scheme-handler/jetbrains;
```
The changes I made are specifically limited to `Exec`, `Icon`, and `Terminal`. I changed `Terminal` to `true` just to see what it did and I changed `Icon` and `Exec` to reflect the new file paths. I highly doubt that this did anything though.
You will want to change "john" to reflect your home directory instead of mine.
9. I opened `~/Documents/ToolboxResearch/Extracted/jetbrains-toolbox/store/bin/jetbrains-toolbox` (again, copy-pasting from Thunar) in my editor and edited line 5, which starts with `path=`. I changed it to `path=~/Documents/ToolboxResearch/Extracted/jetbrains-toolbox/store/share/$app`.
10. Navigated to `~/Documents/ToolboxResearch/Extracted/jetbrains-toolbox/store/bin/` in my terminal.
11. Ran `./jetbrains-toolbox`
12. It worked!
Sorry for making this post. I Never would've thought that I'd figure this out so soon after I made it. I actually thought I was hopeless.
If someone has this problem and can't fix it even after reading this, you can leave a reply and I'll hopefully be able to help you out. My apologies if this explanation wasn't very clear. |
994,020 | I am using visual web developer express 2008 for one of my personal projects. I am looking for a source safe or similar product that is free and that can integrate with visual web developer 2008. Please let me know if you know any products.
Thanks,
sridhar. | 2009/06/14 | [
"https://Stackoverflow.com/questions/994020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54429/"
] | As far as I know, extension points allowing for such integration are unavailable in VWD. That's the price for using free Express version...
In your place I would use Subversion and Tortoise SVN, which is quite convenient, even though you'll need to manage your source control in Explorer windows, not in VWD. For some time I was working in a such way even using full VS.NET
Good luck :) | There's simply nothing better then **Subversion**.
Take a look at the article on how to set it up and integrate with Visual Web Developer Express 2008
[Subversion with Visual Studio 2008](http://incsharp.blogspot.com/2007/11/subversion-visual-studio-2008.html) |
33,934,389 | I have some trouble with grouping the data by the order number and aggregating the "support columns" while selecting always the "highest" value.
```
╔═════════════╦══════════════╦════════════════╗
║ OrderNumber ║ PhoneSupport ║ ServiceSupport ║
╠═════════════╬══════════════╬════════════════╣
║ 0000000001 ║ 0020 ║ ║
║ 0000000001 ║ 0010 ║ 0030 ║
║ 0000000001 ║ 0010 ║ 0020 ║
║ 0000000002 ║ ║ 0030 ║
║ 0000000002 ║ 0030 ║ ║
║ 0000000003 ║ 0020 ║ ║
║ 0000000003 ║ 0030 ║ ║
╚═════════════╩══════════════╩════════════════╝
```
In this example the output should be like this.
```
╔═════════════╦══════════════╦════════════════╗
║ OrderNumber ║ PhoneSupport ║ ServiceSupport ║
╠═════════════╬══════════════╬════════════════╣
║ 0000000001 ║ 0020 ║ 0030 ║
║ 0000000002 ║ 0030 ║ 0030 ║
║ 0000000003 ║ 0030 ║ ║
╚═════════════╩══════════════╩════════════════╝
```
So far I have often read in various forums something about cursors but I don't like to use it.
My idea was to use the over clause but I am not sure if it is a solution for that case. | 2015/11/26 | [
"https://Stackoverflow.com/questions/33934389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5607537/"
] | Use `GROUP BY`, do `MAX` on the columns you want the "highest" value for.
```
select OrderNumber, max(PhoneSupport), max(ServiceSupport)
from tablename
group by OrderNumber
``` | You can use `Group By` and `Max` and then wrap the query in parent to do `Order By` on aggregate columns. Example shown below.
```
select *
from (
select OrderNumber, max(PhoneSupport) as PhoneSupport, max(ServiceSupport) as ServiceSupport
from tablename
group by OrderNumber) aa
Order By aa.PhoneSupport
``` |
44,402,590 | ```
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return interests.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt cellForItemAtindexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell
cell.interest = self.interest[indexPath.item]
return cell
}
``` | 2017/06/07 | [
"https://Stackoverflow.com/questions/44402590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8122887/"
] | Correct your method signature as
Swift
```
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
```
Objective c
```
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
```
[documentation](https://developer.apple.com/documentation/uikit/uicollectionviewdatasource/1618029-collectionview) | Change to this:
```
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell
cell.interest = self.interest[indexPath.item]
return cell
}
```
**UPDATE**
And if this is the UICollectionView function you also needs to add the `override` keyword before `func`
```
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell
cell.interest = self.interest[indexPath.item]
return cell
}
``` |
3,170,539 | I was given an unconventional combinatorics question I was struggling with.
Suppose we have 4 books and 7 different bookshelves.
In how many ways the books can be arranged without loss of generality?
I can either put all 4 of them on 1 shelf, or either split each one in a different shelf. In a case such as that, how do I consider the shelves that can't be picked? how to sum the number of options I have left when I do pick $k < 4$ books on 1 shelf (which are arranged in $k!$ options) and left with 6 different shelves and $4-k$ books?
Best regards for the helpers. | 2019/04/01 | [
"https://math.stackexchange.com/questions/3170539",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/459400/"
] | (Assume all books and shelves identical)
So you can have $(4,0,...,0)$ - 7 ways to choose which shelf this is
$(3,1,0,...,0)$ - 42 ways to choose the two shelves i.e. 6\*7
$(2,2,0,...,0)$ - 7C2 ways to choose the two shelves (i.e. 6\*7/2)
$(2,1,1,0,...,0)$ - 7\*(6C2)
$(1,1,1,1,0,...,0)$ - 7C4
Now add all of these solutions together to get the final answer. | Each book can be put into $7$ different book shelves. So the total number of ways is $7^4.$ |
23,355,252 | Saw a sweet video on gcloud and wanted to give it a shot but was stymied at the start. I did the setup, downloaded the tools, ran gcloud auth login, all good. Tried to init a project and got an error I'm not sure how to fix.
```
$ gcloud init my-awesome-project-555
Initialized gcloud directory in [/Users/freddy/my-awesome-project-555/.gcloud].
Cloning [https://source.developers.google.com/p/my-awesome-project-555/r/default] into [default].
Initialized empty Git repository in /Users/freddy/my-awesome-project-555/default/.git/
fatal: remote error: 403 Forbidden
ERROR: Unable to initialize project [my-awesome-project-555], cleaning up [/Users/freddy/my-awesome-project-555].
ERROR: (gcloud.init) Could not fetch repository.
$
```
For good measure:
```
$ which git
/usr/local/git/bin/git
$ git --version
git version 1.7.12.1
$
```
I'm on a macbook air with OSX 10.9.2
Any ideas on what I may be doing wrong? | 2014/04/29 | [
"https://Stackoverflow.com/questions/23355252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3583700/"
] | The integration between gcloud auth and git only works for git clients version 1.8 and up. Please try updating your git client and try again. We will add a more clear error message for this in a future release. Thanks! | The 403 indicates that you do not own my-awesome-project-555. You can use the cloud console (<https://console.developers.google.com/project>) to create a new project, and use that project ID with 'gcloud init'. |
5,658,702 | I am trying to write a ruby script that interacts with a PostgreSQL database. I am trying to piece together how to do this from the documentation, but a nice tutorial or sample code would work wonders to decrease the amount of time to get this working. If anyone has a link, some tips or has some code they could share I would be most grateful.
Edit, made this note more clear:
Note: this isn't to do with rails ActiveRecord, I am writing a Ruby script that will be involved in a program that is completely independent from Rails. | 2011/04/14 | [
"https://Stackoverflow.com/questions/5658702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638529/"
] | Please be more specific about what postgresql library you're using.
I'm going to assume the 'pg' gem, apart from ActiveRecord.
The project source has an html file that might be helpful.
Go to <https://bitbucket.org/ged/ruby-pg/src/b477174160c8/doc/postgres.html>
Then click "raw" at the upper right side of the html. Open the file in your web browser.
This sample code helps you connect (copied from the html file):
```
require "postgres"
conn = PGconn.connect("localhost", 5432, "", "", "test1")
# or: conn = PGconn.open('dbname=test1')
res = conn.exec("select * from a;")
```
The res object is a PGResult. Scroll down to that section in the html to see what methods you can call.
This link has a PGResult example:
<http://rubydoc.info/gems/pg/0.10.0/PGresult>
Excerpt:
```
require 'pg'
conn = PGconn.open(:dbname => 'test')
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
res.getvalue(0,0) # '1'
res[0]['b'] # '2'
res[0]['c'] # nil
``` | You only need to require the `pg` gem and establish the connection to the DB:
```
require 'pg'
# require 'active_record' # uncomment for not Rails environment
ActiveRecord::Base.establish_connection(:adapter => "postgresql",
:username => "username",
:password => "password",
:database => "database")
```
When you define models to inherit from `ActiveRecord::Base` they will use this database connection. Everything else should work like it does in Rails. |
10,194 | If I want to make an XML sitemap for my site, do I need to map every forum topic in my forum as a separate URL?
If this would help, how do you deal with the hugeness of the sitemap for forums with over 100,000 urls?
Or is it just meant to map entry pages to the rest of your content? And can you semantically nest URLS? | 2011/03/07 | [
"https://webmasters.stackexchange.com/questions/10194",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/5727/"
] | @Tom
For a forum I would make sure to filter off (both in analysis and output filters) e.g. user profile pages and similar. Only include real discussion topics/pages.
@Gaurav
The max URLs per XML sitemap file is 50,000 URLs / 10 MB (but some tools may default to less per sitemap file) You can configure tools like A1 Sitemap Generator to parse through forms and most Javascript. You can also add multiple start search paths and combine it with a variety of filters. So I disagree 3rd party apps are bound to miss URLs :) | Third party apps basically rely on page crawling for generating sitemaps. They are bound to miss out a good chunk of URL's. I'll suggest that you code up a small script which generates an XML sitemap by iterating over your CMS's database. If you have more than 10,000 URL's, you'll need to generate partial sitemaps and link them up via an index sitemap. |
22,765,756 | I have an array something like this:
```
[
{id: 5, attr: 99},
{id: 7, attr: null},
{id: 2, attr: 8},
{id: 9, attr: 3},
{id: 4, attr: null}
]
```
What would be the most efficient to put all objects with `attr === null` at the beginning of the array, without changing order of other elements in the array? (e.g. I need ids to go in this order: 7, 4, 5, 2, 9 (the order of 7 and 4 don't matter, but the order of 5, 2, 9 must never change.)
Simple fiddle to test your code: <http://jsfiddle.net/8GEPC/> | 2014/03/31 | [
"https://Stackoverflow.com/questions/22765756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008798/"
] | Could used built in filter methods that require two loops or one while loop to find the elements and remove them.
```
var x = [
{id: 5, attr: 99},
{id: 7, attr: null},
{id: 2, attr: 8},
{id: 9, attr: 3},
{id: 4, attr: null}
];
var temp = [];
for(var i = x.length-1;i>=0;i--){
if (x[i].attr===null) { //if we have a null
temp.unshift(x.splice(i,1)[0]); //remove the element from org and add to temp
}
}
x = temp.concat(x); //add the original to the temp to maintain the order
``` | Grab the objects where `attr === null`.
```
var withNull = arr.filter(function (el) { return el.attr === null });
```
Grab the objects where `attr !== null`.
```
var withVal = arr.filter(function (el) { return el.attr !== null });
```
Add the 'null array' to the front of the 'values array'.
```
withVal.unshift.apply(withVal, withNull);
```
[Fiddle](http://jsfiddle.net/VU9n7/11/) |
34,072,910 | There are many different techniques to disable unused variable warnings. Some with void, same with attribute. They all though assume that you know that it is a variable.
I have a case of macro that changes its behavior from release and debug, say:
```
#if NDEBUG
#define MACRO(X)
#else
#define MACRO(X) do_something(X)
#endif
```
Code like:
```
void foo(int a) {
MACRO(a);
}
```
may result in warning in release. I would like to change this to:
```
#if NDEBUG
#define MACRO(X) UNUSED(X)
#else
#define MACRO(X) do_something(X)
#endif
```
So the question is what I should define `UNUSED` to, when the task is complicated from the fact that the argument to `MACRO` is not limited to variable, but it could also be a function call or any other expression. Or
```
MACRO(5);
MACRO(a+b);
MACRO(foo());
```
are also valid uses of `MACRO` | 2015/12/03 | [
"https://Stackoverflow.com/questions/34072910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870790/"
] | Your divs are getting skewed additionally, as you didn't close the ones before. Close the divs:
```
<div id="para">
<div class="parallelogram-1"></div>
<div class="parallelogram-1"></div>
<div class="parallelogram-1"></div>
</div>
``` | You did not close your divs. Also if you wanted them to be side by side, make them inline-block or they will be each block on its own line.
HTML:
```
<div id="para">
<div class="parallelogram-1"></div>
<div class="parallelogram-1"></div>
<div class="parallelogram-1"></div>
</div>
```
CSS:
```
.parallelogram-1 {
display: inline-block;
width: 30px;
height: 45px;
margin: 0px 3px;
border-left: 1px solid #000;
-webkit-transform: skew(-20deg);
-moz-transform: skew(-20deg);
-o-transform: skew(-20deg);
background: red;
}
```
Here's the fiddle:
<http://jsfiddle.net/0u14evtx/8/> |
6,185,016 | I generate my jqgrid from model class which I pass into view. I get constructed and working jqgrid. However, I want to set postData on one view, where I use jqGrid, from script in that view, after I call helper for creating jqgrid, without having to change whole partial view which creates jqgrid.
I tried running
```
$("#@Model.Id").jqGrid('setGridParam', { postData: { test: 233} });
```
and
```
$("#@Model.Id").setGridParam({ postData: { test: 233} });
```
but without error or any result. If I set postData in jqgrid parameters (in partial view where it is constructed, it works.
I also checked that grid exists, added
```
console.log($("#@Model.Id").size());
```
before the first line, and it shows 1.
UPDATE: This .setGirdParam function started to work for me for no apparent reason, so I will accept answer if someone can give some insight what can prevent this from working.
Thanks | 2011/05/31 | [
"https://Stackoverflow.com/questions/6185016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/408643/"
] | You didn't include the definition of jqGrid in your question and we can't see **the place** where the `setGridParam` is called. First of all you should use `setGridParam` **after** the jqGrid is created, but **before** the request will be sent. If you will change the `postData` **the next** jqGrid request can use the new parameter. So one typically uses
```
$("#@Model.Id").trigger('reloadGrid', [{page:1}]);
```
see [here](https://stackoverflow.com/questions/3807623/jqgrid-paging-question/3808014#3808014).
I suppose that the best option for you will be the usage of function `test` property of the `postData` as the function:
```
$("#@Model.Id").jqGrid({
// ... other jqGrid parameters ...
postData: {
test: function() {
// the code can by dynamic, read contain of some elements
// on the page use "if"s and so on and return the value which
// should be posted to the server
return 233;
}
}
// other jqGrid parameters ...
});
```
See [here](https://stackoverflow.com/questions/2928371/how-to-filter-the-jqgrid-data-not-using-the-built-in-search-filter-box/2928819#2928819) for details. In this way you can implement practically **any** scenario.
By the way if you don't want that jqGrid to send any request to the server till the event is happened you can use `datatype:'local'` at the initialization time. Then if you want that the grid should be filled you can use `setGridParam` to change the `datatype` from `'local'` to `'json'` (or `'xml'`) and call `.trigger('reloadGrid',...)`. | ```
$("#grid id").setGridParam({ postData: {data:dataval} });
$("#grid id").trigger('reloadGrid', [{page:1,data:dataval}]);ntn
``` |
249,953 | Often on advertising material, one will see instructions to "quote *(phrase)* for a discount", for example when booking a hotel or other service. [Examples here](https://skillsmatter.com/conferences/6712-droidcon-2015#venue), [here](http://www.theadvisory.co.uk/online-estate-agents.php) [and here](http://www.bath.ac.uk/hr/working/pay-reward/benefits/staff-discounts/).
How would one be expected to quote such a phrase?
>
> Hello, can I quote *(often odd-sounding) phrase* please?
>
>
>
strikes me as awkward. | 2015/06/02 | [
"https://english.stackexchange.com/questions/249953",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/1572/"
] | If you are booking or purchasing online, there is usually a place to enter a discount code. If you are doing so by phone or in person, they will often ask if you have any discounts. If not, simply say that you have a discount code, say where you found it, and either say it or show the clerk a copy. | In US usage, the phrase *mention [code, term, or phrase] when ordering for a x% discount* is often seen.
When filling out an online form, the phrase *enter [code, term, or phrase] in the **Discount Code** box/field* is common. |
37,000,416 | I know how to redirect/rewrite non-www to www using .htaccess in apache server. But I have no clue, about s3 bucket, and CloudFront. I have hosted the website on an s3 bucket using CloudFront.
How do I redirect all <http://example.com/> requests to <http://www.example.com> | 2016/05/03 | [
"https://Stackoverflow.com/questions/37000416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6285054/"
] | There is a feature in S3 where you can to this. Select a bucket, in **Properties** under **Static Web Hosting** select **Redirect all requests to another host name**.
Read more here: <https://aws.amazon.com/blogs/aws/root-domain-website-hosting-for-amazon-s3/>
Update from comment:
Add a cname in your domain setup for example.com to point to your bucket endpoint and a cname for your www.example.com to point to the cloudfront endpoint. | 1. Create a `www.example.com` S3 bucket and place all the code in this bucket
2. Create a `example.com` S3 bucket and set redirect to `www.example.com` as mentioned in <https://aws.amazon.com/blogs/aws/root-domain-website-hosting-for-amazon-s3/>
3. Create CloudFront and configure with S3 bucket link of `www.example.com` and add `cname` entry only for `www.example.com`.
4. In Route 53 for `www.example.com` point alias as CloudFront link related to S3 bucket
5. In Route 53 for `example.com` point alias S3 bucket of `example.com` |
8,063,287 | Hello fellow developers!
We are almost finished with developing first phase of our ajax web app.
In our app we are using hash fragments like:
```
http://ourdomain.com/#!list=last_ads&order=date
```
I understand google will fetch this url and make a request to the server in this form:
```
http://ourdomain.com/?_escaped_fragment_=list=last_ads?order=date&direction=desc
```
everything is perfect, except...
I would like to route this kind of request to another script
like so:
```
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)$
RewriteRule ^$ /webroot/crawler.php$1 [L]
```
The problem is, that when I try to print\_r($\_REQUEST) in crawler.php I get only:
```
Array
(
[_escaped_fragment_] => list=last_ads?order=date
[direction] => desc
)
```
what I'd like to get is
```
Array
(
[list] => last_ads
[order] => date
[directions] => des
)
```
I know I could use php to further break the first argument, but I don't want to ;)
please advise
====================================================
EDIT... some corrections in text and logic | 2011/11/09 | [
"https://Stackoverflow.com/questions/8063287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484025/"
] | Your forgot QSA directive (everyone missed the point =D )
```
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)$
RewriteRule ^$ /webroot/crawler.php%1 [QSA,L]
```
By the way your `$1` is well err... useless because it refers to nothing. So this should be:
```
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)$
RewriteRule ^$ /webroot/crawler.php [QSA,L]
```
Tell me if this works. | If I'm not mistaken.
```
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)$
RewriteRule ^$ /webroot/crawler.php?%1 [L]
``` |
44,905,211 | I need to set from the main viewmodel a property inside an observable array.
I'm using the classic `pre` to debug and display the content of my observable array.
By using `types.valueHasMutated()` I can see the applied changes - just only to `vm.types` (which wouldn't be the case otherwise).
However, I need to see this changes reflected inside my component.
In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.
What I'm doing wrong?
```js
ko.components.register("available-items", {
viewModel: function(params) {
function AvailableItems(params) {
var self = this;
self.params = params;
self.location = "A";
self.types = ko.computed(function() {
var types = self.params.types();
return ko.utils.arrayFilter(types, function(item) {
return item.location == self.location;
});
});
self.addItem = function(data, event) {
self.params.items.addItem(self.location, data.type);
};
}
return new AvailableItems(params);
},
template: '<div>' +
'<h4>Add item</h4>' +
'<ul data-bind="foreach: types">' +
'<li>' +
'<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
'</li>' +
'</ul>' +
'</div>',
synchronous: true
});
var types = [{
type: "Apples",
location: "A",
available: true
}, {
type: "Bananas",
location: "A",
available: false
}];
function Vm(data) {
var self = this;
self.items = ko.observableArray();
self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
return item;
}));
self.items.addItem = function(location, type) {
self.items.push({
location: location,
type: type
});
if (location == "A" && type == "Apples") {
self.types()[0].available = false;
self.types.valueHasMutated();
}
};
}
ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);
```
```css
pre {
position: absolute;
width: 300px;
right: 0;
top: 0;
}
```
```html
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
</head>
<body>
<div data-bind="component:{name:'available-items',params:vm}"></div>
<ul data-bind="foreach: items">
<li><span data-bind="text: location"></span> - <span data-bind="text: type"></span></li>
</ul>
<pre data-bind="text: ko.toJSON(vm.types, null, 2)"></pre>
</body>
</html>
``` | 2017/07/04 | [
"https://Stackoverflow.com/questions/44905211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4845566/"
] | I have run this on jfiddle and even when I added a new type, I wasn't getting any update.
It seems like there was an issue with the
```
'<ul data-bind="foreach: types">' +
```
I changed it to
`'<ul data-bind="foreach: $root.types">' +`
<https://jsfiddle.net/fabwoofer/9szbqhj7/1/>
Now the type gets added but it seems like the re-rendering of the first item is not handled. People with similar problems have suggested using template rendering as described here
[Knockout.js Templates Foreach - force complete re-render](https://stackoverflow.com/questions/7516636/knockout-js-templates-foreach-force-complete-re-render)
Hope this helps | You could use this solution given by the user JotaBe: [Refresh observableArray when items are not observables](https://stackoverflow.com/a/28150736/4065876).
```
ko.observableArray.fn.refresh = function (item) {
var index = this['indexOf'](item);
if (index >= 0) {
this.splice(index, 1);
this.splice(index, 0, item);
}
}
```
Now, I need to change `addItem()` and add the call to `refresh` with the updated element:
```
self.items.addItem = function(location, type) {
self.items.push({
location: location,
type: type
});
if (location == "A" && type == "Apples") {
self.types()[0].available = false;
self.types.refresh(self.types()[0]); // <--- New sentence
}
};
```
This will refresh the `<pre>`, that has a list of `types`. But will not refresh the component, that also has a list of `types`.
Then I used this link, [Forcing deferred notifications to happen early](https://knockoutjs.com/documentation/deferred-updates.html), and I added `ko.tasks.runEarly()` in the `refresh`, and now it works ok, I think.
```
ko.observableArray.fn.refresh = function (item) {
var index = this['indexOf'](item);
if (index >= 0) {
this.splice(index, 1);
ko.tasks.runEarly(); // <--- New sentence
this.splice(index, 0, item);
}
}
```
Here it is a [Codepen](https://codepen.io/anon/pen/RgJBrK). |
8,155,618 | >
> **Possible Duplicate:**
>
> [Conditional operator cannot cast implicitly?](https://stackoverflow.com/questions/2215745/conditional-operator-cannot-cast-implicitly)
>
> [Why does null need an explicit type cast here?](https://stackoverflow.com/questions/2608878/why-does-null-need-an-explicit-type-cast-here)
>
>
>
I've had a search and haven't found a good explanation for why the following occurs.
I have two classes which have an interface in common and I have tried initializing an instance of this interface type using the ternary operator as below but this fails to compile with the error "Type of conditional expression cannot be determined because there is no implicit conversion between 'xxx.Class1' and 'xxx.Class2':
```
public ConsoleLogger : ILogger { .... }
public SuppressLogger : ILogger { .... }
static void Main(string[] args)
{
.....
// The following creates the compile error
ILogger logger = suppressLogging ? new SuppressLogger() : new ConsoleLogger();
}
```
This works if I explicitly cast the first conditioin to my interface:
```
ILogger logger = suppressLogging ? ((ILogger)new SuppressLogger()) : new ConsoleLogger();
```
and obviously I can always do this:
```
ILogger logger;
if (suppressLogging)
{
logger = new SuppressLogger();
}
else
{
logger = new ConsoleLogger();
}
```
The alternatives are fine but I can't quite get my head around why the first option fails with the implicit conversion error as, in my view, both classes are of type ILogger and I am not really looking to do a conversion (implicit or explicit). I'm sure this is probably a static language compilation issue but I would like to understand what is going on. | 2011/11/16 | [
"https://Stackoverflow.com/questions/8155618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762/"
] | This is a consequence of the confluence of two characteristics of C#.
The first is that C# never "magics up" a type for you. If C# must determine a "best" type from a given set of types, it always picks one of the types you gave it. It never says "none of the types you gave me are the best type; since the choices you gave me are all bad, I'm going to pick some random thing that you did not give me to choose from."
The second is that C# reasons from *inside* to *outside*. We do not say "Oh, I see you are trying to assign the conditional operator result to an ILogger; let me make sure that both branches work." The opposite happens: C# says "let me determine the best type returned by both branches, and verify that the best type is convertible to the target type."
The second rule is sensible because *the target type might be what we are trying to determine.* When you say `D d = b ? c : a;` it is clear what the target type is. But suppose you were instead calling `M(b?c:a)`? There might be a hundred different overloads of M each with a different type for the formal parameter! We have to determine what the type of the argument is, and then discard overloads of M which are not applicable because the argument type is not compatible with the formal parameter type; we don't go the other way.
Consider what would happen if we went the other way:
```
M1( b1 ? M2( b3 ? M4( ) : M5 ( ) ) : M6 ( b7 ? M8() : M9() ) );
```
Suppose there are a hundred overloads each of M1, M2 and M6. What do you do? Do you say, OK, if this is M1(Foo) then M2(...) and M6(...) must be both convertible to Foo. Are they? Let's find out. What's the overload of M2? There are a hundred possibilities. Let's see if each of them is convertible from the return type of M4 and M5... OK, we've tried all those, so we've found an M2 that works. Now what about M6? What if the "best" M2 we find is not compatible with the "best" M6? Should we backtrack and keep on re-trying all 100 x 100 possibilities until we find a compatible pair? The problem just gets worse and worse.
We *do* reason in this manner for lambdas and as a result overload resolution involving lambdas is at least NP-HARD in C#. That is bad right there; we would rather not add more NP-HARD problems for the compiler to solve.
You can see the first rule in action in other place in the language as well. For example, if you said: `ILogger[] loggers = new[] { consoleLogger, suppressLogger };` you'd get a similar error; the inferred array element type must be the *best type* of the typed expressions given. If no best type can be determined from them, we don't try to find a type you did not give us.
Same thing goes in type inference. If you said:
```
void M<T>(T t1, T t2) { ... }
...
M(consoleLogger, suppressLogger);
```
Then T would not be inferred to be ILogger; this would be an error. T is inferred to be the best type amongst the supplied argument types, and there is no best type amongst them.
For more details on how this design decision influences the behaviour of the conditional operator, see [my series of articles on that topic](http://blogs.msdn.com/b/ericlippert/archive/tags/conditional+operator/).
If you are interested in why overload resolution that works "from outside to inside" is NP-HARD, see [this article](http://blogs.msdn.com/b/ericlippert/archive/2007/03/28/lambda-expressions-vs-anonymous-methods-part-five.aspx). | The problem is that the right hand side of the statement is evaluated without looking at the type of the variable it is assigned to.
There's no way the compiler can look at
```
suppressLogging ? new SuppressLogger() : new ConsoleLogger();
```
and decide what the return type should be, since there's no implicit conversion between them. It doesn't look for common ancestors, and even if it did, how would it know which one to pick. |
38,149,745 | I've searched a lot but I didn't find any anwser to my issue.
I recently discovered JNativeHook and I use it to bring to the foreground an application window when I click on a key, even if the application has not the focus. Everything works good when I use keys like "a" or "f" but what I want is to use the "left-home" key of my keyboard.
The problem is when I do that, the windows menu appears but not my application which blinks in orange on the bottom launcher bar.
I think this is a normal behavior since the windows menu has a stronger priority than my application.
Do you think there is a possibility to override the default home button behavior? What I need is to bring to the front my application from elsewhere when I clicked on the left-home button.
Thanks for your replies, | 2016/07/01 | [
"https://Stackoverflow.com/questions/38149745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4393495/"
] | Looks like there is *no* “proper” way to do it, but we can try monkey-patching our way around the problem. Here’s the best kludge I could do:
```
from mpl_toolkits.mplot3d import proj3d
def make_get_proj(self, rx, ry, rz):
'''
Return a variation on :func:`~mpl_toolkit.mplot2d.axes3d.Axes3D.getproj` that
makes the box aspect ratio equal to *rx:ry:rz*, using an axes object *self*.
'''
rm = max(rx, ry, rz)
kx = rm / rx; ky = rm / ry; kz = rm / rz;
# Copied directly from mpl_toolkit/mplot3d/axes3d.py. New or modified lines are
# marked by ##
def get_proj():
relev, razim = np.pi * self.elev/180, np.pi * self.azim/180
xmin, xmax = self.get_xlim3d()
ymin, ymax = self.get_ylim3d()
zmin, zmax = self.get_zlim3d()
# transform to uniform world coordinates 0-1.0,0-1.0,0-1.0
worldM = proj3d.world_transformation(xmin, xmax,
ymin, ymax,
zmin, zmax)
# adjust the aspect ratio ##
aspectM = proj3d.world_transformation(-kx + 1, kx, ##
-ky + 1, ky, ##
-kz + 1, kz) ##
# look into the middle of the new coordinates
R = np.array([0.5, 0.5, 0.5])
xp = R[0] + np.cos(razim) * np.cos(relev) * self.dist
yp = R[1] + np.sin(razim) * np.cos(relev) * self.dist
zp = R[2] + np.sin(relev) * self.dist
E = np.array((xp, yp, zp))
self.eye = E
self.vvec = R - E
self.vvec = self.vvec / proj3d.mod(self.vvec)
if abs(relev) > np.pi/2:
# upside down
V = np.array((0, 0, -1))
else:
V = np.array((0, 0, 1))
zfront, zback = -self.dist, self.dist
viewM = proj3d.view_transformation(E, R, V)
perspM = proj3d.persp_transformation(zfront, zback)
M0 = np.dot(viewM, np.dot(aspectM, worldM)) ##
M = np.dot(perspM, M0)
return M
return get_proj
# and later in the code:
ax.get_proj = make_get_proj(ax, 1, 1, 2)
ax.set_aspect(1.0)
```
[](https://i.stack.imgur.com/4lNos.png) | Have you tried stretching your canvas in the vertical direction? For instance,
```
plt.figure(figsize=(5,10))
```
or something similar should give you more space. I am not sure, though, if that will solve your problem. |
38,949 | I am trying to understand how SSL certificate and signing and the chain of trust works.
I know about `root CAs` and that they are used to sign `intermediate CAs` that sign the end certificates that are issued to a website. I also understand how the chain of trust works and that because a ceritifcate signed for `X.com` is signed by the intermediate certificate that issued it which is signed by the root CA, I can be assured that I am connecting to `X.com`.
My question is, how long does this chain extend? Can't I use `X.com` to sign a certificate for another domain, say `Y.com`. If no, why not? If yes, I don't see the purpose of signing. | 2013/07/15 | [
"https://security.stackexchange.com/questions/38949",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/28286/"
] | In order to be accepted as an issuer for other certificates, a CA certificate must be marked as such: they must contain a [`Basic Constraints` extension](https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9) with the `cA` flag set to `TRUE`. If a client (e.g. a Web browser) sees a purported server certificate chain, with the "X.com" certificate, not marked as a CA, used as an intermediate CA, then the client will reject the chain, in application of the standard certificate validation algorithm, in [section 6.1.4](https://www.rfc-editor.org/rfc/rfc5280#section-6.1.4), step (k):
>
> (k) If certificate i is a version 3 certificate, verify that the
> basicConstraints extension is present and that cA is set to
> TRUE. (If certificate i is a version 1 or version 2
> certificate, then the application MUST either verify that
> certificate i is a CA certificate through out-of-band means
> or reject the certificate. Conforming implementations may
> choose to reject all version 1 and version 2 intermediate
> certificates.)
>
>
>
Note the comments about "version 1" and "version 2" certificates. Modern X.509 certificates are "version 3" (their `version` field contains 2, not 0 or 1). Previous versions for the X.509 format did not have room for extensions, so no `Basic Constraints`. The glaring vulnerability that you feared, with any certificate owner being able to act as a CA, was, well, glaring indeed. But it took several years for people to catch up.
Fortunately, all current implementations of SSL consider v1 and v2 certificates as "definitely non-CA", just like v3 certificate which lack a `Basic Constraints` extension.
On a similar vein, Internet Explorer, up to circa 2003 (if I remember correctly), did not check the `cA` flag... and it was indeed a serious problem, which was promptly fixed when discovered. It says quite a lot about X.509 that nobody had actually tested that for quite some time, because IE already had SSL support back in 1996 and v3 certificates were standardized [in early 1999](https://www.rfc-editor.org/rfc/rfc2459) (so, as is typical for Web thing, they were already deployed at that time, and the standard was more of a documentation of existing practice than anything else).
---
As for your specific question: *how long* does this chain extend ? There is no intrinsic limit, in the X.509 standard, about chain length, as long as all certificates in the chain are duly marked as CA (except possibly the last one) and have proper signatures and all the fields in certificates match up as they should. However, certification is **trust delegation** and trust dilutes *very fast* when delegated too much. Thus, overly long chains are a strong indication that the whole PKI process has gone bad.
Also, long chains may hit internal limits in some implementations. Chain building (the operation which prepares potential chains to be validated) can become expensive (with specially crafted certificates, it can have *factorial* cost for a given chain length), so implementations must include some guarding mechanism, which often is an internal maximum chain length. Practically encountered chains have length 2 to 4 certificates (i.e. one root, three intermediate CA at most, and then the end-entity certificate). My own code tends to reject chains beyond 8 certificates, and that arbitrary limit has never been, in my experience, an issue. | >
> How long does this chain extend?
>
>
>
There is no specified limit, but clients (browsers, mail programs, etc) may have some internal limit as to how many hops they're willing to follow.
>
> Can't I use X.com to sign a certificate for another domain, say Y.com. If no, why not? If yes, I don't see the purpose of signing.
>
>
>
No, since `X.com`'s certificate is not marked as a signing certificate.
Or rather: yes, you *could*, the underlying technology doesn't *prevent* you from doing so. But browsers are programmed to check for the `CA: true` basic constraint for all signing and intermediate certificates, and will not trust the signature if that isn't true.
Convincing a CA to sign an intermediate certificate for you is no small feat, since they're staking their reputation on the assertion that you will not sign anything that shouldn't be signed. Not a small guarantee. |
705,857 | I want to do some calendar manipulations in bash - specifically, I want to figure out the last date of a given month (including leap-year, and a preparing a table for a lookup is not a valid solution for me).
Supposedly I have the following code:
```
$year=2009
$start_month=2
$end_month=10
for $month in $(seq $start_month $end_month); do
echo "Last date of "$(date +"%B" -d "${year}-${month}-01")" is: " ???
done
```
I can't figure out how to do something like this. I though `date -d` would work like POSIX mktime and fold invalid dates to their valid equivalents, so I could say something like `date -d "2009-03-00"` and get '2009-02-28', but no such luck.
Is there anyway to do it using only what is available on bash in a standard GNU environment? | 2009/04/01 | [
"https://Stackoverflow.com/questions/705857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/53538/"
] | Try: `date -d 'yesterday 2009-03-01'`
Intuitive I know. Earlier versions of date used to work the POSIX way. | If you don't mind playing with grep/awk/perl, you can take a look at `cal`.
```
$ cal 4 2009
April 2009
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
```
Edit (MarkusQ): To atone for my joke solution below I'll contribute to yours:
```
cal 4 2009 | tr ' ' '\n' | grep -v ^$ | tail -n 1
``` |
45,826,243 | I have a table in SAS where in one column, the date is stored (e.g. "2005/10").
How do I have to convert this to a SAS data format?
Among many other tries, I tried this code:
data test;
```
format date YYMMS.;
date = input(ObservationMonth, YYMMS.);
put date=date9.;
run;
``` | 2017/08/22 | [
"https://Stackoverflow.com/questions/45826243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8502463/"
] | One way is to use `substr()` and `mdy()` to extract the date components:
```
data _null_;
ObservationMonth ="2005/10";
date =mdy(substr(ObservationMonth,6,2),1,substr(ObservationMonth,1,4));
put date = date9.;
run;
```
Another option is to use the `anydtdte` informat (note that results may differ depending on your locale):
```
data _null_;
ObservationMonth ="2005/10";
date =input(ObservationMonth,anydtdte.);
put date = date9.;
run;
```
Yet another option is to modify the input to enable use of the `YYMMDDw.` informat:
```
data _null_;
ObservationMonth ="2005/10";
date =input(ObservationMonth!!'/01', YYMMDD10.);
put date = date9.;
run;
``` | you're fantastic, guys! Thank you so much, with a "set" statement it works fine! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.