Programs & Examples On #Break

A break statement is a flow-control feature provided by most programming languages that allows for an early exit from a loop; once a break statement is reached, its enclosing loop is immediately exited.

illegal use of break statement; javascript

break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller.

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        requestAnimFrame(loop);
        if (game == 1) {
           return
        }
    }
}

Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the drawAllEnemies and requestAnimFrame method as well as how game value is updated

R: Break for loop

Well, your code is not reproducible so we will never know for sure, but this is what help('break')says:

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.

So yes, break only breaks the current loop. You can also see it in action with e.g.:

for (i in 1:10)
{
    for (j in 1:10)
    {
        for (k in 1:10)
        {
            cat(i," ",j," ",k,"\n")
            if (k ==5) break
        }   
    }
}

Line Break in XML?

<description><![CDATA[first line<br/>second line<br/>]]></description>

Is it bad practice to use break to exit a loop in Java?

Good lord no. Sometimes there is a possibility that something can occur in the loop that satisfies the overall requirement, without satisfying the logical loop condition. In that case, break is used, to stop you cycling around a loop pointlessly.

Example

String item;

for(int x = 0; x < 10; x++)
{
    // Linear search.
    if(array[x].equals("Item I am looking for"))
    {
       //you've found the item. Let's stop.
       item = array[x];
       break; 
    }
}

What makes more sense in this example. Continue looping to 10 every time, even after you've found it, or loop until you find the item and stop? Or to put it into real world terms; when you find your keys, do you keep looking?

Edit in response to comment

Why not set x to 11 to break the loop? It's pointless. We've got break! Unless your code is making the assumption that x is definitely larger than 10 later on (and it probably shouldn't be) then you're fine just using break.

Edit for the sake of completeness

There are definitely other ways to simulate break. For example, adding extra logic to your termination condition in your loop. Saying that it is either loop pointlessly or use break isn't fair. As pointed out, a while loop can often achieve similar functionality. For example, following the above example..

while(x < 10 && item == null)
{
    if(array[x].equals("Item I am looking for"))
    {
        item = array[x];
    }

    x++;
}

Using break simply means you can achieve this functionality with a for loop. It also means you don't have to keep adding in conditions into your termination logic, whenever you want the loop to behave differently. For example.

for(int x = 0; x < 10; x++)
{
   if(array[x].equals("Something that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("Something else that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("This is what I want"))
   {
       item = array[x];
   }
}

Rather than a while loop with a termination condition that looks like this:

while(x < 10 && !array[x].equals("Something that will make me want to cancel") && 
                !array[x].equals("Something else that will make me want to cancel"))

break out of if and foreach

if is not a loop structure, so you cannot "break out of it".

You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:

$device = "wanted";
foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;

        // will leave the foreach loop and also the if statement
        break;
        some_function(); // never reached!
    }
    another_function();  // not executed after match/break
}

Just for completeness for others that stumble upon this question looking for an answer..

break takes an optional argument, which defines how many loop structures it should break. Example:

foreach (array('1','2','3') as $a) {
    echo "$a ";
    foreach (array('3','2','1') as $b) {
        echo "$b ";
        if ($a == $b) { 
            break 2;  // this will break both foreach loops
        }
    }
    echo ". ";  // never reached!
}
echo "!";

Resulting output:

1 3 2 1 !

How to break out of nested loops?

I note that the question is simply, "Is there any other way to break all of the loops?" I don't see any qualification but that it not be goto, in particular the OP didn't ask for a good way. So, how about we longjmp out of the inner loop? :-)

#include <stdio.h>
#include <setjmp.h>

int main(int argc, char* argv[]) {
  int counter = 0;
  jmp_buf look_ma_no_goto;
  if (!setjmp(look_ma_no_goto)) {
    for (int i = 0; i < 1000; i++) {
      for (int j = 0; j < 1000; j++) {
        if (i == 500 && j == 500) {
          longjmp(look_ma_no_goto, 1);
        }
        counter++;
      }
    }
  }
  printf("counter=%d\n", counter);
}

The setjmp function returns twice. The first time, it returns 0 and the program executes the nested for loops. Then when the both i and j are 500, it executes longjmp, which causes setjmp to return again with the value 1, skipping over the loop.

Not only will longjmp get you out of nested loops, it works with nested functions too!

Breaking out of a for loop in Java

If for some reason you don't want to use the break instruction (if you think it will disrupt your reading flow next time you will read your programm, for example), you can try the following :

boolean test = true;
for (int i = 0; i < 1220 && test; i++) {
    System.out.println(i);
    if (i == 20) {
        test = false;
    }
 }

The second arg of a for loop is a boolean test. If the result of the test is true, the loop will stop. You can use more than just an simple math test if you like. Otherwise, a simple break will also do the trick, as others said :

for (int i = 0; i < 1220 ; i++) {
    System.out.println(i);
    if (i == 20) {
        break;
    }
 }

How to break out of a loop from inside a switch?

There's no C++ construct for breaking out of the loop in this case.

Either use a flag to interrupt the loop or (if appropriate) extract your code into a function and use return.

How to kill a while loop with a keystroke?

There is a solution that requires no non-standard modules and is 100% transportable

import thread

def input_thread(a_list):
    raw_input()
    a_list.append(True)

def do_stuff():
    a_list = []
    thread.start_new_thread(input_thread, (a_list,))
    while not a_list:
        stuff()

How to break nested loops in JavaScript?

You need to name your outer loop and break that loop, rather than your inner loop - like this.

outer_loop: 
for(i=0;i<5;i++) {
    for(j=i+1;j<5;j++) {
        break outer_loop;
    }
    alert(1);
}

HTML5 canvas ctx.fillText won't do line breaks?

The code for word-wrapping (breaking at spaces) provided by @Gaby Petrioli is very helpful. I've extended his code to provide support for newline characters \n. Also, often times it's useful to have the dimensions of the bounding box, so multiMeasureText() returns both the width and the height.

You can see the code here: http://jsfiddle.net/jeffchan/WHgaY/76/

Line Break in XML formatting?

Here is what I use when I don't have access to the source string, e.g. for downloaded HTML:

// replace newlines with <br>
public static String replaceNewlinesWithBreaks(String source) {
    return source != null ? source.replaceAll("(?:\n|\r\n)","<br>") : "";
}

For XML you should probably edit that to replace with <br/> instead.

Example of its use in a function (additional calls removed for clarity):

// remove HTML tags but preserve supported HTML text styling (if there is any)
public static CharSequence getStyledTextFromHtml(String source) {
    return android.text.Html.fromHtml(replaceNewlinesWithBreaks(source));
}

...and a further example:

textView.setText(getStyledTextFromHtml(someString));

Exiting out of a FOR loop in a batch file?

My answer
Use nested for loops to provide break points to the for /l loop.

for %%a in (0 1 2 3 4 5 6 7 8 9) do (
   for %%b in (0 1 2 3 4 5 6 7 8 9) do (
      for /l %%c in (1,1,10) do (
         if not exist %%a%%b%%c goto :continue
      )
   )
)
:continue

Explanation The code must be tweaked significantly to properly use the nested loops. For example, what is written will have leading zeros.
"Regular" for loops can be immediately broken out of with a simple goto command, where for /l loops cannot. This code's innermost for /l loop cannot be immediately broken, but an overall break point is present after every 10 iterations (as written). The innermost loop doesn't have to be 10 iterations -- you'll just have to account for the math properly if you choose to do 100 or 1000 or 2873 for that matter (if math even matters to the loop).

History I found this question while trying to figure out why a certain script was running slowly. It turns out I used multiple loops with a traditional loop structure:

set cnt=1
:loop
if "%somecriteria%"=="finished" goto :continue
rem do some things here
set /a cnt += 1
goto :loop

:continue
echo the loop ran %cnt% times

This script file had become somewhat long and it was being run from a network drive. This type of loop file was called maybe 20 times and each time it would loop 50-100 times. The script file was taking too long to run. I had the bright idea of attempting to convert it to a for /l loop. The number of needed iterations is unknown, but less than 10000. My first attempt was this:

setlocal enabledelayedexpansion
set cnt=1
for /l %%a in (1,1,10000) do (
   if "!somecriteria!"=="finished" goto :continue
   rem do some things here
   set /a cnt += 1
)

:continue
echo the loop ran %cnt% times

With echo on, I quickly found out that the for /l loop still did ... something ... without actually doing anything. It ran much faster, but still slower than I thought it could/should. Therefore I found this question and ended up with the nested loop idea presented above.

Side note It turns out that the for /l loop can be sped up quite a bit by simply making sure it doesn't have any output. I was able to do this for a noticeable speed increase:

setlocal enabledelayedexpansion
set cnt=1
@for /l %%a in (1,1,10000) do @(
   if "!somecriteria!"=="finished" goto :continue
   rem do some things here
   set /a cnt += 1
) > nul

:continue
echo the loop ran %cnt% times

How to break a while loop from an if condition inside the while loop?

while(something.hasnext())
do something...
   if(contains something to process){
      do something...
      break;
   }
}

Just use the break statement;

For eg:this just prints "Breaking..."

while (true) {
     if (true) {
         System.out.println("Breaking...");
         break;
     }
     System.out.println("Did this print?");
}

Regarding Java switch statements - using return and omitting breaks in each case

Assigning a value to a local variable and then returning that at the end is considered a good practice. Methods having multiple exits are harder to debug and can be difficult to read.

That said, thats the only plus point left to this paradigm. It was originated when only low-level procedural languages were around. And it made much more sense at that time.

While we are on the topic you must check this out. Its an interesting read.

How do I exit a while loop in Java?

You can use "break" to break the loop, which will not allow the loop to process more conditions

Using continue in a switch statement

It's syntactically correct and stylistically okay.

Good style requires every case: statement should end with one of the following:

 break;
 continue;
 return (x);
 exit (x);
 throw (x);
 //fallthrough

Additionally, following case (x): immediately with

 case (y):
 default:

is permissible - bundling several cases that have exactly the same effect.

Anything else is suspected to be a mistake, just like if(a=4){...} Of course you need enclosing loop (while, for, do...while) for continue to work. It won't loop back to case() alone. But a construct like:

while(record = getNewRecord())
{
    switch(record.type)
    {
        case RECORD_TYPE_...;
            ...
        break;
        default: //unknown type
            continue; //skip processing this record altogether.
    }
    //...more processing...
}

...is okay.

Can I use break to exit multiple nested 'for' loops?

Although this answear was already presented, i think a good approach is to do the following:

for(unsigned int z = 0; z < z_max; z++)
{
    bool gotoMainLoop = false;
    for(unsigned int y = 0; y < y_max && !gotoMainLoop; y++)
    {
        for(unsigned int x = 0; x < x_max && !gotoMainLoop; x++)
        {
                          //do your stuff
                          if(condition)
                            gotoMainLoop = true;
        }
    }

}

Difference between break and continue statement

To prevent anything from execution if a condition is met one should use the continue and to get out of the loop if a condition is met one should use the break.

For example in the below mentioned code.

 for(int i=0;i<5;i++){

        if(i==3){

           continue;

        }
       System.out.println(i);
     }

The above code will print the result : 0 1 2 4

NOw consider this code

 for(int i=0;i<5;i++){


            if(i==3){

                break;

            }
            System.out.println(i);
         }

This code will print 0 1 2

That is the basic difference in the continue and break.

break/exit script

Here:

if(n < 500)
{
    # quit()
    # or 
    # stop("this is some message")
}
else
{
    *insert rest of program here*
}

Both quit() and stop(message) will quit your script. If you are sourcing your script from the R command prompt, then quit() will exit from R as well.

Immediate exit of 'while' loop in C++

cin >> choice;
while(choice!=99) {
    cin>>gNum;
    cin >> choice
}

You don't need a break, in that case.

Is returning out of a switch statement considered a better practice than using break?

Neither, because both are quite verbose for a very simple task. You can just do:

let result = ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[opt] ?? 'Default'    // opt can be 1, 2, 3 or anything (default)

This, of course, also works with strings, a mix of both or without a default case:

let result = ({
  'first': 'One',
  'second': 'Two',
  3: 'Three'
})[opt]                // opt can be 'first', 'second' or 3

Explanation:

It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.

This returns undefined if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ?? and return a default value.

Example:

