Programs & Examples On #Qsplitter

The QSplitter class, part of the Qt framework, implements a splitter widget.

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

Please

  1. locate the file [XAMPP Installation Directory]\php\php.ini (e.g. C:\xampp\php\php.ini)
  2. open php.ini in Notepad or any Text editor
  3. locate the line containing max_execution_time and
  4. increase the value from 30 to some larger number (e.g. set: max_execution_time = 90)
  5. then restart Apache web server from the XAMPP control panel

If there will still be the same error after that, try to increase the value for the max_execution_time further more.

Convert Mercurial project to Git

Ok I finally worked this out. This is using TortoiseHg on Windows. If you're not using that you can do it on the command line.

  1. Install TortoiseHg
  2. Right click an empty space in explorer, and go to the TortoiseHg settings:

TortoiseHg Settings

  1. Enable hggit:

enter image description here

  1. Open a command line, enter an empty directory.

  2. git init --bare .git (If you don't use a bare repo you'll get an error like abort: git remote error: refs/heads/master failed to update

  3. cd to your Mercurial repository.

  4. hg bookmarks hg

  5. hg push c:/path/to/your/git/repo

  6. In the Git directory: git config --bool core.bare false (Don't ask me why. Something about "work trees". Git is seriously unfriendly. I swear writing the actual code is easier than using Git.)

Hopefully it will work and then you can push from that new git repo to a non-bare one.

What is context in _.each(list, iterator, [context])?

Simple use of _.each

_x000D_
_x000D_
_.each(['Hello', 'World!'], function(word){_x000D_
    console.log(word);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

Here's simple example that could use _.each:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
_x000D_
var x = new basket();_x000D_
x.addItem('banana');_x000D_
x.addItem('apple');_x000D_
x.addItem('kiwi');_x000D_
x.show();
_x000D_
_x000D_
_x000D_

Output:

items:  [ 'banana', 'apple', 'kiwi' ]

Instead of calling addItem multiple times you could use underscore this way:

_.each(['banana', 'apple', 'kiwi'], function(item) { x.addItem(item); });

which is identical to calling addItem three times sequentially with these items. Basically it iterates your array and for each item calls your anonymous callback function that calls x.addItem(item). The anonymous callback function is similar to addItem member function (e.g. it takes an item) and is kind of pointless. So, instead of going through anonymous function it's better that _.each avoids this indirection and calls addItem directly:

_.each(['banana', 'apple', 'kiwi'], x.addItem);

but this won't work, as inside basket's addItem member function this won't refer to your x basket that you created. That's why you have an option to pass your basket x to be used as [context]:

_.each(['banana', 'apple', 'kiwi'], x.addItem, x);

Full example that uses _.each and context:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], x.addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In short, if callback function that you pass to _.each in any way uses this then you need to specify what this should be referring to inside your callback function. It may seem like x is redundant in my example, but x.addItem is just a function and could be totally unrelated to x or basket or any other object, for example:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
function addItem(item) {_x000D_
    this.items.push(item);_x000D_
};_x000D_
_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In other words, you bind some value to this inside your callback, or you may as well use bind directly like this:

_.each(['banana', 'apple', 'kiwi'], addItem.bind(x));

how this feature can be useful with some different underscore methods?

In general, if some underscorejs method takes a callback function and if you want that callback be called on some member function of some object (e.g. a function that uses this) then you may bind that function to some object or pass that object as the [context] parameter and that's the primary intention. And at the top of underscorejs documentation, that's exactly what they state: The iteratee is bound to the context object, if one is passed

how to enable sqlite3 for php?

For Ubuntu 18.04 and PHP 7.2:

sudo apt install php-sqlite3

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

What is a Y-combinator?

Here is a JavaScript implementation of the Y-Combinator and the Factorial function (from Douglas Crockford's article, available at: http://javascript.crockford.com/little.html).

function Y(le) {
    return (function (f) {
        return f(f);
    }(function (f) {
        return le(function (x) {
            return f(f)(x);
        });
    }));
}

var factorial = Y(function (fac) {
    return function (n) {
        return n <= 2 ? n : n * fac(n - 1);
    };
});

var number120 = factorial(5);

WPF: Setting the Width (and Height) as a Percentage Value

I know it's not XAML, but I did the same thing with SizeChanged event of the textbox:

private void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
{
   TextBlock textBlock = sender as TextBlock;
   FrameworkElement element = textBlock.Parent as FrameworkElement;
   textBlock.Margin = new Thickness(0, 0, (element.ActualWidth / 100) * 20, 0);
}

The textbox appears to be 80% size of its parent (well right side margin is 20%) and stretches when needed.

How to import image (.svg, .png ) in a React Component

Solved the problem, when moved the folder with the image in src folder. Then I turned to the image (project created through "create-react-app")
let image = document.createElement("img"); image.src = require('../assets/police.png');

Is there a CSS parent selector?

Technically there is no direct way to do this. However, you can sort that out with either jQuery or JavaScript.

However, you can do something like this as well.

a.active h1 {color: blue;}
a.active p {color: green;}

jQuery

$("a.active").parents('li').css("property", "value");

If you want to achieve this using jQuery here is the reference for the jQuery parent selector.

How to add a primary key to a MySQL table?

Remove quotes to work properly...

alter table goods add column id int(10) unsigned primary KEY AUTO_INCREMENT;

converting list to json format - quick and easy way

3 years of experience later, I've come back to this question and would suggest to write it like this:

string output = new JavaScriptSerializer().Serialize(ListOfMyObject);

One line of code.

Regarding 'main(int argc, char *argv[])'

argc is the number of command line arguments and argv is array of strings representing command line arguments.

This gives you the option to react to the arguments passed to the program. If you are expecting none, you might as well use int main.

What does "use strict" do in JavaScript, and what is the reasoning behind it?

There's a good talk by some people who were on the ECMAScript committee: Changes to JavaScript, Part 1: ECMAScript 5" about how incremental use of the "use strict" switch allows JavaScript implementers to clean up a lot of the dangerous features of JavaScript without suddenly breaking every website in the world.

Of course it also talks about just what a lot of those misfeatures are (were) and how ECMAScript 5 fixes them.

Change an image with onclick()

You can try something like this:

CSS

div {
    width:200px;
    height:200px;
    background: url(img1.png) center center no-repeat;
}

.visited {
    background: url(img2.png) center center no-repeat;
}

HTML

<div href="#" onclick="this.className='visited'">
    <p>Content</p>
</div>

Fiddle

How to find which views are using a certain table in SQL Server (2008)?

Simplest way to find used view or stored procedure for the tableName using below query -

exec dbo.dbsearch 'Your_Table_Name'

vbscript output to console

I came across this post and went back to an approach that I used some time ago which is similar to @MadAntrax's.

The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.

This assumes that your objective is to stream output to the console, rather than having output go to message boxes.

The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:

    Option Explicit

'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE

'// Now we can use the Consol object to write to and read from the console
With CONS

    '// Simply write a line
     .print "CSCRIPT Console demo script"

     '// Arguments are passed through correctly, if present
     .Print "Arg count=" & wscript.arguments.count

     '// List all the arguments on the console log
     dim ix
     for ix = 0 to wscript.arguments.count -1
        .print "Arg(" & ix & ")=" & wscript.arguments(ix)
     next

     '// Prompt for some text from the user
     dim sMsg : sMsg = .prompt( "Enter any text:" )

     '// Write out the text in a box
     .Box sMsg

     '// Pause with the message "Hit enter to continue"
     .Pause

End With     




'= =========== End of script - the cCONSOLE class code follows here

Here is the code for the cCONSOLE class

     CLASS cCONSOLE
 '= =================================================================
 '= 
 '=    This class provides automatic switch to CScript and has methods
 '=    to write to and read from the CSCript console. It transparently
 '=    switches to CScript if the script has been started in WScript.
 '=
 '= =================================================================

    Private oOUT
    Private oIN


    Private Sub Class_Initialize()
    '= Run on creation of the cCONSOLE object, checks for cScript operation


        '= Check to make sure we are running under CScript, if not restart
        '= then run using CScript and terminate this instance.
        dim oShell
        set oShell = CreateObject("WScript.Shell")

        If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
            '= Not running under CSCRIPT

            '= Get the arguments on the command line and build an argument list
            dim ArgList, IX
            ArgList = ""

            For IX = 0 to wscript.arguments.count - 1
                '= Add the argument to the list, enclosing it in quotes
                argList = argList & " """ & wscript.arguments.item(IX) & """"
            next

            '= Now restart with CScript and terminate this instance
            oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
            WScript.Quit

        End If

        '= Running under CScript so OK to continue
        set oShell = Nothing

        '= Save references to stdout and stdin for use with Print, Read and Prompt
        set oOUT = WScript.StdOut
        set oIN = WScript.StdIn

        '= Print out the startup box 
            StartBox
            BoxLine Wscript.ScriptName
            BoxLine "Started at " & Now()
            EndBox


    End Sub

    '= Utility methods for writing a box to the console with text in it

            Public Sub StartBox()

                Print "  " & String(73, "_") 
                Print " |" & Space(73) & "|"
            End Sub

            Public Sub BoxLine(sText)

                Print Left(" |" & Centre( sText, 74) , 75) & "|"
            End Sub

            Public Sub EndBox()
                Print " |" & String(73, "_") & "|"
                Print ""
            End Sub

            Public Sub Box(sMsg)
                StartBox
                BoxLine sMsg
                EndBox
            End Sub

    '= END OF Box utility methods


            '= Utility to center given text padded out to a certain width of text
            '= assuming font is monospaced
            Public Function Centre(sText, nWidth)
                dim iLen
                iLen = len(sText)

                '= Check for overflow
                if ilen > nwidth then Centre = sText : exit Function

                '= Calculate padding either side
                iLen = ( nWidth - iLen ) / 2

                '= Generate text with padding
                Centre = left( space(iLen) & sText & space(ilen), nWidth )
            End Function



    '= Method to write a line of text to the console
    Public Sub Print( sText )

        oOUT.WriteLine sText
    End Sub

    '= Method to prompt user input from the console with a message
    Public Function Prompt( sText )
        oOUT.Write sText
        Prompt = Read()
    End Function

    '= Method to read input from the console with no prompting
    Public Function Read()
        Read = oIN.ReadLine
    End Function

    '= Method to provide wait for n seconds
    Public Sub Wait(nSeconds)
        WScript.Sleep  nSeconds * 1000 
    End Sub

    '= Method to pause for user to continue
    Public Sub Pause
        Prompt "Hit enter to continue..."
    End Sub


 END CLASS

How to convert hex to rgb using Java?

For Android development, I use:

int color = Color.parseColor("#123456");

Rmi connection refused with localhost

One difference we can note in Windows is:

If you use Runtime.getRuntime().exec("rmiregistry 1024");

you can see rmiregistry.exe process will run in your Task Manager

whereas if you use Registry registry = LocateRegistry.createRegistry(1024);

you can not see the process running in Task Manager,

I think Java handles it in a different way.

and this is my server.policy file

Before running the the application, make sure that you killed all your existing javaw.exe and rmiregistry.exe corresponds to your rmi programs which are already running.

The following code works for me by using Registry.LocateRegistry() or

Runtime.getRuntime.exec("");


// Standard extensions get all permissions by default

grant {
    permission java.security.AllPermission;
};

VM argument

-Djava.rmi.server.codebase=file:\C:\Users\Durai\workspace\RMI2\src\

Code:

package server;    

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class HelloServer 
{
  public static void main (String[] argv) 
  {
    try {

        if(System.getSecurityManager()==null){
            System.setProperty("java.security.policy","C:\\Users\\Durai\\workspace\\RMI\\src\\server\\server.policy");
            System.setSecurityManager(new RMISecurityManager());
        }

 Runtime.getRuntime().exec("rmiregistry 1024");

 //     Registry registry = LocateRegistry.createRegistry(1024);
   //   registry.rebind ("Hello", new Hello ("Hello,From Roseindia.net pvt ltd!"));
   //Process process = Runtime.getRuntime().exec("C:\\Users\\Durai\\workspace\\RMI\\src\\server\\rmi_registry_start.bat");

        Naming.rebind ("//localhost:1024/Hello",new Hello ("Hello,From Roseindia.net pvt ltd!")); 
      System.out.println ("Server is connected and ready for operation.");
    } 
    catch (Exception e) {
      System.out.println ("Server not connected: " + e);
      e.printStackTrace();
    }
  }
}

' << ' operator in verilog

<< is a binary shift, shifting 1 to the left 8 places.

4'b0001 << 1 => 4'b0010

>> is a binary right shift adding 0's to the MSB.
>>> is a signed shift which maintains the value of the MSB if the left input is signed.

4'sb1011 >>  1 => 0101
4'sb1011 >>> 1 => 1101

Three ways to indicate left operand is signed:

module shift;
  logic        [3:0] test1 = 4'b1000;
  logic signed [3:0] test2 = 4'b1000;

  initial begin
    $display("%b", $signed(test1) >>> 1 ); //Explicitly set as signed
    $display("%b", test2          >>> 1 ); //Declared as signed type
    $display("%b", 4'sb1000       >>> 1 ); //Signed constant
    $finish;
  end
endmodule

Best way to extract a subvector from a vector?

std::vector<T>(input_iterator, input_iterator), in your case foo = std::vector<T>(myVec.begin () + 100000, myVec.begin () + 150000);, see for example here

How do I setup the InternetExplorerDriver so it works

If you are using RemoteDriver things are different. From http://element34.ca/blog/iedriverserver-webdriver-and-python :

You will need to start the server using a line like

java -jar selenium-server-standalone-2.26.0.jar -Dwebdriver.ie.driver=C:\Temp\IEDriverServer.exe

I found that if the IEDriverServer.exe was in C:\Windows\System32\ or its subfolders, it couldn't be found automatically (even though System32 was in the %PATH%) or explicitly using the -D flag.

How to echo shell commands as they are executed

shuckc's answer for echoing select lines has a few downsides: you end up with the following set +x command being echoed as well, and you lose the ability to test the exit code with $? since it gets overwritten by the set +x.

Another option is to run the command in a subshell:

echo "getting URL..."
( set -x ; curl -s --fail $URL -o $OUTFILE )

if [ $? -eq 0 ] ; then
    echo "curl failed"
    exit 1
fi

which will give you output like:

getting URL...
+ curl -s --fail http://example.com/missing -o /tmp/example
curl failed

This does incur the overhead of creating a new subshell for the command, though.

Setting Android Theme background color

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
        <item name="android:windowBackground">@android:color/black</item>
    </style>

</resources>

How to change the minSdkVersion of a project?

This is what worked for me:

In the build.gradle file, setting the minSdkVersion under defaultConfig:

enter image description here

Good Luck...

Check if a variable is a string in JavaScript

You can use typeof operator:

var booleanValue = true; 
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"

Example from this webpage. (Example was slightly modified though).

This won't work as expected in the case of strings created with new String(), but this is seldom used and recommended against[1][2]. See the other answers for how to handle these, if you so desire.


  1. The Google JavaScript Style Guide says to never use primitive object wrappers.
  2. Douglas Crockford recommended that primitive object wrappers be deprecated.

Entry point for Java applications: main(), init(), or run()?

The main() method is the entry point for a Java application. run() is typically used for new threads or tasks.

Where have you been writing a run() method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?

Disable a Maven plugin defined in a parent POM

The thread is old, but maybe someone is still interested. The shortest form I found is further improvement on the example from ?lex and bmargulies. The execution tag will look like:

<execution>
    <id>TheNameOfTheRelevantExecution</id>
    <phase/>
</execution>

2 points I want to highlight:

  1. phase is set to nothing, which looks less hacky than 'none', though still a hack.
  2. id must be the same as execution you want to override. If you don't specify id for execution, Maven will do it implicitly (in a way not expected intuitively by you).

After posting found it is already in stackoverflow: In a Maven multi-module project, how can I disable a plugin in one child?

How to set selected item of Spinner by value, not by position?

To make the application remember the last selected spinner values, you can use below code:

  1. Below code reads the spinner value and sets the spinner position accordingly.

    public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    int spinnerPosition;
    
    Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
            this, R.array.ccy_array,
            android.R.layout.simple_spinner_dropdown_item);
    adapter1.setDropDownViewResource(android.R.layout.simple_list_item_activated_1);
    // Apply the adapter to the spinner
    spinner1.setAdapter(adapter1);
    // changes to remember last spinner position
    spinnerPosition = 0;
    String strpos1 = prfs.getString("SPINNER1_VALUE", "");
    if (strpos1 != null || !strpos1.equals(null) || !strpos1.equals("")) {
        strpos1 = prfs.getString("SPINNER1_VALUE", "");
        spinnerPosition = adapter1.getPosition(strpos1);
        spinner1.setSelection(spinnerPosition);
        spinnerPosition = 0;
    }
    
  2. And put below code where you know latest spinner values are present, or somewhere else as required. This piece of code basically writes the spinner value in SharedPreferences.

        Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
        String spinlong1 = spinner1.getSelectedItem().toString();
        SharedPreferences prfs = getSharedPreferences("WHATEVER",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prfs.edit();
        editor.putString("SPINNER1_VALUE", spinlong1);
        editor.commit();
    

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

Call method when home button pressed

I have a simple solution on handling home button press. Here is my code, it can be useful:

public class LifeCycleActivity extends Activity {


boolean activitySwitchFlag = false;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
        activitySwitchFlag = true;
        // activity switch stuff..
        return true;
    }
    return false;
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override 
public void onPause(){
    super.onPause();
    Log.v("TAG", "onPause" );
    if(activitySwitchFlag)
        Log.v("TAG", "activity switch");
    else
        Log.v("TAG", "home button");
    activitySwitchFlag = false;
}

public void gotoNext(View view){
    activitySwitchFlag = true;
    startActivity(new Intent(LifeCycleActivity.this, NextActivity.class));
}

}

As a summary, put a boolean in the activity, when activity switch occurs(startactivity event), set the variable and in onpause event check this variable..

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

How can I position my div at the bottom of its container?

Its an old question, but this is a unique approach that can help in several cases.

Pure CSS, Without Absolute positioning, Without Fixing any Height, Cross-Browser (IE9+)

check out that Working Fiddle

Because normal flow is 'top-to-bottom' we can't simply ask the #copyright div to stick to the bottom of his parent without absolutely positioning of some sort, But if we wanted the #copyright div to stick to the top of his parent, it will be very simple - because this is the normal flow way.

So we will use this in our advantage. we will change the order of the divs in the HTML, now the #copyright div is at the top, and the content follow it right away. we also make the content div stretch all the way (using pseudo elements and clearing techniques)

now it's just a matter of inverting that order back in the view. that can be easily done with CSS transform.

We rotate the container by 180deg, and now: up-is-down. (and we inverse back the content to look normal again)

If we want to have a scroolbar within the content area, we need to apply a little bit more of CSS magic. as can be showed Here [in that example, the content is below a header - but its the same idea]

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body,_x000D_
#Container {_x000D_
  height: 100%;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#Container:before {_x000D_
  content: '';_x000D_
  height: 100%;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
#Copyright {_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
#Stretch {_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
#Stretch:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
#Container,_x000D_
#Container>div {_x000D_
  -moz-transform: rotateX(180deg);_x000D_
  -ms-transform: rotateX(180deg);_x000D_
  -o-transform: rotate(180deg);_x000D_
  -webkit-transform: rotateX(180deg);_x000D_
  transform: rotateX(180deg);_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div id="Copyright">_x000D_
    Copyright Foo web designs_x000D_
  </div>_x000D_
  <div id="Stretch">_x000D_
    <!-- Other elements here -->_x000D_
    <div>Element 1</div>_x000D_
    <div>Element 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

The sqlite answer is

update TABLE set mydatetime = datetime('now');

in case someone else was looking for it.

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

SelectedValue vs SelectedItem.Value of DropDownList

In droupDown list there are two item add property.

1) Text 2) value

If you want to get text property then u use selecteditem.text

and If you want to select value property then use selectedvalue property

In your case i thing both value and text property are the same so no matter if u use selectedvalue or selecteditem.text

If both are different then they give us different results

How to overload __init__ method based on argument type?

You probably want the isinstance builtin function:

self.data = data if isinstance(data, list) else self.parse(data)

Using prepared statements with JDBCTemplate

Try the following:

PreparedStatementCreator creator = new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement updateSales = con.prepareStatement(
        "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
        updateSales.setInt(1, 75); 
        updateSales.setString(2, "Colombian"); 
        return updateSales;
    }
};

How to apply CSS to iframe?

Here, There are two things inside the domain

  1. iFrame Section
  2. Page Loaded inside the iFrame

So you want to style those two sections as follows,

1. Style for the iFrame Section

It can style using CSS with that respected id or class name. You can just style it in your parent Style sheets also.

<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>

<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>

2. Style the Page Loaded inside the iFrame

This Styles can be loaded from the parent page with the help of Javascript

var cssFile  = document.createElement("link") 
cssFile.rel  = "stylesheet"; 
cssFile.type = "text/css"; 
cssFile.href = "iFramePage.css"; 

then set that CSS file to the respected iFrame section

//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile); 
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);

Here, You can edit the Head Part of the Page inside the iFrame using this way also

var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
   $("<link/>",{ 
      rel: "stylesheet", 
      href: urlPath, 
      type: "text/css" }
     ));

Confirm button before running deleting routine from website

You can do it with an confirm() message using Javascript.

PHP Fatal error: Cannot access empty property

To access a variable in a class, you must use $this->myVar instead of $this->$myvar.

And, you should use access identifier to declare a variable instead of var.

Please read the doc here.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

The Pythonic way of summing an array is using sum. For other purposes, you can sometimes use some combination of reduce (from the functools module) and the operator module, e.g.:

def product(xs):
    return reduce(operator.mul, xs, 1)

Be aware that reduce is actually a foldl, in Haskell terms. There is no special syntax to perform folds, there's no builtin foldr, and actually using reduce with non-associative operators is considered bad style.

Using higher-order functions is quite pythonic; it makes good use of Python's principle that everything is an object, including functions and classes. You are right that lambdas are frowned upon by some Pythonistas, but mostly because they tend not to be very readable when they get complex.

Handling very large numbers in Python

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the int type has been dropped completely.

That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.

You can find all the gory details in PEP 0237.

What is the best IDE to develop Android apps in?

I think intellij is the best option for android. i have used both eclipse and intellij and found intellij is much easier to use with android as compared to eclipse because of these reasons :-

Intellij provides a built-in support for android and you don't have to configure it as you need to do with eclipse. Intellij gives you auto-lookup feature which is really important for developer like us to increase our productivity. And if we talk about eclipse you have to type each and every method, classname etc on your own. (May be eclipse has this feature too but i never found it and trust me i tried to find it like anything) Its much more user friendly and easy to use than eclipse. I hope it will help you and other members of stack overflow to decide which IDE is best for Android development.

My personal choice is Intellij.

EDIT

But there is one thing i love about eclipse and that is visual layout creator. You can use drag and drop technique to create a layout and eclipse will automatically generate an XML file for you just like XCODE.

EDIT

Good News!! Intellij added a new feature which shows how your app's view is going to look like. It doesn't work exactly like Eclipse but it will give you a good idea about your layout.

My personal choice is still Intellij because it helps me to type faster than eclipse.

EDIT

Ok guys these days i am using eclipse juno and found its kind of buggy and slow. So if you still want to use eclipse better stick to some older version. And finally i am able to found how to enable auto-complete in eclipse. Below is a small tutorial.

Eclipse -> Preference - > Java -> Editor -> Content Assist -> Auto Activation

Now put following in the three given boxes

Auto Activation delay(ms) - 0
Auto activation triggers for java - .(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Auto activation triggers for javadoc - @#

You are now good to go. Happy coding.

EDIT

As now Google has adopted Intellij for their own Android dev tool, there is no question now about which one is better. Intellij is far far better than eclipse. And i switched back to Intellij and it feels like i am back home!! :D

How to get folder directory from HTML input type "file" or any other way?

You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" /> control doesn't handle that.

If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change event then strip the filename portion and save the path somewhere--but that's about as good as it gets.

Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

Scikit-learn train_test_split with indices

The docs mention train_test_split is just a convenience function on top of shuffle split.

I just rearranged some of their code to make my own example. Note the actual solution is the middle block of code. The rest is imports, and setup for a runnable example.

from sklearn.model_selection import ShuffleSplit
from sklearn.utils import safe_indexing, indexable
from itertools import chain
import numpy as np
X = np.reshape(np.random.randn(20),(10,2)) # 10 training examples
y = np.random.randint(2, size=10) # 10 labels
seed = 1

cv = ShuffleSplit(random_state=seed, test_size=0.25)
arrays = indexable(X, y)
train, test = next(cv.split(X=X))
iterator = list(chain.from_iterable((
    safe_indexing(a, train),
    safe_indexing(a, test),
    train,
    test
    ) for a in arrays)
)
X_train, X_test, train_is, test_is, y_train, y_test, _, _  = iterator

print(X)
print(train_is)
print(X_train)

Now I have the actual indexes: train_is, test_is

How can I truncate a double to only two decimal places in Java?

Maybe Math.floor(value * 100) / 100? Beware that the values like 3.54 may be not exactly represented with a double.

Fetch: reject promise and catch the error if status is not OK?

Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

export function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())    
                .catch(error => {
                    return Promise.reject()
                })
            });
    };
}


function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    }
    return res;
}

Convert JS date time to MySQL datetime

I'm using this long time and it's very helpful for me, use as you like

Date.prototype.date=function() {
    return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')
}

Date.prototype.time=function() {
    return String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}

Date.prototype.dateTime=function() {
    return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')+' '+String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}

Date.prototype.addTime=function(time) {
    var time=time.split(":")
    var rd=new Date(this.setHours(this.getHours()+parseInt(time[0])))
    rd=new Date(rd.setMinutes(rd.getMinutes()+parseInt(time[1])))
    return new Date(rd.setSeconds(rd.getSeconds()+parseInt(time[2])))
}

Date.prototype.addDate=function(time) {
    var time=time.split("-")
    var rd=new Date(this.setFullYear(this.getFullYear()+parseInt(time[0])))
    rd=new Date(rd.setMonth(rd.getMonth()+parseInt(time[1])))
    return new Date(rd.setDate(rd.getDate()+parseInt(time[2])))
}

Date.prototype.subDate=function(time) {
    var time=time.split("-")
    var rd=new Date(this.setFullYear(this.getFullYear()-parseInt(time[0])))
    rd=new Date(rd.setMonth(rd.getMonth()-parseInt(time[1])))
    return new Date(rd.setDate(rd.getDate()-parseInt(time[2])))
}

and then just:

new Date().date()

which returns current date in 'MySQL format'

for add time is

new Date().addTime('0:30:0')

which will add 30 minutes.... and so on

Selecting one row from MySQL using mysql_* API

Functions mysql_ are not supported any longer and have been removed in PHP 7. You must use mysqli_ instead. However it's not recommended method now. You should consider PDO with better security solutions.

$result = mysqli_query($con, "SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysqli_fetch_assoc($result);
echo $row['option_value'];

Replacement for "rename" in dplyr

While not exactly renaming, dplyr::select_all() can be used to reformat column names. This example replaces spaces and periods with an underscore and converts everything to lower case:

iris %>%  
  select_all(~gsub("\\s+|\\.", "_", .)) %>% 
  select_all(tolower) %>% 
  head(2)
  sepal_length sepal_width petal_length petal_width species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa

Remove duplicated rows

With sqldf:

# Example by Mehdi Nellen
a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)

Solution:

 library(sqldf)
    sqldf('SELECT DISTINCT * FROM df')

Output:

  a b
1 A 1
2 A 2
3 B 4
4 B 1
5 C 2

Looking for simple Java in-memory cache

If you're needing something simple, would this fit the bill?

Map<K, V> myCache = Collections.synchronizedMap(new WeakHashMap<K, V>());

It wont save to disk, but you said you wanted simple...

Links:

(As Adam commented, synchronising a map has a performance hit. Not saying the idea doesn't have hairs on it, but would suffice as a quick and dirty solution.)

How to check if function exists in JavaScript?

How about:

if('functionName' in Obj){
    //code
}

e.g.

var color1 = new String("green");
"length" in color1 // returns true
"indexOf" in color1 // returns true
"blablabla" in color1 // returns false

or as for your case:

if('onChange' in me){
    //code
}

See MDN docs.

Unnamed/anonymous namespaces vs. static functions

The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:

The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.

Static only applies to names of objects, functions, and anonymous unions, not to type declarations.

Edit:

The decision to deprecate this use of the static keyword (affecting visibility of a variable declaration in a translation unit) has been reversed (ref). In this case using a static or an unnamed namespace are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question.

Unnamed namespace's still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details.

Credit goes to Mike Percy for bringing this to my attention.

ProcessStartInfo hanging on "WaitForExit"? Why?

After reading all the posts here, i settled on the consolidated solution of Marko Avlijaš. However, it did not solve all of my issues.

In our environment we have a Windows Service which is scheduled to run hundreds of different .bat .cmd .exe,... etc. files which have accumulated over the years and were written by many different people and in different styles. We have no control over the writing of the programs & scripts, we are just responsible for scheduling, running, and reporting on success/failure.

So i tried pretty much all of the suggestions here with different levels of success. Marko's answer was almost perfect, but when run as a service, it didnt always capture stdout. I never got to the bottom of why not.

The only solution we found that works in ALL our cases is this : http://csharptest.net/319/using-the-processrunner-class/index.html

Passing parameters to JavaScript files

Another idea I came across was assigning an id to the <script> element and passing the arguments as data-* attributes. The resulting <script> tag would look something like this:

<script id="helper" data-name="helper" src="helper.js"></script>

The script could then use the id to programmatically locate itself and parse the arguments. Given the previous <script> tag, the name could be retrieved like this:

var name = document.getElementById("helper").getAttribute("data-name");

We get name = helper

oracle sql: update if exists else insert

You could use the SQL%ROWCOUNT Oracle variable:

UPDATE table1
  SET field2 = value2, 
      field3 = value3 
WHERE field1 = value1; 

IF (SQL%ROWCOUNT = 0) THEN 

  INSERT INTO table (field1, field2, field3)
  VALUES (value1, value2, value3);

END IF; 

It would be easier just to determine if your primary key (i.e. field1) has a value and then perform an insert or update accordingly. That is, if you use said values as parameters for a stored procedure.

Detect a finger swipe through JavaScript on the iPhone and Android

Some mod of uppest answer(can't comment...) to deal with to short swipes

document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null;                                                        
var yDown = null;                                                        
function handleTouchStart(evt) {                                         
    xDown = evt.touches[0].clientX;                                      
    yDown = evt.touches[0].clientY;                                      
};                                                
function handleTouchMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }

    var xUp = evt.touches[0].clientX;                                    
    var yUp = evt.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;
    if(Math.abs( xDiff )+Math.abs( yDiff )>150){ //to deal with to short swipes

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {/* left swipe */ 
            alert('left!');
        } else {/* right swipe */
            alert('right!');
        }                       
    } else {
        if ( yDiff > 0 ) {/* up swipe */
            alert('Up!'); 
        } else { /* down swipe */
            alert('Down!');
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;
    }
};

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

How to dynamically add elements to String array?

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

ASP.NET Identity reset password

I think Microsoft guide for ASP.NET Identity is a good start.

https://docs.microsoft.com/en-us/aspnet/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity

Note:

If you do not use AccountController and wan't to reset your password, use Request.GetOwinContext().GetUserManager<ApplicationUserManager>();. If you dont have the same OwinContext you need to create a new DataProtectorTokenProvider like the one OwinContext uses. By default look at App_Start -> IdentityConfig.cs. Should look something like new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));.

Could be created like this:

Without Owin:

[HttpGet]
[AllowAnonymous]
[Route("testReset")]
public IHttpActionResult TestReset()
{
    var db = new ApplicationDbContext();
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
    var provider = new DpapiDataProtectionProvider("SampleAppName");
    manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(
        provider.Create("SampleTokenName"));

    var email = "[email protected]";

    var user = new ApplicationUser() { UserName = email, Email = email };

    var identityUser = manager.FindByEmail(email);

    if (identityUser == null)
    {
        manager.Create(user);
        identityUser = manager.FindByEmail(email);
    }

    var token = manager.GeneratePasswordResetToken(identityUser.Id);
    return Ok(HttpUtility.UrlEncode(token));
}

[HttpGet]
[AllowAnonymous]
[Route("testReset")]
public IHttpActionResult TestReset(string token)
{
    var db = new ApplicationDbContext();
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
    var provider = new DpapiDataProtectionProvider("SampleAppName");
    manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(
        provider.Create("SampleTokenName"));
    var email = "[email protected]";
    var identityUser = manager.FindByEmail(email);
    var valid = Task.Run(() => manager.UserTokenProvider.ValidateAsync("ResetPassword", token, manager, identityUser)).Result;
    var result = manager.ResetPassword(identityUser.Id, token, "TestingTest1!");
    return Ok(result);
}

With Owin:

[HttpGet]
[AllowAnonymous]
[Route("testResetWithOwin")]
public IHttpActionResult TestResetWithOwin()
{
    var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

    var email = "[email protected]";

    var user = new ApplicationUser() { UserName = email, Email = email };

    var identityUser = manager.FindByEmail(email);

    if (identityUser == null)
    {
        manager.Create(user);
        identityUser = manager.FindByEmail(email);
    }

    var token = manager.GeneratePasswordResetToken(identityUser.Id);
    return Ok(HttpUtility.UrlEncode(token));
}

[HttpGet]
[AllowAnonymous]
[Route("testResetWithOwin")]
public IHttpActionResult TestResetWithOwin(string token)
{
    var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

    var email = "[email protected]";
    var identityUser = manager.FindByEmail(email);
    var valid = Task.Run(() => manager.UserTokenProvider.ValidateAsync("ResetPassword", token, manager, identityUser)).Result;
    var result = manager.ResetPassword(identityUser.Id, token, "TestingTest1!");
    return Ok(result);
}

The DpapiDataProtectionProvider and DataProtectorTokenProvider needs to be created with the same name for a password reset to work. Using Owin for creating the password reset token and then creating a new DpapiDataProtectionProvider with another name won't work.

Code that I use for ASP.NET Identity:

Web.Config:

<add key="AllowedHosts" value="example.com,example2.com" />

AccountController.cs:

[Route("RequestResetPasswordToken/{email}/")]
[HttpGet]
[AllowAnonymous]
public async Task<IHttpActionResult> GetResetPasswordToken([FromUri]string email)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var user = await UserManager.FindByEmailAsync(email);
    if (user == null)
    {
        Logger.Warn("Password reset token requested for non existing email");
        // Don't reveal that the user does not exist
        return NoContent();
    }

    //Prevent Host Header Attack -> Password Reset Poisoning. 
    //If the IIS has a binding to accept connections on 80/443 the host parameter can be changed.
    //See https://security.stackexchange.com/a/170759/67046
    if (!ConfigurationManager.AppSettings["AllowedHosts"].Split(',').Contains(Request.RequestUri.Host)) {
            Logger.Warn($"Non allowed host detected for password reset {Request.RequestUri.Scheme}://{Request.Headers.Host}");
            return BadRequest();
    }

    Logger.Info("Creating password reset token for user id {0}", user.Id);

    var host = $"{Request.RequestUri.Scheme}://{Request.Headers.Host}";
    var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
    var callbackUrl = $"{host}/resetPassword/{HttpContext.Current.Server.UrlEncode(user.Email)}/{HttpContext.Current.Server.UrlEncode(token)}";

    var subject = "Client - Password reset.";
    var body = "<html><body>" +
               "<h2>Password reset</h2>" +
               $"<p>Hi {user.FullName}, <a href=\"{callbackUrl}\"> please click this link to reset your password </a></p>" +
               "</body></html>";

    var message = new IdentityMessage
    {
        Body = body,
        Destination = user.Email,
        Subject = subject
    };

    await UserManager.EmailService.SendAsync(message);

    return NoContent();
}

[HttpPost]
[Route("ResetPassword/")]
[AllowAnonymous]
public async Task<IHttpActionResult> ResetPasswordAsync(ResetPasswordRequestModel model)
{
    if (!ModelState.IsValid)
        return NoContent();

    var user = await UserManager.FindByEmailAsync(model.Email);
    if (user == null)
    {
        Logger.Warn("Reset password request for non existing email");
        return NoContent();
    }            

    if (!await UserManager.UserTokenProvider.ValidateAsync("ResetPassword", model.Token, UserManager, user))
    {
        Logger.Warn("Reset password requested with wrong token");
        return NoContent();
    }

    var result = await UserManager.ResetPasswordAsync(user.Id, model.Token, model.NewPassword);

    if (result.Succeeded)
    {
        Logger.Info("Creating password reset token for user id {0}", user.Id);

        const string subject = "Client - Password reset success.";
        var body = "<html><body>" +
                   "<h1>Your password for Client was reset</h1>" +
                   $"<p>Hi {user.FullName}!</p>" +
                   "<p>Your password for Client was reset. Please inform us if you did not request this change.</p>" +
                   "</body></html>";

        var message = new IdentityMessage
        {
            Body = body,
            Destination = user.Email,
            Subject = subject
        };

        await UserManager.EmailService.SendAsync(message);
    }

    return NoContent();
}

public class ResetPasswordRequestModel
{
    [Required]
    [Display(Name = "Token")]
    public string Token { get; set; }

    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 10)]
    [DataType(DataType.Password)]
    [Display(Name = "New password")]
    public string NewPassword { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm new password")]
    [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I had the same problem. Just after enabling Internet Virtualization from BIOS. After that let the system boot and install HAXM once again. Now emulator will run faster than before and HAXM will work. Enjoy!!

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Getting the count of unique values in a column in bash

Ruby(1.9+)

#!/usr/bin/env ruby
Dir["*"].each do |file|
    h=Hash.new(0)
    open(file).each do |row|
        row.chomp.split("\t").each do |w|
            h[ w ] += 1
        end
    end
    h.sort{|a,b| b[1]<=>a[1] }.each{|x,y| print "#{x}:#{y}\n" }
end

What does "subject" mean in certificate?

The subject of the certificate is the entity its public key is associated with (i.e. the "owner" of the certificate).

As RFC 5280 says:

The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.

X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.

The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".

In the context of the article you're linking to, the subject would be the user/owner of the cert.

Git clone without .git directory

Alternatively, if you have Node.js installed, you can use the following command:

npx degit GIT_REPO

npx comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit globally using npm i -g degit).

Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...

Assembly Language - How to do Modulo?

If you compute modulo a power of two, using bitwise AND is simpler and generally faster than performing division. If b is a power of two, a % b == a & (b - 1).

For example, let's take a value in register EAX, modulo 64.
The simplest way would be AND EAX, 63, because 63 is 111111 in binary.

The masked, higher digits are not of interest to us. Try it out!

Analogically, instead of using MUL or DIV with powers of two, bit-shifting is the way to go. Beware signed integers, though!

How can I uninstall Ruby on ubuntu?

You can use sudo apt remove ruby

How to measure height, width and distance of object using camera?

If you know the viewport angle of the camera, you can use the height in pixels to determine the angle from the top to bottom of the object. Then, using the distance and arctangent calculate the height:

height = arctan(angle) * distance

To find the viewport angle, point the camera at something which is of known height, and make it exactly fill the screen. For example, point it at a ruler, and make it just far enough away that you can only barely see the ends of the ruler. Measure the distance from the camera, and then your total viewport angle is

viewportAngle = tan(ruler_length / distance)

Then, suppose your camera is 480px tall (cheap webcam), and the view angle is 20°. If you have an object onscreen which is 240px tall, then its angle is 10°. If you know it's 2 feet away, you would say 2 feet * arctan(10°) = ~4.1 inches tall. (I think... it's 2am so this may be a little off)

How do I trigger a macro to run after a new mail is received in Outlook?

This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.

Private WithEvents Items As Outlook.Items 
Private Sub Application_Startup() 
  Dim olApp As Outlook.Application 
  Dim objNS As Outlook.NameSpace 
  Set olApp = Outlook.Application 
  Set objNS = olApp.GetNamespace("MAPI") 
  ' default local Inbox
  Set Items = objNS.GetDefaultFolder(olFolderInbox).Items 
End Sub
Private Sub Items_ItemAdd(ByVal item As Object) 

  On Error Goto ErrorHandler 
  Dim Msg As Outlook.MailItem 
  If TypeName(item) = "MailItem" Then
    Set Msg = item 
    ' ******************
    ' do something here
    ' ******************
  End If
ProgramExit: 
  Exit Sub
ErrorHandler: 
  MsgBox Err.Number & " - " & Err.Description 
  Resume ProgramExit 
End Sub

After pasting the code in ThisOutlookSession module, you must restart Outlook.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

You can also "fix" this by replacing the image with its inline Base64 representation:

img.src= "data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
Useful, when you do not intend to publish the page on the web, but instead use it on local machines only.

How to merge two json string in Python?

What do you mean by merging? JSON objects are key-value data structure. What would be a key and a value in this case? I think you need to create new directory and populate it with old data:

d = {}
d["new_key"] = jsonStringA[<key_that_you_did_not_mention_here>] + \ 
               jsonStringB["timestamp_in_ms"]

Merging method is obviously up to you.

How to get commit history for just one branch?

I think an option for your purposes is git log --online --decorate. This lets you know the checked commit, and the top commits for each branch that you have in your story line. By doing this, you have a nice view on the structure of your repo and the commits associated to a specific branch. I think reading this might help.

How do I position a div relative to the mouse pointer using jQuery?

<script type="text/javascript" language="JavaScript">

  var cX = 0;
  var cY = 0;
  var rX = 0;
  var rY = 0;

  function UpdateCursorPosition(e) {
    cX = e.pageX;
    cY = e.pageY;
  }

  function UpdateCursorPositionDocAll(e) {
    cX = event.clientX;
    cY = event.clientY;
  }
  if (document.all) {
    document.onmousemove = UpdateCursorPositionDocAll;
  } else {
    document.onmousemove = UpdateCursorPosition;
  }

  function AssignPosition(d) {
    if (self.pageYOffset) {
      rX = self.pageXOffset;
      rY = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      rX = document.documentElement.scrollLeft;
      rY = document.documentElement.scrollTop;
    } else if (document.body) {
      rX = document.body.scrollLeft;
      rY = document.body.scrollTop;
    }
    if (document.all) {
      cX += rX;
      cY += rY;
    }
    d.style.left = (cX + 10) + "px";
    d.style.top = (cY + 10) + "px";
  }

  function HideContent(d) {
    if (d.length < 1) {
      return;
    }
    document.getElementById(d).style.display = "none";
  }

  function ShowContent(d) {
    if (d.length < 1) {
      return;
    }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    dd.style.display = "block";
  }

  function ReverseContentDisplay(d) {
    if (d.length < 1) {
      return;
    }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    if (dd.style.display == "none") {
      dd.style.display = "block";
    } else {
      dd.style.display = "none";
    }
  }
  //-->
</script>


<a onmouseover="ShowContent('uniquename3'); return true;" onmouseout="HideContent('uniquename3'); return true;" href="javascript:ShowContent('uniquename3')">
[show on mouseover, hide on mouseout]
</a>
<div id="uniquename3" style="display:none;
position:absolute;
border-style: solid;
background-color: white;
padding: 5px;">
  Content goes here.
</div>

How to get Month Name from Calendar?

Month::getDisplayName

Since Java 8, use the Month enum. The getDisplayName method automatically localizes the name of the month.

Pass:

  • A TextStyle to determine how long or how abbreviated.
  • A Locale to specify the human language used in translation, and the cultural norms used for abbreviation, punctuation, etc.

Example:

public static String getMonthStandaloneName(Month month) {
    return month.getDisplayName(
        TextStyle.FULL_STANDALONE, 
        Locale.getDefault()
    );
}

Comments in Android Layout xml

As other said, the comment in XML are like this

<!-- this is a comment -->

Notice that they can span on multiple lines

<!--
    This is a comment
    on multiple lines
-->

But they cannot be nested

<!-- This <!-- is a comment --> This is not -->

Also you cannot use them inside tags

<EditText <!--This is not valid--> android:layout_width="fill_parent" />

Counting inversions in an array

C++ T(n lg n) Solution with the printing of pair which constitute in inversion count.

int merge(vector<int>&nums , int low , int mid , int high){
    int size1 = mid - low +1;
    int size2= high - mid;
    vector<int>left;
    vector<int>right;
    for(int i = 0  ; i < size1 ; ++i){
        left.push_back(nums[low+i]);
    }
    for(int i = 0 ; i <size2 ; ++i){
        right.push_back(nums[mid+i+1]);
    }
    left.push_back(INT_MAX);
    right.push_back(INT_MAX);
    int i = 0 ;
    int j = 0;
    int start  = low;
    int inversion = 0 ;
    while(i < size1 && j < size2){
        if(left[i]<right[j]){
            nums[start] = left[i];
            start++;
            i++;
        }else{
            for(int l = i ; l < size1; ++l){
                cout<<"("<<left[l]<<","<<right[j]<<")"<<endl;
            }
            inversion += size1 - i;
            nums[start] = right[j];
            start++;
            j++;
        }
    }
    if(i == size1){
        for(int c = j ; c< size2 ; ++c){
            nums[start] = right[c];
            start++;
        }
    }
    if(j == size2){
        for(int c =  i ; c< size1 ; ++c){
            nums[start] = left[c];
            start++;
        }
    }
    return inversion;
}
int inversion_count(vector<int>& nums , int low , int high){
    if(high>low){
        int mid = low + (high-low)/2;
        int left = inversion_count(nums,low,mid);
        int right = inversion_count(nums,mid+1,high);
        int inversion = merge(nums,low,mid,high) + left + right;
        return inversion;
    }
    return 0 ;
}

Android Studio cannot resolve R in imported project?

just clean project and then sync your project with gradle file.

How to remove leading and trailing zeros in a string? Python

Did you try with strip() :

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]

>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']

Cannot read property 'push' of undefined when combining arrays

answer to your question is simple order is not a object make it an array. var order = new Array(); order.push(/item to push/); when ever this error appears just check the left of which property the error is in this case it is push which is order[] so it is undefined.

AngularJS - add HTML element to dom in directive without jQuery

Why not to try simple (but powerful) html() method:

iElement.html('<svg width="600" height="100" class="svg"></svg>');

Or append as an alternative:

iElement.append('<svg width="600" height="100" class="svg"></svg>');

And , of course , more cleaner way:

 var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');
 iElement.append(svg);

Fiddle: http://jsfiddle.net/cherniv/AgGwK/

get dictionary value by key

Here is an example which I use in my source code. I am getting key and value from Dictionary from element 0 to number of elements in my Dictionary. Then I fill my string[] array which I send as a parameter after in my function which accept only params string[]

Dictionary<string, decimal> listKomPop = addElements();
int xpopCount = listKomPop.Count;
if (xpopCount > 0)
{
    string[] xpostoci = new string[xpopCount];
    for (int i = 0; i < xpopCount; i++)
    {
        /* here you have key and value element */
        string key = listKomPop.Keys.ElementAt(i);
        decimal value = listKomPop[key];

        xpostoci[i] = value.ToString();
    }
...

This solution works with SortedDictionary also.

Return string without trailing slash

function stripTrailingSlash(text) {
    return text
        .split('/')
        .filter(Boolean)
        .join('/');
}

another solution.

Change fill color on vector asset in Android Studio

if you look to support old version pre lolipop

use the same xml code with some changes

instead of normal ImageView --> AppCompatImageView

instead of android:src --> app:srcCompat

here is example

<android.support.v7.widget.AppCompatImageView
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:id="@+id/button"
        app:srcCompat="@drawable/ic_more_vert_24dp"
        android:tint="@color/primary" />

dont forget update your gradle as @ Sayooj Valsan mention

// Gradle Plugin 2.0+  
 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
   }  
 }  

 compile 'com.android.support:design:23.4.0'

Notice To any one use vector dont ever ever never give your vector reference to color like this one android:fillColor="@color/primary" give its hex value .

How to get the date from jQuery UI datepicker

Sometimes a lot of troubles with it. In attribute value of datapicker data is 28-06-2014, but datepicker is show or today or nothing. I decided it in a such way:

<input type="text" class="form-control datepicker" data-value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" />

I added to the input of datapicker attribute data-value, because if call jQuery(this).val() OR jQuery(this).attr('value') - nothing works. I decided init in cycle each datapicker and take its value from attribute data-value:

 $("form .datepicker").each(function() {
        var time = jQuery(this).data('value');
        time = time.split('-');
        $(this).datepicker('setDate', new Date(time[2], time[1], time[0], 0, 0, 0));
    });

and it is works fine =)

How to write and save html file in python?

print('<tr><td>%04d</td>' % (i+1), file=Html_file)

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

[ :Unexpected operator in shell programming

POSIX sh doesn't understand == for string equality, as that is a bash-ism. Use = instead.

The other people saying that brackets aren't supported by sh are wrong, btw.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

If you just want to check the value is in Range, use this:

   MIN_VALUE = 1;
   MAX_VALUE = 100;
   $customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));

How do you see the entire command history in interactive Python?

Since the above only works for python 2.x for python 3.x (specifically 3.5) is similar but with a slight modification:

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

note the extra ()

(using shell scripts to parse .python_history or using python to modify the above code is a matter of personal taste and situation imho)

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

How to put text over images in html?

The <img> element is empty — it doesn't have an end tag.

If the image is a background image, use CSS. If it is a content image, then set position: relative on a container, then absolutely position the image and/or text within it.

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')

Extract subset of key-value pairs from Python dictionary object?

You can also use map (which is a very useful function to get to know anyway):

sd = dict(map(lambda k: (k, l.get(k, None)), l))

Example:

large_dictionary = {'a1':123, 'a2':45, 'a3':344}
list_of_keys = ['a1', 'a3']
small_dictionary = dict(map(lambda key: (key, large_dictionary.get(key, None)), list_of_keys))

PS: I borrowed the .get(key, None) from a previous answer :)

Uploading Files in ASP.net without using the FileUpload server control

As others has answer, the Request.Files is an HttpFileCollection that contains all the files that were posted, you only need to ask that object for the file like this:

Request.Files["myFile"]

But what happen when there are more than one input mark-up with the same attribute name:

Select file 1 <input type="file" name="myFiles" />
Select file 2 <input type="file" name="myFiles" />

On the server side the previous code Request.Files["myFile"] only return one HttpPostedFile object instead of the two files. I have seen on .net 4.5 an extension method called GetMultiple but for prevoious versions it doesn't exists, for that matter i propose the extension method as:

public static IEnumerable<HttpPostedFile> GetMultiple(this HttpFileCollection pCollection, string pName)
{
        for (int i = 0; i < pCollection.Count; i++)
        {
            if (pCollection.GetKey(i).Equals(pName))
            {
                yield return pCollection.Get(i);
            }
        }
}

This extension method will return all the HttpPostedFile objects that have the name "myFiles" in the HttpFileCollection if any exists.

Putting GridView data in a DataTable

protected void btnExportExcel_Click(object sender, EventArgs e)
{
    DataTable _datatable = new DataTable();
    for (int i = 0; i < grdReport.Columns.Count; i++)
    {
        _datatable.Columns.Add(grdReport.Columns[i].ToString());
    }
    foreach (GridViewRow row in grdReport.Rows)
    {
        DataRow dr = _datatable.NewRow();
        for (int j = 0; j < grdReport.Columns.Count; j++)
        {
            if (!row.Cells[j].Text.Equals("&nbsp;"))
                dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
        }

        _datatable.Rows.Add(dr);
    }
    ExportDataTableToExcel(_datatable);
}

indexOf method in an object array?

If you are only interested into finding the position see @Pablo's answer.

pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');

However, if you are looking forward to finding the element (i.e. if you were thinking of doing something like this myArray[pos]), there is a more efficient one-line way to do it, using filter.

element = myArray.filter((e) => e.hello === 'stevie')[0];

See perfomance results (~ +42% ops/sec): http://jsbench.github.io/#7fa01f89a5dc5cc3bee79abfde80cdb3

Access denied for root user in MySQL command-line

I re-installed the ODBC connector msi and re-installed mySQL directly (aside from xampp) and it now works. It was a connector problem I think, as SHOW DATABASES wasn't actually showing my databases at all.

My 'root' login wasn't getting access to the DB, which made it seem like it had limited priviliges but it actually wasn't connected properly.

How to set a header for a HTTP GET request, and trigger file download?

i want to post my solution here which was done AngularJS, ASP.NET MVC. The code illustrates how to download file with authentication.

WebApi method along with helper class:

[RoutePrefix("filess")]
class FileController: ApiController
{
    [HttpGet]
    [Route("download-file")]
    [Authorize(Roles = "admin")]
    public HttpResponseMessage DownloadDocument([FromUri] int fileId)
    {
        var file = "someFile.docx"// asking storage service to get file path with id
        return Request.ReturnFile(file);
    }
}

static class DownloadFIleFromServerHelper
{
    public static HttpResponseMessage ReturnFile(this HttpRequestMessage request, string file)
    {
        var result = request.CreateResponse(HttpStatusCode.OK);

        result.Content = new StreamContent(new FileStream(file, FileMode.Open, FileAccess.Read));
        result.Content.Headers.Add("x-filename", Path.GetFileName(file)); // letters of header names will be lowercased anyway in JS.
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = Path.GetFileName(file)
        };

        return result;
    }
}

Web.config file changes to allow sending file name in custom header.

<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
                <add name="Access-Control-Allow-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Expose-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Allow-Origin" value="*" />

Angular JS Service Part:

function proposalService($http, $cookies, config, FileSaver) {
        return {
                downloadDocument: downloadDocument
        };

    function downloadFile(documentId, errorCallback) {
    $http({
        url: config.apiUrl + "files/download-file?documentId=" + documentId,
        method: "GET",
        headers: {
            "Content-type": "application/json; charset=utf-8",
            "Authorization": "Bearer " + $cookies.get("api_key")
        },
        responseType: "arraybuffer"  
        })
    .success( function(data, status, headers) {
        var filename = headers()['x-filename'];

        var blob = new Blob([data], { type: "application/octet-binary" });
        FileSaver.saveAs(blob, filename);
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);
        errorCallback(data, status);
    });
};
};

Module dependency for FileUpload: angular-file-download (gulp install angular-file-download --save). Registration looks like below.

var app = angular.module('cool',
[
    ...
    require('angular-file-saver'),
])
. // other staff.

What is key=lambda

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())

Actually, above codes can be:

>>> sorted(['Some','words','sort','differently'],key=str.lower)

According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

How can I get the day of a specific date with PHP

$date = '2014-02-25';
date('D', strtotime($date));

Change grid interval and specify tick labels in Matplotlib

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop ? put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things: You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax. Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid
ax.grid(which='both')

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

plt.show()

Output is this:

result

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

What can you do if you need to make a change to a file, but don’t know the file’s encoding? If you know the encoding is ASCII-compatible and only want to examine or modify the ASCII parts, you can open the file with the surrogateescape error handler:

with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
    data = f.read()

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

How can I use grep to show just filenames on Linux?

From the grep(1) man page:

  -l, --files-with-matches
          Suppress  normal  output;  instead  print the name of each input
          file from which output would normally have  been  printed.   The
          scanning  will  stop  on  the  first match.  (-l is specified by
          POSIX.)

How to calculate distance between two locations using their longitude and latitude value

private float distanceFrom_in_Km(float lat1, float lng1, float lat2, float lng2) {

     if (lat1== null || lng1== null || lat2== null || lng2== null) 
     {
                return null;
     }

 double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }    

Python: Figure out local timezone

First, note that the question presents an incorrect initialization of an aware datetime object:

>>> local_time=datetime.datetime(2010, 4, 27, 12, 0, 0, 0,
...                                  tzinfo=pytz.timezone('Israel'))

creates an invalid instance. One can see the problem by computing the UTC offset of the resulting object:

>>> print(local_time.utcoffset())
2:21:00

(Note the result which is an odd fraction of an hour.)

To initialize an aware datetime properly using pytz one should use the localize() method as follows:

>>> local_time=pytz.timezone('Israel').localize(datetime.datetime(2010, 4, 27, 12))
>>> print(local_time.utcoffset())
3:00:00

Now, if you require a local pytz timezone as the new tzinfo, you should use the tzlocal package as others have explained, but if all you need is an instance with a correct local time zone offset and abbreviation then tarting with Python 3.3, you can call the astimezone() method with no arguments to convert an aware datetime instance to your local timezone:

>>> local_time.astimezone().strftime('%Y-%m-%d %H:%M %Z %z')
'2010-04-27 05:00 EDT -0400'

Reshape an array in NumPy

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

How can I get the sha1 hash of a string in node.js?

You can use:

  const sha1 = require('sha1');
  const crypt = sha1('Text');
  console.log(crypt);

For install:

  sudo npm install -g sha1
  npm install sha1 --save

Server certificate verification failed: issuer is not trusted

string cmdArguments = $@"/k svn log --trust-server-cert --non-interactive ""{servidor}"" --username alex --password alex -r {numeroRevisao}";
ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe", cmdArguments);

cmd.CreateNoWindow = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.WindowStyle = ProcessWindowStyle.Hidden;
cmd.UseShellExecute = false;

Process reg = Process.Start(cmd);
string output = "";

using (System.IO.StreamReader myOutput = reg.StandardOutput)
{
    output += myOutput.ReadToEnd();
}
using (System.IO.StreamReader myError = reg.StandardError)
{
    output += myError.ReadToEnd();
}

return output;

jQuery equivalent of JavaScript's addEventListener method

The closest thing would be the bind function:

http://api.jquery.com/bind/

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

Generate random password string with requirements in javascript

Generate a random password of length 8 to 32 characters with at least 1 lower case, 1 upper case, 1 number, 1 spl char (!@$&)

    function getRandomUpperCase() {
       return String.fromCharCode( Math.floor( Math.random() * 26 ) + 65 );
    }
    
    function getRandomLowerCase() {
       return String.fromCharCode( Math.floor( Math.random() * 26 ) + 97 );
    } 
    
    function getRandomNumber() {
       return String.fromCharCode( Math.floor( Math.random() * 10 ) + 48 );
    }
    
    function getRandomSymbol() {
        // const symbol = '!@#$%^&*(){}[]=<>/,.|~?';
        const symbol = '!@$&';
        return symbol[ Math.floor( Math.random() * symbol.length ) ];
    }
    
    const randomFunc = [ getRandomUpperCase, getRandomLowerCase, getRandomNumber, getRandomSymbol ];
    
    function getRandomFunc() {
        return randomFunc[Math.floor( Math.random() * Object.keys(randomFunc).length)];
    }
    
    function generatePassword() {
        let password = '';
        const passwordLength = Math.random() * (32 - 8) + 8;
        for( let i = 1; i <= passwordLength; i++ ) {
            password += getRandomFunc()();
        }
        //check with regex
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/
        if( !password.match(regex) ) {
            password = generatePassword();
        }
        return password;
    }
    
    console.log( generatePassword() );

VC++ fatal error LNK1168: cannot open filename.exe for writing

In my case, cleaning and rebuilding the project resolved the problem.

SQL WITH clause example

This has been fully answered here.

See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:

WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'

React Native add bold or italics to single words in <Text> field

Use this react native library

To install

npm install react-native-htmlview --save

Basic Usage

 import React from 'react';
 import HTMLView from 'react-native-htmlview';

  class App extends React.Component {
  render() {
   const htmlContent = 'This is a sentence <b>with</b> one word in bold';

  return (
   <HTMLView
     value={htmlContent}
   />    );
  }
}

Supports almost all html tags.

For more advanced usage like

  1. Link handling
  2. Custom Element Rendering

View this ReadMe

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

The user and password are DEFINITELY incorrect. Oracle 11g credentials are case sensitive.

Try ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE; and alter password.

http://oracle-base.com/articles/11g/case-sensitive-passwords-11gr1.php

Return array in a function

int *fillarr(int arr[])

You can still use the result like

int *returned_array = fillarr(some_other_array);
if(returned_array[0] == 3)
    do_important_cool_stuff();

How to use Tomcat 8 in Eclipse?

I follow Jason's step, but not works.

And then I find the WTP Update site http://download.eclipse.org/webtools/updates/.

Help -> Install new software -> Add > WTP:http://download.eclipse.org/webtools/updates/ -> OK

Then Help -> Check for update, just works, I don't know whether Jason's affect this .

python capitalize first letter only

This is similar to @Anon's answer in that it keeps the rest of the string's case intact, without the need for the re module.

def sliceindex(x):
    i = 0
    for c in x:
        if c.isalpha():
            i = i + 1
            return i
        i = i + 1

def upperfirst(x):
    i = sliceindex(x)
    return x[:i].upper() + x[i:]

x = '0thisIsCamelCase'

y = upperfirst(x)

print(y)
# 0ThisIsCamelCase

As @Xan pointed out, the function could use more error checking (such as checking that x is a sequence - however I'm omitting edge cases to illustrate the technique)

Updated per @normanius comment (thanks!)

Thanks to @GeoStoneMarten in pointing out I didn't answer the question! -fixed that

Evaluate empty or null JSTL c tags

Here's the one liner.

Ternary operator inside EL

${empty value?'value is empty or null':'value is NOT empty or null'}

Java constant examples (Create a java file having only constants)

- Create a Class with public static final fields.

- And then you can access these fields from any class using the Class_Name.Field_Name.

- You can declare the class as final, so that the class can't be extended(Inherited) and modify....

Error: class X is public should be declared in a file named X.java

I had the same problem but solved it when I realized that I didn't compile it with the correct casing. You may have been doing

javac Weatherarray.java

when it should have been

javac WeatherArray.java

incompatible character encodings: ASCII-8BIT and UTF-8

ASCII-8BIT is Ruby's description for characters above the normal 0-0x7f ASCII character-set, and that are single-byte characters. Typically that would be something like ISO-8859-1, or one of its siblings.

If you can identify which character is causing the problem, then you can tell Ruby 1.9.2 to convert between the character set of that character to UTF-8.

James Grey wrote a series of blogs talking about these sort of problems and how to deal with them. I'd recommend going through them.

incompatible character encodings: ASCII-8BIT and UTF-8

That typically happens because you are trying to concatenate two strings, and one contains characters that do not map to the character-set of the other string. There are characters in ISO-8859-1 that do not have equivalents in UTF-8, and vice-versa and how to handle string joining with those incompatibilities requires the programmer to step in.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

How do I prevent mails sent through PHP mail() from going to spam?

There is no sure shot trick. You need to explore the reasons why your mails are classified as spam. SpamAssassin hase a page describing Some Tips for Legitimate Senders to Avoid False Positives. See also Coding Horror: So You'd Like to Send Some Email (Through Code)

When does Java's Thread.sleep throw InterruptedException?

You should generally NOT ignore the exception. Take a look at the following paper:

Don't swallow interrupts

Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to "reinterrupt" the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.

public class TaskRunner implements Runnable {
    private BlockingQueue<Task> queue;

    public TaskRunner(BlockingQueue<Task> queue) { 
        this.queue = queue; 
    }

    public void run() { 
        try {
             while (true) {
                 Task task = queue.take(10, TimeUnit.SECONDS);
                 task.execute();
             }
         }
         catch (InterruptedException e) { 
             // Restore the interrupted status
             Thread.currentThread().interrupt();
         }
    }
}

See the entire paper here:

http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-

When to use RabbitMQ over Kafka?

I realize that this is an old question, but one scenario where RabbitMQ might be a better choice is when dealing with data redaction.

With RabbitMQ, by default once the message has been consumed, it's deleted. With Kafka, by default, messages are kept for a week. It's common to set this to a much longer time, or even to never delete them.

While both products can be configured to retain (or not retain) messages, if CCPA or GDPR compliance is a concern, I'd go with RabbitMQ.

Python Requests throwing SSLError

In my case the reason was fairly trivial.

I had known that the SSL verification had worked until a few days earlier, and was infact working on a different machine.

My next step was to compare the certificate contents and size between the machine on which verification was working, and the one on which it was not.

This quickly led to me determining that the Certificate on the 'incorrectly' working machine was not good, and once I replaced it with the 'good' cert, everything was fine.

Laravel migration table field's type change

Not really an answer, but just a note about ->change():

Only the following column types can be "changed": bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger and unsignedSmallInteger.

https://laravel.com/docs/5.8/migrations#modifying-columns

If your column isn't one of these you will need to either drop the column or use the alter statement as mentioned in other answers.

Flutter: how to make a TextField with HintText but no Underline?

new flutter sdk since after integration of web and desktop support you need to specify individually like this

TextFormField(
    cursorColor: Colors.black,
    keyboardType: inputType,
    decoration: new InputDecoration(
        border: InputBorder.none,
        focusedBorder: InputBorder.none,
        enabledBorder: InputBorder.none,
        errorBorder: InputBorder.none,
        disabledBorder: InputBorder.none,
        contentPadding:
            EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15),
        hintText: "Hint here"),
  )

Get webpage contents with Python?

Because you're using Python 3.1, you need to use the new Python 3.1 APIs.

Try:

urllib.request.urlopen('http://www.python.org/')

Alternately, it looks like you're working from Python 2 examples. Write it in Python 2, then use the 2to3 tool to convert it. On Windows, 2to3.py is in \python31\tools\scripts. Can someone else point out where to find 2to3.py on other platforms?

Edit

These days, I write Python 2 and 3 compatible code by using six.

from six.moves import urllib
urllib.request.urlopen('http://www.python.org')

Assuming you have six installed, that runs on both Python 2 and Python 3.

Can CSS detect the number of children an element has?

yes we can do this using nth-child like so

div:nth-child(n + 8) {
    background: red;
}

This will make the 8th div child onwards become red. Hope this helps...

Also, if someone ever says "hey, they can't be done with styled using css, use JS!!!" doubt them immediately. CSS is extremely flexible nowadays

Example :: http://jsfiddle.net/uWrLE/1/

In the example the first 7 children are blue, then 8 onwards are red...

How can I use Timer (formerly NSTimer) in Swift?

NSTimer has been renamed to Timer in Swift 4.2. this syntax will work in 4.2:

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)

When to use LinkedList over ArrayList in Java?

Correct or Incorrect: Please execute test locally and decide for yourself!

Edit/Remove is faster in LinkedList than ArrayList.

ArrayList, backed by Array, which needs to be double the size, is worse in large volume application.

Below is the unit test result for each operation.Timing is given in Nanoseconds.


Operation                       ArrayList                      LinkedList  

AddAll   (Insert)               101,16719                      2623,29291 

Add      (Insert-Sequentially)  152,46840                      966,62216

Add      (insert-randomly)      36527                          29193

remove   (Delete)               20,56,9095                     20,45,4904

contains (Search)               186,15,704                     189,64,981

Here's the code:

import org.junit.Assert;
import org.junit.Test;

import java.util.*;

public class ArrayListVsLinkedList {
    private static final int MAX = 500000;
    String[] strings = maxArray();

    ////////////// ADD ALL ////////////////////////////////////////
    @Test
    public void arrayListAddAll() {
        Watch watch = new Watch();
        List<String> stringList = Arrays.asList(strings);
        List<String> arrayList = new ArrayList<String>(MAX);

        watch.start();
        arrayList.addAll(stringList);
        watch.totalTime("Array List addAll() = ");//101,16719 Nanoseconds
    }

    @Test
    public void linkedListAddAll() throws Exception {
        Watch watch = new Watch();
        List<String> stringList = Arrays.asList(strings);

        watch.start();
        List<String> linkedList = new LinkedList<String>();
        linkedList.addAll(stringList);
        watch.totalTime("Linked List addAll() = ");  //2623,29291 Nanoseconds
    }

    //Note: ArrayList is 26 time faster here than LinkedList for addAll()

    ///////////////// INSERT /////////////////////////////////////////////
    @Test
    public void arrayListAdd() {
        Watch watch = new Watch();
        List<String> arrayList = new ArrayList<String>(MAX);

        watch.start();
        for (String string : strings)
            arrayList.add(string);
        watch.totalTime("Array List add() = ");//152,46840 Nanoseconds
    }

    @Test
    public void linkedListAdd() {
        Watch watch = new Watch();

        List<String> linkedList = new LinkedList<String>();
        watch.start();
        for (String string : strings)
            linkedList.add(string);
        watch.totalTime("Linked List add() = ");  //966,62216 Nanoseconds
    }

    //Note: ArrayList is 9 times faster than LinkedList for add sequentially

    /////////////////// INSERT IN BETWEEN ///////////////////////////////////////

    @Test
    public void arrayListInsertOne() {
        Watch watch = new Watch();
        List<String> stringList = Arrays.asList(strings);
        List<String> arrayList = new ArrayList<String>(MAX + MAX / 10);
        arrayList.addAll(stringList);

        String insertString0 = getString(true, MAX / 2 + 10);
        String insertString1 = getString(true, MAX / 2 + 20);
        String insertString2 = getString(true, MAX / 2 + 30);
        String insertString3 = getString(true, MAX / 2 + 40);

        watch.start();

        arrayList.add(insertString0);
        arrayList.add(insertString1);
        arrayList.add(insertString2);
        arrayList.add(insertString3);

        watch.totalTime("Array List add() = ");//36527
    }

    @Test
    public void linkedListInsertOne() {
        Watch watch = new Watch();
        List<String> stringList = Arrays.asList(strings);
        List<String> linkedList = new LinkedList<String>();
        linkedList.addAll(stringList);

        String insertString0 = getString(true, MAX / 2 + 10);
        String insertString1 = getString(true, MAX / 2 + 20);
        String insertString2 = getString(true, MAX / 2 + 30);
        String insertString3 = getString(true, MAX / 2 + 40);

        watch.start();

        linkedList.add(insertString0);
        linkedList.add(insertString1);
        linkedList.add(insertString2);
        linkedList.add(insertString3);

        watch.totalTime("Linked List add = ");//29193
    }


    //Note: LinkedList is 3000 nanosecond faster than ArrayList for insert randomly.

    ////////////////// DELETE //////////////////////////////////////////////////////
    @Test
    public void arrayListRemove() throws Exception {
        Watch watch = new Watch();
        List<String> stringList = Arrays.asList(strings);
        List<String> arrayList = new ArrayList<String>(MAX);

        arrayList.addAll(stringList);
        String searchString0 = getString(true, MAX / 2 + 10);
        String searchString1 = getString(true, MAX / 2 + 20);

        watch.start();
        arrayList.remove(searchString0);
        arrayList.remove(searchString1);
        watch.totalTime("Array List remove() = ");//20,56,9095 Nanoseconds
    }

    @Test
    public void linkedListRemove() throws Exception {
        Watch watch = new Watch();
        List<String> linkedList = new LinkedList<String>();
        linkedList.addAll(Arrays.asList(strings));

        String searchString0 = getString(true, MAX / 2 + 10);
        String searchString1 = getString(true, MAX / 2 + 20);

        watch.start();
        linkedList.remove(searchString0);
        linkedList.remove(searchString1);
        watch.totalTime("Linked List remove = ");//20,45,4904 Nanoseconds
    }

    //Note: LinkedList is 10 millisecond faster than ArrayList while removing item.

    ///////////////////// SEARCH ///////////////////////////////////////////
    @Test
    public void arrayListSearch() throws Exception {
        Watch watch = new Watch();
        List<String> stringList = Arrays.asList(strings);
        List<String> arrayList = new ArrayList<String>(MAX);

        arrayList.addAll(stringList);
        String searchString0 = getString(true, MAX / 2 + 10);
        String searchString1 = getString(true, MAX / 2 + 20);

        watch.start();
        arrayList.contains(searchString0);
        arrayList.contains(searchString1);
        watch.totalTime("Array List addAll() time = ");//186,15,704
    }

    @Test
    public void linkedListSearch() throws Exception {
        Watch watch = new Watch();
        List<String> linkedList = new LinkedList<String>();
        linkedList.addAll(Arrays.asList(strings));

        String searchString0 = getString(true, MAX / 2 + 10);
        String searchString1 = getString(true, MAX / 2 + 20);

        watch.start();
        linkedList.contains(searchString0);
        linkedList.contains(searchString1);
        watch.totalTime("Linked List addAll() time = ");//189,64,981
    }

    //Note: Linked List is 500 Milliseconds faster than ArrayList

    class Watch {
        private long startTime;
        private long endTime;

        public void start() {
            startTime = System.nanoTime();
        }

        private void stop() {
            endTime = System.nanoTime();
        }

        public void totalTime(String s) {
            stop();
            System.out.println(s + (endTime - startTime));
        }
    }


    private String[] maxArray() {
        String[] strings = new String[MAX];
        Boolean result = Boolean.TRUE;
        for (int i = 0; i < MAX; i++) {
            strings[i] = getString(result, i);
            result = !result;
        }
        return strings;
    }

    private String getString(Boolean result, int i) {
        return String.valueOf(result) + i + String.valueOf(!result);
    }
}

symfony2 twig path with parameter url creation

/**
 * @Route("/category/{id}", name="_category")
 * @Route("/category/{id}/{active}", name="_be_activatecategory")
 * @Template()
 */
public function categoryAction($id, $active = null)
{ .. }

May works.

Use JSTL forEach loop's varStatus as an ID

The variable set by varStatus is a LoopTagStatus object, not an int. Use:

<div id="divIDNo${theCount.index}">

To clarify:

  • ${theCount.index} starts counting at 0 unless you've set the begin attribute
  • ${theCount.count} starts counting at 1

when I run mockito test occurs WrongTypeOfReturnValue Exception

Another reason for similar error message is trying to mock a final method. One shouldn't attempt to mock final methods (see Final method mocking).

I have also confronted the error in a multi-threaded test. Answer by gna worked in that case.

how to log in to mysql and query the database from linux terminal

To stop or start mysql on most linux systems the following should work:

/etc/init.d/mysqld stop

/etc/init.d/mysqld start

The other answers look good for accessing the mysql client from the command line.

Good luck!

How to store token in Local or Session Storage in Angular 2?

That totally depends of what do you need exactly. If you just need to store and retrieve a token in order to use it in your http requests, i suggest you to simply create a service and use it in your whole project.

example of basic integration:

import {Injectable} from 'angular@core'

@Injectable()
export class TokenManager {

    private tokenKey:string = 'app_token';

    private store(content:Object) {
        localStorage.setItem(this.tokenKey, JSON.stringify(content));
    }

    private retrieve() {
        let storedToken:string = localStorage.getItem(this.tokenKey);
        if(!storedToken) throw 'no token found';
        return storedToken;
    }

    public generateNewToken() {
        let token:string = '...';//custom token generation;
        let currentTime:number = (new Date()).getTime() + ttl;
        this.store({ttl: currentTime, token});
    }

    public retrieveToken() {

        let currentTime:number = (new Date()).getTime(), token = null;
        try {
            let storedToken = JSON.parse(this.retrieve());
            if(storedToken.ttl < currentTime) throw 'invalid token found';
            token = storedToken.token;
        }
        catch(err) {
            console.error(err);
        }
        return token;

    }

}

However if you need to use the local storage more often, by using the stored values in your app views for example. You can use one of the libraries that provides a wrapper of the webstorages like you did with angular2-localstorage.

I created some months ago ng2-webstorage that should respond to your needs. It provides two ng2 services and two decorators to sync the webstorage's values and the service/component's attributes.

import {Component} from '@angular/core';
import {LocalStorageService, LocalStorage} from 'ng2-webstorage';

@Component({
    selector: 'foo',
    template: `
        <section>{{boundValue}}</section>
        <section><input type="text" [(ngModel)]="attribute"/></section>
        <section><button (click)="saveValue()">Save</button></section>
    `,
})
export class FooComponent {

    @LocalStorage()
    boundValue; // attribute bound to the localStorage
    value;

    constructor(private storage:LocalStorageService) {
        this.localSt.observe('boundValue')// triggers the callback each time a new value is set
            .subscribe((newValue) => console.log('new value', newValue));
    }

    saveValue() {
      this.storage.store('boundValue', this.value); // store the given value
    }

}

How to set the background image of a html 5 canvas to .png image

You can give the background image in css :

#canvas { background:url(example.jpg) }

it will show you canvas back ground image

RGB to hex and hex to RGB

function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

This error has occurred when i was importing a project from Github. This happens as the project was of older version. Just try to delete these methods below from your root gradle.

android { compileSdkVersion 19 buildToolsVersion "19.1" }

then try again.

I hope it works.

Remove leading comma from a string

var s = ",'first string','more','even more'";

var array = s.split(',').slice(1);

That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.

Give all permissions to a user on a PostgreSQL database

All commands must be executed while connected to the right database in the right database cluster. Make sure of it.

The user needs access to the database, obviously:

GRANT CONNECT ON DATABASE my_db TO my_user;

And (at least) the USAGE privilege on the schema:

GRANT USAGE ON SCHEMA public TO my_user;

Or grant USAGE on all custom schemas:

DO
$$
BEGIN
   -- RAISE NOTICE '%', (  -- use instead of EXECUTE to see generated commands
   EXECUTE (
   SELECT string_agg(format('GRANT USAGE ON SCHEMA %I TO my_user', nspname), '; ')
   FROM   pg_namespace
   WHERE  nspname <> 'information_schema' -- exclude information schema and ...
   AND    nspname NOT LIKE 'pg\_%'        -- ... system schemas
   );
END
$$;

Then, all permissions for all tables (requires Postgres 9.0 or later).
And don't forget sequences (if any):

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO my_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO my_user;

For older versions you could use the "Grant Wizard" of pgAdmin III (the default GUI).

There are some other objects, the manual for GRANT has the complete list as of Postgres 12:

privileges on a database object (table, column, view, foreign table, sequence, database, foreign-data wrapper, foreign server, function, procedure, procedural language, schema, or tablespace)

But the rest is rarely needed. More details:

Consider upgrading to a current version.

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

For plain ASP.NET MVC Controllers

Create a new attribute

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

Tag your action:

[AllowCrossSiteJson]
public ActionResult YourMethod()
{
    return Json("Works better?");
}

For ASP.NET Web API

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

Tag a whole API controller:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

Or individual API calls:

[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
    ...
}

For Internet Explorer <= v9

IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).

Download it using nuget corsproxy and follow the included instructions.

Blog post | Source code

How to send Request payload to REST API in java?

The following code works for me.

//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);

method implementation:

public static String sendPostRequest(String requestUrl, String payload) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer jsonString = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
                jsonString.append(line);
        }
        br.close();
        connection.disconnect();
        return jsonString.toString();
    } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
    }

}

Prevent jQuery UI dialog from setting focus to first textbox

I have a similar problem. I open an error dialog when validation fails and it grabs the focus, just like Flugan shows it in his answer. The problem is that even if no element inside the dialog is tabbable, the dialog itself is still focused. Here is the original unminified code from jquery-ui-1.8.23\js\jquery.ui.dialog.js:

// set focus to the first tabbable element in the content area or the first button
// if there are no tabbable elements, set focus on the dialog itself
$(self.element.find(':tabbable').get().concat(
  uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat(
    uiDialog.get()))).eq(0).focus();

The comment is theirs!

This is really bad for me for several reasons. The most annoying thing is that the first reaction of the user is to hit the backspace to delete the last character, but instead (s)he is prompted to leave the page, because the backspace is hit outside an input control.

I found that the following workaround works pretty good for me:

jqueryFocus = $.fn.focus;
$.fn.focus = function (delay, fn) {
  jqueryFocus.apply(this.filter(':not(.ui-dialog)'), arguments);
};

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

I had the same problem. My project layout looked like

\---super
    \---thirdparty
        +---mod1-root
        |   +---mod1-linux32
        |   \---mod1-win32
        \---mod2-root
            +---mod2-linux32
            \---mod2-win32

In my case, I had a mistake in my pom.xmls at the modX-root-level. I had copied the mod1-root tree and named it mod2-root. I incorrectly thought I had updated all the pom.xmls appropriately; but in fact, mod2-root/pom.xml had the same group and artifact ids as mod1-root/pom.xml. After correcting mod2-root's pom.xml to have mod2-root specific maven coordinates my issue was resolved.

Can I have multiple background images using CSS?

If you want multiple background images but don't want them to overlap, you can use this CSS:

body {
  font-size: 13px;
  font-family:Century Gothic, Helvetica, sans-serif;
  color: #333;
  text-align: center;
  margin:0px;
  padding: 25px;
}

#topshadow {
  height: 62px
  width:1030px;
  margin: -62px
  background-image: url(images/top-shadow.png);
}

#pageborders {
width:1030px;
min-height:100%;
margin:auto;        
    background:url(images/mid-shadow.png);
}

#bottomshadow {
    margin:0px;
height:66px;
width:1030px;
background:url(images/bottom-shadow.png);
}

#page {
  text-align: left;
  margin:62px, 0px, 20px;
  background-color: white;
  margin:auto;
  padding:0px;
  width:1000px;
}

with this HTML structure:

<body 

<?php body_class(); ?>>

  <div id="topshadow">
  </div>

  <div id="pageborders">

    <div id="page">
    </div>
  </div>
</body>

jquery change div text

Put the title in its own span.

<span id="dialog_title_span">'+dialog_title+'</span>
$('#dialog_title_span').text("new dialog title");

Where will log4net create this log file?

FileAppender appender = repository.GetAppenders().OfType<FileAppender>().FirstOrDefault();
if (appender != null)
    logger.DebugFormat("log file located at : {0}", appender.File);
else
    logger.Error("Could not locate fileAppender");

How to make asynchronous HTTP requests in PHP

Symfony HttpClient is asynchronous https://symfony.com/doc/current/components/http_client.html.

For example you can

use Symfony\Component\HttpClient\HttpClient;

$client = HttpClient::create();
$response1 = $client->request('GET', 'https://website1');
$response2 = $client->request('GET', 'https://website1');
$response3 = $client->request('GET', 'https://website1');
//these 3 calls with return immediately
//but the requests will fire to the website1 webserver

$response1->getContent(); //this will block until content is fetched
$response2->getContent(); //same 
$response3->getContent(); //same

Difference of keywords 'typename' and 'class' in templates?

  1. No difference
  2. Template type parameter Container is itself a template with two type parameters.

Spark Dataframe distinguish columns with duplicated name

I would recommend that you change the column names for your join.

df1.select(col("a") as "df1_a", col("f") as "df1_f")
   .join(df2.select(col("a") as "df2_a", col("f") as "df2_f"), col("df1_a" === col("df2_a"))

The resulting DataFrame will have schema

(df1_a, df1_f, df2_a, df2_f)

jQuery UI Dialog - missing close icon

I am late to this one by a while, but I'm going to blow your mind, ready?

The reason this is happening, is because you are calling bootstrap in, after you are calling jquery-ui in.

Literally, swap the two so that instead of:

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="js/bootstrap.min.js"></script>

it becomes

<script src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

:)

Edit - 26/06/2015 - this keeps attracting interest months later so I thought it was worth an edit. I actually really like the noConflict solution offered in the comment underneath this answer and clarified by user Pretty Cool as a separate answer. As some have reported issues with the bootstrap tooltip when the scripts are swapped. I didn't experience that issue however because I downloaded jquery UI without the tooltip as I didn't need it because bootstrap. So this issue never came up for me.

Edit - 22/07/2015 - Don't confuse jquery-ui with jquery! While Bootstrap's JavaScript requires jQuery to be loaded before, it doesn't rely on jQuery-UI. So jquery-ui.js can be loaded after bootstrap.min.js, while jquery.js always needs to be loaded before Bootstrap.

What is the reason for a red exclamation mark next to my project in Eclipse?

It means there is a problem with the build path in your project. If it is an android project then it mostly means the target value specified in project.properties file cannot be found. This can also be caused because of other kinds of built problems. But it is shown mostly for built problems only. See here for more details. It is about built error decorater seen in eclipse.

An extract from that page:

Build path problems are sometimes easy to miss among other problems in a project. The Package Explorer and Project Explorer views now show a new decorator on Java projects and working sets that contain build path errors:

enter image description here

The concrete errors can be seen in the Problems view, and if you open the view menu and select Group By > Java Problem Type, they all show up in the Build Path category:

enter image description here

XML serialization in Java?

XMLBeans works great if you have a schema for your XML. It creates Java objects for the schema and creates easy to use parse methods.

How to make a .jar out from an Android Studio project

the way i found was to find the project compiler output (project structure > project). then find the complied folder of the module you wish to turn to a jar, compress it with zip and change the extension of the output from zip to jar.

Find and copy files

You need to use cp -t /home/shantanu/tosend in order to tell it that the argument is the target directory and not a source. You can then change it to -exec ... + in order to get cp to copy as many files as possible at once.

What is com.sun.proxy.$Proxy

  1. Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler, which defines a method that is invoked when a proxy method is invoked.

  2. You create them by using the call

    Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
    

    The arguments are:

    1. classLoader. Once the class is generated, it is loaded with this class loader.
    2. interfaces. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
    3. invocationHandler. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler. When a method from any of the supported interfaces, or hashCode, equals, or toString, is invoked, the method invoke is invoked on the handler, passing the Method object for the method to be invoked and the arguments passed.

    For more on this, see the documentation for the Proxy class.

  3. Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.

How large is a DWORD with 32- and 64-bit code?

Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.

In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.

You can find the official list here: http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx

All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).

How to remove all of the data in a table using Django

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

Duplicate / Copy records in the same MySQL table

I have a similar issue, and this is what I'm doing:

insert into Preguntas  (`EncuestaID`, `Tipo` , `Seccion` , `RespuestaID` , `Texto` )  select '23', `Tipo`, `Seccion`, `RespuestaID`, `Texto` from Preguntas where `EncuestaID`= 18

Been Preguntas:

CREATE TABLE IF NOT EXISTS `Preguntas` (
  `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `EncuestaID` int(11) DEFAULT NULL,
  `Tipo` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Seccion` int(11) DEFAULT NULL,
  `RespuestaID` bigint(11) DEFAULT NULL,
  `Texto` text COLLATE utf8_unicode_ci ,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=522 ;

So, the ID is automatically incremented and also I'm using a fixed value ('23') for EncuestaID.

Javascript Equivalent to PHP Explode()

var str = "helloword~this~is~me";
var exploded = str.splice(~);

the exploded variable will return array and you can access elements of the array be accessing it true exploded[nth] where nth is the index of the value you want to get

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

How to get last key in an array?

Just use : echo $array[count($array) - 1];

How do I do base64 encoding on iOS?

I Think This will be helpful

 + (NSString *)toBase64String:(NSString *)string {
    NSData *data = [string dataUsingEncoding: NSUnicodeStringEncoding];

    NSString *ret = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    return ret;
    }

    + (NSString *)fromBase64String:(NSString *)string {
NSData *aData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSData *aDataDecoded = [[NSData alloc]initWithBase64EncodedString:string options:0];
NSString *decryptedStr = [[NSString alloc]initWithData:aDataDecoded encoding:NSUTF8StringEncoding];

return [decryptedStr autorelease];

}

ld: framework not found Pods

This is usually caused by having the .xcodeproj file open instead of .xcworkspace.

When you run 'pod install' for the first time, it will create an .xcworkspace file, which includes your original .xcodeproj and a Pods project. You'll need to close your .xcodeproj and open the .xcworkspace instead.

This is a common issue when creating a project through Xcode's new project wizard - I often forget that I'm not in a workspace, which is required to get Cocoapods to link correctly.

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

Add new column with foreign key constraint in one command

For SQL Server it should be something like

ALTER TABLE one
ADD two_id integer constraint fk foreign key references two(id)

What does the explicit keyword mean?

The explicit-keyword can be used to enforce a constructor to be called explicitly.

class C{
public:
    explicit C(void) = default;
};

int main(void){
    C c();
    return 0;
}

the explicit-keyword in front of the constructor C(void) tells the compiler that only explicit call to this constructor is allowed.

The explicit-keyword can also be used in user-defined type cast operators:

class C{
public:
    explicit inline operator bool(void) const{
        return true;
    }
};

int main(void){
    C c;
    bool b = static_cast<bool>(c);
    return 0;
}

Here, explicit-keyword enforces only explicit casts to be valid, so bool b = c; would be an invalid cast in this case. In situations like these explicit-keyword can help programmer to avoid implicit, unintended casts. This usage has been standardized in C++11.

How can I Convert HTML to Text in C#?

Another post suggests the HTML agility pack:

This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).

python catch exception and continue try block

'continue' is allowed within an 'except' or 'finally' only if the try block is in a loop. 'continue' will cause the next iteration of the loop to start.

So you can try put your two or more functions in a list and use loop to call your function.

Like this:

funcs = [f,g]
for func in funcs:
    try: func()
    except: continue

For full information you can go to this link

True/False vs 0/1 in MySQL

Some "front ends", with the "Use Booleans" option enabled, will treat all TINYINT(1) columns as Boolean, and vice versa.

This allows you to, in the application, use TRUE and FALSE rather than 1 and 0.

This doesn't affect the database at all, since it's implemented in the application.

There is not really a BOOLEAN type in MySQL. BOOLEAN is just a synonym for TINYINT(1), and TRUE and FALSE are synonyms for 1 and 0.

If the conversion is done in the compiler, there will be no difference in performance in the application. Otherwise, the difference still won't be noticeable.

You should use whichever method allows you to code more efficiently, though not using the feature may reduce dependency on that particular "front end" vendor.

How to update a single pod without touching other dependencies

It's 2015

So because pod update SomePod touches everything in the latest versions of cocoapods, I found a workaround.

Follow the next steps:

  1. Remove SomePod from the Podfile

  2. Run pod install

pods will now remove SomePod from our project and from the Podfile.lock file.

  1. Put back SomePod into the Podfile

  2. Run pod install again

This time the latest version of our pod will be installed and saved in the Podfile.lock.

Pretty git branch graphs

This is my take on this matter:

Screenshot:

Screenshot

Usage:

git hist - Show the history of current branch

git hist --all - Show the graph of all branches (including remotes)

git hist master devel - Show the relationship between two or more branches

git hist --branches - Show all local branches

Add --topo-order to sort commits topologically, instead of by date (default in this alias)

Benefits:

  • Looks just like plain --decorate, so with separate colors for different branch names
  • Adds committer email
  • Adds commit relative and absolute date
  • Sorts commits by date

Setup:

git config --global alias.hist "log --graph --date-order --date=short \
--pretty=format:'%C(auto)%h%d %C(reset)%s %C(bold blue)%ce %C(reset)%C(green)%cr (%cd)'"

Detect if a page has a vertical scrollbar?

$(document).ready(function() {
    // Check if body height is higher than window height :)
    if ($("body").height() > $(window).height()) {
        alert("Vertical Scrollbar! D:");
    }

    // Check if body width is higher than window width :)
    if ($("body").width() > $(window).width()) {
        alert("Horizontal Scrollbar! D:<");
    }
});

How do I put text on ProgressBar?

I tried placing a label with transparent background over a progress bar but never got it to work properly. So I found Barry's solution here very useful, although I missed the beautiful Vista style progress bar. So I merged Barry's solution with http://www.dreamincode.net/forums/topic/243621-percent-into-progress-bar/ and managed to keep the native progress bar, while displaying text percentage or custom text over it. I don't see any flickering in this solution either. Sorry to dig up and old thread but I needed this today and so others may need it too.

public enum ProgressBarDisplayText
{
    Percentage,
    CustomText
}

class ProgressBarWithCaption : ProgressBar
{
    //Property to set to decide whether to print a % or Text
    private ProgressBarDisplayText m_DisplayStyle;
    public ProgressBarDisplayText DisplayStyle {
        get { return m_DisplayStyle; }
        set { m_DisplayStyle = value; }
    }

    //Property to hold the custom text
    private string m_CustomText;
    public string CustomText {
        get { return m_CustomText; }
        set {
            m_CustomText = value;
            this.Invalidate();
        }
    }

    private const int WM_PAINT = 0x000F;
    protected override void WndProc(ref Message m)
    {
        base.WndProc(m);

        switch (m.Msg) {
            case WM_PAINT:
                int m_Percent = Convert.ToInt32((Convert.ToDouble(Value) / Convert.ToDouble(Maximum)) * 100);
                dynamic flags = TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.WordEllipsis;

                using (Graphics g = Graphics.FromHwnd(Handle)) {
                    using (Brush textBrush = new SolidBrush(ForeColor)) {

                        switch (DisplayStyle) {
                            case ProgressBarDisplayText.CustomText:
                                TextRenderer.DrawText(g, CustomText, new Font("Arial", Convert.ToSingle(8.25), FontStyle.Regular), new Rectangle(0, 0, this.Width, this.Height), Color.Black, flags);
                                break;
                            case ProgressBarDisplayText.Percentage:
                                TextRenderer.DrawText(g, string.Format("{0}%", m_Percent), new Font("Arial", Convert.ToSingle(8.25), FontStyle.Regular), new Rectangle(0, 0, this.Width, this.Height), Color.Black, flags);
                                break;
                        }

                    }
                }

                break;
        }

    }

}

Callback after all asynchronous forEach callbacks are completed

This is the solution for Node.js which is asynchronous.

using the async npm package.

(JavaScript) Synchronizing forEach Loop with callbacks inside

Subtract two dates in Java

Edit 2018-05-28 I have changed the example to use Java 8's Time API:

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

Add a default value to a column through a migration

For Rails 4+, use change_column_default

def change
  change_column_default :table, :column, value
end

What does AND 0xFF do?

it clears the all the bits that are not in the first byte

Converting a String to DateTime

Since you are handling 24-hour based time and you have a comma separating the seconds fraction, I recommend that you specify a custom format:

DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);

LINQ query to return a Dictionary<string, string>

Use the ToDictionary method directly.

var result = 
  // as Jon Skeet pointed out, OrderBy is useless here, I just leave it 
  // show how to use OrderBy in a LINQ query
  myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
                   .ToDictionary(mc => mc.KeyProp.ToString(), 
                                 mc => mc.ValueProp.ToString(), 
                                 StringComparer.OrdinalIgnoreCase);

How to check if directory exists in %PATH%?

In general this is to put an exe/dll on the path. As long as this file wont appear anywhere else:

@echo off
where /q <put filename here>    
if %errorlevel% == 1 (
    setx PATH "%PATH%;<additional path stuff>"
) else (
    echo "already set path"
)

Create a Bitmap/Drawable from file path

here is a solution:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

What is a void pointer in C++?

A void* pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C's malloc returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.

How to use adb command to push a file on device without sd card

You are trying to write to system folders. With ADB you have root (admin) access so you see the system folders of which sdcard is one of them so to send a picture you could use

D:\Program Files\Android\sdk\platform-tools\adb push am files\android sdk\adb.exe push C:\Downloads\anand.jpg /sdcard/pictures/

NB: C:\Downloads\anand.jpg replace with path and name to picture..

How can I see the size of files and directories in linux?

I do the following all the time:

$ du -sh backup-lr-May-02-2017-1493723588.tar.gz

NB:

-s, --summarize
            display only a total for each argument
-h, --human-readable
            print sizes in human readable format (e.g., 1K 234M 2G)

@RequestParam vs @PathVariable

it may be that the application/x-www-form-urlencoded midia type convert space to +, and the reciever will decode the data by converting the + to space.check the url for more info.http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1

How do I return the response from an asynchronous call?

Here are some approaches to work with asynchronous requests:

  1. Browser Promise object
  2. Q - A promise library for JavaScript
  3. A+ Promises.js
  4. jQuery deferred
  5. XMLHttpRequest API
  6. Using callback concept - As implementation in first answer

Example: jQuery deferred implementation to work with multiple requests

_x000D_
_x000D_
var App = App || {};

App = {
    getDataFromServer: function(){

      var self = this,
                 deferred = $.Deferred(),
                 requests = [];

      requests.push($.getJSON('request/ajax/url/1'));
      requests.push($.getJSON('request/ajax/url/2'));

      $.when.apply(jQuery, requests).done(function(xhrResponse) {
        return deferred.resolve(xhrResponse.result);
      });
      return deferred;
    },

    init: function(){

        this.getDataFromServer().done(_.bind(function(resp1, resp2) {

           // Do the operations which you wanted to do when you
           // get a response from Ajax, for example, log response.
        }, this));
    }
};
App.init();
_x000D_
_x000D_
_x000D_

How to normalize a histogram in MATLAB?

For some Distributions, Cauchy I think, I have found that trapz will overestimate the area, and so the pdf will change depending on the number of bins you select. In which case I do

[N,h]=hist(q_f./theta,30000); % there Is a large range but most of the bins will be empty
plot(h,N/(sum(N)*mean(diff(h))),'+r')

Homebrew: Could not symlink, /usr/local/bin is not writable

If you go to the folder in finder, right click and select "Get Info" you can go to the "Sharing and Permissions" section for the folder and allow "Read & Write" to "everyone"

This is what I do to make symlinks pass with this error. Also brew seems to reset the permissions on the folder also as if you hadn't altered anything