id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,968,416 | How to do HTTP authentication in android? | <p>I am checking out the class org.apache.http.auth.
Any more reference or example if anyone has?</p> | 1,968,873 | 6 | 2 | null | 2009-12-28 07:39:28.387 UTC | 44 | 2016-11-15 13:27:06.073 UTC | null | null | null | null | 199,525 | null | 1 | 73 | android|http-authentication | 125,763 | <p>I've not met that particular package before, but it says it's for client-side HTTP authentication, which I've been able to do on Android using the <code>java.net</code> APIs, like so:</p>
<pre><code>Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("myuser","mypass".toCharArray());
}});
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setUseCaches(false);
c.connect();
</code></pre>
<p>Obviously your getPasswordAuthentication() should probably do something more intelligent than returning a constant.</p>
<p>If you're trying to make a request with a body (e.g. <code>POST</code>) with authentication, beware of <a href="http://code.google.com/p/android/issues/detail?id=4326" rel="noreferrer">Android issue 4326</a>. I've linked a suggested fix to the platform there, but there's a simple workaround if you only want Basic auth: don't bother with Authenticator, and instead do this:</p>
<pre><code>c.setRequestProperty("Authorization", "basic " +
Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));
</code></pre> |
2,276,000 | Program web applications in python without a framework? | <p>I am just starting Python and I was wondering how I would go about programming web applications without the need of a framework. I am an experienced PHP developer but I have an urge to try out Python and I usually like to write from scratch without the restriction of a framework like flask or django to name a few. </p> | 2,276,018 | 7 | 8 | null | 2010-02-16 20:15:09.09 UTC | 22 | 2022-07-28 22:59:48.753 UTC | 2019-12-13 13:02:28.577 UTC | null | 11,845,682 | null | 274,080 | null | 1 | 44 | python | 36,785 | <p><a href="http://www.wsgi.org/wsgi/" rel="nofollow noreferrer">WSGI</a> is the Python standard for web server interfaces. If you want to create your own framework or operate without a framework, you should look into that. Specifically I have found <a href="https://paste.readthedocs.io/en/latest/do-it-yourself-framework.html" rel="nofollow noreferrer">Ian Bicking's DIY Framework</a> article helpful.</p>
<p>As an aside, I tend to think frameworks are useful and personally use Django, like the way Pylons works, and have used <a href="https://bottlepy.org/" rel="nofollow noreferrer">Bottle</a> in the past for prototyping—you may want to look at Bottle if you want a stay-out-of-your-way microframework.</p> |
2,232,238 | How to bring an activity to foreground (top of stack)? | <p>In Android, I defined an activity ExampleActivity.</p>
<p>When my application was launched, an instance of this A-Activity was created, say it is <code>A</code>.
When user clicked a button in <code>A</code>, another instance of B-Activity, B was created. Now the task stack is B-A, with B at the top. Then, user clicked a button on B, another instance of C-Activity, and C was created. Now the task stack is C-B-A, with C at the top.</p>
<p>Now, when user click a button on C, I want the application to bring A to the foreground, i.e. make A to be at the top of task stack, A-C-B.</p>
<p>How can I write the code to make it happen?</p> | 2,235,130 | 9 | 0 | null | 2010-02-09 20:18:22.59 UTC | 28 | 2015-06-12 20:08:24.587 UTC | 2013-09-22 03:20:08.86 UTC | null | 445,131 | null | 256,239 | null | 1 | 94 | android|android-intent|android-activity | 133,706 | <p>You can try this <a href="http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_REORDER_TO_FRONT" rel="noreferrer"><code>FLAG_ACTIVITY_REORDER_TO_FRONT</code></a> (the document describes exactly what you want to)</p> |
1,669,821 | Scanf skips every other while loop in C | <p>I'm trying to develop a simple text-based hangman game, and the main game loop starts with a prompt to enter a guess at each letter, then goes on to check if the letter is in the word and takes a life off if it isn't. However, when I run the game the prompt comes up twice each time, and the program doesn't wait for the user's input. It also takes off a life (one life if it was the right input, two if it wasn't), so whatever it's taking in isn't the same as the previous input. Here's my game loop, simplified a bit:</p>
<pre><code>while (!finished)
{
printf("Guess the word '%s'\n",covered);
scanf("%c", &currentGuess);
i=0;
while (i<=wordLength)
{
if (i == wordLength)
{
--numLives;
printf("Number of lives: %i\n", numLives);
break;
} else if (currentGuess == secretWord[i]) {
covered[i] = secretWord[i];
secretWord[i] = '*';
break;
}
++i;
}
j=0;
while (j<=wordLength)
{
if (j == (wordLength)) {
finished = 1;
printf("Congratulations! You guessed the word!\n");
break;
} else {
if (covered[j] == '-') {
break;
}
}
++j;
if (numLives == 0) {
finished = 1;
}
}
}
</code></pre>
<p>I assume the problem is scanf thinking it's taken something in when it hasn't, but I have no idea why. Does anyone have any idea? I'm using gcc 4.0.1 on Mac OS X 10.5.</p> | 1,670,290 | 10 | 0 | null | 2009-11-03 20:04:19.51 UTC | 12 | 2018-03-06 16:29:26.397 UTC | 2016-10-31 05:59:40.123 UTC | null | 450,609 | null | 49,128 | null | 1 | 17 | c|gcc|scanf | 21,054 | <p>When you read keyboard input with <code>scanf()</code>, the input is read after enter is pressed but the newline generated by the enter key is not consumed by the call to <code>scanf()</code>. That means the next time you read from standard input there will be a newline waiting for you (which will make the next <code>scanf()</code> call return instantly with no data).</p>
<p>To avoid this, you can modify your code to something like:</p>
<pre><code>scanf("%c%*c", &currentGuess);
</code></pre>
<p>The <code>%*c</code> matches a single character, but the asterisk indicates that the character will not be stored anywhere. This has the effect of consuming the newline character generated by the enter key so that the next time you call <code>scanf()</code> you are starting with an empty input buffer.</p>
<p><strong>Caveat:</strong> If the user presses two keys and then presses enter, <code>scanf()</code> will return the first keystroke, eat the second, and leave the newline for the next input call. Quirks like this are one reason why <code>scanf()</code> and friends are avoided by many programmers.</p> |
2,214,651 | Efficient Python array with 100 million zeros? | <p>What is an efficient way to initialize and access elements of a large array in Python?</p>
<p>I want to create an array in Python with 100 million entries, unsigned 4-byte integers, initialized to zero. I want fast array access, preferably with contiguous memory.</p>
<p>Strangely, <a href="http://en.wikipedia.org/wiki/NumPy" rel="noreferrer">NumPy</a> arrays seem to be performing very slow. Are there alternatives I can try?</p>
<p>There is the <a href="http://docs.python.org/library/array.html" rel="noreferrer">array.array</a> module, but I don't see a method to efficiently allocate a block of 100 million entries.</p>
<p>Responses to comments:</p>
<ul>
<li>I cannot use a sparse array. It will be too slow for this algorithm because the array becomes dense very quickly.</li>
<li>I know Python is interpreted, but surely there is a way to do fast array operations?</li>
<li>I did some profiling, and I get about 160K array accesses (looking up or updating an element by index) per second with NumPy. This seems very slow.</li>
</ul> | 2,214,771 | 10 | 5 | null | 2010-02-06 20:46:40.403 UTC | 9 | 2016-05-21 11:58:18.863 UTC | 2010-02-06 22:41:16.937 UTC | null | 63,550 | null | 82,733 | null | 1 | 29 | python|arrays|performance | 37,941 | <p>I have done some profiling, and the results are completely counterintuitive.
For simple array access operations, <strong>numpy and array.array are 10x slower than native Python arrays</strong>.</p>
<p>Note that for array access, I am doing operations of the form:</p>
<pre><code>a[i] += 1
</code></pre>
<p>Profiles:</p>
<ul>
<li><p>[0] * 20000000</p>
<ul>
<li>Access: 2.3M / sec</li>
<li>Initialization: 0.8s</li>
</ul></li>
<li><p>numpy.zeros(shape=(20000000,), dtype=numpy.int32)</p>
<ul>
<li>Access: 160K/sec</li>
<li>Initialization: 0.2s</li>
</ul></li>
<li><p>array.array('L', [0] * 20000000)</p>
<ul>
<li>Access: 175K/sec</li>
<li>Initialization: 2.0s</li>
</ul></li>
<li><p>array.array('L', (0 for i in range(20000000)))</p>
<ul>
<li>Access: 175K/sec, presumably, based upon the profile for the other array.array</li>
<li>Initialization: 6.7s</li>
</ul></li>
</ul> |
2,268,102 | How to view data stored in Core Data? | <p>I'm creating a Core Data model for my application. I would like to be able to look inside it to see what I have stored in there. </p>
<p>Is there an <strong>easier way than searching for the backing store</strong> (mine should be SQLite) and reading it from there? Doesn't seem very Apple-esque.</p> | 2,268,118 | 11 | 2 | null | 2010-02-15 18:32:17.533 UTC | 15 | 2020-10-27 21:21:59.913 UTC | 2020-10-27 21:21:59.913 UTC | null | 1,161,412 | null | 108,478 | null | 1 | 51 | iphone|core-data | 63,922 | <p>Once your app has run in the simulator and created the persistent store file, you can find the file in your app's Documents directory.</p>
<p>Your app data will be folder inside (~ is your home directory): </p>
<p><code>~/Library/Developer/CoreSimulator/<device></code></p>
<p>In versions prior to XCode 6, the path was:</p>
<p><code>~/Library/Application Support/iPhone Simulator/User/Applications/</code></p>
<p>I sort by "Date Modified" to find the app that I just built.</p>
<p>For viewing a SQLite file, check out <a href="http://menial.co.uk/software/base/" rel="noreferrer">Base</a> and/or <a href="https://github.com/ChristianKienle/Core-Data-Editor" rel="noreferrer">Core Data Editor</a>.</p> |
2,101,524 | Is it abusive to use IDisposable and "using" as a means for getting "scoped behavior" for exception safety? | <p>Something I often used back in C++ was letting a class <code>A</code> handle a state entry and exit condition for another class <code>B</code>, via the <code>A</code> constructor and destructor, to make sure that if something in that scope threw an exception, then B would have a known state when the scope was exited. This isn't pure RAII as far as the acronym goes, but it's an established pattern nevertheless.</p>
<p>In C#, I often want to do</p>
<pre><code>class FrobbleManager
{
...
private void FiddleTheFrobble()
{
this.Frobble.Unlock();
Foo(); // Can throw
this.Frobble.Fiddle(); // Can throw
Bar(); // Can throw
this.Frobble.Lock();
}
}
</code></pre>
<p>Which needs to be done like this</p>
<pre><code>private void FiddleTheFrobble()
{
this.Frobble.Unlock();
try
{
Foo(); // Can throw
this.Frobble.Fiddle(); // Can throw
Bar(); // Can throw
}
finally
{
this.Frobble.Lock();
}
}
</code></pre>
<p>if I want to guarantee the <code>Frobble</code> state when <code>FiddleTheFrobble</code> returns. The code would be nicer with</p>
<pre><code>private void FiddleTheFrobble()
{
using (var janitor = new FrobbleJanitor(this.Frobble))
{
Foo(); // Can throw
this.Frobble.Fiddle(); // Can throw
Bar(); // Can throw
}
}
</code></pre>
<p>where <code>FrobbleJanitor</code> looks <strong>roughly</strong> like</p>
<pre><code>class FrobbleJanitor : IDisposable
{
private Frobble frobble;
public FrobbleJanitor(Frobble frobble)
{
this.frobble = frobble;
this.frobble.Unlock();
}
public void Dispose()
{
this.frobble.Lock();
}
}
</code></pre>
<p>And that's how I want to do it. Now reality catches up, since what I <strong>want</strong> to use <strong>requires</strong> that the <code>FrobbleJanitor</code> is used <strong>with</strong> <code>using</code>. I could consider this a code review issue, but something is nagging me.</p>
<p><strong>Question:</strong> Would the above be considered as abusive use of <code>using</code> and <code>IDisposable</code>?</p> | 2,101,577 | 12 | 7 | null | 2010-01-20 13:13:47.95 UTC | 36 | 2020-10-27 05:19:20.22 UTC | null | null | null | null | 6,345 | null | 1 | 113 | c#|exception-handling|raii | 7,016 | <p>I don't think so, necessarily. IDisposable technically <i>is</i> meant to be used for things that have non-managed resources, but then the using directive is just a neat way of implementing a common pattern of <code>try .. finally { dispose }</code>.</p>
<p>A purist would argue 'yes - it's abusive', and in the purist sense it is; but most of us do not code from a purist perspective, but from a semi-artistic one. Using the 'using' construct in this way is quite artistic indeed, in my opinion.</p>
<p>You should probably stick another interface on top of IDisposable to push it a bit further away, explaining to other developers why that interface implies IDisposable.</p>
<p>There are lots of other alternatives to doing this but, ultimately, I can't think of any that will be as neat as this, so go for it!</p> |
2,258,932 | Embed a JRE in a Windows executable? | <p>Suppose I want to distribute a Java application.</p>
<p>Suppose I want to distribute it as a single executable. I could easily build a .jar with both the application and all its external dependencies in a single file (with some Ant hacking).</p>
<p>Now suppose I want to distribute it as an .exe file on Windows. That's easy enough, given the nice tools out there (such as Launch4j and the likes).</p>
<p>But suppose now that I also don't want to depend on the end user having the right JRE (or any JRE at all for that matter) installed. I want to distribute a JRE with my app, and my app should run on this JRE. It's easy enough to create a Windows installer executable, and embed a folder with all necessary JRE files in it. But then I'm distributing an <i>installer</i> and not a single-file app.</p>
<p>Is there a way to embed both the application, <i>and</i> a JRE, into an .exe file acting as the application launcher (and not as an installer)?</p> | 11,556,563 | 13 | 5 | null | 2010-02-13 20:28:59.603 UTC | 30 | 2020-11-11 22:56:08.717 UTC | 2010-04-26 11:03:56.683 UTC | null | 56,285 | null | 152,661 | null | 1 | 68 | java|windows|deployment|executable|software-distribution | 48,697 | <p>Try to use <a href="http://readytalk.github.io/avian/" rel="noreferrer">Avian</a> and <a href="http://proguard.sourceforge.net/" rel="noreferrer">ProGuard</a> toolkits.
Avian allows to embed lightweight virtual machine in you app. Linux, MacOS, Windows and iOS are supported. And ProGuard allows you to shrink large jar file to prepare to embed.</p> |
1,975,128 | Why isn't the size of an array parameter the same as within main? | <p>Why isn't the size of an array sent as a parameter the same as within main?</p>
<pre><code>#include <stdio.h>
void PrintSize(int p_someArray[10]);
int main () {
int myArray[10];
printf("%d\n", sizeof(myArray)); /* As expected, 40 */
PrintSize(myArray);/* Prints 4, not 40 */
}
void PrintSize(int p_someArray[10]){
printf("%d\n", sizeof(p_someArray));
}
</code></pre> | 1,975,133 | 13 | 0 | null | 2009-12-29 15:12:31.953 UTC | 42 | 2018-11-07 14:14:10.563 UTC | 2017-05-22 08:32:14.077 UTC | null | 584,518 | null | 163,407 | null | 1 | 113 | c|arrays|function|sizeof | 74,737 | <p>An array-type is <strong>implicitly</strong> converted into pointer type when you pass it in to a function.</p>
<p>So,</p>
<pre><code>void PrintSize(int p_someArray[10]) {
printf("%zu\n", sizeof(p_someArray));
}
</code></pre>
<p>and</p>
<pre><code>void PrintSize(int *p_someArray) {
printf("%zu\n", sizeof(p_someArray));
}
</code></pre>
<p>are equivalent. So what you get is the value of <strong><code>sizeof(int*)</code></strong></p> |
33,550,260 | Convert Julian Date to YYYY-MM-DD | <p>I have searched far and wide, but I can't seem find a way to convert julian to <code>yyyy-mm-dd</code>. </p>
<p>Here is the format of my julian:</p>
<p>The Julian format consists of the year, the first two digits, and the day within the year, the last three digits. </p>
<p>For example, <code>95076</code> is <code>March 17, 1995</code>. The <code>95</code> indicates the year and the
<code>076</code> indicates it is the 76th day of the year.</p>
<pre><code>15260
</code></pre>
<p>I have tried this but it isn't working:</p>
<pre><code>dateadd(d,(convert(int,LAST_CHANGED_DATE) % 1000)-1, convert(date,(convert(varchar,convert(int,LAST_CHANGED_DATE) /1000 + 1900) + '/1/1'))) as GrgDate
</code></pre> | 33,550,405 | 9 | 3 | null | 2015-11-05 16:48:41.533 UTC | 2 | 2021-08-31 12:13:09.537 UTC | 2020-09-25 14:32:27.073 UTC | null | 107,625 | null | 3,739,288 | null | 1 | 4 | sql|sql-server|julian-date | 41,864 | <p>You can select each part of the date using <code>datepart()</code></p>
<pre><code>SELECT DATEPART(yy, 95076), DATEPART(dy, 95076)
</code></pre>
<p>+++EDIT: I misunderstood something. Here's my correction: +++++</p>
<pre><code>SELECT DATEADD(day, CAST(RIGHT('95076',3) AS int) – 1, CONVERT(datetime,LEFT('95076',2) + '0101', 112))
</code></pre> |
17,863,490 | Animate CSS display | <p>Is there a way to animate the CSS display property in jQuery? I have the following:</p>
<pre><code>$(".maincontent").css("display","block");
</code></pre>
<p>and want it to do something like this:</p>
<pre><code>$(".maincontent").animate({"display": "block"}, 2500);
</code></pre> | 17,863,576 | 4 | 8 | null | 2013-07-25 16:18:22.24 UTC | 3 | 2017-07-28 06:41:25.753 UTC | 2013-07-25 16:28:03.673 UTC | null | 555,544 | null | 1,214,660 | null | 1 | 21 | jquery|css|jquery-animate | 93,252 | <p>Just use <code>.show()</code> passing it a parameter:</p>
<pre><code>$(".maincontent").show(2500);
</code></pre>
<p><strong>Edit (based on comments)</strong>:</p>
<p>The above code fades in the element over a 2.5 second span. If instead you want a 2.5 second delay and then want the element to display, use the following:</p>
<pre><code>$(".maincontent").delay(2500).fadeIn();
</code></pre>
<p>If, of course, you want a delay and a longer fade, just pass the number of milliseconds desired into each method.</p> |
17,713,037 | How do I open a project without a .sln file in Visual Studio? | <p>I was writing this program all in Vim and now I'm thinking of moving to Visual Studio, but since I didn't start in Visual Studio in the first place, there is no .sln file to open from. How should I open such a project in Visual Studio?</p> | 17,713,503 | 4 | 6 | null | 2013-07-18 01:34:59.283 UTC | 7 | 2019-07-20 21:34:25.18 UTC | 2019-07-20 21:31:28.91 UTC | null | 63,550 | null | 2,461,808 | null | 1 | 25 | visual-studio-2010 | 49,004 | <p>If a *.csproj file exists, you can build a new solution by Visual Studio at first. Next, you can open this *.csproj file in Visual Studio.</p> |
17,933,522 | Postgres on Rails FATAL: database does not exist | <p>I've reinstalled Postgres (9.2.4) and I'm having trouble getting it set back up with Rails 3.2.11. I did:</p>
<pre><code>brew install postgresql
initdb /usr/local/var/postgres
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
</code></pre>
<p>So now I have</p>
<pre><code>$ psql --version
psql (PostgreSQL) 9.2.4
$ which psql
/usr/local/bin/psql
</code></pre>
<p>My database.yml file looks like</p>
<pre><code>development:
adapter: postgresql
encoding: unicode
database: myapp_development
pool: 5
username: Tyler
password:
host: localhost
port: 5432
</code></pre>
<p>And when I run <code>rake db:create:all</code> then <code>rake db:migrate</code> I get the error:</p>
<pre><code>PG::Error: ERROR: relation "posts" does not exist
LINE 5: WHERE a.attrelid = '"posts"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"posts"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
</code></pre>
<p>I have tried to clear out everything related to past db, migrations, etc. </p>
<p>I've deleted the schema.rb, seed.rb, and all files in the migrations folder, and anything else I can think of. But the error referring to "posts" makes me think there is still some old reference to my prior database (which had a table called "posts").</p>
<p>Does anyone know how to troubleshoot this error, when trying to completely reinstall/refresh my database?</p> | 20,642,823 | 4 | 4 | null | 2013-07-29 20:25:00.723 UTC | 9 | 2019-02-28 05:20:28 UTC | null | null | null | null | 1,023,216 | null | 1 | 38 | ruby-on-rails|ruby-on-rails-3|postgresql|activerecord|database-migration | 44,148 | <p>I was having a similar problem.
I checked different websites and tried what they suggested but didn't work.
Then I tried what you suggested.
<strong><code>rake db:create:all</code></strong> and <strong><code>rake db:migrate</code></strong> it worked for me. Thank you!</p> |
17,878,751 | How to disable dates before today date in DatePickerDialog Android? | <p>I want to disable the dates before today date in the DatePickerDialog .I am new in android please suggest me how could i do this .Here is my code that i have written for DatePickerDialog</p>
<pre><code> final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel(val);
}
};
depart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
val=1;
}
});
returnDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
val=2;
}
});
private void updateLabel(int val) {
String myFormat = "dd/MM/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
Log.d("Date vlue ", "==="+sdf.format(myCalendar.getTime()));
if(val==1)
depart.setText(sdf.format(myCalendar.getTime()));
else
returnDate.setText(sdf.format(myCalendar.getTime()));
}
</code></pre>
<p>Please suggest me what have to do </p> | 17,879,678 | 5 | 1 | null | 2013-07-26 10:15:55.047 UTC | 7 | 2017-02-09 13:56:19.937 UTC | 2013-07-26 11:43:47.867 UTC | null | 2,618,323 | null | 2,618,323 | null | 1 | 11 | android|android-layout|android-datepicker | 53,971 | <p>See this example..!</p>
<pre><code>import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class MyAndroidAppActivity extends Activity {
private TextView tvDisplayDate;
private Button btnChangeDate;
private int myear;
private int mmonth;
private int mday;
static final int DATE_DIALOG_ID = 999;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setCurrentDateOnView();
addListenerOnButton();
}
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
final Calendar c = Calendar.getInstance();
myear = c.get(Calendar.YEAR);
mmonth = c.get(Calendar.MONTH);
mday = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(mmonth + 1).append("-").append(mday).append("-")
.append(myear).append(" "));
}
public void addListenerOnButton() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
DatePickerDialog _date = new DatePickerDialog(this, datePickerListener, myear,mmonth,
mday){
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year < myear)
view.updateDate(myear, mmonth, mday);
if (monthOfYear < mmonth && year == myear)
view.updateDate(myear, mmonth, mday);
if (dayOfMonth < mday && year == myear && monthOfYear == mmonth)
view.updateDate(myear, mmonth, mday);
}
};
return _date;
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
myear = selectedYear;
mmonth = selectedMonth;
mday = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(mmonth + 1)
.append("-").append(mday).append("-").append(myear)
.append(" "));
}
};
}
</code></pre>
<p>main.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnChangeDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Date" />
<TextView
android:id="@+id/lblDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current Date (M-D-YYYY): "
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</code></pre> |
52,149,051 | Implementing methods using default methods of interfaces - Contradictory? | <h2>Introduction</h2>
<p>I have read multiple posts about implementing interfaces and abstract classes here on SO. I have found one in particular that I would like to link here - <a href="https://stackoverflow.com/questions/19998454/interface-with-default-methods-vs-abstract-class-in-java-8">Link - Interface with default methods vs abstract class</a>, it covers the same question. As the accepted answer, it is recommended to use the default methods of interfaces when it is possible to do this. But the comment below this answer stating "this feature feels more like a hack to me" explains my problem.</p>
<p>Default methods have been introduced to make implementations of interfaces more flexible - when an interface is changed it is not necessarily required in the implementing classes to (re)write code. Therefore, using a default method of an interface just to realize a method in all implementing classes - quote: "feels more like a hack to me". </p>
<h2>Example for my examination:</h2>
<p>Classes overview:</p>
<ul>
<li>Item - Abstract Superclass of all Items</li>
<li>Water - Item which is consumable</li>
<li>Stone - Item which is not consumable</li>
<li>Consumable - Interface with some methods for consumable items (those methods have to be overriden by all implementing classes)</li>
</ul>
<p>Combining those:</p>
<p>Water is an Item and implements Consumable; Stone is also an Item and does not implement Consumable. </p>
<h2>My examination</h2>
<p>I would like to implement a method which all Items have to implement. Therefore, I declare the signature in the class Item.</p>
<pre><code>protected abstract boolean isConsumable();
//return true if class implements (or rather "is consumable") Consumable and false in case it does not
</code></pre>
<blockquote>
<p>Quick edit: I am aware that instanceof might solve this particular example - if possible think of a more complicated example that makes it necessary to implement the method in the first place. (Thanks to Sp00m and Eugene)</p>
</blockquote>
<p>Now I have several options:</p>
<blockquote>
<ol>
<li>Implement the method by hand in every single subclass of Item (this is definitely not possible when scaling the application).</li>
</ol>
</blockquote>
<p>As mentioned above when scaling the application this would be impractical or highly inefficient.</p>
<blockquote>
<ol start="2">
<li>Implementing the method inside of the interface as a default method so the Consumable classes already implement the method which is required by the superclass Item.</li>
</ol>
</blockquote>
<p>This is the solution recommended by the other post - I see the advantages of implementing it in this way: </p>
<blockquote>
<p>Quote - "The good thing about this new feature is that, where before you were forced to use an abstract class for the convenience methods, thus constraining the implementor to single inheritance, now you can have a really clean design with just the interface and a minimum of implementation effort forced on the programmer." <a href="https://stackoverflow.com/questions/19998454/interface-with-default-methods-vs-abstract-class-in-java-8">Link</a></p>
</blockquote>
<p>But in my opinion, it still seems contradictory to the original idea of default methods which I mentioned in my introduction. Furthermore, when scaling the application and introducing more methods that share the same implementation for all Consumables (as the example method <code>isConsumable()</code>), the interface would implement several default methods which contradicts the idea of an interface not implementing the actual method.</p>
<blockquote>
<ol start="3">
<li>Introducing sub-superclasses instead of an interface - for example the class Consumable as an abstract subclass of Item and superclass of Water.</li>
</ol>
</blockquote>
<p>It offers the opportunity to write the default case for a method in Item (example: <code>isConsumable() //return false</code>) and afterwards override this in the sub-superclass. The problem that occurs here: When scaling the application and introducing more sub-superclasses (as the Consumable class), the actual Items would start to extend more than one sub-superclass. It might not be a bad thing because it is necessary to do the same with interfaces too but it makes the inheritance tree complicated - Example: An item might now extend a subsuperclass ALayer2 which is a sub-superclass of ALayer1 which extends Item (layer0).</p>
<blockquote>
<ol start="4">
<li>Introducing another superclass (thus same layer as Item) - for example the class Consumable as an abstract class which will be another superclass of Water. That means that Water would have to extend Item & Consumable</li>
</ol>
</blockquote>
<p>This option offers flexibility. It is possible to create a whole new inheritance tree for the new superclass while still being able to see the actual inheritance of Item. But the downside I discovered is the implementation of this structure in the actual classes and using those later on - Example: How would I be able to say: A Consumable is an Item when Consumable would be able to have subclasses that are not meant for Items. The whole converting process will possibly cause a headache - more likely than the structure of Option 3.</p>
<h2>Question</h2>
<p>What would be the right option to implement this structure? </p>
<ul>
<li>Is it one of my listed options?</li>
<li>Is it a variation of those?</li>
<li>Or is it another option I have not thought about, yet?</li>
</ul>
<p>I have chosen a very simple example - please keep scalability for future implementations in mind when answering. Thanks for any help in advance.</p>
<h2>Edit#1</h2>
<p>Java does not allow multiple inheritance. This will effect the option 4.
Using multiple interfaces (because you can implement more than one) might be a workaround, unfortunately the default-method will be necessary again which is exactly the kind of implementation I have been trying to avoid originally. <a href="https://stackoverflow.com/questions/21824402/java-multiple-inheritance">Link - Multiple inheritance problem with possible solution</a></p> | 52,150,226 | 1 | 9 | null | 2018-09-03 11:38:01.607 UTC | 8 | 2018-09-22 05:16:10.727 UTC | 2018-09-22 05:16:10.727 UTC | user177800 | null | null | 10,280,191 | null | 1 | 12 | java|inheritance|interface|java-8|default-method | 806 | <p>I am missing option 5 (or maybe I didn't read correctly):
supply the method inside the <code>Item</code> itself.</p>
<p>Assuming that consumable items are identifiable via the <code>Consumable</code>-interface here are the reasons why I can not recommend most of the points you listed:
The first one (i.e. implement it in every subclass) is just too much for something as simple as <code>this instanceof Consumable</code>. The second might be ok, but wouldn't be my first choice. The third and the fourth I can't recommend at all. If I can just give one advice then it's probably to think about inheritance twice and to never ever use intermediate classes just because they made your life easier at one point in time. Probably this will hurt you in future when your class hierarchy becomes more complex (note: I do not say that you shouldn't use intermediate classes at all ;-)).</p>
<p>So what I would do for this specific case? I would rather implement something like the following in the abstract <code>Item</code> class:</p>
<pre><code>public final boolean isConsumable() {
return this instanceof Consumable;
}
</code></pre>
<p>But maybe I wouldn't even supply such a method as it is as good as writing <code>item instanceof Consumable</code> in the first place.</p>
<p>When would I use the default methods of interfaces instead? Maybe when the interface has rather a mixin character or when the implementation makes more sense for the interface then the abstract class, e.g. a specific function of the <code>Consumable</code> I would probably supply as default method there and not in any pseudo-implementing class just so that other classes can then again extend from it... I also really like the <a href="https://stackoverflow.com/a/17988444/6202869">following answer (or rather the quote) regarding mixin</a>.</p>
<p>Regarding your edit: <em>"Java does not allow multiple inheritance"</em> ... well, with the mixins something similar as multiple inheritance is possible. You can implement many interfaces and the interfaces themselves can extend also many others. With the default methods you have something reusable in place then :-)</p>
<p>So, why are <code>default</code> methods in interfaces ok to use (or not contradicting the interface definition itself):</p>
<ul>
<li>to supply a simple or naive implementation that already suffices the most use cases (where implementing classes may deliver specific, specialized and/or optimized functionality)</li>
<li>when it is clear from all the parameters and the context what the method has to do (and there is no suitable abstract class in place)</li>
<li>for template methods, i.e. when they issue calls to abstract methods to perform some work whose scope is broader. Typical example would be <code>Iterable.forEach</code>, which uses the abstract method <code>iterator()</code> of <code>Iterable</code> and applies the provided action to each one of its elements.</li>
</ul>
<p>Thanks <a href="https://stackoverflow.com/users/1876620/federico-peralta-schaffner">Federico Peralta Schaffner</a> for the suggestions.</p>
<p>Backward compatibility is here for completeness too, but listed seperately as are the functional interfaces:
The default implementation also helps to not break existing code, when adding new functions (either by just throwing an exception so that the code still keeps compiling or by supplying an appropriate implementation that works for all implementing classes).
For functional interfaces, which is rather a special interface case, the default methods are rather crucial. Functional interfaces can easily be enhanced with functionality, which itself doesn't need any specific implementation. Just consider <a href="https://docs.oracle.com/javase/10/docs/api/index.html?overview-summary.html" rel="nofollow noreferrer"><code>Predicate</code></a> as an example.. you supply <code>test</code>, but you get also <code>negate</code>, <code>or</code> and <code>and</code> in addition (supplied as default methods). Lots of functional interfaces supply additional contextual functions via default methods.</p> |
52,366,271 | How to change label text in xamarin | <p>I am relatively new to Xamarin forms. I have found out I am unable to change label text from the code behind. Normally I would do <code>myLabel.text = variable</code>. Does this work in Xamarin? If it does why does this code not change the text?</p>
<pre><code>Label_ControlSW.Text = controlSW_Out;
Label_BLESW.Text = bleSW_Out;
Label_Mode.Text = mode_Out;
</code></pre>
<p>Xaml file</p>
<pre><code><Label x:Name="Label_ControlSW" Grid.Row="1" Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center" FontSize="17" TextColor="White"/>
<Label x:Name="Label_BLESW" Grid.Row="2" Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center" FontSize="17" TextColor="#525252"/>
<Label x:Name="Label_Mode" Grid.Row="4" Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center" FontSize="17" TextColor="White"/>
</code></pre> | 52,372,364 | 5 | 9 | null | 2018-09-17 11:02:30.817 UTC | null | 2021-01-23 09:46:33.033 UTC | 2018-09-17 11:06:09.607 UTC | null | 8,977,696 | null | 9,159,074 | null | 1 | 13 | c#|xaml|xamarin|xamarin.forms | 38,225 | <blockquote>
<p>Does this work in Xamarin?</p>
</blockquote>
<p>Yes, it does.</p>
<blockquote>
<p>If it does why does this code not change the text?</p>
</blockquote>
<p>Because the <code>Label</code> component is not bounded to the variable, it just gets its value when you did <code>Label_ControlSW.Text = controlSW_Out;</code> and no furthermore.</p>
<p>To make it works you have basically two choices:</p>
<p><strong>1. Set the value to the label on every change;</strong></p>
<p>There's no magic here. Just set the values or variables like <a href="https://stackoverflow.com/a/52366708/8093394">Ali Heikal's answer</a> suggests, but you must do that every time manually.</p>
<p><strong>2. Bind the page (View) to an Observable object (Model)</strong>, then the view will listen to every change on your model and react to this (changing it's own <code>Text</code> value, for example).</p>
<p>I guess what you're intending to do is the second one. So you can create a public string property on your page's code-behind and bind the instance of your page to itself. Like this:</p>
<p><strong>XAML</strong></p>
<pre><code><Label Text="{Binding MyStringProperty}"
.../>
</code></pre>
<p><strong>Code behind</strong></p>
<pre><code>public partial class MyTestPage : ContentPage
{
private string myStringProperty;
public string MyStringProperty
{
get { return myStringProperty; }
set
{
myStringProperty = value;
OnPropertyChanged(nameof(MyStringProperty)); // Notify that there was a change on this property
}
}
public MyTestPage()
{
InitializeComponents();
BindingContext = this;
MyStringProperty = "New label text"; // It will be shown at your label
}
}
</code></pre>
<p>You should take a look at <a href="https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm" rel="noreferrer">official docs about data bindings and MVVM pattern on XF</a> and if you're starting with Xamarin.Forms, I highly recommend you to follow the <a href="https://docs.microsoft.com/en-us/xamarin/xamarin-forms/get-started/" rel="noreferrer">official getting started guide</a> that addresses each topic clear and deep enough to learn everything you need.</p>
<p>I hope it helps.</p> |
18,793,165 | Use cell's color as condition in if statement (function) | <p>I am trying to get a cell to perform a function based on the hilight color of a cell.</p>
<p>Here is the function I currently have:</p>
<pre><code>=IF(A6.Interior.ColorIndex=6,IF(ROUNDDOWN(IF(M6<3,0,IF(M6<5,1,IF(M6<10,3,(M6/5)+2))),0)=0,0,ROUNDDOWN(IF(M6<3,0,IF(M6<5,1,IF(M6<10,2,(M6/5)+2))),0)),IF(ROUNDDOWN(IF(M6<7,0,IF(M6<10,1,M6/5)),0)=0,0,ROUNDDOWN(IF(M6<7,0,IF(M6<10,1,M6/5)),0)))
</code></pre>
<p>Just so you don't have to read through all of that, here's a more simple example</p>
<pre><code>=IF(A6.Interior.ColorIndex=6,"True","False")
</code></pre>
<p>All that his is returning is #NAME? . Is there any way that I can do this as a function in a cell or is VBA absolutely required?</p>
<p>Thanks,</p>
<p>Jordan</p> | 18,793,568 | 5 | 2 | null | 2013-09-13 18:45:55.687 UTC | 0 | 2016-03-25 18:44:55.223 UTC | 2013-09-13 19:20:54.767 UTC | null | 620,444 | null | 2,547,035 | null | 1 | 11 | excel|function|vba | 278,445 | <p>You cannot use VBA (<code>Interior.ColorIndex</code>) in a formula which is why you receive the error.</p>
<p>It is not possible to do this without VBA.</p>
<pre><code>Function YellowIt(rng As Range) As Boolean
If rng.Interior.ColorIndex = 6 Then
YellowIt = True
Else
YellowIt = False
End If
End Function
</code></pre>
<p>However, I do not recommend this: it is not how user-defined VBA functions (UDFs) are intended to be used. They should reflect the behaviour of Excel functions, which cannot read the colour-formatting of a cell. (This function may not work in a future version of Excel.)</p>
<p>It is far better that you base a formula on the <strong>original condition</strong> (decision) that makes the cell yellow in the first place. Or, alternatively, run a Sub procedure to fill in the True or False values (although, of course, these values will no longer be linked to the original cell's formatting).</p> |
19,003,055 | Convert comma separated string into a HashSet | <p>So, how would you go about converting </p>
<pre><code>String csv = "11,00,33,66,44,33,22,00,11";
</code></pre>
<p>to a hashset in the quickest-most optimized way.</p>
<p>This is for a list of user-ids.</p>
<h2>Update</h2>
<p>I ran all the answers provided through a test program where each method was called 500,000 times for a bigger CSV string. This test was performed 5 times continously (in case program startup slowed initial method) and I got the following in milliseconds (ms):</p>
<pre><code>Method One Liner-> 6597
Method Split&Iterate-> 6090
Method Tokenizer-> 4306
------------------------------------------------
Method One Liner-> 6321
Method Split&Iterate-> 6012
Method Tokenizer-> 4227
------------------------------------------------
Method One Liner-> 6375
Method Split&Iterate-> 5986
Method Tokenizer-> 4340
------------------------------------------------
Method One Liner-> 6283
Method Split&Iterate-> 5974
Method Tokenizer-> 4302
------------------------------------------------
Method One Liner-> 6343
Method Split&Iterate-> 5920
Method Tokenizer-> 4227
------------------------------------------------
static void method0_oneLiner() {
for (int j = 0; j < TEST_TIMES; j++) {
Set<String> hashSet = new HashSet<String>(Arrays.asList(csv
.split(",")));
}
}
// ———————————————————————————————–
static void method1_splitAndIterate() {
for (int j = 0; j < TEST_TIMES; j++) {
String[] values = csv.split(",");
HashSet<String> hSet = new HashSet<String>(values.length);
for (int i = 0; i < values.length; i++)
hSet.add(values[i]);
}
}
static void method2_tokenizer() {
for (int j = 0; j < TEST_TIMES; j++) {
HashSet<String> hSet = new HashSet<String>();
StringTokenizer st = new StringTokenizer(csv, ",");
while (st.hasMoreTokens())
hSet.add(st.nextToken());
}
}
</code></pre> | 19,003,565 | 10 | 3 | null | 2013-09-25 10:57:57.49 UTC | 3 | 2021-08-16 16:36:19.44 UTC | 2013-09-25 11:45:06.33 UTC | null | 1,688,441 | null | 1,688,441 | null | 1 | 25 | java|csv|hashset | 60,323 | <p>The 6 other answers are great, in that they're the most straight-forward way of converting.</p>
<p>However, since <code>String.split()</code> involves regexps, and <code>Arrays.asList</code> is doing redundant conversion, you might want to do it this way, which may improve performance somewhat. </p>
<p><strong>Edit</strong> if you have a general idea on how many items you will have, use the <code>HashSet</code> constructor parameter to avoid unnecessary resizing/hashing :</p>
<pre><code>HashSet<String> myHashSet = new HashSet(500000); // Or a more realistic size
StringTokenizer st = new StringTokenizer(csv, ",");
while(st.hasMoreTokens())
myHashSet.add(st.nextToken());
</code></pre> |
16,391,528 | Query mysql and export data as CSV in PHP | <p>I have myssql db with different tables. The data between the tables are linked and I retrieve and display them by using the userid. I used the reference from <a href="https://stackoverflow.com/questions/14618304/php-mysqli-displaying-all-tables-in-a-database">PHP MYSQLi Displaying all tables in a database</a></p>
<p>But how do I export this information as a csv file? I have tried instead of echo changed it to a string and print the string to a csv file but it is not working.</p>
<p>I have also tried the example from:
<a href="http://sudobash.net/php-export-mysql-query-to-csv-file/" rel="nofollow noreferrer">http://sudobash.net/php-export-mysql-query-to-csv-file/</a></p>
<p>But I can see the data but on top there is also junk (like <code>"<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>"</code><br>
etc) inside the csv file.</p>
<p>Is there another way to do this?</p> | 16,392,050 | 5 | 0 | null | 2013-05-06 03:19:31.663 UTC | 6 | 2017-10-04 06:42:49.443 UTC | 2017-05-23 10:30:10.067 UTC | null | -1 | null | 1,826,383 | null | 1 | 8 | php|mysql|csv | 65,385 | <p>If you want to write each MySQL row to a CSV file, you could use the built in PHP5 function <code>fputcsv</code></p>
<pre><code>$result = mysqli_query($con, 'SELECT * FROM table');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$fp = fopen('file.csv', 'w');
foreach ($row as $val) {
fputcsv($fp, $val);
}
fclose($fp);
</code></pre>
<p>Which should return a comma separated string for each row written to <code>file.csv</code>: </p>
<pre><code>row1 val1, row1 val2
row2 val1, row2 val2
etc..
</code></pre>
<p>Also be sure to check permissions for the directory you are writing to.</p> |
16,320,397 | detect user input language javascript | <p>Is there a way to detect in which language user is typing in input/textarea field?
I have seen such on facebook, If user starts typing in RTL language then cursor move on right side of input box.
I tried to find but coould not see any idea, Thanks for any help</p> | 16,322,907 | 2 | 7 | null | 2013-05-01 14:48:31.41 UTC | 8 | 2019-04-26 01:54:48.653 UTC | null | null | null | null | 969,068 | null | 1 | 10 | javascript|html | 12,001 | <p><a href="https://stackoverflow.com/a/14824756/104380">https://stackoverflow.com/a/14824756/104380</a></p>
<p>I had come up with a new, much shorter solution:</p>
<pre><code>function isRTL(s){
var ltrChars = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF'+'\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF',
rtlChars = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC',
rtlDirCheck = new RegExp('^[^'+ltrChars+']*['+rtlChars+']');
return rtlDirCheck.test(s);
};
</code></pre>
<p><a href="http://jsfiddle.net/MeeW7/1/" rel="noreferrer"><strong>playground page</strong></a></p> |
326,509 | java background/daemon/service cross platform best practices | <p>I am looking for the best way to make my desktop java program run in the background (<strong>daemon/service</strong>?) across most platforms (Windows, Mac OS, Linux [Ubuntu in particular]).</p>
<p>By "best way" I am hoping to find a way that will:</p>
<ol>
<li>require a <strong>minimum</strong> amount of platform-specific code. </li>
<li>not require the user to do anything a general computer user couldn't/wouldn't do </li>
<li>not be a resource hog.</li>
</ol>
<p>I understand that my requirements may be unrealistic but I am hoping there is some sort of "best practice" for this type of situation.</p>
<p>How to go forward?</p> | 326,528 | 7 | 2 | null | 2008-11-28 19:38:36.04 UTC | 13 | 2017-04-26 16:39:05.77 UTC | 2017-04-26 16:39:05.77 UTC | null | 1,033,581 | Jack | 24,998 | null | 1 | 27 | java|cross-platform|desktop-application|daemon | 15,402 | <p>You can use the <a href="http://java.sun.com/javase/6/docs/api/java/awt/SystemTray.html" rel="nofollow noreferrer">SystemTray</a> classes and install your app as any other in the default platform.</p>
<p>For windows it could be an scheduled task that run at startup.
For Linux and OSX I don't know (besides crontab wich is somehow too technical) but I'm pretty sure they both have a way to do the same thing easily.</p>
<p>Unfortunately (as of today) Apple hasn't finished the 1.6 port. </p>
<p>It won't be a real demon, but an app like Google Desktop. </p>
<p>I've heard Quartz is a good option. But I've never used it.</p> |
91,576 | crti.o file missing | <p>I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find <code>crti.o</code>. This is not one of my object files, it seems to be related to libc but I can't understand why it would need this <code>crti.o</code>, wouldn't it use a library file, e.g. <code>libc.a</code>?</p>
<p>I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it? </p>
<p><code>crti.o</code> is on one of the 'libraries' search path, but should it look for <code>.o</code> file on the library path? </p>
<p>Is the search path the same for <code>gcc</code> and <code>ld</code>?</p> | 91,595 | 8 | 1 | null | 2008-09-18 10:50:42.483 UTC | 12 | 2020-04-10 22:44:26.357 UTC | 2017-02-20 07:32:57.667 UTC | Richard | 1,797,006 | Richard | 76,121 | null | 1 | 28 | makefile|linker | 69,134 | <p><code>crti.o</code> is the bootstrap library, generally quite small. It's usually statically linked into your binary. It should be found in <code>/usr/lib</code>.</p>
<p>If you're running a binary distribution they tend to put all the developer stuff into -dev packages (e.g. libc6-dev) as it's not needed to run compiled programs, just to build them.</p>
<p>You're not cross-compiling are you? </p>
<p>If you're cross-compiling it's usually a problem with gcc's search path not matching where your crti.o is. It should have been built when the toolchain was. The first thing to check is <code>gcc -print-search-dirs</code> and see if crti.o is in any of those paths.</p>
<p>The linking is actually done by ld but it has its paths passed down to it by gcc. Probably the quickest way to find out what's going on is compile a helloworld.c program and strace it to see what is getting passed to ld and see what's going on.</p>
<pre><code>strace -v -o log -f -e trace=open,fork,execve gcc hello.c -o test
</code></pre>
<p>Open the log file and search for crti.o, as you can see my non-cross compiler:</p>
<pre><code>10616 execve("/usr/bin/ld", ["/usr/bin/ld", "--eh-frame-hdr", "-m", "elf_x86_64", "--hash-style=both", "-dynamic-linker", "/lib64/ld-linux-x86-64.so.2", "-o"
, "test", "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "-L/usr/lib/gcc/x86_64-linux-g
nu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/lib/../lib", "-L/usr/lib/../lib", "-L/usr/lib/gcc/x86_64-linux-gnu
/"..., "/tmp/cc4rFJWD.o", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "-lc", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "/usr/lib/gcc/x86_
64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."...], "COLLECT_GCC=gcc", "COLLECT_GCC_OPTIONS=\'-o\' \'test\' "..., "COMPILER_PATH=/usr/lib/gcc/x86_6"..., "LIBRARY_PATH=/usr/lib/gcc/x86_64"..., "CO
LLECT_NO_DEMANGLE="]) = 0
10616 open("/etc/ld.so.cache", O_RDONLY) = 3
10616 open("/usr/lib/libbfd-2.18.0.20080103.so", O_RDONLY) = 3
10616 open("/lib/libc.so.6", O_RDONLY) = 3
10616 open("test", O_RDWR|O_CREAT|O_TRUNC, 0666) = 3
10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crt1.o", O_RDONLY) = 4
10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crti.o", O_RDONLY) = 5
10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/crtbegin.o", O_RDONLY) = 6
10616 open("/tmp/cc4rFJWD.o", O_RDONLY) = 7
</code></pre>
<p>If you see a bunch of attempts to <code>open(...crti.o) = -1 ENOENT</code>, <code>ld</code> is getting confused and you want to see where the path it's opening came from...</p> |
908,188 | Is there any way of detecting if a drive is a SSD? | <p>I'm getting ready to release a tool that is only effective with regular hard drives, not SSD (solid state drive). In fact, it shouldn't be used with SSD's because it will result in a lot of read/writes with no real effectiveness.</p>
<p>Anyone knows of a way of detecting if a given drive is solid-state?</p> | 908,252 | 9 | 2 | null | 2009-05-25 21:59:06.773 UTC | 11 | 2019-03-09 21:27:33.45 UTC | 2014-07-24 16:56:56.407 UTC | null | 2,961,540 | null | 36,544 | null | 1 | 36 | disk|hard-drive|solid-state-drive | 39,971 | <p>Detecting SSDs is not as impossible as dseifert makes out. There is already some progress in linux's libata (<a href="http://linux.derkeiler.com/Mailing-Lists/Kernel/2009-04/msg03625.html" rel="nofollow noreferrer">http://linux.derkeiler.com/Mailing-Lists/Kernel/2009-04/msg03625.html</a>), though it doesn't seem user-ready yet.</p>
<p>And I definitely understand why this needs to be done. It's basically the difference between a linked list and an array. Defragmentation and such is usually counter-productive on a SSD.</p> |
1,269,994 | nanoseconds to milliseconds - fast division by 1000000 | <p>I'm wanting to convert the output from gethrtime to milliseconds.</p>
<p>The obvious way to do this is to divide by 1000000.
However, I'm doing this quite often and wonder if it could become a bottleneck.</p>
<p>Is there an optimized divide operation when dealing with numbers like 1000000?</p>
<p>Note: Any code must be portable. I'm using gcc and this is generally on Sparc hardware</p>
<p>Some quick testing using the code below... hope that is right.</p>
<pre><code>#include <sys/time.h>
#include <iostream>
using namespace std;
const double NANOSECONDS_TO_MILLISECONDS = 1.0 / 1000000.0;
int main()
{
hrtime_t start;
hrtime_t tmp;
hrtime_t fin;
start = gethrtime();
tmp = (hrtime_t)(start * NANOSECONDS_TO_MILLISECONDS);
fin = gethrtime();
cout << "Method 1"
cout << "Original val: " << start << endl;
cout << "Computed: " << tmp << endl;
cout << "Time:" << fin - start << endl;
start = gethrtime();
tmp = (start / 1000000);
fin = gethrtime();
cout "Method 2"
cout << "Original val: " << start << endl;
cout << "Computed: " << tmp << endl;
cout << "Time:" << fin - start << endl;
return 0;
}
</code></pre>
<p>Example outputs:</p>
<pre><code>Original val: 3048161553965997
Computed: 3048161553
Time:82082
Original val: 3048161556359586
Computed: 3048161556
Time:31230
Original val: 3048239663018915
Computed: 3048239663
Time:79381
Original val: 3048239665393873
Computed: 3048239665
Time:31321
Original val: 3048249874282285
Computed: 3048249874
Time:81812
Original val: 3048249876664084
Computed: 3048249876
Time:34830
</code></pre>
<p>If this is correct, then the multiple by reciprocal is actually slower in this case. It's probably due to using floating point math instead of fixed point math. I will just stick to integer division then which still takes hardly any time at all.</p> | 1,270,011 | 10 | 7 | null | 2009-08-13 04:13:07.383 UTC | 7 | 2009-08-13 10:19:26.01 UTC | 2009-08-13 05:32:38.223 UTC | null | 15,168 | null | 134,702 | null | 1 | 13 | c++|gcc|solaris|sparc | 41,198 | <p>Division is <em>not</em> an expensive operation. I doubt very much if a divide-by-1000000 operation will be anywhere near the main bottleneck in your application. Floating-point processors will be way faster than any sort of "tricks" you can come up with than just doing the single operation.</p> |
971,039 | JavaScript string and number conversion | <p>How can I do the following in JavaScript?</p>
<ol>
<li><p>Concatenate "1", "2", "3" into "123"</p></li>
<li><p>Convert "123" into 123</p></li>
<li><p>Add 123 + 100 = 223</p></li>
<li><p>Covert 223 into "223"</p></li>
</ol> | 971,112 | 10 | 6 | null | 2009-06-09 16:08:07.93 UTC | 25 | 2019-03-11 08:30:07.79 UTC | 2014-07-05 22:34:29.493 UTC | null | 1,849,664 | JMSA | 159,072 | null | 1 | 92 | javascript|string|numbers | 216,510 | <p>You want to become familiar with <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt" rel="noreferrer"><code>parseInt()</code></a> and <a href="https://developer.mozilla.org/en-US/docs/toString" rel="noreferrer"><code>toString()</code></a>.</p>
<p>And useful in your toolkit will be to look at a variable to find out what type it is—<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof" rel="noreferrer"><code>typeof</code></a>:</p>
<pre><code><script type="text/javascript">
/**
* print out the value and the type of the variable passed in
*/
function printWithType(val) {
document.write('<pre>');
document.write(val);
document.write(' ');
document.writeln(typeof val);
document.write('</pre>');
}
var a = "1", b = "2", c = "3", result;
// Step (1) Concatenate "1", "2", "3" into "123"
// - concatenation operator is just "+", as long
// as all the items are strings, this works
result = a + b + c;
printWithType(result); //123 string
// - If they were not strings you could do
result = a.toString() + b.toString() + c.toString();
printWithType(result); // 123 string
// Step (2) Convert "123" into 123
result = parseInt(result,10);
printWithType(result); // 123 number
// Step (3) Add 123 + 100 = 223
result = result + 100;
printWithType(result); // 223 number
// Step (4) Convert 223 into "223"
result = result.toString(); //
printWithType(result); // 223 string
// If you concatenate a number with a
// blank string, you get a string
result = result + "";
printWithType(result); //223 string
</script>
</code></pre> |
776,286 | Given a string, generate a regex that can parse *similar* strings | <p>For example, given the string "2009/11/12" I want to get the regex ("\d{2}/d{2}/d{4}"), so I'll be able to match "2001/01/02" too.</p>
<p>Is there something that does that? Something similar? Any idea' as to how to do it?</p> | 776,323 | 11 | 2 | null | 2009-04-22 09:00:13.677 UTC | 11 | 2015-01-20 11:36:39.87 UTC | 2009-04-22 09:14:03.41 UTC | null | 28,169 | null | 4,038 | null | 1 | 27 | java|regex | 69,599 | <p>There is <a href="http://www.txt2re.com/" rel="noreferrer">text2re</a>, a free web-based "regex by example" generator.</p>
<p>I don't think this is available in source code, though. I dare to say there is no automatic regex generator that gets it right without user intervention, since this would require the machine knowing what you want.</p>
<hr>
<p>Note that text2re uses a template-based, modularized and very generalized approach to regular expression generation. The expressions it generates work, but they are much more complex than the equivalent hand-crafted expression. It is not a good tool to <em>learn</em> regular expressions because it does a pretty lousy job at setting examples.</p>
<p>For instance, the string <code>"2009/11/12"</code> would be recognized as a <code>yyyymmdd</code> pattern, which is helpful. The tool transforms it into <em>this</em> 125 character monster:</p>
<pre><code>((?:(?:[1]{1}\d{1}\d{1}\d{1})|(?:[2]{1}\d{3}))[-:\/.](?:[0]?[1-9]|[1][012])[-:\/.](?:(?:[0-2]?\d{1})|(?:[3][01]{1})))(?![\d])
</code></pre>
<p>The hand-made equivalent would take up merely two fifths of that (50 characters):</p>
<pre><code>([12]\d{3})[-:/.](0?\d|1[0-2])[-:/.]([0-2]?\d|3[01])\b
</code></pre> |
338,075 | CAST and IsNumeric | <p>Why would the following query return "Error converting data type varchar to bigint"? Doesn't IsNumeric make the CAST safe? I've tried every numeric datatype in the cast and get the same "Error converting..." error. I don't believe the size of the resulting number is a problem because overflow is a different error.</p>
<p>The interesting thing is, in management studio, the results actually show up in the results pane for a split second before the error comes back.</p>
<pre><code>SELECT CAST(myVarcharColumn AS bigint)
FROM myTable
WHERE IsNumeric(myVarcharColumn) = 1 AND myVarcharColumn IS NOT NULL
GROUP BY myVarcharColumn
</code></pre>
<p>Any thoughts?</p> | 338,122 | 11 | 1 | null | 2008-12-03 17:51:26.737 UTC | 9 | 2017-01-05 18:29:12.843 UTC | 2012-02-15 00:33:38.103 UTC | null | 61,305 | MarkB | 22,355 | null | 1 | 29 | sql-server|sql-server-2005 | 86,716 | <p>IsNumeric returns 1 if the varchar value can be converted to ANY number type. This includes int, bigint, decimal, numeric, real & float.</p>
<p>Scientific notation could be causing you a problem. For example:</p>
<pre><code>Declare @Temp Table(Data VarChar(20))
Insert Into @Temp Values(NULL)
Insert Into @Temp Values('1')
Insert Into @Temp Values('1e4')
Insert Into @Temp Values('Not a number')
Select Cast(Data as bigint)
From @Temp
Where IsNumeric(Data) = 1 And Data Is Not NULL
</code></pre>
<p>There is a trick you can use with IsNumeric so that it returns 0 for numbers with scientific notation. You can apply a similar trick to prevent decimal values.</p>
<p>IsNumeric(YourColumn + 'e0')</p>
<p>IsNumeric(YourColumn + '.0e0')</p>
<p>Try it out.</p>
<pre><code>SELECT CAST(myVarcharColumn AS bigint)
FROM myTable
WHERE IsNumeric(myVarcharColumn + '.0e0') = 1 AND myVarcharColumn IS NOT NULL
GROUP BY myVarcharColumn
</code></pre> |
1,253,303 | What's the best way to set cursor/caret position? | <p>If I'm inserting content into a textarea that TinyMCE has co-opted, what's the best way to set the position of the cursor/caret?</p>
<p>I'm using <code>tinyMCE.execCommand("mceInsertRawHTML", false, content);</code> to insert the content, and I'd like set the cursor position to the end of the content.</p>
<p>Both <code>document.selection</code> and <code>myField.selectionStart</code> won't work for this, and I feel as though this is going to be supported by TinyMCE (through something I can't find on their forum) or it's going to be a really ugly hack.</p>
<p><strong>Later:</strong> It gets better; I just figured out that, when you load TinyMCE in WordPress, it loads the entire editor in an embedded iframe.</p>
<p><strong>Later (2):</strong> I can use <code>document.getElementById('content_ifr').contentDocument.getSelection();</code> to get the selection as a string, but not a Selection Object that I can use <code>getRangeAt(0)</code> on. Making progress little by little.</p> | 1,291,352 | 12 | 1 | null | 2009-08-10 06:04:30.51 UTC | 21 | 2020-04-15 09:07:09.91 UTC | 2009-08-12 15:03:32.89 UTC | null | 59,827 | null | 59,827 | null | 1 | 33 | javascript|wordpress|iframe|tinymce|getselection | 54,508 | <p>After spending over 15 hours on this issue (dedication, I know), I found a partial solution that works in FF and Safari, but not in IE. For the moment, this is good enough for me although I might continue working on it in the future.</p>
<p>The solution: When inserting HTML at the current caret position, the best function to use is:</p>
<p><code>tinyMCE.activeEditor.selection.setContent(htmlcontent);</code></p>
<p>In Firefox and Safari, this function will insert the content at the current caret position within the iframe that WordPress uses as a TinyMCE editor. The issue with IE 7 and 8 is that the function seems to add the content to the top of the page, not the iframe (i.e. it completely misses the text editor). To address this issue, I added a conditional statement <a href="http://www.quirksmode.org/js/detect.html" rel="noreferrer">based on this code</a> that will use this function instead for IE:</p>
<p><code>tinyMCE.activeEditor.execCommand("mceInsertRawHTML", false, htmlcontent);</code></p>
<p>The issue for this second function, however, is that the caret position is set to the beginning of the post area after it has been called (with no hope of recalling it based on the browser range, etc.). Somewhere near the end I discovered that this function works to restore the caret position at the end of the inserted content with the first function:</p>
<p><code>tinyMCE.activeEditor.focus();</code></p>
<p>In addition, it restores the caret position to the end of the inserted content without having to calculate the length of the inserted text. The downside is that it only works with the first insertion function which seems to cause problems in IE 7 and IE 8 (which might be more of a WordPress fault than TinyMCE).</p>
<p>A wordy answer, I know. Feel free to ask questions for clarification.</p> |
652,276 | Is it possible to create anonymous objects in Python? | <p>I'm debugging some Python that takes, as input, a list of objects, each with some attributes.</p>
<p>I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number.</p>
<p>Is there a more concise way than this?</p>
<pre><code>x1.foo = 1
x2.foo = 2
x3.foo = 3
x4.foo = 4
myfunc([x1, x2, x3, x4])
</code></pre>
<p>Ideally, I'd just like to be able to say something like:</p>
<pre><code>myfunc([<foo=1>, <foo=2>, <foo=3>, <foo=4>])
</code></pre>
<p>(Obviously, that is made-up syntax. But is there something similar that really works?)</p>
<p>Note: This will never be checked in. It's just some throwaway debug code. So don't worry about readability or maintainability.</p> | 652,417 | 13 | 0 | null | 2009-03-16 21:50:45.693 UTC | 9 | 2021-01-30 14:04:33.897 UTC | 2013-07-17 12:57:13.06 UTC | null | 698,585 | Mike | 91,385 | null | 1 | 77 | python|anonymous-types | 61,317 | <p>I like Tetha's solution, but it's unnecessarily complex.</p>
<p>Here's something simpler:</p>
<pre><code>>>> class MicroMock(object):
... def __init__(self, **kwargs):
... self.__dict__.update(kwargs)
...
>>> def print_foo(x):
... print x.foo
...
>>> print_foo(MicroMock(foo=3))
3
</code></pre> |
1,175,244 | SQL Server error on update command - "A severe error occurred on the current command" | <p>Running the following query in SQL Server Management Studio gives the error below.</p>
<pre><code>update table_name set is_active = 0 where id = 3
</code></pre>
<blockquote>
<p>A severe error occurred on the current command. The results, if any, should be discarded.</p>
</blockquote>
<ul>
<li>The logs have been truncated</li>
<li>there is an update trigger but this isnt the issue</li>
<li>the transaction count is zero (@@trancount)</li>
</ul>
<p>I have tried the same update statement on a couple of other tables in the database and they work fine.</p>
<pre><code>DBCC CHECKTABLE('table_name');
</code></pre>
<p>gives</p>
<pre><code>DBCC results for 'table_name'.
There are 13 rows in 1 pages for object "table_name".
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
</code></pre> | 3,514,273 | 14 | 1 | null | 2009-07-24 00:34:13.66 UTC | 7 | 2022-06-19 07:14:42.237 UTC | 2012-09-14 15:12:12.43 UTC | null | 23,199 | null | 6,268 | null | 1 | 50 | sql-server|sql-server-2005|tsql | 123,813 | <p>I just had the same error, and it was down to a corrupted index.
Re-indexing the table fixed the problem.</p> |
1,168,131 | How to measure software development performance? | <p>I am looking after some ways to measure the performance of a software development team. Is it a good idea to use the build tool? We use Hudson as an automatic build tool. I wonder if I can take the information from Hudson reports and obtain from it the progress of each of the programmers.</p> | 1,168,153 | 15 | 3 | null | 2009-07-22 20:45:36.123 UTC | 19 | 2016-03-15 02:33:39.817 UTC | 2014-06-10 16:45:35.63 UTC | null | 1,473,751 | null | 137,570 | null | 1 | 30 | project-management|metrics | 58,544 | <p>Do NOT measure the performance of each individual programmer simply using the build tool. You can measure the team as a whole, sure, or you can certainly measure the progress of each programmer, but you cannot measure their <em>performance</em> with such a tool. Some modules are more complicated than others, some programmers are tasked with other projects, etc. It's not a recommended way of doing this, and it will encourage programmers to write sloppy code so that it looks like they did the most work.</p> |
299,704 | What are good ways to make my Python code run first time? | <p>I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?</p> | 299,737 | 16 | 3 | null | 2008-11-18 18:39:05.35 UTC | 47 | 2016-03-31 18:22:12.003 UTC | 2012-09-05 09:18:03.47 UTC | null | 9,827,379 | Amara | 37,804 | null | 1 | 53 | python|debugging | 28,160 | <p>If you're having problems with syntax, you could try an editor with syntax highlighting. Until you get the feel for a language, simple errors won't just pop out at you.</p>
<p>The simplest form of debugging is just to insert some print statements. A more advanced (and extensible) way to do this would be to use the <a href="http://docs.python.org/library/logging.html#module-logging" rel="noreferrer">logging</a> module from the std lib.</p>
<p>The interactive interpreter is a wonderful tool for working with python code, and <a href="http://ipython.org" rel="noreferrer">IPython</a> is a great improvement over the built-in REPL (Read Eval Print Loop).</p>
<p>If you actually want to step through your code, the python debugger is called <a href="http://docs.python.org/library/pdb.html#module-pdb" rel="noreferrer">pdb</a>, which can be called from the command line, or embedded in your code.</p>
<p>If you're used to a fully integrated IDE, I would recommend using Eclipse with pydev, and PyCharm has a great commercial offering, with autocomplete, quick access to docs, and numerous shortcuts, among many other interesting features.</p> |
179,904 | What is MATLAB good for? Why is it so used by universities? When is it better than Python? | <p>I've been recently asked to learn some MATLAB basics for a class.</p>
<p>What does make it so cool for researchers and people that works in university?
I saw it's cool to work with matrices and plotting things... (things that can be done easily in Python using some libraries).</p>
<p>Writing a function or parsing a file is just painful. I'm still at the start, what am I missing?</p>
<p>In the "real" world, what should I think to use it for? When should it can do better than Python? For better I mean: easy way to write something performing.</p>
<hr>
<p><strong>UPDATE 1:</strong> One of the things I'd like to know the most is "Am I missing something?" :D</p>
<p><strong>UPDATE 2:</strong> Thank you for your answers. My question is not about buy or not to buy MATLAB. The university has the possibility to give me a copy of an old version of MATLAB (MATLAB 5 I guess) for free, without breaking the license. I'm interested in its capabilities and if it deserves a deeper study (I won't need anything more than <em>basic</em> MATLAB in oder to pass the exam :P ) it will really be better than Python for a specific kind of task in the real world.</p> | 180,341 | 21 | 2 | null | 2008-10-07 19:11:46.427 UTC | 58 | 2012-10-22 15:13:33.8 UTC | 2009-10-13 18:24:39.613 UTC | raven | 63,550 | Andrea Ambu | 21,384 | null | 1 | 53 | python|matlab | 201,969 | <p>Adam is only partially right. Many, if not most, mathematicians will never touch it. If there is a computer tool used at all, it's going to be something like <a href="http://en.wikipedia.org/wiki/Mathematica" rel="noreferrer">Mathematica</a> or <a href="http://en.wikipedia.org/wiki/Maple_(software)" rel="noreferrer">Maple</a>. Engineering departments, on the other hand, often rely on it and there are definitely useful things for some applied mathematicians. It's also used heavily in industry in some areas.</p>
<p>Something you have to realize about MATLAB is that it started off as a wrapper on <a href="http://en.wikipedia.org/wiki/Fortran" rel="noreferrer">Fortran</a> libraries for linear algebra. For a long time, it had an attitude that "all the world is an array of doubles (floats)". As a language, it has grown very organically, and there are some flaws that are very much baked in, if you look at it just as a programming language.</p>
<p>However, if you look at it as an environment for doing certain types of research in, it has some real strengths. It's about as good as it gets for doing floating point linear algebra. The notation is simple and powerful, the implementation fast and trusted. It is very good at generating plots and other interactive tasks. There are a large number of `toolboxes' with good code for particular tasks, that are affordable. There is a large community of users that share numerical codes (Python + <a href="http://en.wikipedia.org/wiki/NumPy" rel="noreferrer">NumPy</a> has nothing in the same league, at least yet)</p>
<p>Python, warts and all, is a much better programming language (as are many others). However, it's a decade or so behind in terms of the tools.</p>
<p>The key point is that the majority of people who use MATLAB are not programmers really, and don't want to be. </p>
<p>It's a lousy choice for a general programming language; it's quirky, slow for many tasks (you need to vectorize things to get efficient codes), and not easy to integrate with the outside world. On the other hand, for the things it is good at, it is very very good. Very few things compare. There's a company with reasonable support and who knows how many man-years put into it. This can matter in industry.</p>
<p>Strictly looking at your Python vs. MATLAB comparison, they are mostly different tools for different jobs. In the areas where they do overlap a bit, it's hard to say what the better route to go is (depends a lot on what you're trying to do). But mostly Python isn't all that good at MATLAB's core strengths, and vice versa.</p> |
1,265,309 | Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!) | <p>I have a Java EE project which build fine with Ant, deploys perfectly to JBoss, and runs without any trouble. This project includes a few <strong>custom</strong> tag libraries (which is not <a href="https://stackoverflow.com/tags/jstl/info">JSTL</a>!), which are also working without any difficulties.</p>
<p>The problem is with the Eclipse IDE (Ganymede): in every single JSP file which uses our custom tags, the JSP parser flags the taglib include line with with this error:</p>
<p><code>Cannot find the tag library descriptor for (example).tld</code></p>
<p>This also causes every use of the tab library to be flagged as an error, and since the IDE doesn't have their definition, it can't check tag parameters, etc.</p>
<p>Our perfectly-working JSP files are a sea of red errors, and my eyes are beginning to burn.</p>
<p>How can I simply tell Eclipse, "The tag library descriptor you are looking for is "src/web/WEB-INF/(example)-taglib/(example).tld"?</p>
<p>I've already asked this question on the Eclipse support forums, with no helpful results.</p> | 1,587,526 | 22 | 1 | null | 2009-08-12 10:05:59.347 UTC | 22 | 2018-02-09 17:21:36.45 UTC | 2018-02-09 17:21:36.45 UTC | null | 2,074,605 | null | 149,522 | null | 1 | 61 | java|eclipse|jsp|taglib|custom-tags | 196,898 | <p>It turns out that the cause was that this project wasn't being considered by Eclipse to actually be a Java EE project at all; it was an old project from 3.1, and the Eclipse 3.5 we are using now requires several "natures" to be set in the project configuration file.</p>
<pre><code><natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>InCode.inCodeNature</nature>
<nature>org.eclipse.dltk.javascript.core.nature</nature>
<nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
</natures>
</code></pre>
<p>I was able to find the cause by creating a new "Dynamic Web Project" which properly read its JSP files, and diffing against the config of the older project.</p>
<p>The only way I could find to add these was by editing the .project file, but after re-opening the project, everything magically worked. The settings referenced by pribeiro, above, weren't necessary since the project already conformed to the default settings.</p>
<p>Both pribeiro and nitind's answers gave me ideas to jumpstart my search, thanks.</p>
<p>Is there a way of editing these "natures" from within the UI?</p> |
1,144,703 | What should the penalty/response for missing a deadline be? | <p>Being relatively new to the software industry I have come across a question of deadline enforcement: </p>
<p>Back in the idyllic age of academia, the deadline was the end of the semester and the penalty was a well defined 'F' (or local equivalent). Out here in the real world we need to make code our current and future peers can work with, I face the situation where deadline comes, deadline goes, and the project is still not finished. </p>
<p>Now what? On one extreme we could fire everyone involved, on the other we could richly reward everyone involved.</p>
<ol>
<li><p>What actions have you seen applied as 'penalty' for missed deadline, and which of these eventually resulted in more-good-code? </p></li>
<li><p>What project-management responses caused the project to fail outright, </p></li>
<li><p>What responses restored working order and resulted in code that could be maintained afterward?</p></li>
<li><p>What responses resulted in more-bad-code?</p></li>
</ol> | 1,144,723 | 37 | 19 | 2009-07-18 02:37:45.133 UTC | 2009-07-17 17:36:07.223 UTC | 26 | 2010-11-12 02:57:11.063 UTC | 2009-07-21 21:49:02.11 UTC | null | 90,801 | null | 90,801 | null | 1 | 34 | project-management|development-process | 19,513 | <p>Deadlines are part of a fundamentally wrong idea about how to do software development. People new to, or outside of, the software development industry do not understand this:</p>
<p><strong>Software is done when it is done, no sooner and no later.</strong></p>
<p>If a developer has a task and a week to do it, and it looks like it will take more than a week, nothing can be done to change that. No matter how much harder the developer works, no matter how many people are added to the task, it will still take as long as it takes (in fact adding people usually makes it take longer).</p>
<p>Instead, read up on the agile development process. Software should be developed iteratively, and each iteration should be based on the results of the previous iteration, <em>not</em> on external requirements imposed.</p>
<p>Edit based on the extensive comments below:</p>
<p>I would never argue that developers cannot be held to some kind of delivery expectation. My point is in response to the <em>specific</em> hypothesis which the asker posed - that the nature of software development in business is somehow analogous to schoolwork, or any other kind of work for that matter. I contend that it absolutely is not. "Deadline" implies much more than a simple delivery date. It is a fixed point by which a fixed amount of work must be completed. Software simply does not work that way. I wrote a few more paragraphs explaining why, but honestly if you don't already believe that, nothing I say is going to convince you.</p>
<p>If you are working on a software project and it is clear you will not be able to reach your deadline, what can you do to rectify that? The answer is well-known by now: practically nothing. You can't add more people. You can't "work faster". It's just not going to get done on time. You tell the stakeholders, everyone adjusts, and keep working (or not). What, then, did the original date mean?</p>
<p>Anyone who claims software development is analogous to bridge-building or homework or that impending deadlines can still be met if the developers would just get their shit together and work their asses off, are deeply confused about their own profession.</p> |
6,402,311 | Python conditional assignment operator | <p>Does a Python equivalent to the Ruby <code>||=</code> operator ("set the variable if the variable is not set") exist?</p>
<p>Example in Ruby :</p>
<pre><code> variable_not_set ||= 'bla bla'
variable_not_set == 'bla bla'
variable_set = 'pi pi'
variable_set ||= 'bla bla'
variable_set == 'pi pi'
</code></pre> | 6,402,327 | 10 | 3 | null | 2011-06-19 12:21:11.607 UTC | 8 | 2021-12-21 09:59:14.59 UTC | 2014-12-18 16:58:04.77 UTC | null | 128,421 | null | 735,779 | null | 1 | 76 | python|variables|conditional | 145,057 | <p>No, the replacement is:</p>
<pre><code>try:
v
except NameError:
v = 'bla bla'
</code></pre>
<p>However, wanting to use this construct is a sign of overly complicated code flow. Usually, you'd do the following:</p>
<pre><code>try:
v = complicated()
except ComplicatedError: # complicated failed
v = 'fallback value'
</code></pre>
<p>and never be unsure whether <code>v</code> is set or not. If it's one of many options that can either be set or not, use a dictionary and its <a href="http://docs.python.org/library/stdtypes.html#dict.get" rel="noreferrer"><code>get</code></a> method which allows a default value.</p> |
6,925,156 | How to avoid a Toast if there's one Toast already being shown | <p>I have several <code>SeekBar</code> and <code>onSeekBarProgressStop()</code>, I want to show a <code>Toast</code> message.</p>
<p>But if on <code>SeekBar</code> I perform the action rapidly then UI thread somehow blocks and <code>Toast</code> message waits till UI thread is free.</p>
<p>Now my concern is to avoid the new <code>Toast</code> message if the <code>Toast</code> message is already displaying. Or is their any condition by which we check that UI thread is currently free then I'll show the <code>Toast</code> message.</p>
<p>I tried it in both way, by using <code>runOnUIThread()</code> and also creating new <code>Handler</code>.</p> | 11,441,738 | 11 | 0 | null | 2011-08-03 10:37:41.23 UTC | 10 | 2022-06-17 14:56:53.84 UTC | 2014-07-23 07:03:47.853 UTC | null | 1,276,636 | null | 628,291 | null | 1 | 45 | android|android-toast | 36,967 | <p>I've tried a variety of things to do this. At first I tried using the <code>cancel()</code>, which had no effect for me (see also <a href="https://stackoverflow.com/a/7235755/1276636">this answer</a>).</p>
<p>With <code>setDuration(n)</code> I wasn't coming to anywhere either. It turned out by logging <code>getDuration()</code> that it carries a value of 0 (if <code>makeText()</code>'s parameter was <code>Toast.LENGTH_SHORT</code>) or 1 (if <code>makeText()</code>'s parameter was <code>Toast.LENGTH_LONG</code>).</p>
<p>Finally I tried to check if the toast's view <code>isShown()</code>. Of course it isn't if no toast is shown, but even more, it returns a fatal error in this case. So I needed to try and catch the error.
Now, <code>isShown()</code> returns true if a toast is displayed.
Utilizing <code>isShown()</code> I came up with the method:</p>
<pre><code> /**
* <strong>public void showAToast (String st)</strong></br>
* this little method displays a toast on the screen.</br>
* it checks if a toast is currently visible</br>
* if so </br>
* ... it "sets" the new text</br>
* else</br>
* ... it "makes" the new text</br>
* and "shows" either or
* @param st the string to be toasted
*/
public void showAToast (String st){ //"Toast toast" is declared in the class
try{ toast.getView().isShown(); // true if visible
toast.setText(st);
} catch (Exception e) { // invisible if exception
toast = Toast.makeText(theContext, st, toastDuration);
}
toast.show(); //finally display it
}
</code></pre> |
6,518,802 | Check if element is a div | <p>How do I check if <code>$(this)</code> is a <code>div</code>, <code>ul</code> or <code>blockquote</code>?</p>
<p>For example:</p>
<pre><code>if ($(this) is a div) {
alert('its a div!');
} else {
alert('its not a div! some other stuff');
}
</code></pre> | 6,518,828 | 11 | 0 | null | 2011-06-29 09:57:37.153 UTC | 9 | 2020-07-31 12:59:36.867 UTC | 2019-07-17 15:38:13.27 UTC | null | 385,273 | null | 398,431 | null | 1 | 88 | javascript|jquery|html|css | 106,293 | <p>Something like this:</p>
<pre class="lang-js prettyprint-override"><code>if(this.tagName == 'DIV') {
alert("It's a div!");
} else {
alert("It's not a div! [some other stuff]");
}
</code></pre> |
45,487,647 | Input number in Angular Material Design? | <p>There is the standard input as:</p>
<pre><code> <input type="number" placeholder="Hours">
</code></pre>
<p>Is there something in Angular Material Design?</p>
<p><a href="https://i.stack.imgur.com/0iOva.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0iOva.png" alt="enter image description here"></a></p>
<p>I use Angular latest version</p>
<p>I tried this, but it is just simple input:</p>
<pre><code><md-input-container>
<input mdInput type="number" placeholder="Favorite food" value="Sushi">
</md-input-container>
</code></pre>
<p>It should be <code>< md-input-container input="number"></code>? <code>ot input type="number"></code> ?</p> | 45,487,908 | 3 | 3 | null | 2017-08-03 14:48:36.29 UTC | 4 | 2021-03-14 06:19:22.73 UTC | 2017-08-03 15:00:37.257 UTC | null | 7,647,670 | null | 7,647,670 | null | 1 | 22 | angular|material-design|angular-material2 | 80,889 | <p>In short, yes. You want < md-input-container > wrapper which supports the following input types</p>
<ol>
<li>date</li>
<li>datetime-local</li>
<li>email</li>
<li>month</li>
<li>number</li>
<li>password</li>
<li>search</li>
<li>tel</li>
<li>text</li>
<li>time</li>
<li>url</li>
<li>week</li>
</ol>
<p>For example</p>
<pre><code><md-input-container>
<input
mdInput
type="number"
id="myNumber"
/>
</md-input-container>
</code></pre>
<p>Checkout <a href="https://material.angular.io/components/input/overview" rel="noreferrer">https://material.angular.io/components/input/overview</a></p> |
45,293,436 | How to specify python version used to create Virtual Environment? | <p>My Python virtual environments use <code>python3.6</code> when I create them using <code>virtualenv</code></p>
<blockquote>
<p><code>~ $ virtualenv my_env</code></p>
</blockquote>
<p>but I need to use <code>python3.5</code> as 3.6 is <a href="https://github.com/menpo/conda-opencv3/issues/21" rel="noreferrer">not currently supported by <code>Opencv3</code>.</a></p>
<p>I've tried using the <code>--python=<py_version></code> flag when creating a virtual environment but this doesn't work.</p>
<h1>How do I specify the python (3.x) version to install using <code>virtualenv</code> for Mac and/or Linux?</h1> | 45,293,556 | 7 | 5 | null | 2017-07-25 03:31:12.047 UTC | 17 | 2022-08-19 09:10:45.13 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 4,486,146 | null | 1 | 65 | python|python-3.x|virtualenv | 105,861 | <p>Assuming that you have installed <code>python3</code> or any desired version of Python (2.6, 2.7, 3.5, 3.6), Now while creating the virtual environment directly pass the python executable path. Hence here are few valid example</p>
<pre><code>$ virtualenv new_p2_env # Creates a new default python environment (usually python 2)
$ virtualenv -p python3 new_p3_env # Creates a new default python3 (python3 must be a valid command i.e found in the PATH)
</code></pre>
<p>And last</p>
<pre><code># Directly point to any version of python binary, this can be even another virtualenv's bin/python.
$ virtualenv -p /path/to/any/bin/python new_env
</code></pre> |
15,778,645 | Passing ArrayList as value only and not reference | <p>Simply put, I have a method with an ArrayList parameter. In the method I modify the contents of the ArrayList for purposes relevant only to what is returned by the method. Therefore, I do not want the ArrayList which is being passed as the parameter to be affected at all (i.e. not passed as a reference).</p>
<p>Everything I have tried has failed to achieve the desired effect. What do I need to do so that I can make use of a copy of the ArrayList within the method only, but not have it change the actual variable?</p> | 15,778,672 | 8 | 4 | null | 2013-04-03 04:03:58.303 UTC | 5 | 2016-09-07 04:36:56.863 UTC | 2015-11-21 04:09:25.983 UTC | null | 1,562,138 | null | 1,562,138 | null | 1 | 41 | java|reference|arraylist|pass-by-reference | 63,305 | <p>Even if you had a way to pass the array list as a copy and not by reference it would have been only a shallow copy.</p>
<p>I would do something like:</p>
<pre><code>void foo(final ArrayList list) {
ArrayList listCopy = new ArrayList(list);
// Rest of the code
}
</code></pre>
<p>And just work on the copied list.</p> |
15,540,321 | Pre- or post-process roxygen snippets | <p>Is there some mechanism by which I can transform the comments that roxygen sees, preferably before it does the roxygen->rd conversion?</p>
<p>For example, suppose I have:</p>
<pre><code>#' My function. Does stuff with numbers.
#'
#' This takes an input `x` and does something with it.
#' @param x a number.
myFunction <- function (x) {
}
</code></pre>
<p>Now, suppose I want to do some conversion of the comment before roxygen parses it, for example replacing all instances of things in backticks with <code>\code{}</code>. Ie:</p>
<pre><code>preprocess <- function (txt) {
gsub('`([^ ]+)`', '\\\\code{\\1}', txt)
}
# cat(preprocess('Takes an input `x` and does something with it'.))
# Takes an input \code{x} and does something with it.
</code></pre>
<p>Can I feed <code>preprocess</code> into roxygen somehow so that it will run it on the doclets before (or after would work in this case) roxygen does its document generation?</p>
<p>I don't want to do a permanent find-replace in my <code>.r</code> files. As you might guess from my example, I'm aiming towards some rudimentary markdown support in my roxygen comments, and hence wish to keep my <code>.r</code> files as-is to preserve readability (and insert the <code>\code{..}</code> stuff programmatically).</p>
<p>Should I just write my own version of <code>roxygenise</code> that runs <code>preprocess</code> on all detected roxygen-style comments in my files, saves them temporarily somewhere, and then runs the <em>actual</em> <code>roxygenise</code> on those?</p> | 32,729,071 | 1 | 3 | null | 2013-03-21 05:42:14.93 UTC | 2 | 2015-09-23 00:16:26.35 UTC | 2015-07-10 01:27:06.123 UTC | null | 2,562,463 | null | 913,184 | null | 1 | 68 | r|roxygen2 | 629 | <p>Revisiting this a couple of years later, it looks like Roxygen has a function <code>register.preref.parsers</code> that one can use to inject their own parsers into roxygen.
One such use of this is the promising <a href="https://github.com/gaborcsardi/maxygen" rel="nofollow">maxygen package</a> (markdown + roxygen = maxygen), which a very neat implementation of markdown processing of roxygen comments (albeit only to the CommonMark spec), and you can see how it is used in that package's <a href="https://github.com/gaborcsardi/maxygen/blob/master/R/package.R" rel="nofollow">macument function</a>. I eagerly await "pandoc + roxygen = pandoxygen"... :)</p> |
50,559,636 | Is there a way to write a large number in C++ source code with spaces to make it more readable? | <p>Imagine I have the code:</p>
<pre><code>vector<int> temp = vector<int>(1 000 000 000);
</code></pre>
<p>The above will not compile as the compiler will complain about the spaces. Is it possible to indicate to C++ to ommit those spaces when compiling, or otherwise make the number easier to read?</p> | 50,559,694 | 6 | 8 | null | 2018-05-28 05:28:24.55 UTC | 3 | 2022-01-04 15:27:45.48 UTC | 2018-05-28 16:47:47.763 UTC | null | 6,202,327 | null | 6,202,327 | null | 1 | 52 | c++|syntax|numbers | 12,607 | <p>Try digit separator:</p>
<pre><code>int i = 1'000'000'000;
</code></pre>
<p>This feature is introduced <a href="http://en.cppreference.com/w/cpp/language/integer_literal" rel="noreferrer">since C++14</a>. It uses single quote (<code>'</code>) as digit separator.</p>
<hr>
<p>Also see:</p>
<ul>
<li><a href="https://stackoverflow.com/q/27767781/2486888">Why was the space character not chosen for C++14 digit separators?</a></li>
<li><a href="http://www.stroustrup.com/whitespace98.pdf" rel="noreferrer">Generalizing Overloading for C++2000</a> (April's joke by the father of C++ himself)</li>
</ul> |
56,512,769 | Unable to find docker image locally | <p>I was following <a href="https://medium.com/@shakyShane/lets-talk-about-docker-artifacts-27454560384f" rel="noreferrer">this post</a> - the reference code is on <a href="https://github.com/shakyShane/cra-docker" rel="noreferrer">GitHub</a>. I have cloned the repository on my local.</p>
<p>The project has got a react app inside it. I'm trying to run it on my local following <strong>step 7</strong> on the <a href="https://medium.com/@shakyShane/lets-talk-about-docker-artifacts-27454560384f" rel="noreferrer">same post</a>:</p>
<pre><code>docker run -p 8080:80 shakyshane/cra-docker
</code></pre>
<p>This returns:</p>
<pre><code>Unable to find image 'shakyshane/cra-docker:latest' locally
docker: Error response from daemon: pull access denied for shakyshane/cra-docker, repository does not exist or may require 'docker login'.
See 'docker run --help'.
</code></pre>
<p>I tried login to docker again but looks like since it belongs to <a href="https://medium.com/@shakyShane" rel="noreferrer">@shakyShane</a> I cannot access it.</p>
<p>I idiotically tried <code>npm start</code> too but it's not a simple react app running on node - it's in the container and containers are not controlled by <code>npm</code></p>
<p>Looks like <code>docker pull shakyshane/cra-docker:latest</code> throws this:</p>
<pre><code>Error response from daemon: pull access denied for shakyshane/cra-docker, repository does not exist or may require 'docker login'
</code></pre>
<p>So the question is how do I run this docker image on my local mac machine?</p> | 56,512,954 | 13 | 7 | null | 2019-06-09 07:31:26.81 UTC | 12 | 2022-08-12 17:48:59.17 UTC | 2019-06-09 12:54:47.09 UTC | null | 2,404,470 | null | 2,404,470 | null | 1 | 80 | macos|docker|docker-run | 213,153 | <blockquote>
<p>Well this is anti-logical but still sharing so future people like me don't get stuck</p>
</blockquote>
<p>So the problem was that I was trying to run a docker image which <a href="https://stackoverflow.com/questions/56512769/how-to-run-somone-elses-docker-image-on-local-machine#comment99612033_56512769">doesn't exist</a>.</p>
<p>I needed to build the image:</p>
<pre><code>docker build . -t xameeramir/cra-docker
</code></pre>
<p>And then run it:</p>
<pre><code>docker run -p 8080:80 xameeramir/cra-docker
</code></pre> |
22,465,332 | Setting PATH environment variable in OSX permanently | <p>I have read several answers on how to set environment variables on OSX permanently.</p>
<p>First, I tried this, <a href="https://stackoverflow.com/questions/14637979/how-to-permanently-set-path-on-linux">How to permanently set $PATH on Linux/Unix</a> but I had an error message saying <code>no such file and directory</code>, so I thought I could try <code>~/.bash_profile</code> instead of <code>~/.profile</code> but it did not work.</p>
<p>Second, I found this solution <a href="https://stackoverflow.com/questions/460835/how-to-set-the-path-as-used-by-applications-in-os-x">How to set the $PATH as used by applications in os x</a> , which advises to make changes in</p>
<blockquote>
<p>~/.MacOSX/environment.plist</p>
</blockquote>
<p>but again I had <code>no such file and directory</code> error.</p>
<p>I need a way to set these variables such that it won't require setting them again and again each time I open a new terminal session.</p> | 22,465,399 | 11 | 2 | null | 2014-03-17 21:02:04.18 UTC | 78 | 2022-08-18 22:06:55.177 UTC | 2022-07-03 16:57:04.627 UTC | null | 527,702 | null | 3,399,468 | null | 1 | 203 | macos|bash|unix|path|environment-variables | 334,267 | <p>You have to add it to <code>/etc/paths</code>.</p>
<p>Reference (which works for me) : <a href="http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.Uydjga1dXDg">Here</a></p> |
13,325,008 | Typewriter Effect with jQuery | <p><em>Edit: I didn't really ask all the questions I should have asked in my original question. To help make this easier for people looking for a similar answer, this is what the question ended up being:</em></p>
<p><strong>How do I make a typewriter effect with a blinking cursor that pauses at the end of the statement, erases the statement, and writes a new one?</strong></p>
<p>Check out Yoshi's answer below. It does exactly that...</p> | 13,325,547 | 3 | 1 | null | 2012-11-10 18:45:13.26 UTC | 9 | 2021-05-15 12:25:39.23 UTC | 2012-11-11 10:50:13.25 UTC | null | 1,253,498 | null | 1,253,498 | null | 1 | 15 | jquery | 24,384 | <p>demo: <a href="http://jsbin.com/araget/5/" rel="nofollow noreferrer">http://jsbin.com/araget/5/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*** Plugin ***/
(function($) {
// writes the string
//
// @param jQuery $target
// @param String str
// @param Numeric cursor
// @param Numeric delay
// @param Function cb
// @return void
function typeString($target, str, cursor, delay, cb) {
$target.html(function(_, html) {
return html + str[cursor];
});
if (cursor < str.length - 1) {
setTimeout(function() {
typeString($target, str, cursor + 1, delay, cb);
}, delay);
} else {
cb();
}
}
// clears the string
//
// @param jQuery $target
// @param Numeric delay
// @param Function cb
// @return void
function deleteString($target, delay, cb) {
var length;
$target.html(function(_, html) {
length = html.length;
return html.substr(0, length - 1);
});
if (length > 1) {
setTimeout(function() {
deleteString($target, delay, cb);
}, delay);
} else {
cb();
}
}
// jQuery hook
$.fn.extend({
teletype: function(opts) {
var settings = $.extend({}, $.teletype.defaults, opts);
return $(this).each(function() {
(function loop($tar, idx) {
// type
typeString($tar, settings.text[idx], 0, settings.delay, function() {
// delete
setTimeout(function() {
deleteString($tar, settings.delay, function() {
loop($tar, (idx + 1) % settings.text.length);
});
}, settings.pause);
});
}($(this), 0));
});
}
});
// plugin defaults
$.extend({
teletype: {
defaults: {
delay: 100,
pause: 5000,
text: []
}
}
});
}(jQuery));
/*** init ***/
$('#target').teletype({
text: [
'Lorem ipsum dolor sit amet, consetetur sadipscing elitr,',
'sed diam nonumy eirmod tempor invidunt ut labore et dolore',
'magna aliquyam erat, sed diam voluptua. At vero eos et',
'accusam et justo duo dolores et ea rebum. Stet clita kasd',
'gubergren, no sea takimata sanctus est Lorem ipsum dolor sit',
'amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr,',
'sed diam nonumy eirmod tempor invidunt ut labore et dolore',
'magna aliquyam erat, sed diam voluptua. At vero eos et accusam',
'et justo duo dolores et ea rebum. Stet clita kasd gubergren,',
'no sea takimata sanctus est Lorem ipsum dolor sit amet.'
]
});
$('#cursor').teletype({
text: ['_', ' '],
delay: 0,
pause: 500
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="target"></span>
<span id="cursor"></span>
<!-- used for the blinking cursor effect --></code></pre>
</div>
</div>
</p>
<p><strong>plugin</strong>:</p>
<pre><code>(function ($) {
// writes the string
//
// @param jQuery $target
// @param String str
// @param Numeric cursor
// @param Numeric delay
// @param Function cb
// @return void
function typeString($target, str, cursor, delay, cb) {
$target.html(function (_, html) {
return html + str[cursor];
});
if (cursor < str.length - 1) {
setTimeout(function () {
typeString($target, str, cursor + 1, delay, cb);
}, delay);
}
else {
cb();
}
}
// clears the string
//
// @param jQuery $target
// @param Numeric delay
// @param Function cb
// @return void
function deleteString($target, delay, cb) {
var length;
$target.html(function (_, html) {
length = html.length;
return html.substr(0, length - 1);
});
if (length > 1) {
setTimeout(function () {
deleteString($target, delay, cb);
}, delay);
}
else {
cb();
}
}
// jQuery hook
$.fn.extend({
teletype: function (opts) {
var settings = $.extend({}, $.teletype.defaults, opts);
return $(this).each(function () {
(function loop($tar, idx) {
// type
typeString($tar, settings.text[idx], 0, settings.delay, function () {
// delete
setTimeout(function () {
deleteString($tar, settings.delay, function () {
loop($tar, (idx + 1) % settings.text.length);
});
}, settings.pause);
});
}($(this), 0));
});
}
});
// plugin defaults
$.extend({
teletype: {
defaults: {
delay: 100,
pause: 5000,
text: []
}
}
});
}(jQuery));
</code></pre>
<p><strong>html</strong>:</p>
<pre><code><span id="target"></span>
<span id="cursor"></span> <!-- used for the blinking cursor effect -->
</code></pre>
<p><strong>init</strong>:</p>
<pre><code>$('#target').teletype({
text: [
'Lorem ipsum dolor sit amet, consetetur sadipscing elitr,',
'sed diam nonumy eirmod tempor invidunt ut labore et dolore',
'magna aliquyam erat, sed diam voluptua. At vero eos et',
'accusam et justo duo dolores et ea rebum. Stet clita kasd',
'gubergren, no sea takimata sanctus est Lorem ipsum dolor sit',
'amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr,',
'sed diam nonumy eirmod tempor invidunt ut labore et dolore',
'magna aliquyam erat, sed diam voluptua. At vero eos et accusam',
'et justo duo dolores et ea rebum. Stet clita kasd gubergren,',
'no sea takimata sanctus est Lorem ipsum dolor sit amet.'
]
});
$('#cursor').teletype({
text: ['_', ' '],
delay: 0,
pause: 500
});
</code></pre> |
13,785,210 | Why in Java (high + low) / 2 is wrong but (high + low) >>> 1 is not? | <p>I understand the <code>>>></code> fixes the overflow: when adding two big positive longs you may end up with a negative number. Can someone explain how this bitwise shift magically fixes the overflow problem? And how it is different from <code>>></code> ?</p>
<hr />
<p>My suspicion: I think it has to do with the fact that Java uses two's-complement so the overflow is the right number if we had the extra space but because we don't it becomes negative. So when you shift and pad with zero it magically gets fixed due to the two's-complement. But I can be wrong and someone with a bitwise brain has to confirm. :)</p> | 13,785,317 | 3 | 3 | null | 2012-12-09 06:19:12.1 UTC | 14 | 2021-06-27 15:04:59.83 UTC | 2021-06-27 15:04:59.83 UTC | null | 622,266 | null | 967,300 | null | 1 | 30 | java|bit-manipulation|bitwise-operators|binary-search | 5,341 | <p>In short, <code>(high + low) >>> 1</code> is a trick that uses the unused sign-bit to perform a correct average of non-negative numbers.</p>
<hr>
<p>Under the assumption that <code>high</code> and <code>low</code> are both non-negative, we know for sure that the upper-most bit (the sign-bit) is zero.</p>
<p>So both <code>high</code> and <code>low</code> are in fact 31-bit integers.</p>
<pre><code>high = 0100 0000 0000 0000 0000 0000 0000 0000 = 1073741824
low = 0100 0000 0000 0000 0000 0000 0000 0000 = 1073741824
</code></pre>
<p>When you add them together they may "spill" over into the top-bit.</p>
<pre><code>high + low = 1000 0000 0000 0000 0000 0000 0000 0000
= 2147483648 as unsigned 32-bit integer
= -2147483648 as signed 32-bit integer
(high + low) / 2 = 1100 0000 0000 0000 0000 0000 0000 0000 = -1073741824
(high + low) >>> 1 = 0100 0000 0000 0000 0000 0000 0000 0000 = 1073741824
</code></pre>
<ul>
<li><p>As a signed 32-bit integer, it is overflow and flips negative. Therefore <code>(high + low) / 2</code> is wrong because <code>high + low</code> could be negative.</p></li>
<li><p>As unsigned 32-bit integers, the sum is correct. All that's needed is to divide it by 2.</p></li>
</ul>
<p>Of course Java doesn't support unsigned integers, so the best thing we have to divide by 2 (as an unsigned integer) is the logical right-shift <code>>>></code>.</p>
<p>In languages with unsigned integers (such as C and C++), it gets trickier since your input can be full 32-bit integers. One solution is: <code>low + ((high - low) / 2)</code></p>
<hr>
<p>Finally to enumerate the differences between <code>>>></code>, <code>>></code>, and <code>/</code>:</p>
<ul>
<li><code>>>></code> is logical right-shift. It fills the upper bits with zero.</li>
<li><code>>></code> is arithmetic right-shift. It fills the upper its with copies of the original top bit.</li>
<li><code>/</code> is division.</li>
</ul>
<p>Mathematically:</p>
<ul>
<li><code>x >>> 1</code> treats <code>x</code> as an unsigned integer and divides it by two. It rounds down.</li>
<li><code>x >> 1</code> treats <code>x</code> as a signed integer and divides it by two. It rounds towards negative infinity.</li>
<li><code>x / 2</code> treats <code>x</code> as a signed integer and divides it by two. It rounds towards zero.</li>
</ul> |
13,428,042 | AngularJS - Access to child scope | <p>If I have the following controllers:</p>
<pre><code>function parent($scope, service) {
$scope.a = 'foo';
$scope.save = function() {
service.save({
a: $scope.a,
b: $scope.b
});
}
}
function child($scope) {
$scope.b = 'bar';
}
</code></pre>
<p>What's the proper way to let <code>parent</code> read <code>b</code> out of <code>child</code>? If it's necessary to define <code>b</code> in <code>parent</code>, wouldn't that make it semantically incorrect assuming that <code>b</code> is a property that describes something related to <code>child</code> and not <code>parent</code>?</p>
<p><strong>Update:</strong> Thinking further about it, if more than one child had <code>b</code> it would create a conflict for <code>parent</code> on which <code>b</code> to retrieve. My question remains, what's the proper way to access <code>b</code> from <code>parent</code>?</p> | 13,428,220 | 6 | 1 | null | 2012-11-17 05:38:46.157 UTC | 45 | 2019-02-12 15:01:19.85 UTC | 2012-11-17 05:55:46.957 UTC | null | 938,207 | null | 938,207 | null | 1 | 113 | angularjs | 162,418 | <p>Scopes in AngularJS use prototypal inheritance, when looking up a property in a child scope the interpreter will look up the prototype chain starting from the child and continue to the parents until it finds the property, not the other way around. </p>
<p>Check Vojta's comments on the issue <a href="https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J">https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J</a></p>
<p>In a nutshell: You cannot access child scopes from a parent scope. </p>
<p>Your solutions:</p>
<ol>
<li>Define properties in parents and access them from children (read the link above)</li>
<li>Use a service to share state</li>
<li>Pass data through events. <code>$emit</code> sends events upwards to parents until the root scope and <code>$broadcast</code> dispatches events downwards. This might help you to keep things semantically correct.</li>
</ol> |
16,424,502 | jQuery '#' + data("target") pattern | <p>I've seen this a bunch: </p>
<pre><code><a href="#" id="trigger" data-target="content">Click me</a>
<div id="content">And something will happen here</div>
</code></pre>
<p>With JS like this:</p>
<pre><code>$("#trigger").click(function(){
$("#" + $(this).data("target")).hide();
})
</code></pre>
<p>It looks a little weird to me to be doing this string concatenation to create selectors which are then used to get the target element. Is there a better pattern in Javascript (with jQuery available) for setting up handlers on one element which need to know about another target element?</p> | 16,424,567 | 6 | 2 | null | 2013-05-07 16:52:46.957 UTC | 8 | 2017-08-17 13:19:25.523 UTC | null | null | null | null | 625,365 | null | 1 | 14 | javascript|jquery | 81,872 | <p>Why you do string concatenation just store the id with <code>#</code></p>
<pre><code><a href="#" id="trigger" data-target="#content">Click me</a>
$("#trigger").click(function(){
$($(this).data("target")).hide();
})
</code></pre>
<p>Similarly you can store any selectors as is in <code>data-target</code> say for ex:- <code>.tab1</code> etc so that you do not have to perform string concatenation again inside the click or any event.</p> |
16,559,642 | Android: How to draw free on top of anything (any activity) | <p>How do you draw a view on top of all other activities regardless of what they are showing and without using transparent activities or consuming its touch events.</p>
<p>Its like to display a custom icon on the screen on top of all other apps that reacts when you touch it but you can still touch the other views on the screen.</p>
<p>Example: facebook chat heads that displays a dragable and clickable icon on screen regardless of what you are doing whether you are on home screen or app menus or any app. Still you can click the chat head icon and background app elements seperately </p>
<p>How to do anything like that?</p> | 16,563,380 | 2 | 0 | null | 2013-05-15 07:54:51.483 UTC | 14 | 2017-03-24 11:23:38.813 UTC | null | null | null | null | 1,062,760 | null | 1 | 25 | java|android|view|android-activity | 14,354 | <p>Take a look at this cool article, I think that's exactly what you want :</p>
<p><a href="http://www.piwai.info/chatheads-basics" rel="noreferrer">http://www.piwai.info/chatheads-basics</a></p>
<p>In short : you want to add this permission to your manifest : </p>
<pre><code><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
</code></pre>
<p>For <a href="https://stackoverflow.com/questions/7569937/unable-to-add-window-android-view-viewrootw44da9bc0-permission-denied-for-t#answer-34061521">api >= 23</a>, you'll need to request the runtime permission <code>Settings.ACTION_MANAGE_OVERLAY_PERMISSION</code></p>
<p>Then in a service, get the window manager</p>
<pre><code>windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
</code></pre>
<p>and add your views with the <code>addView</code> method</p> |
16,155,266 | MongoDB: How to get distinct list of sub-document field values? | <p>Let's say I have the following documents in collection:</p>
<pre><code>{
"family": "Smith",
"children": [
{
"child_name": "John"
},
{
"child_name": "Anna"
},
]
}
{
"family": "Williams",
"children": [
{
"child_name": "Anna"
},
{
"child_name": "Kevin"
},
]
}
</code></pre>
<p>Now I want to get somehow the following list of unique child names cross all families:</p>
<pre><code>[ "John", "Anna", "Kevin" ]
</code></pre>
<p>Structure of result might be different. How to achieve that in MongoDB? Should be something simple but I can't figure out. I tried aggregate() function on collection but then I don't know how to apply distinct() function.</p> | 16,155,623 | 2 | 1 | null | 2013-04-22 19:35:20.04 UTC | 9 | 2017-07-07 08:04:44.173 UTC | 2017-09-22 18:01:22.247 UTC | null | -1 | null | 1,281,980 | null | 1 | 31 | mongodb|distinct|nosql | 24,757 | <p>You can just do:</p>
<pre><code>db.collection.distinct("children.child_name");
</code></pre>
<p>In your case it returns:</p>
<pre><code>[ "John", "Anna", "Kevin" ]
</code></pre> |
41,963,898 | XOR Operation Intuition | <p>I recently came across <a href="https://leetcode.com/problems/single-number/">this</a> question on Leetcode and figured out a solution that I need some clarification with:</p>
<blockquote>
<p>Given an array of integers, every element appears twice except for one. Find that single one.</p>
<p>Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?</p>
</blockquote>
<pre><code>class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = 0;
for(auto & c : nums) {
result ^= c;
}
return result;
}
};
</code></pre>
<p>First of all, what sorts of keywords should I be paying attention to in order to figure out that I should be using an XOR operation for this question?</p>
<p>Also, why does XOR'ing all items in the vector with each other give us the one that is not repeated?</p>
<hr>
<p>Thank you all for these responses, here is some more information on bitwise properties for anyone else interested: <a href="http://www.geeksforgeeks.org/interesting-facts-bitwise-operators-c/">More bitwise info</a></p> | 41,964,276 | 8 | 12 | null | 2017-01-31 17:32:29.81 UTC | 11 | 2022-06-28 16:48:13.943 UTC | 2022-06-28 03:57:22.53 UTC | null | 501,557 | null | 3,716,049 | null | 1 | 42 | c++|algorithm|bit-manipulation|xor | 13,183 | <ol>
<li><p><code>A ^ 0 == A</code></p></li>
<li><p><code>A ^ A == 0</code></p></li>
<li><p><code>A ^ B == B ^ A</code></p></li>
<li><p><code>(A ^ B) ^ C == A ^ (B ^ C)</code></p></li>
</ol>
<p>(3) and (4) together mean that the order in which numbers are <code>xor</code>ed doesn't matter.</p>
<p>Which means that, for example, <code>A^B^X^C^B^A^C</code> is equal to <code>A^A ^ B^B ^ C^C ^ X</code>.</p>
<p>Because of the (2) that is equal to <code>0^0^0^X</code>.</p>
<p>Because of the (1) that is equal to <code>X</code>.</p>
<hr>
<p>I don't think there are any specific keywords that can help you to identify such problems. You just should know above properties of XOR.</p> |
26,986,932 | Font asset not found helvetica.ttf on lollipop | <p>For some reason on lollipop, I'm getting this error and since lollipop is so new I can't find out why anywhere and I have no idea how to figure it out. Thanks in advance Logcat error:</p>
<pre><code>java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.bent.MissionaryTracker/com.bent.MissionaryTracker.MainActivity}:
java.lang.RuntimeException: Font asset not found helvetica.ttf
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.RuntimeException: Font asset not found helvetica.ttf
at android.graphics.Typeface.createFromAsset(Typeface.java:190)
at com.bent.MissionaryTracker.MainActivity.onCreate(MainActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
</code></pre>
<p>EDIT: HERE IS THE CODE THAT THROWS THE ERROR</p>
<pre><code> title = (TextView) findViewById(R.id.title);
Typeface font = Typeface.createFromAsset(getAssets(), "helvetica.ttf");
title.setTypeface(font);
</code></pre>
<p>I have helvetica.ttf in my assets folder in my project folders.</p>
<p>EDIT:
This app works on all devices up until 5.0 so for some reason 5.0 is not recognizing the file in my assets folder.</p>
<p>I tried to post a screenshot of it in my assets folder but I don't have enough reputation to post images.</p> | 27,741,345 | 9 | 7 | null | 2014-11-18 05:04:04.297 UTC | 5 | 2018-04-25 09:02:32.953 UTC | 2014-11-18 06:52:21.303 UTC | null | 3,388,716 | null | 3,388,716 | null | 1 | 46 | java|android|fonts|android-5.0-lollipop | 50,574 | <p>If you are working on Android Studio make sure your asset folder is under main and not res
This worked for me</p> |
19,532,660 | Webstorm 7 cannot recognize node API methods | <p>I just installed WebStorm. I'm working on a small Node.js app.</p>
<p>I've attached the Node.js source code, and when I click on the Node.js settings, I can see that it can recognize my various node modules, etc.</p>
<p>I'm having two issues:</p>
<ol>
<li><em>Unresolved variable or type</em>: WebStorm doesn't seem to recognize simple API methods (<code>exports</code>, <code>require</code>).</li>
<li><em>No code insight for…</em>: If I call <code>require('winston')</code>, it tells me that it has no code insight. (Is there a way I can add the source code?)</li>
</ol> | 27,930,559 | 5 | 4 | null | 2013-10-23 04:13:37.533 UTC | 1 | 2020-11-08 21:55:23.933 UTC | 2020-06-05 17:10:22.567 UTC | null | 4,157,589 | null | 317,027 | null | 1 | 30 | javascript|node.js|intellij-idea|webstorm | 10,692 | <p>For WebStorm 7 thru 10 (on OSX)…</p>
<p>WebStorm → Preferences → Languages & Frameworks → Javascript → Libraries</p>
<p>Select "Node.js Globals" and "Node.js vXXX Core Modules".</p> |
45,256,038 | Eclipse Organize Imports Shortcut (Ctrl+Shift+O) is not working | <p>Eclipse used to import missing packages when I press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>O</kbd>.</p>
<p>The shortcut key has stopped working when used in Java files but the same shortcut is working in Python files (importing missing packages).</p>
<p>Any thoughts on how to fix the issue. </p>
<p>Below are couple of snapshots for your reference.</p>
<p><a href="https://i.stack.imgur.com/EsKEr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EsKEr.png" alt="Keys Binding"></a></p>
<p><a href="https://i.stack.imgur.com/vtzNx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vtzNx.png" alt="Organize Imports in Source"></a></p> | 45,436,548 | 6 | 3 | null | 2017-07-22 15:09:55.2 UTC | 6 | 2022-01-31 21:37:17.307 UTC | 2017-08-02 15:02:42.743 UTC | null | 6,505,250 | null | 3,259,505 | null | 1 | 37 | java|python|eclipse|spring-tool-suite|shortcut | 38,294 | <p>To fix this issue:</p>
<p>Go to <code>Preferences</code> -> <code>General</code> -> <code>Keys</code>
Click on <code>Filters...</code> and de-select <code>Filter uncategorized commands</code> then <code>Ok</code>.</p>
<p>Then look for the command <code>Go To Symbol in File</code> and select it.
Then click on <code>Unbind</code> and then <code>Apply</code> and Close</p>
<p><strong><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>O</kbd></strong>. should now work.</p>
<p>EDIT:</p>
<p>Also unbind any other conflicting commands and leave only one command for <strong><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>O</kbd></strong> and set the <code>When</code> to <code>Editing Java Source</code>.</p> |
17,291,233 | How can I check Internet access using a Bash script on Linux? | <p>In my school, the Internet is not available (every night after 23:00 the school will kill the Internet connection, to put us to bed >..<), Then the ping will never stop, though I have used the parameter <code>ping -w1 ...</code>.</p>
<p>That is, when I use: <code>ping -q -w1 -c1 8.8.8.8</code> to check if the Internet connection is up/down, it will be there without any output and doesn't exit, just like I am using a single <code>cat</code>.</p>
<p>I don't know why it's like this, But I think the problem is related to the <em>school-internet-service</em>. Any suggestion? (I think <code>wget</code> may be a good alternative, but how can I use it?)</p> | 17,292,700 | 10 | 1 | null | 2013-06-25 07:10:20.217 UTC | 11 | 2021-09-01 21:25:49.377 UTC | 2021-09-01 21:17:42.423 UTC | null | 63,550 | null | 2,507,321 | null | 1 | 20 | linux|bash|wifi|ping | 75,098 | <p>Using wget:</p>
<pre><code>#!/bin/bash
wget -q --tries=10 --timeout=20 --spider http://google.com
if [[ $? -eq 0 ]]; then
echo "Online"
else
echo "Offline"
fi
</code></pre> |
17,428,987 | What is the best way to notify a user after an access_control rule redirects? | <p>From <a href="http://symfony.com/doc/current/book/security.html#understanding-how-access-control-works" rel="noreferrer">Symfony 2.3 Security</a> docs:</p>
<blockquote>
<p>If access is denied, <strong>the system will try to authenticate the user if not already (e.g. redirect the user to the login page)</strong>. If the user is already logged in, the 403 "access denied" error page will be shown. See How to customize Error Pages for more information.</p>
</blockquote>
<p>I am currently using an <code>access_control</code> rule for a few routes. I would like to notify an anonymous user if they're redirected to the login route with a message like "<em>You must login to access that page</em>." I have read through the Security docs a few times and haven't found anything relevant to this. Am I overlooking something?</p>
<p>If not, what would be the best way to notify the user when they're stopped by an <code>access_control</code> rule <strong>only</strong> if they're redirected to login (ie not if they're just in an <em>unauthorized role</em>)?</p>
<p><strong>EDIT:</strong>
For clarification, I am specifically asking how to check if a redirect was caused by an <code>access_control</code> rule (preferably in twig if possible).</p> | 17,432,089 | 4 | 0 | null | 2013-07-02 15:00:38.803 UTC | 15 | 2021-11-11 07:46:42.23 UTC | 2014-02-18 21:01:34.92 UTC | null | 998,328 | null | 998,328 | null | 1 | 22 | php|symfony|redirect|twig|access-control | 6,037 | <p>So after quite a bit of research, I found the right way to do this. You'll need to use an <a href="http://symfony.com/doc/current/components/security/firewall.html#entry-points" rel="nofollow noreferrer">Entry Point</a> service and define it in your firewall configuration.</p>
<p>This method <strong>will not mess</strong> with your <a href="http://symfony.com/doc/current/cookbook/security/form_login.html#changing-the-default-page" rel="nofollow noreferrer">default page</a> settings specified in your firewall config for logging in.</p>
<hr />
<h1>The Code</h1>
<p><strong>security.yml:</strong></p>
<pre><code>firewalls:
main:
entry_point: entry_point.user_login #or whatever you name your service
pattern: ^/
form_login:
# ...
</code></pre>
<p><strong>src/Acme/UserBundle/config/services.yml</strong></p>
<pre><code>services:
entry_point.user_login:
class: Acme\UserBundle\Service\LoginEntryPoint
arguments: [ @router ] #I am going to use this for URL generation since I will be redirecting in my service
</code></pre>
<p><strong>src/Acme/UserBundle/Service/LoginEntryPoint.php:</strong></p>
<pre><code>namespace Acme\UserBundle\Service;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface,
Symfony\Component\Security\Core\Exception\AuthenticationException,
Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpFoundation\RedirectResponse;
/**
* When the user is not authenticated at all (i.e. when the security context has no token yet),
* the firewall's entry point will be called to start() the authentication process.
*/
class LoginEntryPoint implements AuthenticationEntryPointInterface
{
protected $router;
public function __construct($router)
{
$this->router = $router;
}
/*
* This method receives the current Request object and the exception by which the exception
* listener was triggered.
*
* The method should return a Response object
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$session = $request->getSession();
// I am choosing to set a FlashBag message with my own custom message.
// Alternatively, you could use AuthenticationException's generic message
// by calling $authException->getMessage()
$session->getFlashBag()->add('warning', 'You must be logged in to access that page');
return new RedirectResponse($this->router->generate('login'));
}
}
</code></pre>
<p><strong>login.html.twig:</strong></p>
<pre><code>{# bootstrap ready for your convenience ;] #}
{% if app.session.flashbag.has('warning') %}
{% for flashMessage in app.session.flashbag.get('warning') %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">&times;</button>
{{ flashMessage }}
</div>
{% endfor %}
{% endif %}
</code></pre>
<h1>Resources:</h1>
<ul>
<li><a href="http://api.symfony.com/master/Symfony/Component/Security/Http/EntryPoint/AuthenticationEntryPointInterface.html" rel="nofollow noreferrer">AuthenticationEntryPointInterface API</a></li>
<li><a href="http://symfony.com/doc/current/components/security/firewall.html#entry-points" rel="nofollow noreferrer">Entry Points Documentation</a></li>
<li><a href="http://symfony.com/doc/current/reference/configuration/security.html" rel="nofollow noreferrer">Security Configuration Reference</a></li>
<li><a href="http://symfony.com/doc/current/cookbook/security/form_login.html#" rel="nofollow noreferrer">How to Customize your Form Login</a></li>
<li><a href="https://stackoverflow.com/questions/11968354/symfony2-why-access-denied-handler-doesnt-work">Why access_denied_handle doesn't work</a> <em>- thanks to <a href="https://stackoverflow.com/users/1443490/cheesemacfly">cheesemacfly</a> for <a href="https://chat.stackoverflow.com/transcript/message/10341330#10341330">tip</a></em></li>
</ul> |
17,624,936 | Xampp - Ubuntu - cant access my project in lampp/htdocs | <p>I have installed xampp to Ubuntu 12.04. I have put my project in the folder /opt/lampp/htdocs/project_is_here</p>
<p>When I type in the browser <code>localhost/soap/php</code> (soap/php is in my htdocs folder) which is where <code>index.php</code> I get the following error:</p>
<pre><code>Access forbidden!
You don't have permission to access the requested directory. There is either no index document or the directory is read-protected.
If you think this is a server error, please contact the webmaster.
Error 403
localhost
Apache/2.4.3 (Unix) OpenSSL/1.0.1c PHP/5.4.7
</code></pre>
<p>Any ideas how to fix this? I think this is the right location to put the project, because I tried other places and it said location didnt exist and this error goes away here and I get this.</p>
<p>Any ideas?</p> | 17,625,028 | 5 | 0 | null | 2013-07-12 22:23:58.37 UTC | 16 | 2021-08-22 15:19:36.473 UTC | null | null | null | null | 1,828,314 | null | 1 | 25 | php|ubuntu|xampp | 73,523 | <ol>
<li><p>In the linux terminal navigate to your lampp directory.</p>
<pre><code> cd /opt/lampp
</code></pre>
</li>
<li><p>In the command line type:</p>
<pre><code> sudo chmod 777 -R htdocs
</code></pre>
</li>
</ol>
<p>The problem should be solved.</p>
<p>What you just did was:</p>
<p>Navigate to the directory containing the protected directory. Your problem was that it was a folder that was access protected by your system. When you commanded chmod 777 -R htdocs, you set the permissions for <strong>every user</strong> on your computer to <strong>"read/write/execute - allowed"</strong>.</p>
<p>Each number from 0-7 sets a permission level. Here's a link explaining that in more detail.</p>
<p><a href="http://www.pageresource.com/cgirec/chmod.htm" rel="nofollow noreferrer">http://www.pageresource.com/cgirec/chmod.htm</a></p>
<p>The '-R' makes the command recursive and will affect htdocs as well as all subdirectories of htdocs and all subdirectories of those etc.</p> |
17,485,747 | How to convert a nested list into a one-dimensional list in Python? | <p>I tried everything (in my knowledge) from splitting the array and joining them up together
and even using itertools:</p>
<pre><code>import itertools
def oneDArray(x):
return list(itertools.chain(*x))
</code></pre>
<p><strong>The result I want:</strong></p>
<p>a) <code>print oneDArray([1,[2,2,2],4]) == [1,2,2,2,4]</code></p>
<p>Strangely, it works for</p>
<p>b) <code>print oneDArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]</code></p>
<p><strong>Question 1) How do I get part a to work the way I want (any hints?)</strong></p>
<p><strong>Question 2) Why does the following code above work for part b and not part a??</strong></p> | 17,485,785 | 15 | 1 | null | 2013-07-05 09:40:41.12 UTC | 10 | 2022-05-07 23:58:15.21 UTC | 2013-07-05 09:55:22.983 UTC | null | 846,892 | null | 1,186,038 | null | 1 | 28 | python|python-2.7|nested-lists | 86,976 | <p>You need to recursively loop over the list and check if an item is iterable(strings are iterable too, but skip them) or not.</p>
<p><code>itertools.chain</code> will not work for <code>[1,[2,2,2],4]</code> because it requires all of it's items to be iterable, but <code>1</code> and <code>4</code> (integers) are not iterable. That's why it worked for the second one because it's a list of lists.</p>
<pre><code>>>> from collections import Iterable
def flatten(lis):
for item in lis:
if isinstance(item, Iterable) and not isinstance(item, str):
for x in flatten(item):
yield x
else:
yield item
>>> lis = [1,[2,2,2],4]
>>> list(flatten(lis))
[1, 2, 2, 2, 4]
>>> list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>Works for any level of nesting:</p>
<pre><code>>>> a = [1,[2,2,[2]],4]
>>> list(flatten(a))
[1, 2, 2, 2, 4]
</code></pre>
<p>Unlike other solutions, this will work for strings as well:</p>
<pre><code>>>> lis = [1,[2,2,2],"456"]
>>> list(flatten(lis))
[1, 2, 2, 2, '456']
</code></pre> |
17,408,480 | Gradle: How to customize Android Manifest permissions? | <p>For my build system, I need to build several app variants, each requesting a different set of permissions. How can this be done with Gradle, without invoking a separate script?</p> | 17,414,597 | 1 | 0 | null | 2013-07-01 15:43:09.6 UTC | 16 | 2014-04-15 17:58:52.257 UTC | null | null | null | null | 2,539,597 | null | 1 | 35 | android|gradle | 18,434 | <p>I just managed to do this by having different flavors in my gradle file:</p>
<pre><code> free {
packageName 'com.sample.free'
buildConfigField "boolean", "HAS_AD", "true"
}
paid {
packageName 'com.sample.paid'
buildConfigField "boolean", "HAS_AD", "false"
}
</code></pre>
<p>and then I created a new folder under src called "free" and under that a folder called "res"</p>
<pre><code>src/
+ free/
| + res/
+ src/
</code></pre>
<p>and in that folder create a new file "AndroidManifest.xml" with the following code in it:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sample" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
</code></pre>
<p>According to <a href="http://tools.android.com/tech-docs/new-build-system/user-guide">Gradle Plugin User Guide</a> on Android Tools Project Site:</p>
<blockquote>
<p>Similar to Build Types, Product Flavors also contribute code and
resources through their own sourceSets.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>The following rules are used when dealing with all the sourcesets used
to build a single APK:</p>
<ul>
<li>All source code (src/*/java) are used together as multiple folders generating a single output.</li>
<li><em>Manifests are all merged together into a single manifest. This allows Product Flavors to have different components and/or
permissions, similarly to Build Types.</em></li>
<li>All resources (Android res and assets) are used using overlay priority where the Build Type overrides the Product Flavor, which
overrides the main sourceSet.</li>
<li>Each Build Variant generates its own R class (or other generated source code) from the resources. Nothing is shared between
variants.</li>
</ul>
</blockquote>
<p>meaning that you can create a folder with each flavor name under src and put your custom files in them. If said file is an AndroidManifest gradle will merge it with the manifest in the main.</p> |
17,339,830 | Overview of all JSF-related web.xml context parameter names and values | <p>There are several JavaServer Faces <code><context-param></code> in <code>web.xml</code>: <code>facelets.REFRESH_PERIOD</code>, <code>facelets.DEVELOPMENT</code>, <code>facelets.SKIP_COMMENTS</code> etc. Where I can find a complete list of all those params?</p> | 17,341,945 | 1 | 3 | null | 2013-06-27 09:44:08.433 UTC | 35 | 2021-11-26 10:36:38.15 UTC | 2014-04-01 16:38:21.363 UTC | null | 157,882 | null | 1,251,549 | null | 1 | 35 | jsf|web.xml|context-param | 37,947 | <p>First of all, those starting with <code>facelets.</code> are not JSF context parameters, but <a href="https://facelets.java.net/nonav/docs/dev/docbook.html#config-webapp-init" rel="nofollow noreferrer">Facelets 1.x</a> context parameters. Previously, during JSF 1.x era, Facelets was not integrated as part of JSF. However, since JSF 2.0, Facelets is integrated as part of JSF, replacing legacy JSP as the default view technology, and most of the Facelets 1.x context parameters were remapped to JSF 2.x context parameters.</p>
<p>The real JSF context parameter names start with <code>javax.faces.</code>. They are listed in chapter 11.1.3 of the <a href="http://jcp.org/aboutJava/communityprocess/final/jsr314/index.html" rel="nofollow noreferrer">JSF specification</a>. Here's an extract of relevance from the JSF 2.0 specification:</p>
<blockquote>
<h1>11.1.3 Application Configuration Parameters</h1>
<p>Servlet containers support application configuration parameters that may be customized by including <code><context-param></code> elements in the web application deployment descriptor. All JSF implementations are required to support the following application configuration parameter names:</p>
<ul>
<li><p><code>javax.faces.CONFIG_FILES</code> -- Comma-delimited list of context-relative resource paths under which the JSF implementation will look for application configuration resources (see Section 11.4.4 “Application Configuration Resource Format”), before loading a configuration resource named “<code>/WEB-INF/faces-config.xml</code>” (if such a resource exists). If “<code>/WEB-INF/faces-config.xml</code>” is present in the list, it must be ignored.</p>
</li>
<li><p><code>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</code> -- If this param is set,
and calling <code>toLowerCase().equals("true")</code> on a <code>String</code> representation of its value returns <code>true</code>,
<code>Application.createConverter()</code> must guarantee that the default for the timezone of all
<code>javax.faces.convert.DateTimeConverter</code> instances must be equal to <code>TimeZone.getDefault()</code>
instead of “<code>GMT</code>”.</p>
</li>
<li><p><code>javax.faces.DEFAULT_SUFFIX</code> -- Allow the web application to define an alternate suffix for JSP pages
containing JSF content. See the javadocs for the symbolic constant
<code>ViewHandler.DEFAULT_SUFFIX_PARAM_NAME</code> for the complete specification.</p>
</li>
<li><p><code>javax.faces.DISABLE_FACELET_JSF_VIEWHANDLER</code> -- If this param is set, and calling
<code>toLowerCase().equals("true")</code> on a <code>String</code> representation of its value returns <code>true</code>, the default
<code>ViewHandler</code> must behave as specified in the latest 1.2 version of this specification. Any behavior specified in
Section 7.5 “ViewHandler” and implemented in the default <code>ViewHandler</code> that pertains to handling requests for
pages authored in the JavaServer Faces View Declaration Language must not be executed by the runtime.</p>
</li>
<li><p><code>javax.faces.FACELETS_LIBRARIES</code> -- If this param is set, the runtime must interpret it as a semicolon (;)
separated list of paths, starting with “/” (without the quotes). The runtime must interpret each entry in the list as a
path relative to the web application root and interpret the file found at that path as a facelet tag library, conforming to
the schema declared in Section 1.1 “XML Schema Definition for Application Configuration Resource file”and expose
the tags therein according to Section 10.3.2 “Facelet Tag Library mechanism”. The runtime must also consider the
<code>facelets.LIBRARIES</code> param name as an alias to this param name for backwards compatibility with existing
facelets tag libraries.</p>
</li>
<li><p><code>javax.faces.FACELETS_BUFFER_SIZE</code> -- The buffer size to set on the response when the <code>ResponseWriter</code>
is generated. By default the value is -1, which will not assign a buffer size on the response. This should be increased
if you are using development mode in order to guarantee that the response isn't partially rendered when an error is
generated. The runtime must also consider the <code>facelets.BUFFER_SIZE</code> param name as an alias to this param
name for backwards compatibility with existing facelets tag libraries.</p>
</li>
<li><p><code>javax.faces.DECORATORS</code> -- A semicolon (;) delimitted list of class names of type
<code>javax.faces.view.facelets.TagDecorator</code>, with a no-argument constructor. These decorators will be
loaded when the first request for a Facelets VDL view hits the <code>ViewHandler</code> for page compilation.The runtime
must also consider the <code>facelets.DECORATORS</code> param name as an alias to this param name for backwards
compatibility with existing facelets tag libraries.</p>
</li>
<li><p><code>javax.faces.FACELETS_REFRESH_PERIOD</code> -- When a page is requested, what interval in seconds should the
compiler check for changes. If you don't want the compiler to check for changes once the page is compiled, then use
a value of -1. Setting a low refresh period helps during development to be able to edit pages in a running
application.The runtime must also consider the <code>facelets.REFRESH_PERIOD</code> param name as an alias to this
param name for backwards compatibility with existing facelets tag libraries.</p>
</li>
<li><p><code>javax.faces.FACELETS_RESOURCE_RESOLVER</code> -- If this param is set, the runtime must interpret its value as a
fully qualified classname of a java class that extends <code>javax.faces.view.facelets.ResourceResolver</code>
and has a zero argument public constructor or a one argument public constructor where the type of the argument is
<code>ResourceResolver</code>. If this param is set and its value does not conform to those requirements, the runtime must
log a message and continue. If it does conform to these requirements and has a one-argument constructor, the default
<code>ResourceResolver</code> must be passed to the constructor. If it has a zero argument constructor it is invoked directly.
In either case, the new <code>ResourceResolver</code> replaces the old one. The runtime must also consider the
<code>facelets.RESOURCE_RESOLVER</code> param name as an alias to this param name for backwards compatibility with
existing facelets tag libraries.</p>
</li>
<li><p><code>javax.faces.FACELETS_SKIP_COMMENTS</code> -- If this param is set, and calling
<code>toLowerCase().equals("true")</code> on a <code>String</code> representation of its value returns <code>true</code>, the runtime must
ensure that any XML comments in the Facelets source page are not delivered to the client. The runtime must also
consider the <code>facelets.SKIP_COMMENTS</code> param name as an alias to this param name for backwards compatibility
with existing facelets tag libraries.</p>
</li>
<li><p><code>javax.faces.FACELETS_SUFFIX</code> -- Allow the web application to define an alternate suffix for Facelet based
XHTML pages containing JSF content. See the javadocs for the symbolic constant
<code>ViewHandler.FACELETS_SUFFIX_PARAM_NAME</code> for the complete specification.</p>
</li>
<li><p><code>javax.faces.FACELETS_VIEW_MAPPINGS</code> -- If this param is set, the runtime must interpret it as a semicolon
(;) separated list of strings that is used to forcibly declare that certain pages in the application must be interpreted as
using Facelets, regardless of their extension. The runtime must also consider the <code>facelets.VIEW_MAPPINGS</code>
param name as an alias to this param name for backwards compatibility with existing facelets applications. See the
javadocs for the symbolic constant <code>ViewHandler.FACELETS_VIEW_MAPPINGS_PARAM_NAME</code> for the complete
specification.</p>
</li>
<li><p><code>javax.faces.FULL_STATE_SAVING_VIEW_IDS</code> -- The runtime must interpret the value of this parameter as a
comma separated list of view IDs, each of which must have their state saved using the state saving mechanism
specified in JSF 1.2.</p>
</li>
<li><p><code>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</code> -- If this param is set, and
calling <code>toLowerCase().equals("true")</code> on a <code>String</code> representation of its value returns <code>true</code>, any
implementation of <code>UIInput.validate()</code> must take the following additional action.
If the <code>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</code> context parameter value is
<code>true</code> (ignoring case), and <code>UIInput.getSubmittedValue()</code> returns a zero-length <code>String</code> call
<code>UIInput.setSubmittedValue(null)</code> and continue processing using null as the current submitted value</p>
</li>
<li><p><code>javax.faces.LIFECYCLE_ID</code> -- Lifecycle identifier of the <code>Lifecycle</code> instance to be used when processing
JSF requests for this web application. If not specified, the JSF default instance, identified by
<code>LifecycleFactory.DEFAULT_LIFECYCLE</code>, must be used.</p>
</li>
<li><p><code>javax.faces.PARTIAL_STATE_SAVING</code> --The <code>ServletContext</code> init parameter consulted by the runtime to
determine if the partial state saving mechanism should be used.
If undefined, the runtime must determine the version level of the application.</p>
<ul>
<li>For applications versioned at 1.2 and under, the runtime must not use the partial state saving mechanism.</li>
<li>For applications versioned at 2.0 and above, the runtime must use the partial state saving mechanism.</li>
</ul>
</li>
</ul>
<p>If this parameter is defined, and the application is versioned at 1.2 and under, the runtime must not use the partial
state saving mechanism. Otherwise, If this param is defined, and calling <code>toLowerCase().equals("true")</code> on a <code>String</code>
representation of its value returns <code>true</code>, the runtime must use partial state mechanism. Otherwise the partial state
saving mechanism must not be used.</p>
<ul>
<li><p><code>javax.faces.PROJECT_STAGE</code> -- A human readable string describing where this particular JSF application is in
the software development lifecycle. Valid values are “<code>Development</code>”, “<code>UnitTest</code>”, “<code>SystemTest</code>”, or
“<code>Production</code>”, corresponding to the enum constants of the class
<code>javax.faces.application.ProjectStage</code>. It is also possible to set this value via JNDI. See the javadocs
for <code>Application.getProjectStage()</code>.</p>
</li>
<li><p><code>javax.faces.STATE_SAVING_METHOD</code> -- The location where state information is saved. Valid values are
“<code>server</code>” (typically saved in <code>HttpSession</code>) and “<code>client</code>” (typically saved as a hidden field in the subsequent form
submit). If not specified, the default value “<code>server</code>” must be used.</p>
</li>
<li><p><code>javax.faces.VALIDATE_EMPTY_FIELDS</code> -- If this param is set, and calling
<code>toLowerCase().equals("true")</code> on a <code>String</code> representation of its value returns <code>true</code>, all submitted fields
will be validated. This is necessary to allow the model validator to decide whether null or empty values are
allowable in the current application. If the value is <code>false</code>, null or empty values will not be passed to the validators.
If the value is the string “<code>auto</code>”, the runtime must check if JSR-303 Beans Validation is present in the current
environment. If so, the runtime must proceed as if the value “<code>true</code>” had been specified. If JSR-303 Beans Validation
is not present in the current environment, the runtime most proceed as if the value “<code>false</code>” had been specified. If
the param is not set, the system must behave as if the param was set with the value “<code>auto</code>”.</p>
</li>
<li><p><code>javax.faces.validator.DISABLE_DEFAULT_BEAN_VALIDATOR</code> -- If this param is set, and calling
<code>toLowerCase().equals("true")</code> on a <code>String</code> representation of its value returns <code>true</code>, the runtime must not
automatically add the validator with validator-id equal to the value of the symbolic constant
<code>javax.faces.validator.VALIDATOR_ID</code> to the list of default validators. Setting this parameter to true will
have the effect of disabling the automatic installation of Bean Validation to every input component in every view in
the application, though manual installation is still possible.</p>
</li>
</ul>
<p>JSF implementations may choose to support additional configuration parameters, as well as additional mechanisms to
customize the JSF implementation; however, applications that rely on these facilities will not be portable to other JSF
implementations.</p>
</blockquote>
<p>As you can read in the last paragraph, JSF implementations may also have their own set of context parameters. For Mojarra that are the ones starting with <code>com.sun.faces.</code> which are listed on this blog: <a href="http://balusc.omnifaces.org/2015/09/what-mojarra-context-parameters-are.html" rel="nofollow noreferrer">What Mojarra context parameters are available?</a> For MyFaces that are the ones starting with <code>org.apache.myfaces.</code> which are also listed on their own site: <a href="http://myfaces.apache.org/#/core23?id=configuration" rel="nofollow noreferrer">MyFaces documentation - Web Context Parameters</a>.</p> |
17,540,971 | How to use Selenium with Python? | <p>How do I set up Selenium to work with Python? I just want to write/export scripts in Python, and then run them. Are there any resources for that? I tried googling, but the stuff I found was either referring to an outdated version of Selenium (RC), or an outdated version of Python.</p> | 17,541,287 | 3 | 0 | null | 2013-07-09 05:56:48.2 UTC | 25 | 2020-08-14 13:29:49.443 UTC | 2020-05-02 12:05:58.26 UTC | null | 8,392,241 | null | 896,112 | null | 1 | 50 | python|selenium|selenium-webdriver|automation | 112,292 | <p>You mean Selenium WebDriver?
Huh....</p>
<p><strong>Prerequisite</strong>: Install Python based on your OS</p>
<p>Install with following command </p>
<pre><code>pip install -U selenium
</code></pre>
<p>And use this module in your code </p>
<pre><code>from selenium import webdriver
</code></pre>
<p>You can also use many of the following as required </p>
<pre><code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
</code></pre>
<h2>Here is an updated answer</h2>
<p>I would recommend you to run script without IDE... Here is my approach</p>
<ol>
<li>USE IDE to find xpath of object / element</li>
<li>And use find_element_by_xpath().click() </li>
</ol>
<p>An example below shows login page automation </p>
<pre><code>#ScriptName : Login.py
#---------------------
from selenium import webdriver
#Following are optional required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
baseurl = "http://www.mywebsite.com/login.php"
username = "admin"
password = "admin"
xpaths = { 'usernameTxtBox' : "//input[@name='username']",
'passwordTxtBox' : "//input[@name='password']",
'submitButton' : "//input[@name='login']"
}
mydriver = webdriver.Firefox()
mydriver.get(baseurl)
mydriver.maximize_window()
#Clear Username TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).clear()
#Write Username in Username TextBox
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)
#Clear Password TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).clear()
#Write Password in password TextBox
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)
#Click Login button
mydriver.find_element_by_xpath(xpaths['submitButton']).click()
</code></pre>
<p>There is an another way that you can find xpath of any object -</p>
<ol>
<li>Install Firebug and Firepath addons in firefox</li>
<li>Open URL in Firefox</li>
<li>Press F12 to open Firepath developer instance </li>
<li>Select Firepath in below browser pane and chose select by "xpath" </li>
<li>Move cursor of the mouse to element on webpage</li>
<li>in the xpath textbox you will get xpath of an object/element.</li>
<li>Copy Paste xpath to the script.</li>
</ol>
<p>Run script -</p>
<pre><code>python Login.py
</code></pre>
<p>You can also use a CSS selector instead of xpath. CSS selectors are slightly faster than xpath in most cases, and are usually preferred over xpath (if there isn't an ID attribute on the elements you're interacting with).</p>
<p>Firepath can also capture the object's locator as a CSS selector if you move your cursor to the object. You'll have to update your code to use the equivalent find by CSS selector method instead -</p>
<pre><code>find_element_by_css_selector(css_selector)
</code></pre> |
17,530,762 | Only allow properties that are declared in JSON schema | <p>I am using json-schema and wanting to only allow properties that are declared in this file to pass validation. For instance if a user passes a "name" property in their json object it will fail this schema because "name" is not listed here as a property.</p>
<p>Is there some function similar to "required" that will only allow the listed properties to pass?</p>
<pre><code>{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Accounting Resource - Add Item",
"type": "object",
"properties": {
"itemNumber": {
"type":"string",
"minimum": 3
},
"title": {
"type":"string",
"minimum": 5
},
"description": {
"type":"string",
"minimum": 5
}
},
"required": [
"itemNumber",
"title",
"description"
]
}
</code></pre> | 17,531,296 | 3 | 4 | null | 2013-07-08 15:44:27.823 UTC | 8 | 2020-05-29 11:16:33.45 UTC | 2019-06-21 23:20:41.06 UTC | null | 116,286 | null | 834,516 | null | 1 | 106 | json|jsonschema | 32,597 | <p>I believe what you need to do to achieve this is set <code>additionalProperties</code> to false. See the specification <a href="https://github.com/json-schema-org/json-schema-spec" rel="noreferrer">here</a></p> |
30,456,472 | iTerm2 slide down over full screen app | <p>I always have my IDE (phpStorm) in full screen mode (Yosemite). </p>
<p>I want my iTerm2 hotkey to slide my terminal window down over the IDE, so it doesn't open up a new space for the terminal window. As once the window slides back up it leaves me on an empty space, rather than going back to phpStorm.</p> | 37,407,851 | 4 | 2 | null | 2015-05-26 10:52:53.877 UTC | 21 | 2022-08-12 14:11:52.377 UTC | null | null | null | null | 1,262,461 | null | 1 | 53 | macos|osx-yosemite|iterm2 | 20,655 | <blockquote>
<p><strong>Attention</strong>! See Update3 for new iTerm versions (works for 2.1.5)</p>
</blockquote>
<h1>Original Answer</h1>
<p>This command allows iTerm to work over fullscreen apps</p>
<pre><code>defaults write ~/Applications/iTerm.app/Contents/Info LSUIElement true
</code></pre>
<p>But it hides iTerm's context menu. To access iTerm's preferences, right-click on the tabs bar and select the proper menu item; or focus on any iTerm's window and press <kbd>⌘</kbd>-<kbd>,</kbd>.</p>
<h1>Update</h1>
<blockquote>
<p>If you use the beta version of iTerm, there is no need to run the previous command. You can turn on <em>Preferences > Advanced > Hide iTerm2 from the dock and from the <kbd>⌘</kbd>-<kbd>Tab</kbd> app switcher</em>.</p>
<p>Also make sure that the profile you use for the dropdown window (<em>Hotkey window</em> by default) is allowed on all spaces (<em>Preferences > Profiles > "Hotkey window" profile > "Window" tab > Space: "all spaces"</em>).</p>
<p>Remember to restart iTerm2.</p>
</blockquote>
<h1>Update 2</h1>
<blockquote>
<p>If you can't find <em>Preferences</em>, use the shortcut <kbd>⌘</kbd>-<kbd>i</kbd> or <kbd>Right Click</kbd> in an open iTerm2 terminal window, then select <em>"Edit Session"</em>.</p>
</blockquote>
<h1>Update 3</h1>
<blockquote>
<p>In 2.1.5, you should use the <em>"Exclude from Dock and ⌘-Tab Application Switcher"</em> option in <em>Preferences -> Appearance</em>. When iTerm2 is excluded from the dock, you can always get back to the Preferences window using the status bar item, or <kbd>⌘</kbd>-<kbd>,</kbd>. Look for an iTerm2 icon on the right side of your menu bar.</p>
<p><a href="https://i.stack.imgur.com/zw1B6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zw1B6.png" alt="Activate" /></a></p>
</blockquote>
<h1>Update 4</h1>
<p>In v.3.4.15, you should follow the comment from @Sudhi. Profiles -> specific Profile -> Keys -> "A hotkey opens dedicated window with this profile" and configure hotkey.<a href="https://i.stack.imgur.com/WKxIA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WKxIA.png" alt="v3.4 config window screen" /></a></p> |
36,695,438 | Detect click outside div using javascript | <p>I'd like to detect a click inside or outside a div area. The tricky part is that the div will contain other elements and if one of the elements inside the div is clicked, it should be considered a click inside, the same way if an element from outside the div is clicked, it should be considered an outside click.</p>
<p>I've been researching a lot but all I could find were examples in jquery and I need pure javascript.</p>
<p>Any suggestion will be appreciated.</p> | 36,696,086 | 8 | 3 | null | 2016-04-18 13:29:05.923 UTC | 26 | 2022-09-13 20:17:38.49 UTC | null | null | null | user4697579 | null | null | 1 | 93 | javascript | 145,669 | <p>It depends on the individual use case but it sounds like in this example there are likely to be other nested elements inside the main div e.g. more divs, lists etc. Using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/contains" rel="noreferrer">Node.contains</a> would be a useful way to check whether the target element is within the div that is being checked.</p>
<pre><code>window.addEventListener('click', function(e){
if (document.getElementById('clickbox').contains(e.target)){
// Clicked in box
} else{
// Clicked outside the box
}
});
</code></pre>
<p>An example that has a nested list inside is <a href="https://jsfiddle.net/kym2rvyL/1/" rel="noreferrer">here</a>.</p> |
26,358,144 | How to 'reset' a ReactJS element? | <p>I'm trying to 'reset' a ReactJS element.</p>
<p>In this case, the element is 90%+ of the contents of the page.</p>
<p>I'm using <code>replaceState</code> to replace the state of the element with with its initial state.</p>
<p>Unfortunately, sub-elements which have their own 'state' do not reset. In particular, form fields keep their contents.</p>
<p>Is there a way of forcing a re-render of an element, which will also cause sub-elements to re-render, as if the page had just loaded?</p> | 26,358,755 | 5 | 4 | null | 2014-10-14 10:09:34.237 UTC | 8 | 2018-03-27 04:54:22.48 UTC | null | null | null | null | 129,805 | null | 1 | 25 | javascript|reactjs | 27,739 | <p>Adding a <code>key</code> to the element forces the element (and all its children) to be re-rendered when that key changes.</p>
<p>(I set the value of 'key' to simply the timestamp of when the initial data was sent.)</p>
<pre><code>render: function() {
return (
<div key={this.state.timestamp} className="Commissioning">
...
</code></pre> |
31,965,558 | How to display a variable in HTML | <p>I am making a web app using Python and have a variable that I want to display on an HTML page. How can I go about doing so? Would using <code>{% VariableName %}</code> in the HTML page be the right approach to this?</p> | 31,966,504 | 1 | 6 | null | 2015-08-12 12:41:39.19 UTC | 4 | 2019-12-08 23:56:44.107 UTC | 2015-08-12 12:51:28.137 UTC | null | 3,001,761 | null | 5,110,437 | null | 1 | 6 | python|html|python-2.7 | 68,987 | <p>This is very clearly explained in the Flask <a href="http://flask.pocoo.org/docs/0.10/quickstart/#rendering-templates" rel="noreferrer">documentation</a> so I recommend that you read it for a full understanding, but here is a very simple example of rendering template variables.</p>
<p>HTML template file stored in <code>templates/index.html</code>:</p>
<pre><code><html>
<body>
<p>Here is my variable: {{ variable }}</p>
</body>
</html>
</code></pre>
<p>And the simple Flask app:</p>
<pre><code>from flask import Flask, render_template
app = Flask('testapp')
@app.route('/')
def index():
return render_template('index.html', variable='12345')
if __name__ == '__main__':
app.run()
</code></pre>
<p>Run this script and visit <a href="http://127.0.0.1:5000/" rel="noreferrer">http://127.0.0.1:5000/</a> in your browser. You should see the value of <code>variable</code> rendered as <code>12345</code></p> |
31,849,946 | Scala Slick table tag | <p>In slick table there is a tag parameter:</p>
<pre><code>class Companies(tag: Tag) extends Table[Company](tag,"COMPANY") {...}
</code></pre>
<p>What is it used for, and is there any way not to write it with each table class definition?</p> | 63,557,666 | 2 | 7 | null | 2015-08-06 07:55:43.553 UTC | 2 | 2020-08-24 08:49:55.98 UTC | null | null | null | null | 1,431,919 | null | 1 | 33 | scala|slick | 2,765 | <p>The best answer I've seen is: <a href="https://stackoverflow.com/a/27783730/154248">https://stackoverflow.com/a/27783730/154248</a></p>
<p>What's it used for: imagine you needed to join a table on itself. That tag is a way to distinguish between the tables taking part in a query.</p> |
5,529,609 | CodeIgniter/Ajax - Send post values to controller | <p>I'm working on a simple login form. When the user clicks on the Login button, I want to send the post values to my controller, validate them against my database (using a model) and return a value. Based on that value, I want to either send the user to the member area, or display an error message on my form. This error message has a class 'error' and is hidden by default. I want to use jQuery's show() to show it when the credentials are wrong.</p>
<p>My form has two textfields, one for the email address, other one for the password and a submit button. However, I have never really worked with Ajax except for VERY basic things like a simple loader, so I'm not sure what to do next.</p>
<pre><code> $("#btn_login").click(
function()
{
// get values
var email_address = $("#email_address").val();
var password = $("#password").val();
// post values? and ajax call?
//stop submit btn from submitting
return(false);
}
);
</code></pre>
<p>I assume I have to use jQuery's ajax() method here, so I was thinking of working off this example:</p>
<pre><code>$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
</code></pre>
<p>However, I'm not really sure how to get my post values (those two vars) in the data: thingy.. Or should I take another road here? This seems like something I'll never forget how to do once I learn it, so if someone can help me out I'd be grateful. Thanks a lot.</p> | 5,529,642 | 3 | 0 | null | 2011-04-03 12:36:56.833 UTC | 2 | 2016-08-25 03:49:27.813 UTC | null | null | null | null | 613,721 | null | 1 | 4 | ajax|codeigniter|jquery | 41,293 | <p>All you need to do is create a key/value pair with the values and assign it to the data parameter and jQuery will do the rest. </p>
<pre><code>//create a js object with key values for your post data
var postData = {
'email' : email_address,
'password' : password
};
$.ajax({
type: "POST",
url: "some.php",
data: postData , //assign the var here
success: function(msg){
alert( "Data Saved: " + msg );
}
});
</code></pre>
<p>With this, you should be able to access the data with Codeigniters <code>input</code></p>
<p><strong>EDIT</strong></p>
<p>I've set up a test fiddle here : <a href="http://jsfiddle.net/WVpwy/2/" rel="noreferrer">http://jsfiddle.net/WVpwy/2/</a></p>
<pre><code>$('#dostuff').click(function(){
var email_address = $("#email_address").val();
var password = $("#password").val();
var postData = {
'email' : email_address,
'password' : password,
'html' : 'PASS'
};
$.post('/echo/html/', postData, function(data){
//This should be JSON preferably. but can't get it to work on jsfiddle
//Depending on what your controller returns you can change the action
if (data == 'PASS') {
alert('login pased');
} else {
alert('login failed');
}
});
});
</code></pre>
<p>I just prefer .post, but what you used is an equivalent. </p>
<p>Basically your controller should <strong>echo</strong> out data. Not return. You need to send a string representation of your data back so your script can (evaluate if json) and act on it</p>
<p>Here's a good example as a starting point : <a href="http://www.ibm.com/developerworks/opensource/library/os-php-jquery-ajax/index.html" rel="noreferrer">http://www.ibm.com/developerworks/opensource/library/os-php-jquery-ajax/index.html</a></p> |
4,842,575 | How do I display PHP code in HTML? | <p>How do I display PHP code in HTML?</p> | 4,842,598 | 4 | 1 | null | 2011-01-30 11:11:41.15 UTC | 1 | 2015-10-09 11:30:23.393 UTC | 2014-01-21 11:30:02.57 UTC | null | 3,177,032 | user592252 | null | null | 1 | 11 | php|html | 44,203 | <pre><code>highlight_file('myFile.php');
</code></pre>
<p>or change the file extension to phps</p> |
18,568,105 | How to match a paragraph using regex | <p>I have been struggling with python regex for a while trying to match paragraphs within a text, but I haven't been successful. I need to obtain the start and end positions of the paragraphs.</p>
<p>An example of a text:</p>
<pre><code>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At
vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren,
no sea takimata sanctus est Lorem ipsum dolor sit amet.
Ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At
vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
no sea takimata sanctus est Lorem ipsum dolor sit amet.
</code></pre>
<p>In this example case, I would want to separately match all the paragraphs starting with Lorem, Stet and Ipsum respectively (without the empty lines). Does anyone have any idea how to do this?</p> | 18,568,168 | 6 | 3 | null | 2013-09-02 07:50:34.24 UTC | 8 | 2022-06-17 12:58:41.36 UTC | 2020-03-22 23:12:41.14 UTC | null | 1,546,844 | null | 1,546,844 | null | 1 | 10 | python|regex|paragraph | 32,306 | <p>You can split on double-newline like this:</p>
<pre><code>paragraphs = re.split(r"\n\n", DATA)
</code></pre>
<p><strong>Edit:</strong> To capture the paragraphs as matches, so you can get their start and end points, do this:</p>
<pre><code>for match in re.finditer(r'(?s)((?:[^\n][\n]?)+)', DATA):
print match.start(), match.end()
# Prints:
# 0 214
# 215 298
# 299 589
</code></pre> |
18,714,364 | Android divider color DatePicker dialog | <p>I'm trying to change color of the blue dividers for a DatePicker in a dialog. This is just a normal DialogFragment with a DatePicker and a ButtonBar.</p>
<p>Does anyone know to change these dividers, or if it's even possible without replacing the entire DatePicker with a custom one?</p>
<p><img src="https://i.stack.imgur.com/uVqx2l.png" alt="Screenshot DatePicker"></p>
<p><strong>Mini rant</strong></p>
<p>Now I've seen too many answers suggesting the following code:</p>
<pre><code><style name="datePickerTheme" parent="@android:style/Widget.DeviceDefault.DatePicker">
<item name="android:divider">**your @drawable/ or @color/ here**</item>
</style>
</code></pre>
<p>Which simply does not work. Have you guys tried this before suggesting this code? It <em>should</em> work perfectly, but it does not seem to work with the DatePicker.</p> | 36,876,571 | 8 | 0 | null | 2013-09-10 08:46:44.69 UTC | 12 | 2019-03-12 20:28:58.453 UTC | null | null | null | null | 1,888,611 | null | 1 | 13 | android|android-layout|colors|datepicker|divider | 20,485 | <p>The following approach worked for me.This sets divider colours for all fields (also for am/pm)</p>
<pre><code> private void applyStyLing(TimePickerDialog timePickerDialog){
Resources system = Resources.getSystem();
int hourNumberPickerId = system.getIdentifier("hour", "id", "android");
int minuteNumberPickerId = system.getIdentifier("minute", "id", "android");
int ampmNumberPickerId = system.getIdentifier("amPm", "id", "android");
NumberPicker hourNumberPicker = (NumberPicker) timePickerDialog.findViewById(hourNumberPickerId);
NumberPicker minuteNumberPicker = (NumberPicker) timePickerDialog.findViewById(minuteNumberPickerId);
NumberPicker ampmNumberPicker = (NumberPicker) timePickerDialog.findViewById(ampmNumberPickerId);
setNumberPickerDividerColour(hourNumberPicker);
setNumberPickerDividerColour(minuteNumberPicker);
setNumberPickerDividerColour(ampmNumberPicker);
}
private void setNumberPickerDividerColour(NumberPicker number_picker){
final int count = number_picker.getChildCount();
for(int i = 0; i < count; i++){
try{
Field dividerField = number_picker.getClass().getDeclaredField("mSelectionDivider");
dividerField.setAccessible(true);
ColorDrawable colorDrawable = new ColorDrawable(mContext.getResources().getColor(R.color
.interactive_color));
dividerField.set(number_picker,colorDrawable);
number_picker.invalidate();
}
catch(NoSuchFieldException e){
Log.w("setNumberPickerTxtClr", e);
}
catch(IllegalAccessException e){
Log.w("setNumberPickerTxtClr", e);
}
catch(IllegalArgumentException e){
Log.w("setNumberPickerTxtClr", e);
}
}
}
</code></pre> |
18,257,648 | Get the current date in java.sql.Date format | <p>I need to add the current date into a prepared statement of a JDBC call. I need to add the date in a format like <code>yyyy/MM/dd</code>.</p>
<p>I've try with</p>
<pre><code>DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
pstm.setDate(6, (java.sql.Date) date);
</code></pre>
<p>but I have this error:</p>
<pre><code>threw exception
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
</code></pre>
<p>Is there a way to obtain a <code>java.sql.Date</code> object with the same format?</p> | 18,257,703 | 10 | 1 | null | 2013-08-15 16:57:03.02 UTC | 8 | 2020-11-24 09:53:09.073 UTC | 2013-08-15 17:14:53.96 UTC | null | 2,115,680 | null | 1,246,746 | null | 1 | 65 | java|jdbc|java.util.date | 267,020 | <p>A <code>java.util.Date</code> is not a <code>java.sql.Date</code>. It's the other way around. A <code>java.sql.Date</code> is a <code>java.util.Date</code>.</p>
<p>You'll need to convert it to a <code>java.sql.Date</code> by using the <a href="http://docs.oracle.com/javase/7/docs/api/java/sql/Date.html#Date%28long%29">constructor that takes a <code>long</code></a> that a <code>java.util.Date</code> can supply.</p>
<pre><code>java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
</code></pre> |
18,423,896 | Is it possible to install iOS 6 SDK on Xcode 5? | <p>Xcode 5 has a preferences pane that allow one to download iPhone 6.1 simulator, however I can't find a place where it allows downloading of iOS 6 SDK, thus it is not possible to set the active SDK to iOS 6 when developing with Xcode 5. Is there a workaround that would allow Xcode 5 to install iOS 6 SDK?</p>
<p><strong>EDIT:</strong></p>
<p>Workarounds should no longer be necessary now that Xcode 5 is generally available and allows you to download previous versions of the SDK. </p>
<p><img src="https://i.stack.imgur.com/Ihgmd.png" alt="enter image description here"></p> | 18,424,373 | 15 | 5 | null | 2013-08-24 22:43:42.24 UTC | 129 | 2014-04-10 14:20:14.503 UTC | 2014-02-21 09:19:31.98 UTC | null | 235,297 | null | 692,499 | null | 1 | 250 | ios|xcode|ios6|xcode5 | 134,762 | <p>EDIT: Starting Feb 1, 2014, Apple will no longer accept pre-iOS7 apps for submission to App Store. So while this technique still works, it will not be useful for most readers.</p>
<hr>
<p>Yes, this is fine. I still build with iOS 4.3 for one project (it's been awhile since we updated; but they still accepted it after iOS 6 came out), and I currently build 10.5 apps with Xcode 5.</p>
<p>See <a href="https://stackoverflow.com/questions/11424920/how-to-point-xcode-to-my-10-6-sdk-so-it-can-be-used-as-a-base-sdk/11424966">How to point Xcode to an old SDK so it can be used as a "Base SDK"?</a> for details on how to set it up. You can use my <a href="https://gist.github.com/rnapier/3370649" rel="nofollow noreferrer">fix-xcode</a>
script to link everything for you every time you upgrade.</p>
<p>The only trick is getting the old SDKs. If you don't have them, you generally need to download old versions of Xcode (still available on <a href="http://developer.apple.com" rel="nofollow noreferrer">developer.apple.com</a>), open the installer package, and hunt around to find the SDK you need.</p>
<p>SDKs can be found within the installer package at:</p>
<blockquote>
<p>Xcode.app/Contents/Developer/Platforms/</p>
</blockquote> |
27,683,759 | Explain the syntax of Collections.<String>emptyList() | <p>I just studied about generic programming, the <code>List<E></code> interface, and <code>ArrayList</code>, so I can understand the statement below.</p>
<pre><code>ArrayList<String> list = new ArrayList<String>();
</code></pre>
<p>But I don't understand the next statement which I saw while surfing the web.</p>
<pre><code>List<String> list2 = Collections.<String>emptyList();
</code></pre>
<ol>
<li>What is <code>Collections</code>? Why isn't it <code>Collections<E></code> or <code>Collections<String></code>?</li>
<li>Why is <code><String></code> placed before the method name <code>emptyList</code>?</li>
</ol>
<p>(Isn't <code>emptyList<String>()</code> correct for Generic?)</p>
<ol start="3">
<li>What does the statement mean?</li>
</ol> | 27,684,040 | 5 | 8 | null | 2014-12-29 05:18:20.64 UTC | 11 | 2014-12-31 20:45:50.8 UTC | 2014-12-30 04:11:23.17 UTC | null | 1,813,853 | null | 4,397,753 | null | 1 | 71 | java|generics|collections | 5,484 | <p>That line creates an empty list of strings by calling a static method with a generic type parameter.</p>
<p>Inside the <code>Collections</code> class, there is a static method <code>emptyList</code> declared like:</p>
<pre><code>public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
</code></pre>
<p>This has a generic type parameter <code>T</code>. We call call this method by using:</p>
<pre><code>List<String> list = Collections.emptyList();
</code></pre>
<p>and <code>T</code> is infered to be a <code>String</code> because of the type of <code>list</code>.</p>
<p>We can also specify the type of <code>T</code> by putting it in angle brackets when calling <code>emptyList</code>. This may be needed if we want a more specific type than is inferred:</p>
<pre><code>List<? extends Object> list = Collections.<String>emptyList();
</code></pre>
<p><code>emptyList<String>()</code> is not correct because that placement is only valid when creating
instances of generic classes, not calling methods. When using <code>new</code> there are two possible
type parameters, the ones before the class name are for the constructor only, and the ones after the class name are for the whole instance, so with the class:</p>
<pre><code>class MyClass<A> {
public <B> MyClass(A a, B b) {
System.out.println(a + ", " + b);
}
}
</code></pre>
<p>We can call its constructor where <code>A</code> is <code>String</code> and <code>B</code> is <code>Integer</code> like:</p>
<pre><code>MyClass<String> a = new <Integer>MyClass<String>("a", 3);
</code></pre>
<p>or by using type inference:</p>
<pre><code>MyClass<String> a = new MyClass<>("a", 3);
</code></pre>
<p><strong>See also:</strong></p>
<ul>
<li><a href="http://docs.oracle.com/javase/tutorial/java/generics/methods.html" rel="noreferrer">Generic Methods</a></li>
<li><a href="http://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html" rel="noreferrer">Type Inference</a></li>
</ul> |
15,116,460 | Search with grep for two expressions at once | <p>This is basic but I am unable to google it. Can I use on invokation of grep to do</p>
<pre><code>grep expr1 | grep expr2
</code></pre>
<p>so that it prints lines including both expr1 and expr2?</p> | 15,116,545 | 4 | 1 | null | 2013-02-27 15:53:52.597 UTC | 4 | 2018-04-17 14:28:43.493 UTC | null | null | null | null | 1,269,040 | null | 1 | 35 | bash|grep | 42,882 | <p>Try this:</p>
<p><code>grep 'expr1.*expr2\|expr2.*expr1'</code></p>
<p>That's a little more complicated than it needs to be if you know that "expr2" will always come after "expr1". In that case, you could simplify it to:</p>
<p><code>grep 'expr1.*expr2'</code></p> |
15,064,796 | Eclipse file search finds the same file multiple times | <p>In Eclipse I have two maven projects A and B, where A is a parent for B. The directory structure is the following:</p>
<pre><code>A/pom.xml
A/B/pom.xml
A/B/...
</code></pre>
<p>Then I use File search (Ctrl+H) to find any file in the project B. The search result window shows the file two times with different relative paths:</p>
<pre><code>A/B/<my_file>
B/<my_file>
</code></pre>
<p>So, the same file is shown <strong>twice</strong>. Obviously, the first search result is reduntant. Is there a way to exclude these duplicate search results?</p> | 15,067,818 | 11 | 6 | null | 2013-02-25 10:25:51.83 UTC | 14 | 2021-12-16 22:26:29.737 UTC | 2013-02-25 11:03:53.513 UTC | null | 706,317 | null | 706,317 | null | 1 | 37 | eclipse|maven | 11,041 | <p>What I personally do to avoid this is marking each module in the parent project as <em>derived</em> (right-click on the folder > properties > Attributes: Derived).</p>
<p>Then when you perform a file search, uncheck "Consider derived resources" (I don't think it is checked by default) and you won't get the <code>A/B/<my_file></code>.</p>
<p>The only inconvenience is that you must do this for each module, and each time a new module is added.</p> |
14,942,081 | Detect if a browser in a mobile device (iOS/Android phone/tablet) is used | <p>Is there a way to detect if a handheld browser is used (iOS/Android phone/tablet)?</p>
<p>I tried this with the goal to make an element half as wide in a browser on a handheld device but it doesn't make a difference.</p>
<pre><code>width: 600px;
@media handheld { width: 300px; }
</code></pre>
<p>Can it be done and if so how?</p>
<p><strong>edit:</strong> From the referred page in jmaes' answer I used</p>
<p><code>@media only screen and (max-device-width: 480px)</code>.</p> | 14,942,185 | 10 | 3 | null | 2013-02-18 17:35:00.73 UTC | 25 | 2022-08-09 18:49:37.92 UTC | 2013-02-18 20:14:50.733 UTC | null | 1,257,965 | null | 1,257,965 | null | 1 | 75 | css|media-queries | 213,654 | <p><strong>Update (June 2016)</strong>: I now try to support touch and mouse input on every resolution, since the device landscape is slowly blurring the lines between what things are and aren't touch devices. iPad Pros are touch-only with the resolution of a 13" laptop. Windows laptops now frequently come with touch screens.</p>
<p>Other similar SO answers (see other answer on this question) might have different ways to try to figure out what sort of device the user is using, but none of them are fool-proof. I encourage you to check those answers out if you absolutely need to try to determine the device.</p>
<hr>
<p>iPhones, for one, ignore the <code>handheld</code> query (<a href="https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/OptimizingforSafarioniPhone.html" rel="noreferrer">Source</a>). And I wouldn't be surprised if other smartphones do, too, for similar reasons.</p>
<p>The current best way that I use to detect a mobile device is to know its width and use the <a href="http://css-tricks.com/snippets/css/media-queries-for-standard-devices/" rel="noreferrer">corresponding media query</a> to catch it. That link there lists some popular ones. A quick Google search would yield you any others you might need, I'm sure.</p>
<p>For more iPhone-specific ones (such as Retina display), check out that first link I posted.</p> |
15,091,300 | POSTing JSON to URL via WebClient in C# | <p>I have some JavaScript code that I need to convert to C#. My JavaScript code POSTs some JSON to a web service that's been created. This JavaScript code works fine and looks like the following:</p>
<pre><code>var vm = { k: "1", a: "2", c: "3", v: "4" };
$.ajax({
url: "http://www.mysite.com/1.0/service/action",
type: "POST",
data: JSON.stringify(vm),
contentType: "application/json;charset=utf-8",
success: action_Succeeded,
error: action_Failed
});
function action_Succeeded(r) {
console.log(r);
}
function log_Failed(r1, r2, r3) {
alert("fail");
}
</code></pre>
<p>I'm trying to figure out how to convert this to C#. My app is using .NET 2.0. From what I can tell, I need to do something like the following:</p>
<pre><code>using (WebClient client = new WebClient())
{
string json = "?";
client.UploadString("http://www.mysite.com/1.0/service/action", json);
}
</code></pre>
<p>I'm a little stuck at this point. I'm not sure what <code>json</code> should look like. I'm not sure if I need to set the content type. If I do, I'm not sure how to do that. I also saw <code>UploadData</code>. So, I'm not sure if I'm even using the right method. In a sense, the serialization of my data is my problem. </p>
<p>Can someone tell me what I'm missing here?</p>
<p>Thank you!</p> | 15,091,622 | 3 | 0 | null | 2013-02-26 14:14:45.323 UTC | 26 | 2020-11-11 12:31:42.98 UTC | null | null | null | null | 2,107,803 | null | 1 | 99 | c#|webclient | 202,636 | <p>You need a json serializer to parse your content, probably you already have it,
for your initial question on how to make a request, this might be an idea:</p>
<pre><code>var baseAddress = "http://www.example.com/1.0/service/action";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
</code></pre>
<p>hope it helps,</p> |
48,077,890 | Laravel Eloquent: multiple foreign keys for relationship | <p>I am in the process of porting a project to Laravel.</p>
<p>I have two database tables which are in a One-To-Many relationship with each other. They are joined by three conditions. How do I model this relationship in Eloquent? </p>
<p>I am not supposed to modify the database schema, since it has to remain backwards compatible with other things.</p>
<p>I have tried the following, but it doesn't work.</p>
<p>The owning side:</p>
<pre><code>use Illuminate\Database\Eloquent\Model;
class Route extends Model
{
public function trips()
{
return $this->hasMany('Trip', 'route_name,source_file', 'route_name,source_file')
}
}
</code></pre>
<p>The inverse side:</p>
<pre><code>use Illuminate\Database\Eloquent\Model;
class Trip extends Model
{
public function routes()
{
return $this->belongsTo('Route', 'route_name,source_file', 'route_name,source_file');
}
}
</code></pre>
<p>Example <code>Route</code> database values:</p>
<pre><code>id | route_name | source_file
---------------------------------------
1 | Berlin - Paris | file1.xls
2 | Madrid - London| file2.xls
3 | Berlin - Paris | file3.xls
</code></pre>
<p>Example <code>Trip</code> database values:</p>
<pre><code>id | route_name | source_file | duration
---------------------------------------------------------
1 | Berlin - Paris | file1.xls | 78
2 | Madrid - London | file2.xls | 241
3 | Berlin - Paris | file3.xls | 65
1 | Berlin - Paris | file1.xls | 95
1 | Berlin - Paris | file1.xls | 65
</code></pre>
<p><code>Route</code> and <code>Trip</code> have other attributes, which I did not include here for brevity.</p>
<p>Is this possible in Eloquent?</p> | 49,834,070 | 3 | 4 | null | 2018-01-03 12:57:34.153 UTC | 5 | 2018-05-16 17:47:01.473 UTC | 2018-01-03 13:36:31.283 UTC | null | 277,106 | null | 277,106 | null | 1 | 28 | laravel|eloquent | 54,046 | <p>I had to deal with a similar problem. The solution provided by @fab won't work with eager loading because <em>$this->source_fil</em>e would be <em>null</em> at the time the relationship is processed. I came up with <a href="https://github.com/topclaudy/compoships" rel="noreferrer">this solution</a></p>
<p>After installing <a href="https://github.com/topclaudy/compoships" rel="noreferrer">Compoships</a> and configuring it in your models, you can define your relationships matching multiple columns.</p>
<p>The owning side:</p>
<pre><code>use Illuminate\Database\Eloquent\Model;
use Awobaz\Compoships\Compoships;
class Route extends Model
{
use Compoships;
public function trips()
{
return $this->hasMany('Trip', ['id', 'route_name', 'source_file'], ['route_id', 'route_name', 'source_file']);
}
}
</code></pre>
<p>The inverse side:</p>
<pre><code>use Illuminate\Database\Eloquent\Model;
use Awobaz\Compoships\Compoships;
class Trip extends Model
{
use Compoships;
public function route()
{
return $this->belongsTo('Route', ['route_id', 'route_name', 'source_file'], ['id', 'route_name', 'source_file']);
}
}
</code></pre>
<p>Compoships supports eager loading.</p> |
8,948,918 | Performance 32 bit vs. 64 bit arithmetic | <p>Are native <code>64 bit</code> integer arithmetic instructions slower than their <code>32 bit</code> counter parts (on <code>x86_64</code> machine with <code>64 bit</code> OS)?</p>
<p>Edit: On current CPUs such Intel Core2 Duo, i5/i7 etc.</p> | 8,948,936 | 3 | 3 | null | 2012-01-20 22:57:59.833 UTC | 2 | 2021-02-02 03:58:38.493 UTC | 2021-02-02 03:58:38.493 UTC | null | 224,132 | null | 684,534 | null | 1 | 35 | c++|c|linux|performance|x86-64 | 13,457 | <p>It depends on the exact CPU and operation. On 64-bit Pentium IVs, for example, multiplication of 64-bit registers was quite a bit slower. Core 2 and later CPUs have been designed for 64-bit operation from the ground up.</p>
<p>Generally, even code written for a 64-bit platform uses 32-bit variables where values will fit in them. This isn't primarily because arithmetic is faster (on modern CPUs, it generally isn't) but because it uses less memory and memory bandwidth.</p>
<p>A structure containing a dozen integers will be half the size if those integers are 32-bit than if they are 64-bit. This means it will take half as many bytes to store, half as much space in the cache, and so on.</p>
<p>64-bit native registers and arithmetic are used where values may not fit into 32-bits. But the main performance benefits come from the extra general purpose registers available in the x86_64 instruction set. And of course, there are all the benefits that come from 64-bit pointers.</p>
<p>So the real answer is that it doesn't matter. Even if you use x86_64 mode, you can (and generally do) still use 32-bit arithmetic where it will do, and you get the benefits of larger pointers and more general purpose registers. When you use 64-bit native operations, it's because you need 64-bit operations, and you know they'll be faster than faking it with multiple 32-bit operations -- your only other choice. So the relative performance of 32-bit versus 64-bit registers should never be a deciding factor in any implementation decision.</p> |
8,413,857 | Whats the smartest / cleanest way to iterate async over arrays (or objs)? | <p>Thats how I do it:</p>
<pre><code>function processArray(array, index, callback) {
processItem(array[index], function(){
if(++index === array.length) {
callback();
return;
}
processArray(array, index, callback);
});
};
function processItem(item, callback) {
// do some ajax (browser) or request (node) stuff here
// when done
callback();
}
var arr = ["url1", "url2", "url3"];
processArray(arr, 0, function(){
console.log("done");
});
</code></pre>
<p>Is it any good? How to avoid those spaghetti'ish code? </p> | 8,414,369 | 5 | 3 | null | 2011-12-07 10:30:39.5 UTC | 12 | 2021-02-16 19:05:00.593 UTC | 2011-12-07 11:03:08.817 UTC | null | 294,619 | null | 294,619 | null | 1 | 36 | javascript|node.js | 27,769 | <p>Checkout the <a href="https://github.com/caolan/async" rel="noreferrer">async</a> library, it's made for control flow (async stuff) and it has a lot of methods for array stuff: each, filter, map. Check the documentation on github. Here's what you probably need:</p>
<p><strong>each(arr, iterator, callback)</strong></p>
<p>Applies an iterator function to each item in an array, in parallel. The iterator is called with an item from the list and a callback for when it has finished. If the iterator passes an error to this callback, the main callback for the <code>each</code> function is immediately called with the error.</p>
<p><strong>eachSeries(arr, iterator, callback)</strong></p>
<p>The same as <code>each</code> only the iterator is applied to each item in the array in series. The next iterator is only called once the current one has completed processing. This means the iterator functions will complete in order.</p> |
5,202,309 | ArrayList to Array of Strings in java | <pre><code>ArrayList<String> newArray = new ArrayList<String>();
newArray = urlList.getUrl();
for( int i = 0 ; i < newArray.size();i++)
{
System.out.println(newArray.get(i));
}
newArray.toArray(mStrings );// is this correct
mStrings = newArray.toArray();// or this to convert ArrayList ot String array here
for( int i = 0 ; i < mStrings.length;i++)
{
System.out.println(mStrings[i]);
}
</code></pre>
<p><strong>EDIT:</strong> when i try as below, I get null pointer exception:</p>
<pre><code>try
{
newArray.toArray(mStrings );
for(int i = 0 ; i < mStrings.length; i++)
{
System.out.println(mStrings[i]);
}
} catch( NullPointerException e )
{
System.out.println(e);
}
</code></pre> | 5,202,331 | 5 | 3 | null | 2011-03-05 07:07:54.22 UTC | 5 | 2017-07-17 19:34:23.65 UTC | 2017-07-17 19:34:23.65 UTC | null | 3,345,644 | null | 335,997 | null | 1 | 16 | java|android | 54,481 | <p>Depends on what you want to do. Both are correct</p>
<blockquote>
<p><strong>toArray()</strong>
Returns an array containing all of the elements in this list in proper sequence (from first to last element).</p>
</blockquote>
<p>Refer <a href="http://download.oracle.com/javase/6/docs/api/java/util/List.html#toArray%28%29" rel="noreferrer">here</a></p>
<blockquote>
<p><strong>toArray(T[] a)</strong>
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. </p>
</blockquote>
<p>Refer <a href="http://download.oracle.com/javase/6/docs/api/java/util/List.html#toArray%28T[]%29" rel="noreferrer">here</a></p>
<p>In former, you want to get an array. In latter you have an array, you just wanted to fill it up.</p>
<p>In your case, first form is preferred as you just want to get an array without bothering size or details.</p>
<hr>
<p>Basically this is what happens in 2nd case:</p>
<ol>
<li>List's size is measures.</li>
<li>(a) If list size is less than that of the array provided, new Array of <em>the type provided as argument</em> is created.<br/><br/>(b)Else, the list is dumped in the specified array.</li>
</ol>
<p>The only benefit of doing so, is you avoid casting. The two form are the same. If you use Object array. i.e.</p>
<pre><code> myList.toArray() <==> toArray(new Object[0])
</code></pre>
<p>Now, If you pass an uninitialized array, you will get a NullPointerException. The best way to do it is:</p>
<pre><code> String[] y = x.toArray(new String[0]);
</code></pre>
<p><em>Please read the document</em></p> |
5,084,801 | Manhattan Distance between tiles in a hexagonal grid | <p>For a square grid the euclidean distance between tile A and B is: </p>
<pre><code>distance = sqrt(sqr(x1-x2)) + sqr(y1-y2))
</code></pre>
<p>For an actor constrained to move along a square grid, the Manhattan Distance is a better measure of actual distance we must travel:</p>
<pre><code>manhattanDistance = abs(x1-x2) + abs(y1-y2))
</code></pre>
<p>How do I get the manhattan distance between two tiles in a hexagonal grid as illustrated with the red and blue lines below?</p>
<p><img src="https://i.stack.imgur.com/Qanua.png" alt="enter image description here"></p> | 5,085,274 | 6 | 3 | null | 2011-02-22 22:30:23.457 UTC | 10 | 2019-08-09 01:17:19.797 UTC | 2015-04-10 13:10:13.16 UTC | null | 1,030,331 | null | 223,888 | null | 1 | 23 | algorithm|path|distance|hexagonal-tiles | 13,210 | <p>I once set up a hexagonal coordinate system in a game so that the <em>y</em>-axis was at a 60-degree angle to the <em>x</em>-axis. This avoids the odd-even row distinction.</p>
<p><a href="https://i.stack.imgur.com/m5cU9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/m5cU9.png" alt="Hexagonal grid"></a><br>
<sub>(source: <a href="http://althenia.net/svn/stackoverflow/hexgrid.png?usemime=1&rev=3" rel="noreferrer">althenia.net</a>)</sub> </p>
<p>The distance in this coordinate system is:</p>
<pre><code>dx = x1 - x0
dy = y1 - y0
if sign(dx) == sign(dy)
abs(dx + dy)
else
max(abs(dx), abs(dy))
</code></pre>
<p>You can convert (<em>x</em>', <em>y</em>) from your coordinate system to (<em>x</em>, <em>y</em>) in this one using:</p>
<pre><code>x = x' - floor(y/2)
</code></pre>
<p>So <code>dx</code> becomes:</p>
<pre><code>dx = x1' - x0' - floor(y1/2) + floor(y0/2)
</code></pre>
<p>Careful with rounding when implementing this using integer division. In C for <code>int y</code> <code>floor(y/2)</code> is <code>(y%2 ? y-1 : y)/2</code>.</p> |
4,997,219 | Disable Maven central repository | <p>My company's policy frowns upon artifacts downloaded automatically (they have to be approved), so in order to use Maven I need to disable access to Maven's central repository. </p>
<p>In other words, I don't want Maven to attempt <strong>any</strong> downloads from central.</p>
<p>I know how to configure a local repository (networked or not), my idea is using a "blessed" machine to update the local repository.</p>
<p>PS: I could block requests at the proxy/network level, but I'm asking about how to do it with Maven's configuration.</p>
<p><strong>UPDATE</strong>
I finally figured out how to do it. In maven's home, in the <code>conf</code> directory is a global <code>settings.xml</code>.
You can either set a mirror to <code>central</code> that points to some internal server or just override it's definition.</p> | 4,997,553 | 7 | 0 | null | 2011-02-14 21:01:03.763 UTC | 24 | 2021-02-14 09:20:07.533 UTC | 2011-06-26 17:10:26.227 UTC | null | 190,223 | null | 190,223 | null | 1 | 73 | configuration|maven|repository | 84,760 | <p>Agreed. No direct downloads from external repositories should be allowed in your release builds.</p>
<p>The specific answer to your question is the second part of my answer :-)</p>
<h1>Setup a repository manager</h1>
<p>I'd recommend setting up a local Maven repository manager. Good options are the following:</p>
<ul>
<li><a href="https://sonatype.com/nexus/repository-oss" rel="noreferrer">Nexus</a></li>
<li><a href="https://jfrog.com/artifactory/" rel="noreferrer">Artifactory</a></li>
<li><a href="https://archiva.apache.org/" rel="noreferrer">Archiva</a></li>
<li><a href="https://reposilite.com/" rel="noreferrer">Reposilite</a></li>
</ul>
<p>All of these are capable of acting as a caching proxy for the externally available Maven central jars.</p>
<p>You might also be interested in the Profession version of Nexus. It includes a <a href="https://www.sonatype.com/nexus-professional---features.html" rel="noreferrer">Procurement suite</a> for managing external libraries. It also provides Maven plugins for centrally managing the Maven settings file, which is the second part of my answer...</p>
<h1>Local Maven settings</h1>
<p>Update the <a href="https://maven.apache.org/settings.html" rel="noreferrer">settings file</a> located in the following directory:</p>
<p>$HOME/.m2/settings.xml</p>
<p>Specify that all central requests should be redirected to the local Maven repository:</p>
<pre><code><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
...
<mirrors>
<mirror>
<id>central-proxy</id>
<name>Local proxy of central repo</name>
<url>http://<hostname>/central</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
...
</settings>
</code></pre> |
4,928,680 | Running multiple instances of Rails Server | <p>I am new to Rails, so please forgive me if this is obvious.</p>
<p>I am doing a lot of experimenting, creating to applications, testing features, etc. It got my first scaffolded app running great, but I wanted to create a second app to test a different feature. </p>
<p>I backed up a folder level on my computer, ran <code>$ rails new taskmaster</code> (a test to-do list app). I ran the scaffolding for the <code>Task</code> model, fired up the server via <code>$ rails server</code>, and attempted to load <code>http://localhost:3000</code>. </p>
<p>But I got a routing error, saying it couldn't find the <code>"members"</code> route. But <code>members</code> was from my first Rails app! I thought by firing off <code>$ rails server</code> in the <code>taskmaster</code> directory, it would startup the server for that application.</p>
<p>How do I tell the Rails server which application to serve up?</p>
<p><strong>UPDATE</strong></p>
<p>I just discovered that if I:</p>
<ol>
<li>Roll back to the fresh install of the <em>first</em> Rails app, before I created the Member scaffold</li>
<li>Fire up the rails server via <code>$ rails server</code> in the application's root directory</li>
<li>Check <code>http://localhost:3000</code></li>
</ol>
<p>It still attempts to go for the <code>members</code> route, the one that no longer exists because I rolled back via git.</p>
<p>I'm guessing this means something in my <code>/usr/local/</code> area, relating to my Ruby and Rails initial installs, is mainatining this info (my apps are setup in my Documents folder in my home dir). </p>
<p>I thought that Rails apps were essentially self contained apps inside the directory - you just needed a working Ruby install to get them going. Does the Rails server sit inside each app directory, or is the some overarching Rails server that accommodates all apps?</p> | 5,000,570 | 8 | 0 | null | 2011-02-08 01:23:49.46 UTC | 8 | 2018-11-16 10:56:43.337 UTC | 2011-02-08 01:40:26.12 UTC | null | 381,443 | null | 381,443 | null | 1 | 39 | ruby-on-rails | 41,792 | <p>Thanks for all your help - turns out it was a rather strange occurrence. Somehow, my entire project folder got copied into the Trash. When I started the server, I was starting the server instance in the Trash copy, while the copy I rolled back and edited stay in the same place. Not sure how that happened (perhaps it relates to git, another tool I am just learning). In any case, thanks for all the help, sorry it was something so simple!</p> |
5,083,914 | Get the whole response body when the response is chunked? | <p>I'm making a HTTP request and listen for "data":</p>
<pre><code>response.on("data", function (data) { ... })
</code></pre>
<p>The problem is that the response is chunked so the "data" is just a piece of the body sent back.</p>
<p>How do I get the whole body sent back?</p> | 5,084,049 | 8 | 1 | null | 2011-02-22 21:01:05.137 UTC | 11 | 2022-05-24 17:10:28.383 UTC | 2011-02-22 21:24:53.4 UTC | null | 112,196 | null | 206,446 | null | 1 | 54 | http|node.js | 56,546 | <pre><code>request.on('response', function (response) {
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
console.log('BODY: ' + body);
});
});
request.end();
</code></pre> |
5,217,721 | How to Remove Array Element and Then Re-Index Array? | <p>I have some troubles with an array. I have one array that I want to modify like below. I want to remove element (elements) of it by index and then re-index array. Is it possible?</p>
<pre><code>$foo = array(
'whatever', // [0]
'foo', // [1]
'bar' // [2]
);
$foo2 = array(
'foo', // [0], before [1]
'bar' // [1], before [2]
);
</code></pre> | 5,217,738 | 8 | 0 | null | 2011-03-07 09:04:20.697 UTC | 37 | 2021-02-16 16:12:55.59 UTC | null | null | null | null | 458,610 | null | 1 | 232 | php|arrays|indexing | 201,689 | <pre><code>unset($foo[0]); // remove item at index 0
$foo2 = array_values($foo); // 'reindex' array
</code></pre> |
17,120,505 | Error: "A field or property with the name was not found on the selected data source" get only on server | <p>I publish my project without any warning on local iis and it works correctly (localhost/[myprojectName]). so, i upload them to server with cute ftp. but in server i get this error apear for all my filed like [tableName].[filedName]:</p>
<blockquote>
<p>A field or property with the name <strong>'ConfirmStatuse.Name'</strong> was not found
on the selected data source</p>
</blockquote>
<p>here's my code:</p>
<pre><code><asp:GridView ID="ordergv" runat="server" DataKeyNames="Id" AutoGenerateColumns="False" DataSourceID="SummaryOfOrderSrc" AllowSorting="True">
<Columns>
<asp:CommandField SelectText="select" ShowSelectButton="True" ButtonType="Button"/>
<asp:BoundField DataField="OrderId" />
<asp:BoundField DataField="ConfirmStatuse.Name" />
<asp:BoundField DataField="OrderStatuse.Name"/>
<asp:BoundField DataField="PaymentStatuse.Name"/>
<asp:BoundField DataField="ShipmentStatuse.Name" />
<asp:TemplateField >
<ItemTemplate>
<asp:Label ID="CreatedDateLabel" runat="server" Text='<%# GetPersianDate( Eval("CreatedDate")) %>' /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="SummaryOfOrderSrc" runat="server" ContextTypeName="Ahooratech.DAL.DataClasses1DataContext" EntityTypeName="" OrderBy="CreatedDate desc" TableName="Orders">
</asp:LinqDataSource>
</code></pre>
<p>I check the size of my project in local iis and on server. both of them are same(8,459,009 bytes)</p>
<p>so it means i use same database and same files for run my application for run on local and server. so why i get this error only in server?</p>
<p>The only difference here is on version of iis, i think my server iis version is 7.0. but is it important for i get this error?!!! i don't think so. i'm really confused. </p>
<p>(My local project and server project use same connection string).</p>
<p>EDIT: I publish project on another host and it works! but it doesn't work on my original server yet. </p> | 17,121,067 | 4 | 9 | null | 2013-06-15 05:30:11.59 UTC | 2 | 2017-08-11 22:56:48.623 UTC | 2013-06-15 06:26:14.257 UTC | null | 775,110 | null | 775,110 | null | 1 | 6 | asp.net|.net-4.0|iis-7.5|sql-server-2012 | 46,557 | <p>I found the IIS Version on my server is 6. but my local is 7.5.
I publish my project on another server with iis 7.5 and it works</p>
<p><strong>Solution1</strong>: I create a summaryOfOrder like this:</p>
<pre><code>class summaryOfOrder
{
public int Id { get; set; }
public int OrderId { get; set; }
public string ConfirmStatusName { get; set; }
public string OrderStatusName { get; set; }
public string PaymentStatusName { get; set; }
public string ShippingStatusName { get; set; }
public string CreatedDate { get; set; }
}
</code></pre>
<p>and change </p>
<pre><code><asp:BoundField DataField="ConfirmStatuse.Name" />
</code></pre>
<p>to </p>
<pre><code><asp:BoundField DataField="ConfirmStatusName" />
</code></pre>
<p>and bind class to grid by</p>
<pre><code>gv.datasource = mySummryOfOrder;
gv.databind();
</code></pre>
<p>and initialize a list of this type and bind it to grid programmatically</p>
<p><strong>Update solution 2</strong> convert </p>
<blockquote>
<p>asp:BoundField</p>
</blockquote>
<p>to </p>
<blockquote>
<p>asp:TemplateField
and using</p>
</blockquote>
<pre><code><%# Eval("Worker.FullName")%>
</code></pre> |
29,655,652 | How to make both header and footer in collection view with swift | <p>How to make both header and footer in collection view in swift ?</p>
<p>I'm trying to combine a header and a footer together but it keep crashing, I couldn't find swift tutorial to understand it.</p>
<p>I don't how to return supplementary view for both rather just one .</p>
<p>I set them both on the storyboard (class + identifier ) </p>
<pre><code> override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
return 2
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return 10
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
var header: headerCell!
var footer: footerCell!
if kind == UICollectionElementKindSectionHeader {
header =
collectionView.dequeueReusableSupplementaryViewOfKind(kind,
withReuseIdentifier: "header", forIndexPath: indexPath)
as? headerCell
}
return header
}
</code></pre>
<blockquote>
<p><strong>Error:</strong>
UICollectionElementKindCell with identifier one - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'</p>
</blockquote>
<pre><code>override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> profileCC {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("one", forIndexPath: indexPath) as! profileCC
// Configure the cell
return cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath) as! headerCell
headerView.backgroundColor = UIColor.blueColor();
return headerView
case UICollectionElementKindSectionFooter:
let footerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "footer", forIndexPath: indexPath) as! footerCell
footerView.backgroundColor = UIColor.greenColor();
return footerView
default:
assert(false, "Unexpected element kind")
}
}
</code></pre>
<p>I hope someone will help.</p> | 29,656,061 | 10 | 5 | null | 2015-04-15 16:23:00.003 UTC | 23 | 2022-02-10 12:24:03.4 UTC | 2015-04-15 18:20:09.493 UTC | null | 2,695,387 | null | 4,783,618 | null | 1 | 69 | ios|swift|uicollectionview | 119,167 | <p>You can make an <code>UICollectionViewController</code> to handle the <code>UICollectionView</code> and in Interface Builder activate the <em>Footer</em> and <em>Header</em> sections, then you can use the following method for preview in you <code>UICollectionView</code> the two sections added :</p>
<pre><code>override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath)
headerView.backgroundColor = UIColor.blue
return headerView
case UICollectionView.elementKindSectionFooter:
let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPath)
footerView.backgroundColor = UIColor.green
return footerView
default:
assert(false, "Unexpected element kind")
}
}
</code></pre>
<p>In the above code I put the <code>identifier</code> for the footer and header as <code>Header</code> and <code>Footer</code> for example, you can do it as you want. If you want to create a custom header or footer then you need to create a subclass of <code>UICollectionReusableView</code> for each and customize it as you want.</p>
<p>You can register your custom footer and header classes in Interface Builder or in code with:</p>
<pre><code>registerClass(myFooterViewClass, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "myFooterView")
</code></pre> |
12,519,290 | Downloading files using FtpWebRequest | <p>I'm trying to download a file using <code>FtpWebRequest</code>.</p>
<pre><code>private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
{
int bytesRead = 0;
byte[] buffer = new byte[1024];
FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, true);
request.Method = WebRequestMethods.Ftp.DownloadFile;
Stream reader = request.GetResponse().GetResponseStream();
BinaryWriter writer = new BinaryWriter(File.Open(localDestinationFilePath, FileMode.CreateNew));
while (true)
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
writer.Write(buffer, 0, bytesRead);
}
}
</code></pre>
<p>It uses this <code>CreateFtpWebRequest</code> method I created:</p>
<pre><code>private FtpWebRequest CreateFtpWebRequest(string ftpDirectoryPath, string userName, string password, bool keepAlive = false)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirectoryPath));
//Set proxy to null. Under current configuration if this option is not set then the proxy that is used will get an html response from the web content gateway (firewall monitoring system)
request.Proxy = null;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = keepAlive;
request.Credentials = new NetworkCredential(userName, password);
return request;
}
</code></pre>
<p>It downloads it. But the information is always corrupted. Anyone know what's going on?</p> | 12,520,382 | 2 | 0 | null | 2012-09-20 19:09:53.833 UTC | 8 | 2022-01-19 18:31:43.333 UTC | 2022-01-19 18:31:43.333 UTC | null | 850,848 | null | 1,214,566 | null | 1 | 11 | c#|.net|c#-4.0|ftp|ftpwebrequest | 61,189 | <p>Just figured it out:</p>
<pre><code> private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
{
int bytesRead = 0;
byte[] buffer = new byte[2048];
FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, true);
request.Method = WebRequestMethods.Ftp.DownloadFile;
Stream reader = request.GetResponse().GetResponseStream();
FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create);
while (true)
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
fileStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}
</code></pre>
<p>Had to use a FileStream instead.</p> |
12,305,318 | How to handle the generic type Object with protocol buffers, in the .proto file? | <p>I've spent some time looking for some alternative to handle generic objects, I've seen questions similar to mine, but not as specific I suppose?
Protocol buffers has multiple scalar types that I can use, however they are mostly primitive.
I want my message to be flexible and be able to have a field that is a List of some sort.</p>
<p>Let's say my .proto file looked like this:</p>
<pre><code> message SomeMessage
{
string datetime = 1;
message inputData // This would be a list
{
repeated Object object = 1;
}
message Object
{
? // this need to be of a generic type - This is my question
// My work around - Using extentions with some Object
//List all primitive scalar types as optional and create an extension 100 to max;
}
message someObject //some random entity - for example, employee/company etc.
{
optional string name = 1; optional int32 id = 2;
}
extend Object
{
optional someObject obj = 101;
}
}
</code></pre>
<p>And this would be fine, and would work, and I'd have a List where Objects could be of any primitive type or could be List < someObject >.
However- The problem here, is that any time I needed to handle a new type of object, I'd need to edit my .proto file, recompile for C# and java (The languages I need it for)...</p>
<p>If protocol buffers is not able to handle generic object types, is there another alternative that can?
Any help on this matter is greatly appreciated.</p> | 12,574,677 | 4 | 3 | null | 2012-09-06 17:27:03.513 UTC | 8 | 2019-01-08 11:10:12.613 UTC | null | null | null | null | 1,292,233 | null | 1 | 16 | object|protocol-buffers|generic-list | 30,565 | <p>As Marc Gravell stated above - Protocol Buffers do not handle generics or inheritance.</p> |
12,270,906 | Why do we need web-services? How different is it from normal web-applications? | <p>Just started with web-services so pardon me if my question sounds stupid.</p>
<p>Why do we need web-services? How are they different from normal web applications?</p>
<p>Two uses have been mentioned in many of the tutorials. One is the <em>communication between different machines/applications</em>, which sounds fine. But the next one is <em>to develop reusable application components</em>. My question is, do we need web services for that purpose?</p>
<p>For Eg: A Currency converter can be implemented as a web service and it can be published on a url. But then, the same can be created as a web-application. Where is the actual advantage of using web-services?</p>
<p>Also as per some posts in SO, webservices should be used if no UI is involved and web-applications if a gui is required. Is the choice all that simple?</p>
<p>Note: Here I'm referring to SOAP based web-service. RESTful ones might be different.</p> | 12,271,010 | 4 | 0 | null | 2012-09-04 20:29:18.067 UTC | 14 | 2019-09-09 09:38:01.78 UTC | 2012-12-25 11:04:54.943 UTC | user966588 | null | null | 1,131,384 | null | 1 | 29 | web-services|web-applications|soap | 49,772 | <p>Web services (esp SOAP) are designed to be consumed / read / used by other programs. If you've ever had to write a "screen scrape" program (i.e., operate a web application and pick out the data you need from all the goo that makes the page pretty and friendly for the user) you'll appreciate the structure.</p>
<blockquote>
<p>Also as per some posts in SO, webservices should be used if no UI is involved and web-applications if a gui is required. Is the choice all that simpe?</p>
</blockquote>
<p>In a nutshell, "yes".</p> |
12,566,493 | How can I assign inserted output value to a variable in sql server? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/5558582/sql-server-output-clause-into-a-scalar-variable">SQL Server Output Clause into a scalar variable</a> </p>
</blockquote>
<pre><code>DECLARE @id int
INSERT INTO MyTable(name)
OUTPUT @id = Inserted.id
VALUES('XYZ')
</code></pre>
<p>I am trying like above. How is it possible?</p> | 12,566,529 | 2 | 0 | null | 2012-09-24 13:53:03.197 UTC | 15 | 2012-09-24 14:55:31.067 UTC | 2017-05-23 11:47:32.423 UTC | null | -1 | null | 1,378,999 | null | 1 | 45 | sql|sql-server|sql-server-2008 | 79,873 | <p>Use table variable to get id </p>
<pre><code>DECLARE @id int
DECLARE @table table (id int)
INSERT INTO MyTable(name)
OUTPUT inserted.id into @table
VALUES('XYZ')
SELECT @id = id from @table
</code></pre> |
12,170,357 | Dynamically add a class to Bootstrap's 'popover' container | <p>I've thoroughly searched through both StackOverflow and Google, but come up empty. So apologies in advance if this has been asked & resolved already.</p>
<p><strong>NB:</strong> I'm a newbie at jQuery, so I'm not sure how to write this up myself. I'm sure this is an easy snippet of code, but can't wrap my head around it.</p>
<p>What I'm looking to do is use a <code>data-</code> element (eg: <code>data-class</code> or similar) to attach a new class (Or ID, I'm not picky anymore!) to the top-level popover <code><div></code>. The code I currently have is as follows:</p>
<p><em>jQuery:</em></p>
<pre><code>$('a[rel=popover]')
.popover({
placement : 'bottom',
trigger : 'hover'
})
.click(function(e) {
e.preventDefault()
});
</code></pre>
<p><em>HTML:</em></p>
<pre><code><a href="" rel="popover" data-class="dynamic-class" title="Title goes here" data-content="Content goes here">
</code></pre>
<p>And ideally the kind of HTML I would have spit out, is something like this:</p>
<pre><code><div class="popover ... dynamic-class">
<!-- remainder of the popover code as per usual -->
</div>
</code></pre>
<p>Is this something I can do? The documentation on the bootstrap site for popovers is a bit sparse, so it's taken me a while just to get to this point, unfortunately :(</p>
<p>Thanks in advance for any & all responses!</p> | 18,717,425 | 22 | 2 | null | 2012-08-29 03:04:45.733 UTC | 26 | 2020-06-15 09:12:21.523 UTC | null | null | null | null | 271,602 | null | 1 | 75 | jquery|css|twitter-bootstrap | 90,855 | <p>You can do this without hacking Bootstrap and without changing the template either, by grabbing the popover object from the caller's <code>data</code> and accessing its <code>$tip</code> property.</p>
<pre><code>$('a[rel=popover]')
.popover({ placement: 'bottom', trigger: 'hover' })
.data('bs.popover')
.tip()
.addClass('my-super-popover');
</code></pre> |
12,596,199 | Android : How to set onClick event for Button in List item of ListView | <p>I want to add <code>onClick</code> event for buttons used in item of <code>Listview</code>.
How can I give <code>onClick</code> event for buttons in List Item.</p> | 12,596,232 | 10 | 4 | null | 2012-09-26 06:58:42.78 UTC | 24 | 2018-08-06 22:10:26.94 UTC | 2018-03-04 03:11:31.277 UTC | null | 4,505,446 | null | 1,534,789 | null | 1 | 82 | android|listview | 204,646 | <p>You can set the <code>onClick</code> event in your custom adapter's <code>getView</code> method..<br>
check the link <a href="http://androidforbeginners.blogspot.it/2010/03/clicking-buttons-in-listview-row.html">http://androidforbeginners.blogspot.it/2010/03/clicking-buttons-in-listview-row.html</a></p> |
19,234,654 | iOS 7 Core Bluetooth Peripheral running in background | <p>What I want is for my iOS device to be advertising a Bluetooth LE service all the time, even when the app isn't running, so that I can have another iOS device scan for it and find it. I have followed Apple's backgrounding instructions here:</p>
<p><a href="https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/PerformingCommonPeripheralRoleTasks/PerformingCommonPeripheralRoleTasks.html#//apple_ref/doc/uid/TP40013257-CH4-SW1">https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/PerformingCommonPeripheralRoleTasks/PerformingCommonPeripheralRoleTasks.html#//apple_ref/doc/uid/TP40013257-CH4-SW1</a>. </p>
<p>I can get it to advertise in the foreground ok and sometimes in the background but it doesn't stay advertising all the time. If you have it setup to run in the background, shouldn't it start advertising even after a device restart, just like background location services automatically start working after a restart? Are their limitations to the backgrounding that are not listed (or hard to find) in Apple's docs? Does anyone have an example of a Core Bluetooth Peripheral advertising correctly in the background?</p>
<p>Thanks...</p> | 19,247,912 | 2 | 6 | null | 2013-10-07 20:59:09.07 UTC | 10 | 2018-03-07 17:18:02.36 UTC | null | null | null | null | 224,023 | null | 1 | 14 | objective-c|bluetooth|ios7|core-bluetooth|bluetooth-lowenergy | 11,516 | <p>Background advertisement is possible if you add the <code>bluetooth-peripheral</code> backgrounding mode to the app's plist. Once you do that, your app will continue to receive the callbacks even if backgrounded.</p>
<p>The advertisement is a tricky beast as Apple implemented several optimizations to reduce the power consumption and these reduce the quality of the advertisement as soon as the app is backgrounded. Namely: the rate is reduced severely, the advertised services are not included and the local name is not included either. Once the app comes back to foreground, these restrictions are invalidated.</p>
<p>In the general case, this kind of backgrounded operation requires the app to be running. With iOS 7 the restoration process has been implemented that allows the OS to act on the app's behalf while it is terminated and restore the app when some transmission or other operation is imminent. This requires you to add the restoration key to the initialization options of the <code>CBPeripheralManager</code>/<code>CBCentralManager</code>. Starting your application once is still required but after that, iOS will continue to act as the BLE facade towards the centrals/peripherals.</p>
<p><strong>UPDATE</strong>: I ran a loop on the Apple bluetooth-dev list as well with this question and found that Core Bluetooth managers were <a href="http://lists.apple.com/archives/bluetooth-dev/2013/Oct/msg00029.html" rel="noreferrer">declared to be not able to restore after reboot</a>. This is not described in any documentation but probably was mentioned in the WWDC videos. We should file a bug and replicate it to raise Apple's awareness.</p> |
24,416,930 | Java Malformed URL Exception | <p>I'm trying to make an http POST request in an android app I'm building, but no matter what url I use for the request, Eclipse keeps raising a Malformed URL Exception. I've tried a line of code from one of the android tutorials:</p>
<pre><code>URL url = new URL("https://wikipedia.org");
</code></pre>
<p>And even that triggers the error. Is there a reason Eclipse keeps raising this error for any URL I try to create?</p> | 24,418,607 | 1 | 5 | null | 2014-06-25 19:26:28.383 UTC | 1 | 2021-01-27 12:47:51.563 UTC | 2014-06-25 21:09:16.683 UTC | null | 964,243 | null | 3,772,689 | null | 1 | 26 | java|android|malformedurlexception | 60,070 | <p>It is not raising the exception, it's complaining that you haven't handled <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html"><strong>the possibility that it might</strong></a>, even though it won't, because the URL in this case is not malformed. (Java's designers thought this concept, "checked exceptions", was a good idea, although in practice <a href="https://stackoverflow.com/questions/613954/the-case-against-checked-exceptions">it hasn't worked well.</a>)</p>
<p>To shut it up, add <code>throws MalformedURLException</code>, or its superclass <code>throws IOException</code>, to the method declaration. For example:</p>
<pre><code>public void myMethod() throws IOException {
URL url = new URL("https://wikipedia.org/");
...
}
</code></pre>
<p>Alternatively, catch and rethrow the annoying exception as an unchecked exception:</p>
<pre><code>public void myMethod() {
try {
URL url = new URL("https://wikipedia.org/");
...
} catch (IOException e) {
throw new RuntimeException(e);
}
}
</code></pre>
<p>Java 8 added the <code>UncheckedIOException</code> class for rethrowing <code>IOException</code>s when you cannot otherwise handle them. In earlier Java versions, use <code>RuntimeException</code>.</p> |
3,242,995 | Convert XML to PSObject | <p>Note: I'm using <code>ConvertTo-XML</code> and cannot use <code>Export-Clixml</code>:</p>
<p>I create a simple <code>PSObjec</code>t:</p>
<pre><code>$a = New-Object PSObject -Property @{
Name='New'
Server = $null
Database = $null
UserName = $null
Password = $null
}
</code></pre>
<p>I then convert it into XML using <code>ConvertTo-XML</code>:</p>
<pre><code>$b = $a | Convertto-XML -NoTypeInformation
</code></pre>
<p>The XML looks like this:</p>
<pre><code><?xml version="1.0"?>
<Objects>
<Object>
<Property Name="Password" />
<Property Name="Name">New</Property>
<Property Name="Server" />
<Property Name="UserName" />
<Property Name="Database" />
</Object>
</Objects>
</code></pre>
<p>I'm having trouble figuring out the dot notation or XPath query to extract the attributes/elements and convert <code>$b</code> back to the original <code>PSObject</code>.</p> | 3,243,025 | 3 | 0 | null | 2010-07-14 02:29:17.723 UTC | 8 | 2017-10-16 00:01:00.713 UTC | 2010-07-15 14:17:11.153 UTC | null | 5,314 | null | 135,965 | null | 1 | 24 | xml|powershell | 52,218 | <p>You can do this pretty easily with XPath. Although PowerShell usually makes working with XML pretty simple, in this case I think the format using strictly PowerShell syntax would be pretty gross.</p>
<pre><code>filter XmlProperty([String]$Property) {
$_.SelectSingleNode("/Objects/Object/Property[@Name='$Property']").InnerText
}
$Name = $b | Xmlproperty Name
$Server = $b | XmlProperty Server
# etc...
</code></pre>
<p>EDIT: To generically do this for an XML document that contains one or more Object elements, you can do something like this:</p>
<pre><code>function ConvertFrom-Xml($XML) {
foreach ($Object in @($XML.Objects.Object)) {
$PSObject = New-Object PSObject
foreach ($Property in @($Object.Property)) {
$PSObject | Add-Member NoteProperty $Property.Name $Property.InnerText
}
$PSObject
}
}
ConvertFrom-Xml $b
</code></pre> |
4,002,819 | Finding the path of the program that will execute from the command line in Windows | <p>Say I have a program <code>X.EXE</code> installed in folder <code>c:\abcd\happy\</code> on the system. The folder is on the system path. Now suppose there is another program on the system that's also called X.EXE but is installed in folder <code>c:\windows\</code>.</p>
<p>Is it possible to quickly find out from the command line that if I type in <code>X.EXE</code> which of the two <code>X.EXE</code>'s will get launched? (but without having to dir search or look at the process details in Task Manager).</p>
<p>Maybe some sort of in-built command, or some program out there that can do something like this? :</p>
<pre><code>detect_program_path X.EXE
</code></pre> | 4,002,828 | 3 | 1 | null | 2010-10-23 06:28:32.393 UTC | 32 | 2020-02-24 01:42:10.977 UTC | null | null | null | null | 382,818 | null | 1 | 165 | windows|command-line|path | 129,823 | <p>Use the <code>where</code> command. The first result in the list is the one that will execute.</p>
<pre>
C:\> where notepad
C:\Windows\System32\notepad.exe
C:\Windows\notepad.exe
</pre>
<p>According to <a href="https://web.archive.org/web/20150628220641/http://blogs.msdn.com/b/ravisu/archive/2004/08/11/213023.aspx" rel="noreferrer">this blog post</a>, <code>where.exe</code> is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.</p>
<p>On Linux, the equivalent is the <a href="https://linux.die.net/man/1/which" rel="noreferrer"><code>which</code></a> command, e.g. <code>which ssh</code>.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.