_x000D_
_x000D_
console.log('Using a valid case:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[1] ?? 'Default')

console.log('Using an invalid case/defaulting:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
_x000D_
_x000D_

break statement in "if else" - java

Because your else isn't attached to anything. The if without braces only encompasses the single statement that immediately follows it.

if (choice==5)
{
    System.out.println("End of Game\n Thank you for playing with us!");
    break;
}
else
{
   System.out.println("Not a valid choice!\n Please try again...\n");
}

Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.

In addition, using a switch here would make more sense.

int choice;
boolean keepGoing = true;
while(keepGoing)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch(choice)
    {
        case 1: 
            playGame();
            break;
        case 2: 
            loadGame();
            break;
        // your other cases
        // ...
        case 5: 
            System.out.println("End of Game\n Thank you for playing with us!");
            keepGoing = false;
            break;
        default:
            System.out.println("Not a valid choice!\n Please try again...\n");
     }
 }         

Note that instead of an infinite for loop I used a while(boolean), making it easy to exit the loop. Another approach would be using break with labels.

How to break out of multiple loops?

Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:

breaker = False #our mighty loop exiter!
while True:
    while True:
        if conditionMet:
            #insert code here...
            breaker = True 
            break
    if breaker: # the interesting part!
        break   # <--- !

If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!

Nested jQuery.each() - continue/break

Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".

How do I break out of a loop in Scala?

To add Rex Kerr answer another way:

  • (1c) You can also use a guard in your loop:

     var sum = 0
     for (i <- 0 to 1000 ; if sum<1000) sum += i
    

Is it a bad practice to use break in a for loop?

General rule: If following a rule requires you to do something more awkward and difficult to read then breaking the rule, then break the rule.

In the case of looping until you find something, you run into the problem of distinguishing found versus not found when you get out. That is:

for (int x=0;x<fooCount;++x)
{
  Foo foo=getFooSomehow(x);
  if (foo.bar==42)
    break;
}
// So when we get here, did we find one, or did we fall out the bottom?

So okay, you can set a flag, or initialize a "found" value to null. But

That's why in general I prefer to push my searches into functions:

Foo findFoo(int wantBar)
{
  for (int x=0;x<fooCount;++x)
  {
    Foo foo=getFooSomehow(x);
    if (foo.bar==wantBar)
      return foo;
  }
  // Not found
  return null;
}

This also helps to unclutter the code. In the main line, "find" becomes a single statement, and when the conditions are complex, they're only written once.

What's the best way to break from nested loops in JavaScript?

I thought I'd show a functional-programming approach. You can break out of nested Array.prototype.some() and/or Array.prototype.every() functions, as in my solutions. An added benefit of this approach is that Object.keys() enumerates only an object's own enumerable properties, whereas "a for-in loop enumerates properties in the prototype chain as well".

Close to the OP's solution:

    Args.forEach(function (arg) {
        // This guard is not necessary,
        // since writing an empty string to document would not change it.
        if (!getAnchorTag(arg))
            return;

        document.write(getAnchorTag(arg));
    });

    function getAnchorTag (name) {
        var res = '';

        Object.keys(Navigation.Headings).some(function (Heading) {
            return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
                if (name == Navigation.Headings[Heading][Item].Name) {
                    res = ("<a href=\""
                                 + Navigation.Headings[Heading][Item].URL + "\">"
                                 + Navigation.Headings[Heading][Item].Name + "</a> : ");
                    return true;
                }
            });
        });

        return res;
    }

Solution that reduces iterating over the Headings/Items:

    var remainingArgs = Args.slice(0);

    Object.keys(Navigation.Headings).some(function (Heading) {
        return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
            var i = remainingArgs.indexOf(Navigation.Headings[Heading][Item].Name);

            if (i === -1)
                return;

            document.write("<a href=\""
                                         + Navigation.Headings[Heading][Item].URL + "\">"
                                         + Navigation.Headings[Heading][Item].Name + "</a> : ");
            remainingArgs.splice(i, 1);

            if (remainingArgs.length === 0)
                return true;
            }
        });
    });

How to break out or exit a method in Java?

use return to exit from a method.

 public void someMethod() {
        //... a bunch of code ...
        if (someCondition()) {
            return;
        }
        //... otherwise do the following...
    }

Here's another example

int price = quantity * 5;
        if (hasCream) {
            price=price + 1;
        }
        if (haschocolat) {
            price=price + 2;
        }
        return price;

How to break out of while loop in Python?

ans=(R)
while True:
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore
    else:
        print("Now I'll see if I can break your score...")
        ans = False
        break

How do I break out of a loop in Perl?

Simply last would work here:

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

If you have nested loops, then last will exit from the innermost loop. Use labels in this case:

LBL_SCORE: {
    for my $entry1 (@array1) {
        for my $entry2 (@array2) {
            if ($entry1 eq $entry2) { # Or any condition
                last LBL_SCORE;
            }
        }
    }
 }

Given a last statement will make the compiler to come out from both the loops. The same can be done in any number of loops, and labels can be fixed anywhere.

How can I use break or continue within for loop in Twig template?

I have found a good work-around for continue (love the break sample above). Here I do not want to list "agency". In PHP I'd "continue" but in twig, I came up with alternative:

{% for basename, perms in permsByBasenames %} 
    {% if basename == 'agency' %}
        {# do nothing #}
    {% else %}
        <a class="scrollLink" onclick='scrollToSpot("#{{ basename }}")'>{{ basename }}</a>
    {% endif %}
{% endfor %}

OR I simply skip it if it doesn't meet my criteria:

{% for tr in time_reports %}
    {% if not tr.isApproved %}
        .....
    {% endif %}
{% endfor %}

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

@echo off

:START
rmdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause

echo.
echo.
echo Note the directory is not found
echo.
echo Press any key to make a temporary directory, cls, and test again
pause

Mkdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause
echo.
echo press any key to goto START and remove temporary directory 
pause 

goto START

How to have comments in IntelliSense for function in Visual Studio?

Also the visual studio add-in ghost doc will attempt to create and fill-in the header comments from your function name.

jQuery getTime function

You don't need jquery to do that, just javascript. For example, you can do a timer using this:

<body onload="clock();">

<script type="text/javascript">
function clock() {
   var now = new Date();
   var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
   document.getElementById('clockDiv').innerHTML=outStr;
   setTimeout('clock()',1000);
}
clock();
</script>   

<div id="clockDiv"></div>

</body>

You can view a complete reference here: http://www.hunlock.com/blogs/Javascript_Dates-The_Complete_Reference

How do I delete an entity from symfony2

Symfony is smart and knows how to make the find() by itself :

public function deleteGuestAction(Guest $guest)
{
    if (!$guest) {
        throw $this->createNotFoundException('No guest found');
    }

    $em = $this->getDoctrine()->getEntityManager();
    $em->remove($guest);
    $em->flush();

    return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}

To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}

how to access master page control from content page

I have a helper method for this in my System.Web.UI.Page class

protected T FindControlFromMaster<T>(string name) where T : Control
{
     MasterPage master = this.Master;
     while (master != null)
     {
         T control = master.FindControl(name) as T;
         if (control != null)
             return control;

         master = master.Master;
     }
     return null;
}

then you can access using below code.

Label lblStatus = FindControlFromMaster<Label>("lblStatus");
if(lblStatus!=null) 
    lblStatus.Text = "something";

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

You don't need to down grade. You can run more than one version of Java on MacOS. You can set the version of your terminal with this command in MacOS.

# List Java versions installed
/usr/libexec/java_home -V

# Java 11
export JAVA_HOME=$(/usr/libexec/java_home -v 11)

# Java 1.8
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

# Java 1.7
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)

# Java 1.6
export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)

You can set the default value in the .bashrc, .profile, or .zprofile

Dynamically updating css in Angular 2

You can dynamically change the style(width and height) of div by attaching dynamic value to inline [style.width] and [style.hiegh] property of div.

In your case you can bind width and height property of HomeComponent class with the div's inline style width and height property like this... As directed by Sasxa

<div class="home-component" 
     [style.width]="width + 'px'" 
     [style.height]="height + 'px'">Some stuff in this div
</div>

For the working demo take a look at this plunker(http://plnkr.co/edit/cUbbo2?p=preview)

   //our root app component
import {Component} from 'angular2/core';
import {FORM_DIRECTIVES,FormBuilder,AbstractControl,ControlGroup,} from "angular2/common";

@Component({
  selector: 'home',
  providers: [],
  template: `
     <div class="home-component" [style.width]="width+'px'" [style.height]="height+'px'">Some this div</div>
     <br/>
     <form [ngFormModel]="testForm">
        width:<input type="number" [ngFormControl]="txtWidth"/> <br>
        Height:<input type="number"[ngFormControl]="txtHeight" />
     </form>
  `,
  styles:[`

      .home-component{
        background-color: red;
        width: 50px;
        height: 50px;
    }

  `],
  directives: [FORM_DIRECTIVES]
})
export class App {
  testForm:ControlGroup;
  public width: Number;
  public height: Number;
  public txtWidth:AbstractControl;
  public txtHeight:AbstractControl;

  constructor(private _fb:FormBuilder) {
      this.testForm=_fb.group({
        'txtWidth':['50'],
        'txtHeight':['50']
      });

      this.txtWidth=this.testForm.controls['txtWidth'];
      this.txtHeight=this.testForm.controls['txtHeight'];

      this.txtWidth.valueChanges.subscribe(val=>this.width=val);
      this.txtHeight.valueChanges.subscribe(val=>this.height =val);
  }
}

open link of google play store in mobile version android

You'll want to use the specified market protocol:

final String appPackageName = "com.example"; // Can also use getPackageName(), as below
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));

Keep in mind, this will crash on any device that does not have the Market installed (the emulator, for example). Hence, I would suggest something like:

final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
}

While using getPackageName() from Context or subclass thereof for consistency (thanks @cprcrack!). You can find more on Market Intents here: link.

How can I use a search engine to search for special characters?

Unfortunately, there doesn't appear to be a magic bullet. Bottom line up front: "context".

Google indeed ignores most punctuation, with the following exceptions:

  1. Punctuation in popular terms that have particular meanings, like [ C++ ] or [ C# ] (both are names of programming languages), are not ignored.
  2. The dollar sign ($) is used to indicate prices. [ nikon 400 ] and [ nikon $400 ] will give different results.
  3. The hyphen - is sometimes used as a signal that the two words around it are very strongly connected. (Unless there is no space after the - and a space before it, in which case it is a negative sign.)
  4. The underscore symbol _ is not ignored when it connects two words, e.g. [ quick_sort ].

As such, it is not well suited for these types of searchs. Google Code however does have syntax for searching through their code projects, that includes a robust language/syntax for dealing with "special characters". If looking at someone else's code could help solve a problem, this may be an option.

Unfortunately, this is not a limitation unique to google. You may find that your best successes hinge on providing as much 'context' to the problem as possible. If you are searching to find what $- means, providing information about the problem's domain may yield good results.

For example, searching "special perl variables" quickly yields your answer in the first entry on the results page.

Fatal error: Call to undefined function: ldap_connect()

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

    extension=php_ldap.dll

  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!

Add the loading screen in starting of the android application

Write the code:

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        Thread welcomeThread = new Thread() {

            @Override
            public void run() {
                try {
                    super.run();
                    sleep(10000)  //Delay of 10 seconds
                } catch (Exception e) {

                } finally {

                    Intent i = new Intent(SplashActivity.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        };
        welcomeThread.start();
    }

How to launch PowerShell (not a script) from the command line

If you go to C:\Windows\system32\Windowspowershell\v1.0 (and C:\Windows\syswow64\Windowspowershell\v1.0 on x64 machines) in Windows Explorer and double-click powershell.exe you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe can be set independently from the default properties.

To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.

Running start powershell from cmd.exe should start a new console with your default settings.

It says that TypeError: document.getElementById(...) is null

I have same problem. It just the javascript's script loads too fast--before the HTML's element loaded. So the browser returning null, since the browser can't find where is the element you like to manipulate.

jQuery: How can I show an image popup onclick of the thumbnail?

This is the most popular (9500 stars) and light weight (20KB minify, 7.5KB minify+gzip) popup gallery I think: Magnific-Popup

How to get query parameters from URL in Angular 5?

Just stumbled upon the same problem and most answers here seem to only solve it for Angular internal routing, and then some of them for route parameters which is not the same as request parameters.

I am guessing that I have a similar use case to the original question by Lars.

For me the use case is e.g. referral tracking:

Angular running on mycoolpage.com, with hash routing, so mycoolpage.com redirects to mycoolpage.com/#/. For referral, however, a link such as mycoolpage.com?referrer=foo should also be usable. Unfortunately, Angular immediately strips the request parameters, going directly to mycoolpage.com/#/.

Any kind of 'trick' with using an empty component + AuthGuard and getting queryParams or queryParamMap did, unfortunately, not work for me. They were always empty.

My hacky solution ended up being to handle this in a small script in index.html which gets the full URL, with request parameters. I then get the request param value via string manipulation and set it on window object. A separate service then handles getting the id from the window object.

index.html script

const paramIndex = window.location.href.indexOf('referrer=');
if (!window.myRef && paramIndex > 0) {
  let param = window.location.href.substring(paramIndex);
  param = param.split('&')[0];
  param = param.substr(param.indexOf('=')+1);
  window.myRef = param;
}

Service

declare var window: any;

@Injectable()
export class ReferrerService {

  getReferrerId() {
    if (window.myRef) {
      return window.myRef;
    }
    return null;
  }
}

How to install node.js as windows service?

Late to the party, but node-windows will do the trick too.

enter image description here

It also has system logging built in.

enter image description here

There is an API to create scripts from code, i.e.

var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

FD: I'm the author of this module.

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

_x000D_
_x000D_
<div>_x000D_
  <div style="width: 20%; float: left;">_x000D_
    <p>Some Contentsssssssssss</p>_x000D_
  </div>_x000D_
  <div style="float: left; width: 80%;">_x000D_
    <textarea style="width: 100%; max-width: 100%;"></textarea>_x000D_
  </div>_x000D_
  <div style="clear: both;"></div>_x000D_
</div>_x000D_
_x000D_
 
_x000D_
_x000D_
_x000D_

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

The accepted answer doesn't work if some package vendors it's own copy of urllib3, in which case this will still work:

import warnings

warnings.filterwarnings('ignore', message='Unverified HTTPS request')

Jquery sortable 'change' event element position

UPDATED: 26/08/2016 to use the latest jquery and jquery ui version plus bootstrap to style it.

$(function() {
    $('#sortable').sortable({
        start: function(event, ui) {
            var start_pos = ui.item.index();
            ui.item.data('start_pos', start_pos);
        },
        change: function(event, ui) {
            var start_pos = ui.item.data('start_pos');
            var index = ui.placeholder.index();
            if (start_pos < index) {
                $('#sortable li:nth-child(' + index + ')').addClass('highlights');
            } else {
                $('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
            }
        },
        update: function(event, ui) {
            $('#sortable li').removeClass('highlights');
        }
    });
});

How to get a value of an element by name instead of ID

$('[name=whatever]').val()

The jQuery documentation is your friend.

Unable to open debugger port in IntelliJ

Merely hitting the debug icon again fixed my problem in a few seconds.

How do I get bit-by-bit data from an integer value in C?

Using std::bitset

int value = 123;
std::bitset<sizeof(int)> bits(value);
std::cout <<bits.to_string();

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

I have come across the same problem, In my case I had two 32 bit pcs. One with .NET4.5 installed and other one was fresh PC.

my 32-bit cpp dll(Release mode build) was working fine with .NET installed PC but Not with fresh PC where I got the below error

Unable to load DLL 'PrinterSettings.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

finally,

I just built my project in Debug mode configuration and this time my cpp dll was working fine.

jquery find closest previous sibling with class

I think all the answers are lacking something. I prefer using something like this

$('li.current_sub').prevUntil("li.par_cat").prev();

Saves you not adding :first inside the selector and is easier to read and understand. prevUntil() method has a better performance as well rather than using prevAll()

Updating Anaconda fails: Environment Not Writable Error

Open this folder "C:\ProgramData\" and right-click on "\Anaconda3". go to properties -> security and check all the boxes for each user. This worked for me.

T-SQL: Deleting all duplicate rows but keeping one

You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar], 
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)

How do I check if a number is positive or negative in C#?

bool isNegative(int n) {
  int i;
  for (i = 0; i <= Int32.MaxValue; i++) {
    if (n == i) 
      return false;
  }
  return true;
}

How to identify a strong vs weak relationship on ERD?

In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.

openCV video saving in python

As an example :

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out_corner = cv2.VideoWriter('img_corner_1.avi',fourcc, 20.0, (640, 480))

At that place, have to define X,Y as width and height

But, when you create an image (a blank image for instance) you have to define Y,X as height and width :

    img_corner = np.zeros((480, 640, 3), np.uint8)

Bring a window to the front in WPF

I have found a solution that brings the window to the top, but it behaves as a normal window:

if (!Window.IsVisible)
{
    Window.Show();
}

if (Window.WindowState == WindowState.Minimized)
{
    Window.WindowState = WindowState.Normal;
}

Window.Activate();
Window.Topmost = true;  // important
Window.Topmost = false; // important
Window.Focus();         // important

How to concatenate variables into SQL strings

You can accomplish this (if I understand what you are trying to do) using dynamic SQL.

The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.

So you can use something like this approach:

SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue 
    + ' AS fld1 FROM tbl' + @KeyValue

EXEC (@stmt)

First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:

'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'

At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE (or EXEC for short).

The old-school sp_executesql procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.


FOLLOWUP

EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.

Consider what would happen if @KeyValue contained the string:

'1 AS foo; DROP TABLE students; -- '

The string we would produce as a SQL statement would be:

'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'

When we EXECUTE that string as a SQL statement:

INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...

And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)

One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'. If an illegal character is found, then reject the value, and exit without executing any SQL.

Download/Stream file from URL - asp.net

You could try using the DirectoryEntry class with the IIS path prefix:

using(DirectoryEntry de = new DirectoryEntry("IIS://Localhost/w3svc/1/root" + DOCUMENT_PATH))
{
    filePath = de.Properties["Path"].Value;
}

if (!File.Exists(filePath))
        return;

var fileInfo = new System.IO.FileInfo(filePath);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(filePath);
Response.End();

if arguments is equal to this string, define a variable like this string

You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets. The proper method is for brackets to contain spacing within, and operators to contain spacing around. In some instances different combinations work; however, the following is intended to be a universal example.

if [ "$1" == "something" ]; then     ## GOOD

if [ "$1" = "something" ]; then      ## GOOD

if [ "$1"="something" ]; then        ## BAD (operator spacing)

if ["$1" == "something"]; then       ## BAD (bracket spacing)

Also, note double brackets are handled slightly differently compared to single brackets ...

if [[ $a == z* ]]; then   # True if $a starts with a "z" (pattern matching).
if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching).

if [ $a == z* ]; then     # File globbing and word splitting take place.
if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching).

I hope that helps!

Unable to run Java GUI programs with Ubuntu

I stopped getting this exception when I installed default-jdk using apt. I'm running Ubuntu 14.04 (Trusty Tahr), and the problem appears to have been the result of having a "headless" Java installed. All I did was:

sudo apt-get install default-jdk

How do I delay a function call for 5 seconds?

var rotator = function(){
  widget.Rotator.rotate();
  setTimeout(rotator,5000);
};
rotator();

Or:

setInterval(
  function(){ widget.Rotator.rotate() },
  5000
);

Or:

setInterval(
  widget.Rotator.rotate.bind(widget.Rotator),
  5000
);

Python not working in command prompt?

This working for me :

PS C:\Users\MyUsername> py -V

Python 3.9.0

Sublime Text 2 multiple line edit

ctrl + shift + right-click it works better that way

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

Difference between $(window).load() and $(document).ready() functions

According to DOM Level 2 Events, the load event is supposed to fire on document, not on window. However, load is implemented on window in all browsers for backwards compatibility.

How to compare character ignoring case in primitive types

You can't actually do the job quite right with toLowerCase, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2 or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)

There is an additional problem with using Char: there are some 80 code points not representable with a single Char that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.

But code points don't help with the variant glyphs.

Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:

  1. Character toLowerCase
  2. Character toUpperCase
  3. String toLowerCase
  4. String toUpperCase
  5. String equalsIgnoreCase
  6. Character toLowerCase(toUpperCase) (or vice versa)

For these methods, S means that the variants are treated the same as each other, D means the variants are treated as different from each other.

Behavior     Unicode                             Glyphs
===========  ==================================  =========
1 2 3 4 5 6  Upper  Lower  Var Up Var Lo Vr Lo2  U L u l l2
- - - - - -  ------ ------ ------ ------ ------  - - - - -
D D D D S S  \u0049 \u0069 \u0130 \u0131         I i I i   
S D S D S S  \u004b \u006b \u212a                K k K     
D S D S S S  \u0053 \u0073        \u017f         S s   ?   
D S D S S S  \u039c \u03bc        \u00b5         ? µ   µ   
S D S D S S  \u00c5 \u00e5 \u212b                Å å Å     
D S D S S S  \u0399 \u03b9        \u0345 \u1fbe  ? ?   ? ? 
D S D S S S  \u0392 \u03b2        \u03d0         ? ß   ?   
D S D S S S  \u0395 \u03b5        \u03f5         ? e   ?   
D D D D S S  \u0398 \u03b8 \u03f4 \u03d1         T ? ? ?   
D S D S S S  \u039a \u03ba        \u03f0         ? ?   ?   
D S D S S S  \u03a0 \u03c0        \u03d6         ? p   ?   
D S D S S S  \u03a1 \u03c1        \u03f1         ? ?   ?   
D S D S S S  \u03a3 \u03c3        \u03c2         S s   ?   
D S D S S S  \u03a6 \u03c6        \u03d5         F f   ?   
S D S D S S  \u03a9 \u03c9 \u2126                O ? ?     
D S D S S S  \u1e60 \u1e61        \u1e9b         ? ?   ?   

Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i and I are the same ignoring case; Turkish, not).

Overall, using toUpperCase gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).

You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c)) on them alone. If you choose your guards carefully (just toUpperCase if c < 0x130 || c > 0x212B, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase on a larger string, you're better off doing that.

Here is sample Scala code that does the job:

def elevateCase(c: Char): Char = {
  if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
  else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
    Character.toUpperCase(Character.toLowerCase(c))
  else Character.toUpperCase(c)
}

Close Bootstrap modal on form submit

Try this code

$('#frmStudent').on('submit', function() {
  $(#StudentModal).on('hide.bs.modal', function (e) {
    e.preventDefault();
  })
});

Calculate difference between two datetimes in MySQL

my two cents about logic:

syntax is "old date" - :"new date", so:

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:00', '2018-11-15 15:00:30')

gives 30,

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:55', '2018-11-15 15:00:15')

gives: -40

What is the difference between JVM, JDK, JRE & OpenJDK?

JDK (Java Development Kit) :

  • contains tools needed to develop the Java programs.
  • You need JDK, if at all you want to write your own programs, and to compile them.
  • JDK is mainly targeted for java development.

JRE (Java Runtime Environment)

Java Runtime Environment contains JVM, class libraries, and other supporting files. JRE is targeted for execution of Java files.

JVM (Java Virtual Machine)

The JVM interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… Java Virtual Machine provides a platform-independent way of executing code.

Using Exit button to close a winform program

Put this little code in the event of the button:

this.Close();

Using LIMIT within GROUP BY to get N results per group?

Took some working, but I thougth my solution would be something to share as it is seems elegant as well as quite fast.

SELECT h.year, h.id, h.rate 
  FROM (
    SELECT id, 
      SUBSTRING_INDEX(GROUP_CONCAT(CONCAT(id, '-', year) ORDER BY rate DESC), ',' , 5) AS l
      FROM h
      WHERE year BETWEEN 2000 AND 2009
      GROUP BY id
      ORDER BY id
  ) AS h_temp
    LEFT JOIN h ON h.id = h_temp.id 
      AND SUBSTRING_INDEX(h_temp.l, CONCAT(h.id, '-', h.year), 1) != h_temp.l

Note that this example is specified for the purpose of the question and can be modified quite easily for other similar purposes.

How to call a Web Service Method?

In visual studio, use the "Add Web Reference" feature and then enter in the URL of your web service.

By adding a reference to the DLL, you not referencing it as a web service, but simply as an assembly.

When you add a web reference it create a proxy class in your project that has the same or similar methods/arguments as your web service. That proxy class communicates with your web service via SOAP but hides all of the communications protocol stuff so you don't have to worry about it.

Add animated Gif image in Iphone UIImageView

This has found an accepted answered, but I recently came across the UIImage+animatedGIF UIImage extension. It provides the following category:

+[UIImage animatedImageWithAnimatedGIFURL:(NSURL *)url]

allowing you to simply:

#import "UIImage+animatedGIF.h"
UIImage* mygif = [UIImage animatedImageWithAnimatedGIFURL:[NSURL URLWithString:@"http://en.wikipedia.org/wiki/File:Rotating_earth_(large).gif"]];

Works like magic.

Remove all subviews?

In monotouch / xamarin.ios this worked for me:

SomeParentUiView.Subviews.All(x => x.RemoveFromSuperview);

jquery variable syntax

The dollarsign as a prefix in the var name is a usage from the concept of the hungarian notation.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

We experienced this problem on pages with long Base64 strings. The problem occurs because we use CloudFlare.

Details: https://community.cloudflare.com/t/err-http2-protocol-error/119619.

Key section from the forum post:

After further testing on Incognito tabs on multiple browsers, then doing the changes on the code from a BASE64 to a real .png image, the issue never happened again, in ANY browser. The .png had around 500kb before becoming a base64,so CloudFlare has issues with huge lines of text on same line (since base64 is a long string) as a proxy between the domain and the heroku. As mentioned before, directly hitting Heroku url also never happened the issue.

The temporary hack is to disable HTTP/2 on CloudFlare.

Hope someone else can produce a better solution that doesn't require disabling HTTP/2 on CloudFlare.

ImportError: No module named sqlalchemy

Probably a stupid mistake; but, I experienced this problem and the issue turned out to be that "pip3 install sqlalchemy" installs libraries in user specific directories.

On my Linux machine, I was logged in as user1 executing a python script in user2's directory. I installed sqlalchemy as user1 and it by default placed the files in user1's directory. After installing sqlalchemy in user2's directory the problem went away.

Nginx location priority

Locations are evaluated in this order:

  1. location = /path/file.ext {} Exact match
  2. location ^~ /path/ {} Priority prefix match -> longest first
  3. location ~ /Paths?/ {} (case-sensitive regexp) and location ~* /paths?/ {} (case-insensitive regexp) -> first match
  4. location /path/ {} Prefix match -> longest first

The priority prefix match (number 2) is exactly as the common prefix match (number 4), but has priority over any regexp.

For both prefix matche types the longest match wins.

Case-sensitive and case-insensitive have the same priority. Evaluation stops at the first matching rule.

Documentation says that all prefix rules are evaluated before any regexp, but if one regexp matches then no standard prefix rule is used. That's a little bit confusing and does not change anything for the priority order reported above.

Django - how to create a file and save it to a model's FileField?

You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save().

Basically, a field declared as a FileField, when accessed, gives you an instance of class FieldFile, which gives you several methods to interact with the underlying file. So, what you need to do is:

self.license_file.save(new_name, new_contents)

where new_name is the filename you wish assigned and new_contents is the content of the file. Note that new_contents must be an instance of either django.core.files.File or django.core.files.base.ContentFile (see given links to manual for the details).

The two choices boil down to:

from django.core.files.base import ContentFile, File

# Using File
with open('/path/to/file') as f:
    self.license_file.save(new_name, File(f))

# Using ContentFile
self.license_file.save(new_name, ContentFile('A string with the file content'))

How to declare a type as nullable in TypeScript?

Just add a question mark ? to the optional field.

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

How do I find duplicates across multiple columns?

A little late to the game on this post, but I found this way to be pretty flexible / efficient

select 
    s1.id
    ,s1.name
    ,s1.city 
from 
    stuff s1
    ,stuff s2
Where
    s1.id <> s2.id
    and s1.name = s2.name
    and s1.city = s2.city

Python match a string with regex

One Liner implementation:

a=[1,3]
b=[1,2,3,4]
all(i in b for i in a)

How to redirect a url in NGINX

This is the top hit on Google for "nginx redirect". If you got here just wanting to redirect a single location:

location = /content/unique-page-name {
  return 301 /new-name/unique-page-name;
}

LINQ .Any VS .Exists - What's the difference?

Additionally, this will only work if Value is of type bool. Normally this is used with predicates. Any predicate would be generally used find whether there is any element satisfying a given condition. Here you're just doing a map from your element i to a bool property. It will search for an "i" whose Value property is true. Once done, the method will return true.

How can I set a website image that will show as preview on Facebook?

Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

Easy Way

Add usesCleartextTraffic to AndroidManifest.xml

<application
...
android:usesCleartextTraffic="true"
...>

Indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP. The default value for apps that target API level 27 or lower is "true". Apps that target API level 28 or higher default to "false".

Does WGET timeout?

According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.


Here are the options in question :

-T seconds
--timeout=seconds

Set the network timeout to seconds seconds. This is equivalent to specifying --dns-timeout, --connect-timeout, and --read-timeout, all at the same time.


And for those three options :

--dns-timeout=seconds

Set the DNS lookup timeout to seconds seconds.
DNS lookups that don't complete within the specified time will fail.
By default, there is no timeout on DNS lookups, other than that implemented by system libraries.

--connect-timeout=seconds

Set the connect timeout to seconds seconds.
TCP connections that take longer to establish will be aborted.
By default, there is no connect timeout, other than that implemented by system libraries.

--read-timeout=seconds

Set the read (and write) timeout to seconds seconds.
The "time" of this timeout refers to idle time: if, at any point in the download, no data is received for more than the specified number of seconds, reading fails and the download is restarted.
This option does not directly affect the duration of the entire download.


I suppose using something like

wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run

should make sure there is no timeout before longer than the duration of your script.

(Yeah, that's probably the most brutal solution possible ^^ )

Google Maps API v2: How to make markers clickable?

Below Kotlin code can help to you

Create Marker

        for (i in arrayList.indices) {
            val marker = googleMap!!.addMarker(
                MarkerOptions().position(
                    LatLng(
                        arrayList[i].location_latitude!!.toDoubleOrNull()!!,
                        arrayList[i].location_latitude!!.toDoubleOrNull()!!
                    )
                ).title(arrayList[i].business_name)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))
            )
            marker.tag = i
        }

Marker Click

        googleMap!!.setOnMarkerClickListener { marker ->
            Log.d(TAG, "Clicked on  ${marker.tag}")
            true
        }

CSS/HTML: What is the correct way to make text italic?

Use <em> if you need some words/characters in italic in content without other styles. It also helps make content semantic.

text-style is better suited for multiple styles and no semantic need.

"Instantiating" a List in Java?

Use List<Integer> list = new ArrayList<Integer>();

Beginner question: returning a boolean value from a function in Python

Have your tried using the 'return' keyword?

def rps():
    return True

How to add a new audio (not mixing) into a video using ffmpeg?

Replace audio

diagram of audio stream replacement

ffmpeg -i video.mp4 -i audio.wav -map 0:v -map 1:a -c:v copy -shortest output.mp4
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Add audio

diagram of audio stream addition

ffmpeg -i video.mkv -i audio.mp3 -map 0 -map 1:a -c:v copy -shortest output.mkv
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Mixing/combining two audio inputs into one

diagram of audio downmix

Use video from video.mkv. Mix audio from video.mkv and audio.m4a using the amerge filter:

ffmpeg -i video.mkv -i audio.m4a -filter_complex "[0:a][1:a]amerge=inputs=2[a]" -map 0:v -map "[a]" -c:v copy -ac 2 -shortest output.mkv

See FFmpeg Wiki: Audio Channels for more info.

Generate silent audio

You can use the anullsrc filter to make a silent audio stream. The filter allows you to choose the desired channel layout (mono, stereo, 5.1, etc) and the sample rate.

ffmpeg -i video.mp4 -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 \
-c:v copy -shortest output.mp4

Also see

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

In order to Run Report Viewer On server with Data from Server

A) Go to Project Property ----> Select Reference ------> Add Reference

1) Import (Microsoft.ReportViewer.Common.dll)-----> (Path "C:\Program Files (x86)\Microsoft Visual Studio 10.0\ReportViewer")

2) Import (Microsoft.ReportViewer.ProcessingObjectModel.dll) -----> (Path "C:\Windows\Assembly\GAC_MSIL\Microsoft.ReportViewer.ProcessingObjectModel")

3) Import (Microsoft.ReportViewer.WebForms.dll)-----> (Path "C:\Program Files (x86)\Microsoft Visual Studio 10.0\ReportViewer")

B) In Above three DLL set its "Local Copy" to True so that while Building Deployment Package it will getcopied to "Bin" folder.

C) Publish the Solution

D) After that Upload all the files along with "Bin" folder with the help of "File Zilla" software to "Web Server".

E) This will install DLL on server hence, client is not required to have "Report Viewer.dll".

This worked for me.

How can I apply a border only inside a table?

For ordinary table markup, here's a short solution that works on all devices/browsers on BrowserStack, except IE 7 and below:

table { border-collapse: collapse; }

td + td,
th + th { border-left: 1px solid; }
tr + tr { border-top: 1px solid; }

For IE 7 support, add this:

tr + tr > td,
tr + tr > th { border-top: 1px solid; }

A test case can be seen here: http://codepen.io/dalgard/pen/wmcdE

Error C1083: Cannot open include file: 'stdafx.h'

You can fix this problem by adding "$(ProjectDir)" (or wherever the stdafx.h is) to list of directories under Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories.

JavaScript blob filename without link

Same principle as the solutions above. But I had issues with Firefox 52.0 (32 bit) where large files (>40 MBytes) are truncated at random positions. Re-scheduling the call of revokeObjectUrl() fixes this issue.

function saveFile(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename);
  } else {
    const a = document.createElement('a');
    document.body.appendChild(a);
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    a.click();
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }, 0)
  }
}

jsfiddle example

Programmatically add new column to DataGridView

Here's a sample method that adds two extra columns programmatically to the grid view:

    private void AddColumnsProgrammatically()
    {
        // I created these columns at function scope but if you want to access 
        // easily from other parts of your class, just move them to class scope.
        // E.g. Declare them outside of the function...
        var col3 = new DataGridViewTextBoxColumn();
        var col4 = new DataGridViewCheckBoxColumn();

        col3.HeaderText = "Column3";
        col3.Name = "Column3";

        col4.HeaderText = "Column4";
        col4.Name = "Column4";

        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
    }

A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

// Note that this info scattered throughout the designer but can easily collected.

        System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        System.Windows.Forms.DataGridViewCheckBoxColumn Column2;

        this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();

        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.Column1,
        this.Column2});

        this.Column1.HeaderText = "Column1";
        this.Column1.Name = "Column1";

        this.Column2.HeaderText = "Column2";
        this.Column2.Name = "Column2";

git pull while not in a git directory

Starting git 1.8.5 (Q4 2013), you will be able to "use a Git command, but without having to change directories".

Just like "make -C <directory>", "git -C <directory> ..." tells Git to go there before doing anything else.

See commit 44e1e4 by Nazri Ramliy:

It takes more keypresses to invoke Git command in a different directory without leaving the current directory:

  1. (cd ~/foo && git status)
    git --git-dir=~/foo/.git --work-tree=~/foo status
    GIT_DIR=~/foo/.git GIT_WORK_TREE=~/foo git status
  2. (cd ../..; git grep foo)
  3. for d in d1 d2 d3; do (cd $d && git svn rebase); done

The methods shown above are acceptable for scripting but are too cumbersome for quick command line invocations.

With this new option, the above can be done with fewer keystrokes:

  1. git -C ~/foo status
  2. git -C ../.. grep foo
  3. for d in d1 d2 d3; do git -C $d svn rebase; done

Since Git 2.3.4 (March 2015), and commit 6a536e2 by Karthik Nayak (KarthikNayak), git will treat "git -C '<path>'" as a no-op when <path> is empty.

'git -C ""' unhelpfully dies with error "Cannot change to ''", whereas the shell treats cd ""' as a no-op.
Taking the shell's behavior as a precedent, teach git to treat -C ""' as a no-op, as well.


4 years later, Git 2.23 (Q3 2019) documents that 'git -C ""' works and doesn't change directory

It's been behaving so since 6a536e2 (git: treat "git -C '<path>'" as a no-op when <path> is empty, 2015-03-06, Git v2.3.4).

That means the documentation now (finally) includes:

If '<path>' is present but empty, e.g. -C "", then the current working directory is left unchanged.


You can see git -C used with Git 2.26 (Q1 2020), as an example.

See commit b441717, commit 9291e63, commit 5236fce, commit 10812c2, commit 62d58cd, commit b87b02c, commit 9b92070, commit 3595d10, commit f511bc0, commit f6041ab, commit f46c243, commit 99c049b, commit 3738439, commit 7717242, commit b8afb90 (20 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 381e8e9, 05 Feb 2020)

t1507: inline full_name()

Signed-off-by: Denton Liu

Before, we were running test_must_fail full_name. However, test_must_fail should only be used on git commands.
Inline full_name() so that we can use test_must_fail on the git command directly.

When full_name() was introduced in 28fb84382b ("Introduce <branch>@{upstream} notation", 2009-09-10, Git v1.7.0-rc0 -- merge), the git -C option wasn't available yet (since it was introduced in 44e1e4d67d ("git: run in a directory given with -C option", 2013-09-09, Git v1.8.5-rc0 -- merge listed in batch #5)).
As a result, the helper function removed the need to manually cd each time. However, since git -C is available now, we can just use that instead and inline full_name().

Execute a stored procedure in another stored procedure in SQL server

Yes, you can do that like this:

BEGIN
   DECLARE @Results TABLE (Tid INT PRIMARY KEY);

   INSERT @Results

   EXEC Procedure2 [parameters];
   SET @total 1;

END
SELECT @total

Insert PHP code In WordPress Page and Post

Description:

there are 3 steps to run PHP code inside post or page.

  1. In functions.php file (in your theme) add new function

  2. In functions.php file (in your theme) register new shortcode which call your function:

add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
  1. use your new shortcode

Example #1: just display text.

In functions:

function simple_function_1() {
    return "Hello World!";
}

add_shortcode( 'own_shortcode1', 'simple_function_1' );

In post/page:

[own_shortcode1]

Effect:

Hello World!

Example #2: use for loop.

In functions:

function simple_function_2() {
    $output = "";
    
    for ($number = 1; $number < 10; $number++) {    
        // Append numbers to the string
        $output .= "$number<br>";
    } 
    
    return "$output";
}

add_shortcode( 'own_shortcode2', 'simple_function_2' );

In post/page:

[own_shortcode2]

Effect:

1
2
3
4
5
6
7
8
9

Example #3: use shortcode with arguments

In functions:

function simple_function_3($name) {
    return "Hello $name";
}

add_shortcode( 'own_shortcode3', 'simple_function_3' );

In post/page:

[own_shortcode3 name="John"]

Effect:

Hello John

Example #3 - without passing arguments

In post/page:

[own_shortcode3]

Effect:

Hello 

PDO error message?

Old thread, but maybe my answer will help someone. I resolved by executing the query first, then setting an errors variable, then checking if that errors variable array is empty. see simplified example:

$field1 = 'foo';
$field2 = 'bar';

$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);

$insert_QUERY->execute();

$databaseErrors = $insert_QUERY->errorInfo();

if( !empty($databaseErrors) ){  
    $errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
    $errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...         

/* 
 $errorLogMsg will return something like: 
 error info:  
 Array(
  [0] => 42000
  [1] => 1064
  [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table bogus(field1, field2) VALUES                                                  ('bar', NULL)' at line 1
 )
*/
} else {
    # no SQL errors.
}

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

My personal preference is to use grep and the while command. This allows one to write powerful yet readable scripts ensuring that you end up doing exactly what you want. Plus by using an echo command you can perform a dry run before carrying out the actual operation. For example:

ls | grep -v "Music" | while read filename
do
echo $filename
done

will print out the files that you will end up copying. If the list is correct the next step is to simply replace the echo command with the copy command as follows:

ls | grep -v "Music" | while read filename
do
cp "$filename" /target_directory
done

Generate random array of floats between a range

This is the simplest way

np.random.uniform(start,stop,(rows,columns))

Convert nullable bool? to bool

bool? a = null;
bool b = Convert.toBoolean(a); 

module.exports vs. export default in Node.js and ES6

You need to configure babel correctly in your project to use export default and export const foo

npm install --save-dev @babel/plugin-proposal-export-default-from

then add below configration in .babelrc

"plugins": [ 
       "@babel/plugin-proposal-export-default-from"
      ]

top nav bar blocking top content of the page

I am using jQuery to solve this problem. This is the snippet for BS 3.0.0:

$(window).resize(function () { 
    $('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);
});

$(window).load(function () { 
    $('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);        
});

How to iterate over arguments in a Bash script

Rewrite of a now-deleted answer by VonC.

Robert Gamble's succinct answer deals directly with the question. This one amplifies on some issues with filenames containing spaces.

See also: ${1:+"$@"} in /bin/sh

Basic thesis: "$@" is correct, and $* (unquoted) is almost always wrong. This is because "$@" works fine when arguments contain spaces, and works the same as $* when they don't. In some circumstances, "$*" is OK too, but "$@" usually (but not always) works in the same places. Unquoted, $@ and $* are equivalent (and almost always wrong).

So, what is the difference between $*, $@, "$*", and "$@"? They are all related to 'all the arguments to the shell', but they do different things. When unquoted, $* and $@ do the same thing. They treat each 'word' (sequence of non-whitespace) as a separate argument. The quoted forms are quite different, though: "$*" treats the argument list as a single space-separated string, whereas "$@" treats the arguments almost exactly as they were when specified on the command line. "$@" expands to nothing at all when there are no positional arguments; "$*" expands to an empty string — and yes, there's a difference, though it can be hard to perceive it. See more information below, after the introduction of the (non-standard) command al.

Secondary thesis: if you need to process arguments with spaces and then pass them on to other commands, then you sometimes need non-standard tools to assist. (Or you should use arrays, carefully: "${array[@]}" behaves analogously to "$@".)

Example:

    $ mkdir "my dir" anotherdir
    $ ls
    anotherdir      my dir
    $ cp /dev/null "my dir/my file"
    $ cp /dev/null "anotherdir/myfile"
    $ ls -Fltr
    total 0
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 my dir/
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 anotherdir/
    $ ls -Fltr *
    my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    anotherdir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ ls -Fltr "./my dir" "./anotherdir"
    ./my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    ./anotherdir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ var='"./my dir" "./anotherdir"' && echo $var
    "./my dir" "./anotherdir"
    $ ls -Fltr $var
    ls: "./anotherdir": No such file or directory
    ls: "./my: No such file or directory
    ls: dir": No such file or directory
    $

Why doesn't that work? It doesn't work because the shell processes quotes before it expands variables. So, to get the shell to pay attention to the quotes embedded in $var, you have to use eval:

    $ eval ls -Fltr $var
    ./my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    ./anotherdir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ 

This gets really tricky when you have file names such as "He said, "Don't do this!"" (with quotes and double quotes and spaces).

    $ cp /dev/null "He said, \"Don't do this!\""
    $ ls
    He said, "Don't do this!"       anotherdir                      my dir
    $ ls -l
    total 0
    -rw-r--r--   1 jleffler  staff    0 Nov  1 15:54 He said, "Don't do this!"
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 anotherdir
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 my dir
    $ 

The shells (all of them) do not make it particularly easy to handle such stuff, so (funnily enough) many Unix programs do not do a good job of handling them. On Unix, a filename (single component) can contain any characters except slash and NUL '\0'. However, the shells strongly encourage no spaces or newlines or tabs anywhere in a path names. It is also why standard Unix file names do not contain spaces, etc.

When dealing with file names that may contain spaces and other troublesome characters, you have to be extremely careful, and I found long ago that I needed a program that is not standard on Unix. I call it escape (version 1.1 was dated 1989-08-23T16:01:45Z).

Here is an example of escape in use - with the SCCS control system. It is a cover script that does both a delta (think check-in) and a get (think check-out). Various arguments, especially -y (the reason why you made the change) would contain blanks and newlines. Note that the script dates from 1992, so it uses back-ticks instead of $(cmd ...) notation and does not use #!/bin/sh on the first line.

:   "@(#)$Id: delget.sh,v 1.8 1992/12/29 10:46:21 jl Exp $"
#
#   Delta and get files
#   Uses escape to allow for all weird combinations of quotes in arguments

case `basename $0 .sh` in
deledit)    eflag="-e";;
esac

sflag="-s"
for arg in "$@"
do
    case "$arg" in
    -r*)    gargs="$gargs `escape \"$arg\"`"
            dargs="$dargs `escape \"$arg\"`"
            ;;
    -e)     gargs="$gargs `escape \"$arg\"`"
            sflag=""
            eflag=""
            ;;
    -*)     dargs="$dargs `escape \"$arg\"`"
            ;;
    *)      gargs="$gargs `escape \"$arg\"`"
            dargs="$dargs `escape \"$arg\"`"
            ;;
    esac
done

eval delta "$dargs" && eval get $eflag $sflag "$gargs"

(I would probably not use escape quite so thoroughly these days - it is not needed with the -e argument, for example - but overall, this is one of my simpler scripts using escape.)

The escape program simply outputs its arguments, rather like echo does, but it ensures that the arguments are protected for use with eval (one level of eval; I do have a program which did remote shell execution, and that needed to escape the output of escape).

    $ escape $var
    '"./my' 'dir"' '"./anotherdir"'
    $ escape "$var"
    '"./my dir" "./anotherdir"'
    $ escape x y z
    x y z
    $ 

I have another program called al that lists its arguments one per line (and it is even more ancient: version 1.1 dated 1987-01-27T14:35:49). It is most useful when debugging scripts, as it can be plugged into a command line to see what arguments are actually passed to the command.

    $ echo "$var"
    "./my dir" "./anotherdir"
    $ al $var
    "./my
    dir"
    "./anotherdir"
    $ al "$var"
    "./my dir" "./anotherdir"
    $

[Added: And now to show the difference between the various "$@" notations, here is one more example:

$ cat xx.sh
set -x
al $@
al $*
al "$*"
al "$@"
$ sh xx.sh     *      */*
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file
He
said,
"Don't
do
this!"
anotherdir
my
dir
xx.sh
anotherdir/myfile
my
dir/my
file
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file
He
said,
"Don't
do
this!"
anotherdir
my
dir
xx.sh
anotherdir/myfile
my
dir/my
file
+ al 'He said, "Don'\''t do this!" anotherdir my dir xx.sh anotherdir/myfile my dir/my file'
He said, "Don't do this!" anotherdir my dir xx.sh anotherdir/myfile my dir/my file
+ al 'He said, "Don'\''t do this!"' anotherdir 'my dir' xx.sh anotherdir/myfile 'my dir/my file'
He said, "Don't do this!"
anotherdir
my dir
xx.sh
anotherdir/myfile
my dir/my file
$

Notice that nothing preserves the original blanks between the * and */* on the command line. Also, note that you can change the 'command line arguments' in the shell by using:

set -- -new -opt and "arg with space"

This sets 4 options, '-new', '-opt', 'and', and 'arg with space'.
]

Hmm, that's quite a long answer - perhaps exegesis is the better term. Source code for escape available on request (email to firstname dot lastname at gmail dot com). The source code for al is incredibly simple:

#include <stdio.h>
int main(int argc, char **argv)
{
    while (*++argv != 0)
        puts(*argv);
    return(0);
}

That's all. It is equivalent to the test.sh script that Robert Gamble showed, and could be written as a shell function (but shell functions didn't exist in the local version of Bourne shell when I first wrote al).

Also note that you can write al as a simple shell script:

[ $# != 0 ] && printf "%s\n" "$@"

The conditional is needed so that it produces no output when passed no arguments. The printf command will produce a blank line with only the format string argument, but the C program produces nothing.

Sniff HTTP packets for GET and POST requests from an application

post in http
Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

The first line of every source file of your project must be the following:

#include <stdafx.h>

Visit here to understand Precompiled Headers

Set default value of javascript object attributes

my code is:

function(s){
    s = {
        top: s.top || 100,    // default value or s.top
        left: s.left || 300,  // default value or s.left
    }
    alert(s.top)
}

Reading from text file until EOF repeats last line

int x;
ifile >> x

while (!iFile.eof())
{  
    cerr << x << endl;        
    iFile >> x;      
}

How to set a transparent background of JPanel?

(Feature Panel).setOpaque(false);

Hope this helps.

Difference between window.location.href, window.location.replace and window.location.assign

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forums is not correct. The assign method does add a new record to the history.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

.val() or .value is IMHO the best solution because it's useful with Ajax. And .reset() only works after page reload and APIs using Ajax never refresh pages unless it's triggered by a different script.

How to completely DISABLE any MOUSE CLICK

something like:

    $('#doc').click(function(e){
       e.preventDefault()
       e.stopImmediatePropagation() //charles ma is right about that, but stopPropagation isn't also needed
});

should do the job you could also bind more mouse events with replacing for: edit: add this in the feezing part

    $('#doc').bind('click mousedown dblclick',function(e){
       e.preventDefault()
       e.stopImmediatePropagation()
});

and this in the unfreezing:

  $('#doc').unbind();

Windows batch: sleep

Microsoft has a sleep function you can call directly.

    Usage:  sleep      time-to-sleep-in-seconds
            sleep [-m] time-to-sleep-in-milliseconds
            sleep [-c] commited-memory ratio (1%-100%)

You can just say sleep 1 for example to sleep for 1 second in your batch script.

IMO Ping is a bit of a hack for this use case.

Capitalize the first letter of string in AngularJs

For Angular 2 and up, you can use {{ abc | titlecase }}.

Check Angular.io API for complete list.

AngularJS $watch window resize inside directive

You shouldn't need a $watch. Just bind to resize event on window:

DEMO

'use strict';

var app = angular.module('plunker', []);

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'E',
        template: '<div>window size: {{width}}px</div>'
     };

     function link(scope, element, attrs){

       scope.width = $window.innerWidth;

       angular.element($window).bind('resize', function(){

         scope.width = $window.innerWidth;

         // manuall $digest required as resize event
         // is outside of angular
         scope.$digest();
       });

     }

 }]);

If statement in aspx page

Here's a simple one written in VB for an ASPX page:

                If myVar > 1 Then
                    response.write("Greater than 1")
                else
                    response.write("Not!")
                End If

Change a HTML5 input's placeholder color with CSS

Now we have a standard way to apply CSS to an input's placeholder : ::placeholder pseudo-element from this CSS Module Level 4 Draft.

How do you UrlEncode without using System.Web?

The answers here are very good, but still insufficient for me.

I wrote a small loop that compares Uri.EscapeUriString with Uri.EscapeDataString for all characters from 0 to 255.

NOTE: Both functions have the built-in intelligence that characters above 0x80 are first UTF-8 encoded and then percent encoded.

Here is the result:

******* Different *******

'#' -> Uri "#" Data "%23"
'$' -> Uri "$" Data "%24"
'&' -> Uri "&" Data "%26"
'+' -> Uri "+" Data "%2B"
',' -> Uri "," Data "%2C"
'/' -> Uri "/" Data "%2F"
':' -> Uri ":" Data "%3A"
';' -> Uri ";" Data "%3B"
'=' -> Uri "=" Data "%3D"
'?' -> Uri "?" Data "%3F"
'@' -> Uri "@" Data "%40"


******* Not escaped *******

'!' -> Uri "!" Data "!"
''' -> Uri "'" Data "'"
'(' -> Uri "(" Data "("
')' -> Uri ")" Data ")"
'*' -> Uri "*" Data "*"
'-' -> Uri "-" Data "-"
'.' -> Uri "." Data "."
'_' -> Uri "_" Data "_"
'~' -> Uri "~" Data "~"

'0' -> Uri "0" Data "0"
.....
'9' -> Uri "9" Data "9"

'A' -> Uri "A" Data "A"
......
'Z' -> Uri "Z" Data "Z"

'a' -> Uri "a" Data "a"
.....
'z' -> Uri "z" Data "z"

******* UTF 8 *******

.....
'Ò' -> Uri "%C3%92" Data "%C3%92"
'Ó' -> Uri "%C3%93" Data "%C3%93"
'Ô' -> Uri "%C3%94" Data "%C3%94"
'Õ' -> Uri "%C3%95" Data "%C3%95"
'Ö' -> Uri "%C3%96" Data "%C3%96"
.....

EscapeUriString is to be used to encode URLs, while EscapeDataString is to be used to encode for example the content of a Cookie, because Cookie data must not contain the reserved characters '=' and ';'.

How to access the correct `this` inside a callback?

The trouble with "context"

The term "context" is sometimes used to refer to the object referenced by this. Its use is inappropriate because it doesn't fit either semantically or technically with ECMAScript's this.

"Context" means the circumstances surrounding something that adds meaning, or some preceding and following information that gives extra meaning. The term "context" is used in ECMAScript to refer to execution context, which is all the parameters, scope, and this within the scope of some executing code.

This is shown in ECMA-262 section 10.4.2:

Set the ThisBinding to the same value as the ThisBinding of the calling execution context

which clearly indicates that this is part of an execution context.

An execution context provides the surrounding information that adds meaning to the code that is being executed. It includes much more information than just the thisBinding.

So the value of this isn't "context", it's just one part of an execution context. It's essentially a local variable that can be set by the call to any object and in strict mode, to any value at all.

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0) you are less likely to to see a difference between the two approaches.

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

Trying to get Laravel 5 email to work

I've had the same problem; my MAIL_ENCRYPTION was tls on mail.php but it was null on .env file.
So I changed null to tls and it worked!

Multiline input form field using Bootstrap

The answer by Nick Mitchinson is for Bootstrap version 2.

If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:

<div class="form-horizontal">
    <div class="form-group">
        <div class="col-md-6">
            <textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
        </div>
    </div>
</div>

Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.

problem with <select> and :after with CSS in WebKit

I haven't checked this extensively, but I'm under the impression that this isn't (yet?) possible, due to the way in which select elements are generated by the OS on which the browser runs, rather than the browser itself.

Using jquery to get all checked checkboxes with a certain class name

If you need to get the value of all checked checkboxes as an array:

let myArray = (function() {
    let a = [];
    $(".checkboxes:checked").each(function() {
        a.push(this.value);
    });
    return a;
})()

Bootstrap 4 img-circle class not working

It's now called rounded-circle as explained here in the BS4 docs

<img src="img/gallery2.JPG" class="rounded-circle">

Demo

How to push local changes to a remote git repository on bitbucket

I'm with Git downloaded from https://git-scm.com/ and set up ssh follow to the answer for instructions https://stackoverflow.com/a/26130250/4058484.

Once the generated public key is verified in my Bitbucket account, and by referring to the steps as explaned on http://www.bohyunkim.net/blog/archives/2518 I found that just 'git push' is working:

git clone https://[email protected]/me/test.git
cd test
cp -R ../dummy/* .
git add .
git pull origin master 
git commit . -m "my first git commit" 
git config --global push.default simple
git push

Shell respond are as below:

$ git push
Counting objects: 39, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (39/39), done.
Writing objects: 100% (39/39), 2.23 MiB | 5.00 KiB/s, done.
Total 39 (delta 1), reused 0 (delta 0)
To https://[email protected]/me/test.git 992b294..93835ca  master -> master

It even works for to push on merging master to gh-pages in GitHub

git checkout gh-pages
git merge master
git push

How to refresh an IFrame using Javascript?

Got this from here

var f = document.getElementById('iframe1');
f.src = f.src;

WebView and HTML5 <video>

I used html5webview to solve this problem.Download and put it into your project then you can code just like this.

private HTML5WebView mWebView;
String url = "SOMEURL";
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mWebView = new HTML5WebView(this);
    if (savedInstanceState != null) {
            mWebView.restoreState(savedInstanceState);
    } else {
            mWebView.loadUrl(url);
    }
    setContentView(mWebView.getLayout());
}
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mWebView.saveState(outState);
}

To make the video rotatable, put android:configChanges="orientation" code into your Activity for example (Androidmanifest.xml)

<activity android:name=".ui.HTML5Activity" android:configChanges="orientation"/>

and override the onConfigurationChanged method.

@Override
public void onConfigurationChanged(Configuration newConfig) {
     super.onConfigurationChanged(newConfig);
}

How many parameters are too many?

For me , when the list crosses one line on my IDE, then it's one parameter too many. I want to see all the parameters in one line without breaking eye contact. But that's just my personal preference.

How to remove "disabled" attribute using jQuery?

2018, without JQuery

I know the question is about JQuery: this answer is just FYI.

document.getElementById('edit').addEventListener(event => {
    event.preventDefault();
    [...document.querySelectorAll('.inputDisabled')].map(e => e.disabled = false);
}); 

How do you right-justify text in an HTML textbox?

Did you try setting the style:

input {
    text-align:right;
}

Just tested, this works fine (in FF3 at least):

<html>
    <head>
        <title>Blah</title>
        <style type="text/css">
        input { text-align:right; }
        </style>
    </head>
    <body>
        <input type="text" value="2">
    </body>
</html>

You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.

Line Break in XML?

@icktoofay was close with the CData

<myxml>
    <record>
        <![CDATA[
        Line 1 <br />
        Line 2 <br />
        Line 3 <br />
        ]]>
    </record>
</myxml>

How to write asynchronous functions for Node.js

You seem to be confusing asynchronous IO with asynchronous functions. node.js uses asynchronous non-blocking IO because non blocking IO is better. The best way to understand it is to go watch some videos by ryan dahl.

How do I write asynchronous functions for Node?

Just write normal functions, the only difference is that they are not executed immediately but passed around as callbacks.

How should I implement error event handling correctly

Generally API's give you a callback with an err as the first argument. For example

database.query('something', function(err, result) {
  if (err) handle(err);
  doSomething(result);
});

Is a common pattern.

Another common pattern is on('error'). For example

process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
});

Edit:

var async_function = function(val, callback){
    process.nextTick(function(){
        callback(val);
    });
};

The above function when called as

async_function(42, function(val) {
  console.log(val)
});
console.log(43);

Will print 42 to the console asynchronously. In particular process.nextTick fires after the current eventloop callstack is empty. That call stack is empty after async_function and console.log(43) have run. So we print 43 followed by 42.

You should probably do some reading on the event loop.

Counting Line Numbers in Eclipse

Search > File Search

Check the Regular expression box.

Use this expression:

\n[\s]*

Select whatever file types (*.java, *.xml, etc..) and working sets are appropriate for you.

How to increase Maximum Upload size in cPanel?

In my case it was wp-admin/.user.ini:

post_max_size = 33M
upload_max_filesize = 32M

Connecting to smtp.gmail.com via command line

Try this:

telnet smtp.gmail.com 587

Bootstrap carousel resizing image

Use this code to set height of the image slider to the full screen / upto 100 view port height. This will helpful when using bootstrap carousel theme slider. I face some issue with height the i use following classes to set image width 100% & height 100vh.

<img class="d-block w-100" src="" alt="" > use this class in image tags & write following css code in style tags or style.css file

.carousel-inner > .carousel-item > img {
  height: 100vh;
}

How to create a stopwatch using JavaScript?

Two native solutions

  • performance.now --> Call to ... took 6.414999981643632 milliseconds.
  • console.time --> Call to ... took 5.815 milliseconds

The difference between both is precision.

For usage and explanation read on.



Performance.now (For microsecond precision use)

_x000D_
_x000D_
    var t0 = performance.now();
    doSomething();
    var t1 = performance.now();

    console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
            
    function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
    }
_x000D_
_x000D_
_x000D_

performance.now

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().



console.time

Example: (timeEnd wrapped in setTimeout for simulation)

_x000D_
_x000D_
console.time('Search page');
  doSomething();
console.timeEnd('Search page');
 

 function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
 }
_x000D_
_x000D_
_x000D_

You can change the Timer-Name for different operations.

Android - SMS Broadcast receiver

intent.getAction().equals(SMS_RECEIVED)

I have tried it out successfully.

What's the right way to decode a string that has special HTML entities in it?

This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

Example: http://jsfiddle.net/k65s3/

Input:

Entity:&nbsp;Bad attempt at XSS:<script>alert('new\nline?')</script><br>

Output:

Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>

MySQL: selecting rows where a column is null

Info from http://w3schools.com/sql/sql_null_values.asp:

1) NULL values represent missing unknown data.

2) By default, a table column can hold NULL values.

3) NULL values are treated differently from other values

4) It is not possible to compare NULL and 0; they are not equivalent.

5) It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

6) We will have to use the IS NULL and IS NOT NULL operators instead

So in case of your problem:

SELECT pid FROM planets WHERE userid IS NULL

Create a shortcut on Desktop

Here is a piece of code that has no dependency on an external COM object (WSH), and supports 32-bit and 64-bit programs:

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;

namespace TestShortcut
{
    class Program
    {
        static void Main(string[] args)
        {
            IShellLink link = (IShellLink)new ShellLink();

            // setup shortcut information
            link.SetDescription("My Description");
            link.SetPath(@"c:\MyPath\MyProgram.exe");

            // save it
            IPersistFile file = (IPersistFile)link;
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            file.Save(Path.Combine(desktopPath, "MyLink.lnk"), false);
        }
    }

    [ComImport]
    [Guid("00021401-0000-0000-C000-000000000046")]
    internal class ShellLink
    {
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("000214F9-0000-0000-C000-000000000046")]
    internal interface IShellLink
    {
        void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out IntPtr pfd, int fFlags);
        void GetIDList(out IntPtr ppidl);
        void SetIDList(IntPtr pidl);
        void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
        void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
        void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
        void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
        void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
        void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
        void GetHotkey(out short pwHotkey);
        void SetHotkey(short wHotkey);
        void GetShowCmd(out int piShowCmd);
        void SetShowCmd(int iShowCmd);
        void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
        void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
        void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
        void Resolve(IntPtr hwnd, int fFlags);
        void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
    }
}

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

Apart from what Andy mentioned, there is another difference which could be important - write-host directly writes to the host and return nothing, meaning that you can't redirect the output, e.g., to a file.

---- script a.ps1 ----
write-host "hello"

Now run in PowerShell:

PS> .\a.ps1 > someFile.txt
hello
PS> type someFile.txt
PS>

As seen, you can't redirect them into a file. This maybe surprising for someone who are not careful.

But if switched to use write-output instead, you'll get redirection working as expected.

Can a background image be larger than the div itself?

Using background-size cover worked for me.

#footer {
    background-color: #eee;
    background-image: url(images/bodybgbottomleft.png);
    background-repeat: no-repeat;
    background-size: cover;
    clear: both;
    width: 100%;
    margin: 0;
    padding: 30px 0 0;
}

Obviously be aware of support issues, check Can I Use: http://caniuse.com/#search=background-size

How to read a line from a text file in c/c++?

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

#include <stdio.h>
#include <stdlib.h>

void handle_line(char *line) {
  printf("%s", line);
}

int main(int argc, char *argv[]) {
    int size = 1024, pos;
    int c;
    char *buffer = (char *)malloc(size);

    FILE *f = fopen("myfile.txt", "r");
    if(f) {
      do { // read all lines in file
        pos = 0;
        do{ // read one line
          c = fgetc(f);
          if(c != EOF) buffer[pos++] = (char)c;
          if(pos >= size - 1) { // increase buffer length - leave room for 0
            size *=2;
            buffer = (char*)realloc(buffer, size);
          }
        }while(c != EOF && c != '\n');
        buffer[pos] = 0;
        // line is now in buffer
        handle_line(buffer);
      } while(c != EOF); 
      fclose(f);           
    }
    free(buffer);
    return 0;
}

Difference between return and exit in Bash functions

First of all, return is a keyword and exit is a function.

That said, here's a simplest of explanations.

return

It returns a value from a function.

exit

It exits out of or abandons the current shell.

How do you push a tag to a remote repository using Git?

You can push the tags like this git push --tags

How can I autoformat/indent C code in vim?

Maybe you can try the followings $indent -kr -i8 *.c

Hope it's useful for you!

setting an environment variable in virtualenv

Using only virtualenv (without virtualenvwrapper), setting environment variables is easy through the activate script you sourcing in order to activate the virtualenv.

Run:

nano YOUR_ENV/bin/activate

Add the environment variables to the end of the file like this:

export KEY=VALUE

You can also set a similar hook to unset the environment variable as suggested by Danilo Bargen in his great answer above if you need.

Transition color fade on hover?

For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

_x000D_
_x000D_
.field-error {_x000D_
    color: #f44336;_x000D_
    padding: 2px 5px;_x000D_
    position: absolute;_x000D_
    font-size: small;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
    animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
    -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
    -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
    -o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
    from { background-color: lightgreen; } /** from color **/_x000D_
    to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
_x000D_
_x000D_

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

You can get also get this error trying to drop a non-existing foreign key. So when dropping foreign keys, always make sure they actually exist.

If the foreign key does exist, and you are still getting this error try the following:

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';

// Drop the foreign key here!

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

This always does the trick for me :)

Why does Java's hashCode() in String use 31 as a multiplier?

In latest version of JDK, 31 is still used. https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/String.html#hashCode()

The purpose of hash string is

  • unique (Let see operator ^ in hashcode calculation document, it help unique)
  • cheap cost for calculating

31 is max value can put in 8 bit (= 1 byte) register, is largest prime number can put in 1 byte register, is odd number.

Multiply 31 is <<5 then subtract itself, therefore need cheap resources.

How to add an extra language input to Android?

Sliding the space bar only works if you gave more then one input language selected.

In that case the space bar will also indicate the selected language and show arrows to indicate Sliding will change selection.

This is easy fast and changes the dictionary at the same time.

First response seems the mist accurate.

Regards

Is there an embeddable Webkit component for Windows / C# development?

Haven't tried yet but found WebKit.NET on SourceForge. It was moved to GitHub.

Warning: Not maintained anymore, last commits are from early 2013

comma separated string of selected values in mysql

First to set group_concat_max_len, otherwise it will not give you all the result:

SET GLOBAL  group_concat_max_len = 999999;
SELECT GROUP_CONCAT(id)  FROM table_level where parent_id=4 group by parent_id;

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

jQuery's .click - pass parameters to user function

I get the simple solution:

 <button id="btn1" onclick="sendData(20)">ClickMe</button>

<script>
   var id; // global variable
   function sendData(valueId){
     id = valueId;
   }
   $("#btn1").click(function(){
        alert(id);
     });
</script>

My mean is that pass the value onclick event to the javascript function sendData(), initialize to the variable and take it by the jquery event handler method.

This is possible since at first sendData(valueid) gets called and initialize the value. Then after jquery event get's executed and use that value.

This is the straight forward solution and For Detail solution go Here.

Git: How configure KDiff3 as merge tool and diff tool

To amend kris' answer, starting with Git 2.20 (Q4 2018), the proper command for git mergetool will be

git config --global merge.guitool kdiff3 

That is because "git mergetool" learned to take the "--[no-]gui" option, just like "git difftool" does.

See commit c217b93, commit 57ba181, commit 063f2bd (24 Oct 2018) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 87c15d1, 30 Oct 2018)

mergetool: accept -g/--[no-]gui as arguments

In line with how difftool accepts a -g/--[no-]gui option, make mergetool accept the same option in order to use the merge.guitool variable to find the default mergetool instead of merge.tool.

Writing JSON object to a JSON file with fs.writeFileSync

Make the json human readable by passing a third argument to stringify:

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output, null, 4));

how to draw directed graphs using networkx in python?

Instead of regular nx.draw you may want to use:

nx.draw_networkx(G[, pos, arrows, with_labels])

For example:

nx.draw_networkx(G, arrows=True, **options)

You can add options by initialising that ** variable like this:

options = {
    'node_color': 'blue',
    'node_size': 100,
    'width': 3,
    'arrowstyle': '-|>',
    'arrowsize': 12,
}

Also some functions support the directed=True parameter In this case this state is the default one:

G = nx.DiGraph(directed=True)

The networkx reference is found here.

Graph with arrows image

Centering in CSS Grid

I know this question is a couple years old, but I am surprised to find that no one suggested:

   text-align: center;

this is a more universal property than justify-content, and is definitely not unique to grid, but I find that when dealing with text, which is what this question specifically asks about, that it aligns text to the center with-out affecting the space between grid items, or the vertical centering. It centers text horizontally where its stands on its vertical axis. I also find it to remove a layer of complexity that justify-content and align-items adds. justify-content and align-items affects the entire grid item or items, text-align centers the text without affecting the container it is in. Hope this helps.

Importing Excel files into R, xlsx or xls

If you are running into the same problem and R is giving you an error -- could not find function ".jnew" -- Just install the library rJava. Or if you have it already just run the line library(rJava). That should be the problem.

Also, it should be clear to everybody that csv and txt files are easier to work with, but life is not easy and sometimes you just have to open an xlsx.

Checking if a SQL Server login already exists

In order to hande naming conflict between logins, roles, users etc. you should check the type column according to Microsoft sys.database_principals documentation

In order to handle special chacters in usernames etc, use N'<name>' and [<name>] accordingly.

Create login

USE MASTER
IF NOT EXISTS (SELECT 1 FROM master.sys.server_principals WHERE 
[name] = N'<loginname>' and [type] IN ('C','E', 'G', 'K', 'S', 'U'))
    CREATE LOGIN [<loginname>] <further parameters>

Create database user

USE [<databasename>]
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE 
[name] = N'<username>' and [type] IN ('C','E', 'G', 'K', 'S', 'U'))
    CREATE USER [<username>] FOR LOGIN [<loginname>]

Create database role

USE [<databasename>]
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE 
[name] = N'<rolename>' and Type = 'R')
    CREATE ROLE [<rolename>]

Add user to role

USE [<databasename>]
EXEC sp_addrolemember N'<rolename>', N'<username>'

Grant rights to role

USE [<databasename>]
GRANT SELECT ON [<tablename>] TO [<rolename>]
GRANT UPDATE ON [<tablename>] ([<columnname>]) TO [<rolename>]
GRANT EXECUTE ON [<procedurename>] TO [<rolename>]

The SQL is tested on SQL Server 2005, 2008, 2008 R2, 2014, 2016, 2017, 2019

Check if a time is between two times (time DataType)

Let us consider a table which stores the shift details

enter image description here

Please check the SQL queries to generate table and finding the schedule based on an input(time)

Declaring the Table variable

declare @MyShiftTable table(MyShift int,StartTime time,EndTime time)

Adding values to Table variable

insert into @MyShiftTable select 1,'01:17:40.3530000','02:17:40.3530000'
insert into @MyShiftTable select 2,'09:17:40.3530000','03:17:40.3530000'
insert into @MyShiftTable select 3,'10:17:40.3530000','18:17:40.3530000'

Creating another table variable with an additional field named "Flag"

declare @Temp table(MyShift int,StartTime time,EndTime time,Flag int)

Adding values to temporary table with swapping the start and end time

insert into @Temp select MyShift,case when (StartTime>EndTime) then EndTime else StartTime end,case when (StartTime>EndTime) then StartTime else EndTime end,case when (StartTime>EndTime) then 1 else 0 end from @MyShiftTable

Creating input variable to find the Shift

declare @time time=convert(time,'10:12:40.3530000')

Query to find the shift corresponding to the time supplied

select myShift from @Temp where
(@time between StartTime and EndTime and Flag=0) or (@time not between StartTime and EndTime and Flag=1)

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

Found this: https://coderwall.com/p/ngisma where Nathan Walker (near bottom of page) suggests a decorator in $rootScope to create func 'safeApply', code:

yourAwesomeModule.config([
  '$provide', function($provide) {
    return $provide.decorator('$rootScope', [
      '$delegate', function($delegate) {
        $delegate.safeApply = function(fn) {
          var phase = $delegate.$$phase;
          if (phase === "$apply" || phase === "$digest") {
            if (fn && typeof fn === 'function') {
              fn();
            }
          } else {
            $delegate.$apply(fn);
          }
        };
        return $delegate;
      }
    ]);
  }
]);

Change image source in code behind - Wpf

None of the above solutions worked for me. But this did:

myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));

ng-model for `<input type="file"/>` (with directive DEMO)

function filesModelDirective(){
  return {
    controller: function($parse, $element, $attrs, $scope){
      var exp = $parse($attrs.filesModel);
      $element.on('change', function(){
        exp.assign($scope, this.files[0]);
        $scope.$apply();
      });
    }
  };
}
app.directive('filesModel', filesModelDirective);

What does "hard coded" mean?

The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.

  • Hard-coding: feature is coded to the system not allowing for configuration;
  • Parametric: feature is configurable via table driven, or properties files with limited parametric values ;
  • Soft-coding: feature uses “engines” that derive results based on any number of parametric values (e.g. business rules in BRE); rules are coded but exist as parameters in system, written in script form

Examples:

// firstName has a hard-coded value of "hello world"
string firstName = "hello world";

// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();

A hard-coded constant[1]:

float areaOfCircle(int radius)
{
    float area = 0;
    area = 3.14*radius*radius;  //  3.14 is a hard-coded value
    return area;
}

Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.

  1. Hard CodingHard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.

    The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.

  2. Soft Coding
    If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.

    In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.

    In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.

Sources and Citations:

1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid

Further Reading:

Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding

How to set the JSTL variable value in javascript?

<script ...
  function(){
   var someJsVar = "<c:out value='${someJstLVarFromBackend}'/>";

  }
</script>

This works even if you dont have a hidden/non-hidden input field set somewhere in the jsp.

Can't access to HttpContext.Current

This is because you are referring to property of controller named HttpContext. To access the current context use full class name:

System.Web.HttpContext.Current

However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current as being deprecated inside ASP.NET MVC. The correct way to access current context is

this.ControllerContext.HttpContext

or if you are inside a Controller, just use member

this.HttpContext

OnItemCLickListener not working in listview

I had the same issue, I was using a style for my texts in the row layout that had the "focusable" attribute. It worked after I removed it.

How do I convert a double into a string in C++?

The boost (tm) way:

std::string str = boost::lexical_cast<std::string>(dbl);

The Standard C++ way:

std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

Note: Don't forget #include <sstream>

UIBarButtonItem in navigation bar programmatically?

Just setup UIBarButtonItem with customView

For example:

  var leftNavBarButton = UIBarButtonItem(customView:yourButton)
  self.navigationItem.leftBarButtonItem = leftNavBarButton

or use setFunction:

  self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(customView: yourButton), animated: true);

How are VST Plugins made?

Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve

How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).

The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:

EXPORTS main=_main

Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.

This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:

  1. Include float.h.
  2. In the constructor of your effect class, write

    _control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
    

That should do the trick.

Here are some more useful sites:

http://www.steinberg.net/en/company/developer.html

how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial

How to read and write excel file

Apache POI can do this for you. Specifically the HSSF module. The quick guide is most useful. Here's how to do what you want - specifically create a sheet and write it out.

Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);

// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

Print a list of space-separated elements in Python 3

Joining elements in a list space separated:

word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
   joined_string = w + joined_string + " "
print(joined_string.rstrim())

Copying files into the application folder at compile time

You can use a MSBuild task on your csproj, like that.

Edit your csproj file

  <Target Name="AfterBuild">
    <Copy SourceFiles="$(OutputPath)yourfiles" DestinationFolder="$(YourVariable)" ContinueOnError="true" />
  </Target>

PHP - Merging two arrays into one array (also Remove Duplicates)

Merging two array will not remove the duplicate you can try the below example to get unique from two array

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_diff($a1,$a2);
print_r($result);

Switch case: can I use a range instead of a one number

I would use ternary operators to categorize your switch conditions.

So...

switch( number > 9 ? "High" :
        number > 5 ? "Mid" :
        number > 1 ? "Low" : "Floor")
        {
              case "High":
                    do the thing;
                    break;
               case "Mid":
                    do the other thing;
                    break;
               case "Low":
                    do something else;
                    break;
               case "Floor":
                    do whatever;
                    break;
         }

How to loop through files matching wildcard in batch file

Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.

According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:

for %%f in (*.in) do call process.cmd %%~nf

Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:

echo The file is %0
copy %0.in %0.out
ren %0.out monkeys_are_cool.txt

There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.

EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...

Recommended way of making React component/div draggable

I implemented react-dnd, a flexible HTML5 drag-and-drop mixin for React with full DOM control.

Existing drag-and-drop libraries didn't fit my use case so I wrote my own. It's similar to the code we've been running for about a year on Stampsy.com, but rewritten to take advantage of React and Flux.

Key requirements I had:

  • Emit zero DOM or CSS of its own, leaving it to the consuming components;
  • Impose as little structure as possible on consuming components;
  • Use HTML5 drag and drop as primary backend but make it possible to add different backends in the future;
  • Like original HTML5 API, emphasize dragging data and not just “draggable views”;
  • Hide HTML5 API quirks from the consuming code;
  • Different components may be “drag sources” or “drop targets” for different kinds of data;
  • Allow one component to contain several drag sources and drop targets when needed;
  • Make it easy for drop targets to change their appearance if compatible data is being dragged or hovered;
  • Make it easy to use images for drag thumbnails instead of element screenshots, circumventing browser quirks.

If these sound familiar to you, read on.

Usage

Simple Drag Source

First, declare types of data that can be dragged.

These are used to check “compatibility” of drag sources and drop targets:

// ItemTypes.js
module.exports = {
  BLOCK: 'block',
  IMAGE: 'image'
};

(If you don't have multiple data types, this libary may not be for you.)

Then, let's make a very simple draggable component that, when dragged, represents IMAGE:

var { DragDropMixin } = require('react-dnd'),
    ItemTypes = require('./ItemTypes');

var Image = React.createClass({
  mixins: [DragDropMixin],

  configureDragDrop(registerType) {

    // Specify all supported types by calling registerType(type, { dragSource?, dropTarget? })
    registerType(ItemTypes.IMAGE, {

      // dragSource, when specified, is { beginDrag(), canDrag()?, endDrag(didDrop)? }
      dragSource: {

        // beginDrag should return { item, dragOrigin?, dragPreview?, dragEffect? }
        beginDrag() {
          return {
            item: this.props.image
          };
        }
      }
    });
  },

  render() {

    // {...this.dragSourceFor(ItemTypes.IMAGE)} will expand into
    // { draggable: true, onDragStart: (handled by mixin), onDragEnd: (handled by mixin) }.

    return (
      <img src={this.props.image.url}
           {...this.dragSourceFor(ItemTypes.IMAGE)} />
    );
  }
);

By specifying configureDragDrop, we tell DragDropMixin the drag-drop behavior of this component. Both draggable and droppable components use the same mixin.

Inside configureDragDrop, we need to call registerType for each of our custom ItemTypes that component supports. For example, there might be several representations of images in your app, and each would provide a dragSource for ItemTypes.IMAGE.

A dragSource is just an object specifying how the drag source works. You must implement beginDrag to return item that represents the data you're dragging and, optionally, a few options that adjust the dragging UI. You can optionally implement canDrag to forbid dragging, or endDrag(didDrop) to execute some logic when the drop has (or has not) occured. And you can share this logic between components by letting a shared mixin generate dragSource for them.

Finally, you must use {...this.dragSourceFor(itemType)} on some (one or more) elements in render to attach drag handlers. This means you can have several “drag handles” in one element, and they may even correspond to different item types. (If you're not familiar with JSX Spread Attributes syntax, check it out).

Simple Drop Target

Let's say we want ImageBlock to be a drop target for IMAGEs. It's pretty much the same, except that we need to give registerType a dropTarget implementation:

var { DragDropMixin } = require('react-dnd'),
    ItemTypes = require('./ItemTypes');

var ImageBlock = React.createClass({
  mixins: [DragDropMixin],

  configureDragDrop(registerType) {

    registerType(ItemTypes.IMAGE, {

      // dropTarget, when specified, is { acceptDrop(item)?, enter(item)?, over(item)?, leave(item)? }
      dropTarget: {
        acceptDrop(image) {
          // Do something with image! for example,
          DocumentActionCreators.setImage(this.props.blockId, image);
        }
      }
    });
  },

  render() {

    // {...this.dropTargetFor(ItemTypes.IMAGE)} will expand into
    // { onDragEnter: (handled by mixin), onDragOver: (handled by mixin), onDragLeave: (handled by mixin), onDrop: (handled by mixin) }.

    return (
      <div {...this.dropTargetFor(ItemTypes.IMAGE)}>
        {this.props.image &&
          <img src={this.props.image.url} />
        }
      </div>
    );
  }
);

Drag Source + Drop Target In One Component

Say we now want the user to be able to drag out an image out of ImageBlock. We just need to add appropriate dragSource to it and a few handlers:

var { DragDropMixin } = require('react-dnd'),
    ItemTypes = require('./ItemTypes');

var ImageBlock = React.createClass({
  mixins: [DragDropMixin],

  configureDragDrop(registerType) {

    registerType(ItemTypes.IMAGE, {

      // Add a drag source that only works when ImageBlock has an image:
      dragSource: {
        canDrag() {
          return !!this.props.image;
        },

        beginDrag() {
          return {
            item: this.props.image
          };
        }
      }

      dropTarget: {
        acceptDrop(image) {
          DocumentActionCreators.setImage(this.props.blockId, image);
        }
      }
    });
  },

  render() {

    return (
      <div {...this.dropTargetFor(ItemTypes.IMAGE)}>

        {/* Add {...this.dragSourceFor} handlers to a nested node */}
        {this.props.image &&
          <img src={this.props.image.url}
               {...this.dragSourceFor(ItemTypes.IMAGE)} />
        }
      </div>
    );
  }
);

What Else Is Possible?

I have not covered everything but it's possible to use this API in a few more ways:

  • Use getDragState(type) and getDropState(type) to learn if dragging is active and use it to toggle CSS classes or attributes;
  • Specify dragPreview to be Image to use images as drag placeholders (use ImagePreloaderMixin to load them);
  • Say, we want to make ImageBlocks reorderable. We only need them to implement dropTarget and dragSource for ItemTypes.BLOCK.
  • Suppose we add other kinds of blocks. We can reuse their reordering logic by placing it in a mixin.
  • dropTargetFor(...types) allows to specify several types at once, so one drop zone can catch many different types.
  • When you need more fine-grained control, most methods are passed drag event that caused them as the last parameter.

For up-to-date documentation and installation instructions, head to react-dnd repo on Github.

Encrypt & Decrypt using PyCrypto AES 256

Here is my implementation and works for me with some fixes and enhances the alignment of the key and secret phrase with 32 bytes and iv to 16 bytes:

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):

    def __init__(self, key): 
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw.encode()))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

JQuery window scrolling event?

See jQuery.scroll(). You can bind this to the window element to get your desired event hook.

On scroll, then simply check your scroll position:

$(window).scroll(function() {
  var scrollTop = $(window).scrollTop();
  if ( scrollTop > $(headerElem).offset().top ) { 
    // display add
  }
});

What is the difference between "long", "long long", "long int", and "long long int" in C++?

This looks confusing because you are taking long as a datatype itself.

long is nothing but just the shorthand for long int when you are using it alone.

long is a modifier, you can use it with double also as long double.

long == long int.

Both of them take 4 bytes.

How to Increase Import Size Limit in phpMyAdmin

I had the same problem with my working correctly by doing the following

changes into the php.ini file

post_max_size = 800M 
upload_max_filesize = 800M 
max_execution_time = 5000 
max_input_time = 5000 
memory_limit = 1000M 

now restart for the changes to take effect

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

Answer is adding this 2 lines of code to Global.asax.cs Application_Start method

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All;

Reference: Handling Circular Object References

Singleton design pattern vs Singleton beans in Spring container

I find "per container per bean" difficult to apprehend. I would say "one bean per bean id in a container".Lets have an example to understand it. We have a bean class Sample. I have defined two beans from this class in bean definition, like:

<bean id="id1" class="com.example.Sample" scope="singleton">
        <property name="name" value="James Bond 001"/>    
</bean>    
<bean id="id7" class="com.example.Sample" scope="singleton">
        <property name="name" value="James Bond 007"/>    
</bean>

So when ever I try to get the bean with id "id1",the spring container will create one bean, cache it and return same bean where ever refered with id1. If I try to get it with id7, another bean will be created from Sample class, same will be cached and returned each time you referred that with id7.

This is unlikely with Singleton pattern. In Singlton pattern one object per class loader is created always. However in Spring, making the scope as Singleton does not restrict the container from creating many instances from that class. It just restricts new object creation for the same ID again, returning previously created object when an object is requested for the same id. Reference

Stop MySQL service windows

This is a newer and easier answer.

  1. Run cmd as admin
  2. Type "net start mysql" then the version number, in my case "net start mysql80" for MySQL 8.0.
  3. If it says it's already running great, otherwise now mysql is running.
  4. Exit cmd, WIN+R and type services.msc, scroll down until you find my sql with the right version.
  5. Right-Click for properties, under startup type select 'Manual', then under service status select 'Stop'
  6. Now you stopped mysql service and it will not run automatically again.
  7. To turn it back on, in cmd admin 'net start mysql' and the version number, in my case 'net start mysql80'

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Making RGB color in Xcode

Objective-C

You have to give the values between 0 and 1.0. So divide the RGB values by 255.

myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;

Update:

You can also use this macro

#define Rgb2UIColor(r, g, b)  [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]

and you can call in any of your class like this

 myLabel.textColor = Rgb2UIColor(160, 97, 5);

Swift

This is the normal color synax

myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0) 
//The values should be between 0 to 1

Swift is not much friendly with macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

So we use extension for this

extension UIColor {
    convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
}

You can use it like

myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)

Select unique or distinct values from a list in UNIX shell script

With zsh you can do this:

% cat infile 
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class

Or you can use AWK:

% awk '!_[$0]++' infile    
tar
more than one word
gz
java
class

How to subtract date/time in JavaScript?

If you wish to get difference in wall clock time, for local timezone and with day-light saving awareness.


Date.prototype.diffDays = function (date: Date): number {

    var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());

    return (utcThis - utcOther) / 86400000;
};

Test


it('diffDays - Czech DST', function () {
    // expect this to parse as local time
    // with Czech calendar DST change happened 2012-03-25 02:00
    var pre = new Date('2012/03/24 03:04:05');
    var post = new Date('2012/03/27 03:04:05');

    // regardless DST, you still wish to see 3 days
    expect(pre.diffDays(post)).toEqual(-3);
});

Diff minutes or seconds is in same fashion.

How do I calculate someone's age in Java?

What about this one?

public Integer calculateAge(Date date) {
    if (date == null) {
        return null;
    }
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(date);
    Calendar cal2 = Calendar.getInstance();
    int i = 0;
    while (cal1.before(cal2)) {
        cal1.add(Calendar.YEAR, 1);
        i += 1;
    }
    return i;
}

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

How can I count all the lines of code in a directory recursively?

Use find's -exec and awk. Here we go:

find . -type f -exec wc -l {} \; | awk '{ SUM += $0} END { print SUM }'

This snippet finds for all files (-type f). To find by file extension, use -name:

find . -name '*.py' -exec wc -l '{}' \; | awk '{ SUM += $0; } END { print SUM; }'

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

How to drop all tables from a database with one SQL query?

If you want to use only one SQL query to delete all tables you can use this:

EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

This is a hidden Stored Procedure in sql server, and will be executed for each table in the database you're connected.

Note: You may need to execute the query a few times to delete all tables due to dependencies.

Note2: To avoid the first note, before running the query, first check if there foreign keys relations to any table. If there are then just disable foreign key constraint by running the query bellow:

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

Writing to a file in a for loop

The main problem was that you were opening/closing files repeatedly inside your loop.

Try this approach:

with open('new.txt') as text_file, open('xyz.txt', 'w') as myfile:  
    for line in text_file:
        var1, var2 = line.split(",");
        myfile.write(var1+'\n')

We open both files at once and because we are using with they will be automatically closed when we are done (or an exception occurs). Previously your output file was repeatedly openend inside your loop.

We are also processing the file line-by-line, rather than reading all of it into memory at once (which can be a problem when you deal with really big files).

Note that write() doesn't append a newline ('\n') so you'll have to do that yourself if you need it (I replaced your writelines() with write() as you are writing a single item, not a list of items).

When opening a file for rread, the 'r' is optional since it's the default mode.

Using RegEx in SQL Server

SELECT * from SOME_TABLE where NAME like '%[^A-Z]%'

Or some other expression instead of A-Z

Get querystring from URL using jQuery

To retrieve the entire querystring from the current URL, beginning with the ? character, you can use

location.search

https://developer.mozilla.org/en-US/docs/DOM/window.location

Example:

// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123" 

In regards to retrieving specific querystring parameters, while although classes like URLSearchParams and URL exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:

/**
 * Accepts either a URL or querystring and returns an object associating 
 * each querystring parameter to its value. 
 *
 * Returns an empty object if no querystring parameters found.
 */
function getUrlParams(urlOrQueryString) {
  if ((i = urlOrQueryString.indexOf('?')) >= 0) {
    const queryString = urlOrQueryString.substring(i+1);
    if (queryString) {
      return _mapUrlParams(queryString);
    } 
  }

  return {};
}

/**
 * Helper function for `getUrlParams()`
 * Builds the querystring parameter to value object map.
 *
 * @param queryString {string} - The full querystring, without the leading '?'.
 */
function _mapUrlParams(queryString) {
  return queryString    
    .split('&') 
    .map(function(keyValueString) { return keyValueString.split('=') })
    .reduce(function(urlParams, [key, value]) {
      if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
        urlParams[key] = parseInt(value);
      } else {
        urlParams[key] = decodeURI(value);
      }
      return urlParams;
    }, {});
}

You can use the above like so:

// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }

// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }

// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName') { 
  console.log(urlParams.parameterName);
}

Cant get text of a DropDownList in code - can get value but not text

had the same problem and just solved it, i used string [variable_Name] =dropdownlist1.SelectedItem.Text;

Creating and returning Observable from Angular 2 Service

I'm a little late to the party, but I think my approach has the advantage that it lacks the use of EventEmitters and Subjects.

So, here's my approach. We can't get away from subscribe(), and we don't want to. In that vein, our service will return an Observable<T> with an observer that has our precious cargo. From the caller, we'll initialize a variable, Observable<T>, and it will get the service's Observable<T>. Next, we'll subscribe to this object. Finally, you get your "T"! from your service.

First, our people service, but yours doesnt pass parameters, that's more realistic:

people(hairColor: string): Observable<People> {
   this.url = "api/" + hairColor + "/people.json";

   return Observable.create(observer => {
      http.get(this.url)
          .map(res => res.json())
          .subscribe((data) => {
             this._people = data

             observer.next(this._people);
             observer.complete();


          });
   });
}

Ok, as you can see, we're returning an Observable of type "people". The signature of the method, even says so! We tuck-in the _people object into our observer. We'll access this type from our caller in the Component, next!

In the Component:

private _peopleObservable: Observable<people>;

constructor(private peopleService: PeopleService){}

getPeople(hairColor:string) {
   this._peopleObservable = this.peopleService.people(hairColor);

   this._peopleObservable.subscribe((data) => {
      this.people = data;
   });
}

We initialize our _peopleObservable by returning that Observable<people> from our PeopleService. Then, we subscribe to this property. Finally, we set this.people to our data(people) response.

Architecting the service in this fashion has one, major advantage over the typical service: map(...) and component: "subscribe(...)" pattern. In the real world, we need to map the json to our properties in our class and, sometimes, we do some custom stuff there. So this mapping can occur in our service. And, typically, because our service call will be used not once, but, probably, in other places in our code, we don't have to perform that mapping in some component, again. Moreover, what if we add a new field to people?....

How to make two plots side-by-side using Python?

You can use - matplotlib.gridspec.GridSpec

Check - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html

The below code displays a heatmap on right and an Image on left.

#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2) 
fig = plt.figure(figsize=(25,3))

#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)

#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])

#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")

plt.imshow(image)
plt.show()

Output image

How can I one hot encode in Python?

Here i tried with this approach :

import numpy as np
#converting to one_hot





def one_hot_encoder(value, datal):

    datal[value] = 1

    return datal


def _one_hot_values(labels_data):
    encoded = [0] * len(labels_data)

    for j, i in enumerate(labels_data):
        max_value = [0] * (np.max(labels_data) + 1)

        encoded[j] = one_hot_encoder(i, max_value)

    return np.array(encoded)

socket programming multiple client to one server

This is the echo server handling multiple clients... Runs fine and good using Threads

// echo server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class Server_X_Client {
public static void main(String args[]){


    Socket s=null;
    ServerSocket ss2=null;
    System.out.println("Server Listening......");
    try{
        ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined

    }
    catch(IOException e){
    e.printStackTrace();
    System.out.println("Server error");

    }

    while(true){
        try{
            s= ss2.accept();
            System.out.println("connection Established");
            ServerThread st=new ServerThread(s);
            st.start();

        }

    catch(Exception e){
        e.printStackTrace();
        System.out.println("Connection Error");

    }
    }

}

}

class ServerThread extends Thread{  

    String line=null;
    BufferedReader  is = null;
    PrintWriter os=null;
    Socket s=null;

    public ServerThread(Socket s){
        this.s=s;
    }

    public void run() {
    try{
        is= new BufferedReader(new InputStreamReader(s.getInputStream()));
        os=new PrintWriter(s.getOutputStream());

    }catch(IOException e){
        System.out.println("IO error in server thread");
    }

    try {
        line=is.readLine();
        while(line.compareTo("QUIT")!=0){

            os.println(line);
            os.flush();
            System.out.println("Response to Client  :  "+line);
            line=is.readLine();
        }   
    } catch (IOException e) {

        line=this.getName(); //reused String line for getting thread name
        System.out.println("IO Error/ Client "+line+" terminated abruptly");
    }
    catch(NullPointerException e){
        line=this.getName(); //reused String line for getting thread name
        System.out.println("Client "+line+" Closed");
    }

    finally{    
    try{
        System.out.println("Connection Closing..");
        if (is!=null){
            is.close(); 
            System.out.println(" Socket Input Stream Closed");
        }

        if(os!=null){
            os.close();
            System.out.println("Socket Out Closed");
        }
        if (s!=null){
        s.close();
        System.out.println("Socket Closed");
        }

        }
    catch(IOException ie){
        System.out.println("Socket Close Error");
    }
    }//end finally
    }
}

Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..

// A simple Client Server Protocol .. Client for Echo Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class NetworkClient {

public static void main(String args[]) throws IOException{


    InetAddress address=InetAddress.getLocalHost();
    Socket s1=null;
    String line=null;
    BufferedReader br=null;
    BufferedReader is=null;
    PrintWriter os=null;

    try {
        s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
        br= new BufferedReader(new InputStreamReader(System.in));
        is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
        os= new PrintWriter(s1.getOutputStream());
    }
    catch (IOException e){
        e.printStackTrace();
        System.err.print("IO Exception");
    }

    System.out.println("Client Address : "+address);
    System.out.println("Enter Data to echo Server ( Enter QUIT to end):");

    String response=null;
    try{
        line=br.readLine(); 
        while(line.compareTo("QUIT")!=0){
                os.println(line);
                os.flush();
                response=is.readLine();
                System.out.println("Server Response : "+response);
                line=br.readLine();

            }



    }
    catch(IOException e){
        e.printStackTrace();
    System.out.println("Socket read Error");
    }
    finally{

        is.close();os.close();br.close();s1.close();
                System.out.println("Connection Closed");

    }

}
}

Visual Studio SignTool.exe Not Found

1.Just Disable signing from the properties of your project it will solve issue :)
2.The other method is to purchase the certificate for your product from Digicert or Comodo or any other you want. You can get some free certificates for One pc use.

How do I find what Java version Tomcat6 is using?

Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.

Android 6.0 Marshmallow. Cannot write to SD Card

Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1

Code:-

If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
            return;
        }`


` @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_RC) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //permission granted  start reading
            } else {
                Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

start MySQL server from command line on Mac OS Lion

I like the aliases too ... however, I've had issues with MySQLCOM for start ... it fails silently ... My workaround is akin to the others ... ~/.bash_aliases

alias mysqlstart='sudo /usr/local/mysql/support-files/mysql.server start'
alias mysqlstop='sudo /usr/local/mysql/support-files/mysql.server stop' 

Set environment variables from file of key/value pairs

How I save variables :

printenv | sed 's/\([a-zA-Z0-9_]*\)=\(.*\)/export \1="\2"/' > myvariables.sh

How I load them

source myvariables.sh

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

Should I use window.navigate or document.location in JavaScript?

I'd go with window.location = "http://...";. I've been coding cross-browser JavaScript for a few years, and I've never experienced problems using this approach.

window.navigate and window.location.href seems a bit odd to me.

Moment.js get day name from date

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('ddd');
console.log(weekDayName);

Result: Wed

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');
console.log(weekDayName);

Result: Wednesday

Python None comparison: should I use "is" or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

Showing line numbers in IPython/Jupyter Notebooks

Select the Toggle Line Number Option from the View -> Toggle Line Number.

The menu looks like this