Programs & Examples On #Npruntime

clear form values after submission ajax

$('.contactForm').submit(function(){
    var that = this;

    //...more form stuff...

    $.post('mail.php',{...params...},function(data){

        //...more success stuff...

        that.reset();
    });
});

Simplest way to set image as JPanel background

Simplest way to set image as JPanel background

Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.

See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:

  1. scaled
  2. tiled
  3. actual

In Maven how to exclude resources from the generated jar?

To exclude any file from a jar / target directory you can use the <excludes> tag in your pom.xml file.

In the next example, all files with .properties extension will not be included:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>*.properties</exclude>
            </excludes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

How can I check if a string is a number?

Use Int32.TryParse()

int num;

bool isNum = Int32.TryParse("[string to test]", out num);

if (isNum)
{
    //Is a Number
}
else
{
    //Not a number
}

MSDN Reference

How to check if a column is empty or null using SQL query select statement?

If you want blanks and NULLS to be displayed as other text, such as "Uncategorized" you can simply say...

SELECT ISNULL(NULLIF([PropertyValue], ''), 'Uncategorized') FROM UserProfile

The above answers the main question very well. This answer is an extension of that and is of value to readers.

How to fix "Incorrect string value" errors?

I got a similar error (Incorrect string value: '\xD0\xBE\xDO\xB2. ...' for 'content' at row 1). I have tried to change character set of column to utf8mb4 and after that the error has changed to 'Data too long for column 'content' at row 1'.
It turned out that mysql shows me wrong error. I turned back character set of column to utf8 and changed type of the column to MEDIUMTEXT. After that the error disappeared.
I hope it helps someone.
By the way MariaDB in same case (I have tested the same INSERT there) just cut a text without error.

How does the data-toggle attribute work? (What's its API?)

The data-* attributes is used to store custom data private to the page or application

So Bootstrap uses these attributes for saving states of objects

W3School data-* description

Switching to a TabBar tab view programmatically?

My opinion is that selectedIndex or using objectAtIndex is not necessarily the best way to switch the tab. If you reorder your tabs, a hard coded index selection might mess with your former app behavior.

If you have the object reference of the view controller you want to switch to, you can do:

tabBarController.selectedViewController = myViewController

Of course you must make sure, that myViewController really is in the list of tabBarController.viewControllers.

How to upsert (update or insert) in SQL Server 2005

Try to check for existence:

IF NOT EXISTS (SELECT * FROM dbo.Employee WHERE ID = @SomeID)

    INSERT INTO dbo.Employee(Col1, ..., ColN)
    VALUES(Val1, .., ValN)

ELSE

    UPDATE dbo.Employee
    SET Col1 = Val1, Col2 = Val2, ...., ColN = ValN
    WHERE ID = @SomeID

You could easily wrap this into a stored procedure and just call that stored procedure from the outside (e.g. from a programming language like C# or whatever you're using).

Update: either you can just write this entire statement in one long string (doable - but not really very useful) - or you can wrap it into a stored procedure:

CREATE PROCEDURE dbo.InsertOrUpdateEmployee
       @ID INT,
       @Name VARCHAR(50),
       @ItemName VARCHAR(50),  
       @ItemCatName VARCHAR(50),
       @ItemQty DECIMAL(15,2)
AS BEGIN
    IF NOT EXISTS (SELECT * FROM dbo.Table1 WHERE ID = @ID)
       INSERT INTO dbo.Table1(ID, Name, ItemName, ItemCatName, ItemQty)
       VALUES(@ID, @Name, @ItemName, @ItemCatName, @ItemQty)
    ELSE
       UPDATE dbo.Table1
       SET Name = @Name,
           ItemName = @ItemName,
           ItemCatName = @ItemCatName,
           ItemQty = @ItemQty
       WHERE ID = @ID
END

and then just call that stored procedure from your ADO.NET code

How do I trim() a string in angularjs?

JS .trim() is supported in basically everthing, except IE 8 and below.

If you want it to work with that, then, you can use JQuery, but it'll need to be <2.0.0 (as they removed support for IE8 in the 2.x.x line).

Your other option, if you care about IE7/8 (As you mention earlier), is to add trim yourself:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Simple proof that GUID is not unique

The odds of a bug in the GUID generating code are much higher than the odds of the algorithm generating a collision. The odds of a bug in your code to test the GUIDs is even greater. Give up.

Select a random sample of results from a query result

SELECT * FROM TABLE_NAME SAMPLE(1)

Will give you olny an approximate 1% share rather than exactly 1/100 of the number of observations. The likely reason is than Oracle generates a random flag for each observation as to whether include in in the sample that it generates. The argument 1 (1%) in such a generation process takes the role of probability of each observation's being selected into the sample.

If this is true, the actual distribution of sample sizes will be binomial.

How to change title of Activity in Android?

If you want to set title in Java file, then write in your activity onCreate

setTitle("Your Title");

if you want to in Manifest then write

    <activity
        android:name=".MainActivity"
        android:label="Your Title" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Detecting request type in PHP (GET, POST, PUT or DELETE)

By using

$_SERVER['REQUEST_METHOD']

Example

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     // The request is using the POST method
}

For more details please see the documentation for the $_SERVER variable.

HTML 5 video recording and storing a stream

MediaRecorder API is the solution you are looking for,

Firefox has been supporting it for some time now, and the buzz is is Chrome is gonna implement it in its next release (Chrome 48), but guess you still might need to enable the experimental flag, apparently the flag won't be need from Chrome version 49, for more info check out this Chrome issue.

Meanwhile, a sample of how to do it in Firefox:

_x000D_
_x000D_
var video, reqBtn, startBtn, stopBtn, ul, stream, recorder;
video = document.getElementById('video');
reqBtn = document.getElementById('request');
startBtn = document.getElementById('start');
stopBtn = document.getElementById('stop');
ul = document.getElementById('ul');
reqBtn.onclick = requestVideo;
startBtn.onclick = startRecording;
stopBtn.onclick = stopRecording;
startBtn.disabled = true;
ul.style.display = 'none';
stopBtn.disabled = true;

function requestVideo() {
  navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true
    })
    .then(stm => {
      stream = stm;
      reqBtn.style.display = 'none';
      startBtn.removeAttribute('disabled');
      video.src = URL.createObjectURL(stream);
    }).catch(e => console.error(e));
}

function startRecording() {
  recorder = new MediaRecorder(stream, {
    mimeType: 'video/mp4'
  });
  recorder.start();
  stopBtn.removeAttribute('disabled');
  startBtn.disabled = true;
}


function stopRecording() {
  recorder.ondataavailable = e => {
    ul.style.display = 'block';
    var a = document.createElement('a'),
      li = document.createElement('li');
    a.download = ['video_', (new Date() + '').slice(4, 28), '.webm'].join('');
    a.href = URL.createObjectURL(e.data);
    a.textContent = a.download;
    li.appendChild(a);
    ul.appendChild(li);
  };
  recorder.stop();
  startBtn.removeAttribute('disabled');
  stopBtn.disabled = true;
}
_x000D_
<div>

  <button id='request'>
    Request Camera
  </button>
  <button id='start'>
    Start Recording
  </button>
  <button id='stop'>
    Stop Recording
  </button>
  <ul id='ul'>
    Downloads List:
  </ul>

</div>
<video id='video' autoplay></video>
_x000D_
_x000D_
_x000D_

http://localhost:50070 does not work HADOOP

Enable the port in your system it is for CentOS 7 flow the commands below

1.firewall-cmd --get-active-zones

2.firewall-cmd --zone=dmz --add-port=50070/tcp --permanent

3.firewall-cmd --zone=public --add-port=50070/tcp --permanent

4.firewall-cmd --zone=dmz --add-port=9000/tcp --permanent

5.firewall-cmd --zone=public --add-port=9000/tcp --permanent 6.firewall-cmd --reload

How do I convert a Django QuerySet into list of dicts?

You need DjangoJSONEncoder and list to make your Queryset to json, ref: Python JSON serialize a Decimal object

import json
from django.core.serializers.json import DjangoJSONEncoder


blog = Blog.objects.all().values()
json.dumps(list(blog), cls=DjangoJSONEncoder)

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

no need to do so many things. for set value using multiple select2 var selectedvalue="1,2,3"; //if first 3 products are selected. $('#ddlProduct').val(selectedvalue);

How do I close an open port from the terminal on the Mac?

One liner is best

kill -9 $(lsof -i:PORT -t) 2> /dev/null

Example : On mac, wanted to clear port 9604. Following command worked like a charm

 kill -9 $(lsof -i:9604 -t) 2> /dev/null 

What is the difference between exit(0) and exit(1) in C?

exit in the C language takes an integer representing an exit status.

Exit Success

Typically, an exit status of 0 is considered a success, or an intentional exit caused by the program's successful execution.

Exit Failure

An exit status of 1 is considered a failure, and most commonly means that the program had to exit for some reason, and was not able to successfully complete everything in the normal program flow.

Here's a GNU Resource talking about Exit Status.


As @Als has stated, two constants should be used in place of 0 and 1.

EXIT_SUCCESS is defined by the standard to be zero.

EXIT_FAILURE is not restricted by the standard to be one, but many systems do implement it as one.

Display special characters when using print statement

Use repr:

a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'

Note you do not get \s for a space. I hope that was a typo...?

But if you really do want \s for spaces, you could do this:

print(repr(a).replace(' ',r'\s'))

Clear Application's Data Programmatically

There's a new API introduced in API 19 (KitKat): ActivityManager.clearApplicationUserData().

I highly recommend using it in new applications:

import android.os.Build.*;
if (VERSION_CODES.KITKAT <= VERSION.SDK_INT) {
    ((ActivityManager)context.getSystemService(ACTIVITY_SERVICE))
            .clearApplicationUserData(); // note: it has a return value!
} else {
    // use old hacky way, which can be removed
    // once minSdkVersion goes above 19 in a few years.
}

If you don't want the hacky way you can also hide the button on the UI, so that functionality is just not available on old phones.

Knowledge of this method is mandatory for anyone using android:manageSpaceActivity.


Whenever I use this, I do so from a manageSpaceActivity which has android:process=":manager". There, I manually kill any other processes of my app. This allows me to let a UI stay running and let the user decide where to go next.

private static void killProcessesAround(Activity activity) throws NameNotFoundException {
    ActivityManager am = (ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE);
    String myProcessPrefix = activity.getApplicationInfo().processName;
    String myProcessName = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).processName;
    for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
        if (proc.processName.startsWith(myProcessPrefix) && !proc.processName.equals(myProcessName)) {
            android.os.Process.killProcess(proc.pid);
        }
    }
}

How do I check for null values in JavaScript?

In JavaScript, no string is equal to null.

Maybe you expected pass == null to be true when pass is an empty string because you're aware that the loose equality operator == performs certain kinds of type coercion.

For example, this expression is true:

'' == 0

In contrast, the strict equality operator === says that this is false:

'' === 0

Given that '' and 0 are loosely equal, you might reasonably conjecture that '' and null are loosely equal. However, they are not.

This expression is false:

'' == null

The result of comparing any string to null is false. Therefore, pass == null and all your other tests are always false, and the user never gets the alert.

To fix your code, compare each value to the empty string:

pass === ''

If you're certain that pass is a string, pass == '' will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.

If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.

How to print a linebreak in a python function?

Also if you're making it a console program, you can do: print(" ") and continue your program. I've found it the easiest way to separate my text.

SQL server stored procedure return a table

Here's an example of a SP that both returns a table and a return value. I don't know if you need the return the "Return Value" and I have no idea about MATLAB and what it requires.

CREATE PROCEDURE test
AS 
BEGIN

    SELECT * FROM sys.databases

    RETURN 27
END

--Use this to test
DECLARE @returnval int

EXEC @returnval = test 

SELECT @returnval

PHP Sort a multidimensional array by element containing date

I came across to this post but I wanted to sort by time when returning the items inside my class and I got an error.

So I research the php.net website and end up doing this:

class MyClass {
   public function getItems(){
      usort( $this->items, array("MyClass", "sortByTime") );
      return $this->items;
   }
   public function sortByTime($a, $b){
      return $b["time"] - $a["time"];
   }
}

You can find very useful examples in the PHP.net website

My array looked like this:

  'recent' => 
    array
      92 => 
        array
          'id' => string '92' (length=2)
          'quantity' => string '1' (length=1)
          'time' => string '1396514041' (length=10)
      52 => 
        array
          'id' => string '52' (length=2)
          'quantity' => string '8' (length=1)
          'time' => string '1396514838' (length=10)
      22 => 
        array
          'id' => string '22' (length=2)
          'quantity' => string '1' (length=1)
          'time' => string '1396514871' (length=10)
      81 => 
        array
          'id' => string '81' (length=2)
          'quantity' => string '2' (length=1)
          'time' => string '1396514988' (length=10)

SSRS Field Expression to change the background color of the Cell

You can use SWITCH() function to evaluate multiple criteria to color the cell. The node <BackgroundColor> is the cell fill, <Color> is font color.

Expression:

=SWITCH(
    (
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND (Fields!User_Name.Value.Contains("TOTAL"))
    ), "Black"
    ,(
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND NOT(Fields!User_Name.Value.Contains("TOTAL"))
    ), "#595959"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "#c65911"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND NOT(Fields!OLAP_Cube.Value.Contains("TOTAL")) 
    ), "#ed7d31"
    ,true, "#e7e6e6"
    )

'Daily Totals... CellFill.&[Dark Orange]-[#c65911], TextBold.&[True]'Daily Totals... CellFill.&[Dark Orange]-[#c65911], TextBold.&[True]
'Daily Cube Totals... CellFill.&[Medium Orange]-[#eb6e19]
'Daily User List... CellFill.&[Light Grey]-[#e7e6e6]
'Date Totals All Users Total... CellFill.&[Black]-["black"], TextColor.&[Light Orange]-[#ed7d31]
'Date Totals Per User... CellFill.&[Dark Grey]-[#595959], TextColor.&[Yellow]-["yellow"]
'(ALL OTHER CONDITIONS)
'Daily User List... CellFill.&[Light Grey]-[#e7e6e6]

XML node in report definition file (SSRS-2016 / VS-2015):

                <TablixRow>
                  <Height>0.2in</Height>
                  <TablixCells>
                    <TablixCell>
                      <CellContents>
                        <Textbox Name="Usage_Date1">
                          <CanGrow>true</CanGrow>
                          <KeepTogether>true</KeepTogether>
                          <Paragraphs>
                            <Paragraph>
                              <TextRuns>
                                <TextRun>
                                  <Value>=Fields!Usage_Date.Value</Value>
                                  <Style>
                                    <FontSize>8pt</FontSize>
                                    <FontWeight>=SWITCH(
    (
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "Bold"
    ,true, "Normal"
    )</FontWeight>
                                    <Color>=SWITCH(
    (
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND (Fields!User_Name.Value.Contains("TOTAL"))
    ), "#ed7d31"
    ,(
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND NOT(Fields!User_Name.Value.Contains("TOTAL"))
    ), "Yellow"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "Black"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND NOT(Fields!OLAP_Cube.Value.Contains("TOTAL")) 
    ), "Black"
    ,true, "Black"
    )

'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]
'Daily Cube Totals... CellFill.&amp;[Medium Orange]-[#eb6e19]
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]
'Date Totals All Users Total... CellFill.&amp;[Black]-["black"], TextColor.&amp;[Light Orange]-[#ed7d31]
'Date Totals Per User... CellFill.&amp;[Dark Grey]-[#595959], TextColor.&amp;[Yellow]-["yellow"]
'(ALL OTHER CONDITIONS)
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]</Color>
                                  </Style>
                                </TextRun>
                              </TextRuns>
                              <Style />
                            </Paragraph>
                          </Paragraphs>
                          <rd:DefaultName>Usage_Date1</rd:DefaultName>
                          <Style>
                            <Border>
                              <Color>LightGrey</Color>
                              <Style>Solid</Style>
                            </Border>
                            <BackgroundColor>=SWITCH(
    (
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND (Fields!User_Name.Value.Contains("TOTAL"))
    ), "Black"
    ,(
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND NOT(Fields!User_Name.Value.Contains("TOTAL"))
    ), "#595959"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "#c65911"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND NOT(Fields!OLAP_Cube.Value.Contains("TOTAL")) 
    ), "#ed7d31"
    ,true, "#e7e6e6"
    )

'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]
'Daily Cube Totals... CellFill.&amp;[Medium Orange]-[#eb6e19]
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]
'Date Totals All Users Total... CellFill.&amp;[Black]-["black"], TextColor.&amp;[Light Orange]-[#ed7d31]
'Date Totals Per User... CellFill.&amp;[Dark Grey]-[#595959], TextColor.&amp;[Yellow]-["yellow"]
'(ALL OTHER CONDITIONS)
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]</BackgroundColor>
                            <PaddingLeft>2pt</PaddingLeft>
                            <PaddingRight>2pt</PaddingRight>
                          </Style>
                        </Textbox>
                        <rd:Selected>true</rd:Selected>
                      </CellContents>
                    </TablixCell>

Can I pass an argument to a VBScript (vbs file launched with cscript)?

You can also use named arguments which are optional and can be given in any order.

Set namedArguments = WScript.Arguments.Named

Here's a little helper function:

Function GetNamedArgument(ByVal argumentName, ByVal defaultValue)
  If WScript.Arguments.Named.Exists(argumentName) Then
    GetNamedArgument = WScript.Arguments.Named.Item(argumentName) 
  Else  
    GetNamedArgument = defaultValue
  End If
End Function

Example VBS:

'[test.vbs]
testArg = GetNamedArgument("testArg", "-unknown-")
wscript.Echo now &": "& testArg

Example Usage:

test.vbs /testArg:123

How do I declare an array with a custom class?

you just need to add a default constructor to your class to look like this:

class name {
  public:
    string first;
    string last;

  name() {
  }

  name(string a, string b){
    first = a;
    last = b;
  }
};

Clearing a text field on button click

If you want to reset it, then simple use:

<input type="reset" value="Reset" />

But beware, it will not clear out textboxes that have default value. For example, if we have the following textboxes and by default, they have the following values:

<input id="textfield1" type="text" value="sample value 1" />
<input id="textfield2" type="text" value="sample value 2" />

So, to clear it out, compliment it with javascript:

function clearText()  
{
    document.getElementById('textfield1').value = "";
    document.getElementById('textfield2').value = "";
}  

And attach it to onclick of the reset button:
<input type="reset" value="Reset" onclick="clearText()" />

java Arrays.sort 2d array

Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.

double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };

java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
    public int compare(double[] a, double[] b) {
        return Double.compare(a[0], b[0]);
    }
});

JAVA-8: Instead of that big comparator, we can use lambda function as following-

Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));

Connect to SQL Server Database from PowerShell

# database Intraction

$SQLServer = "YourServerName" #use Server\Instance for named SQL instances!
$SQLDBName = "YourDBName"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; 
User ID= YourUserID; Password= YourPassword" 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'StoredProcName'
$SqlCmd.Connection = $SqlConnection 
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd 
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet) 
$SqlConnection.Close() 

#End :database Intraction
clear

Generating random numbers in Objective-C

As of iOS 9 and OS X 10.11, you can use the new GameplayKit classes to generate random numbers in a variety of ways.

You have four source types to choose from: a general random source (unnamed, down to the system to choose what it does), linear congruential, ARC4 and Mersenne Twister. These can generate random ints, floats and bools.

At the simplest level, you can generate a random number from the system's built-in random source like this:

NSInteger rand = [[GKRandomSource sharedRandom] nextInt];

That generates a number between -2,147,483,648 and 2,147,483,647. If you want a number between 0 and an upper bound (exclusive) you'd use this:

NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];

GameplayKit has some convenience constructors built in to work with dice. For example, you can roll a six-sided die like this:

GKRandomDistribution *d6 = [GKRandomDistribution d6];
[d6 nextInt];

Plus you can shape the random distribution by using things like GKShuffledDistribution.

Wait Until File Is Completely Written

There is only workaround for the issue you are facing.

Check whether file id in process before starting the process of copy. You can call the following function until you get the False value.

1st Method, copied directly from this answer:

private bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

2nd Method:

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
    //check that problem is not in destination file
    if (File.Exists(file) == true)
    {
        FileStream stream = null;
        try
        {
            stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (Exception ex2)
        {
            //_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
            int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
            if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
            {
                return true;
            }
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
    }
    return false;
}

Show Error on the tip of the Edit Text Android

Simple way to implement this thing following this method

1st initial the EditText Field

  EditText editText = findViewById(R.id.editTextField);

When you done initialization. Now time to keep the imputed value in a variable

  final String userInput = editText.getText().toString();

Now Time to check the condition whether user fulfilled or not

  if (userInput.isEmpty()){
           editText.setError("This field need to fill up");
       
        }else{
         //Do what you want to do
      }

Here is an example how I did with my project

  private void sendMail() {
       final String userMessage = etMessage.getText().toString();
          if (userMessage.isEmpty()) {

            etMessage.setError("Write to us");

    }else{
       Toast.makeText(this, "You write to us"+etMessage, Toast.LENGTH_SHORT).show();
      }
   }

Hope it will help you.

HappyCoding

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

How to test if a double is zero?

Yes; all primitive numeric types default to 0.

However, calculations involving floating-point types (double and float) can be imprecise, so it's usually better to check whether it's close to 0:

if (Math.abs(foo.x) < 2 * Double.MIN_VALUE)

You need to pick a margin of error, which is not simple.

print arraylist element?

You should override toString() method in your Dog class. which will be called when you use this object in sysout.

Finding child element of parent pure javascript

Just adding another idea you could use a child selector to get immediate children

document.querySelectorAll(".parent > .child1");

should return all the immediate children with class .child1

Regular Expressions: Search in list

Full Example (Python 3):
For Python 2.x look into Note below

import re

mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note
print(newlist)

Prints:

['cat', 'wildcat', 'thundercat']

Note:

For Python 2.x developers, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).

Python 3 code example
Python 2.x code example

Eclipse 3.5 Unable to install plugins

Just to add to this as I have had problems with an install of eclipse on my machine.

Specs: Win 7 x64 on macbook pro. The broken eclipse was galileo, and 1 of 4 installations on my machine at the time - the others were all working.

I was not running proxy, so above solution in the question did not work.

I found an answer that said to get updates for eclipse, and that would fix things. I tried this, and eclipse said there were no updates, but then for some reason I can't understand, my plugins could now install.

... more anecdotal evidence of a problem, and a possible solution, however strange ...

mysql_config not found when installing mysqldb python interface

The package libmysqlclient-dev is deprecated, so use the below command to fix it.

Package libmysqlclient-dev is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source

sudo apt-get install default-libmysqlclient-dev

Correct way to use StringBuilder in SQL

When you already have all the "pieces" you wish to append, there is no point in using StringBuilder at all. Using StringBuilder and string concatenation in the same call as per your sample code is even worse.

This would be better:

return "select id1, " + " id2 " + " from " + " table";

In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:

return "select id1, id2 from table";

Using new StringBuilder().append("select id1, ").append(" id2 ")....toString() will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.

If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.

I have an article on String / StringBuffer which I wrote a while ago - before StringBuilder came along. The principles apply to StringBuilder in the same way though.

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

The best and tested solution is to put the following small snippet which will collapse the accordion tab which is already open when you load. In my case the last sixth tab was open so I made it collapsed on page load.

 $(document).ready(){
      $('#collapseSix').collapse("hide");
 }

NoClassDefFoundError for code in an Java library on Android

I have just figured out something with this error.

Just make sure that the library jar file contains the compiled R class under android.support.v7.appcompat package and copy all the res in the v7 appcompat support "project" in your ANDROID_SDK_HOME/extras/android/support/v7/appcompat folder.

I use Netbeans with the Android plugin and this solved my issue.

T-SQL split string

I needed a quick way to get rid of the +4 from a zip code.

UPDATE #Emails 
  SET ZIPCode = SUBSTRING(ZIPCode, 1, (CHARINDEX('-', ZIPCODE)-1)) 
  WHERE ZIPCode LIKE '%-%'

No proc... no UDF... just one tight little inline command that does what it must. Not fancy, not elegant.

Change the delimiter as needed, etc, and it will work for anything.

Creating a LINQ select from multiple tables

If the anonymous type causes trouble for you, you can create a simple data class:

public class PermissionsAndPages
{
     public ObjectPermissions Permissions {get;set}
     public Pages Pages {get;set}
}

and then in your query:

select new PermissionsAndPages { Permissions = op, Page = pg };

Then you can pass this around:

return queryResult.SingleOrDefault(); // as PermissionsAndPages

Can I get Unix's pthread.h to compile in Windows?

Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.

It comprises of the pthread.h header, libwinpthread.a, libwinpthread.dll.a static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll and libwinpthread_64-1.dll(this, as of 01-06-2016).

You'll need to link to the libwinpthread.a library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.

Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.

The above two seem to be the most well known ways for this.

Hope this helps.

Java, How to add library files in netbeans?

For Netbeans 2020 September version. JDK 11

(Suggesting this for Gradle project only)

1. create libs folder in src/main/java folder of the project

2. copy past all library jars in there

3. open build.gradle in files tab of project window in project's root

4. correct main class (mine is mainClassName = 'uz.ManipulatorIkrom')

5. and in dependencies add next string:

apply plugin: 'java' 
apply plugin: 'jacoco' 
apply plugin: 'application'
description = 'testing netbeans'
mainClassName = 'uz.ManipulatorIkrom' //4th step
repositories {
    jcenter()
}
dependencies {
    implementation fileTree(dir: 'src/main/java/libs', include: '*.jar') //5th step   
}

6. save, clean-build and then run the app

Centering brand logo in Bootstrap Navbar

Updated 2018

Bootstrap 3

See if this example helps: http://bootply.com/mQh8DyRfWY

The brand is centered using..

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    text-align: center;
    margin: auto;
}

Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner.

EDIT - Another approach is using transform: translateX(-50%);

.navbar-brand {
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
}

http://www.bootply.com/V7vKDfk46G

Bootstrap 4

In Bootstrap 4, mx-auto or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.

Also see:

Bootstrap NavBar with left, center or right aligned items

Installing Git on Eclipse

Checkout this tutorial Eclipse install Git plugin – Step by Step installation instruction


Eclipse install Git plugin – Step by Step installation instruction

Step 1) Go to: http://eclipse.org/egit/download/ to get the plugin repository location.

Step 2.) Select appropriate repository location. In my case its http://download.eclipse.org/egit/updates

Step 3.) Go to Help > Install New Software

Step 4.) To add repository location, Click Add. Enter repository name as “EGit Plugin”. Location will be the URL copied from Step 2. Now click Ok to add repository location.

Step 5.) Wait for a while and it will display list of available products to be installed. Expend “Eclipse Git Team Provider” and select “Eclipse Git Team Provider”. Now Click Next

Step 6.) Review product and click Next.

Step 7.) It will ask you to Accept the agreement. Accept the agreement and click Finish.

Step 8.) Within few seconds, depending on your internet speed, all the necessary dependencies and executable will be downloaded and installed.

Step 9.) Accept the prompt to restart the Eclipse.

Your Eclipse Git Plugin installation is complete.

To verify your installation.

Step 1.) Go to Help > Install New Software

Step 2.) Click on Already Installed and verify plugin is installed.

Remove last character of a StringBuilder?

I am doing something like below:

    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < value.length; i++) {
        stringBuilder.append(values[i]);
        if (value.length-1) {
            stringBuilder.append(", ");
        }
    }

PHP Warning: Module already loaded in Unknown on line 0

I figured this out by printing the PHP configuration and searching by xml.ini. Notice in the following output how xml is loaded twice (first as 20-xml.ini and then as xml.ini):

$ php -i | grep xml
/etc/php.d/20-simplexml.ini,
/etc/php.d/20-xml.ini,
/etc/php.d/20-xmlwriter.ini,
/etc/php.d/30-xmlreader.ini,
/etc/php.d/xml.ini
xmlrpc_error_number => 0 => 0
xmlrpc_errors => Off => Off
libxml Version => 2.9.1
libxml
mbstring.http_output_conv_mimetypes => ^(text/|application/xhtml\+xml) => ^(text /|application/xhtml\+xml)
xml
libxml2 Version => 2.9.1
xmlreader
xmlwriter
libxslt compiled against libxml Version => 2.9.1

Java converting Image to BufferedImage

One way to handle this is to create a new BufferedImage, and tell it's graphics object to draw your scaled image into the new BufferedImage:

final float FACTOR  = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
buffered.getGraphics().drawImage(image, 0, 0 , null);

That should do the trick without casting.

How can I pad a value with leading zeros?

The following provides a quick and fast solution:

_x000D_
_x000D_
function numberPadLeft(num , max, padder = "0"){_x000D_
     return "" == (num += "") ? "" :_x000D_
     ( dif = max - num.length, dif > 0 ?_x000D_
     padder.repeat(dif < 0 ? 0 : dif) + num :_x000D_
     num )_x000D_
}
_x000D_
_x000D_
_x000D_

Call int() function on every list element?

just a point,

numbers = [int(x) for x in numbers]

the list comprehension is more natural, while

numbers = map(int, numbers)

is faster.

Probably this will not matter in most cases

Useful read: LP vs map

How can I include null values in a MIN or MAX?

It's a bit ugly but because the NULLs have a special meaning to you, this is the cleanest way I can think to do it:

SELECT recordid, MIN(startdate),
   CASE WHEN MAX(CASE WHEN enddate IS NULL THEN 1 ELSE 0 END) = 0
        THEN MAX(enddate)
   END
FROM tmp GROUP BY recordid

That is, if any row has a NULL, we want to force that to be the answer. Only if no rows contain a NULL should we return the MIN (or MAX).

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

For me, I encountered this error when my test target did not have some swift files that my app build target had in compile sources. It was very confusing because the 'undeclared type' was being used in so many other places with no problem, and the error seemed vague. So solution there was of course to add the file containing the 'undeclared type' to the test target.

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Go to browser and search for php.ini and then open it, and change these two values:

post_max_size= 1000000000000M
upload_max_filesize= 10000000000000M

If you open the php.ini file using notepad , you can search for these two values by clicking:
cmd + f

Create PostgreSQL ROLE (user) if it doesn't exist

As you are on 9.x, you can wrap that into a DO statement:

do 
$body$
declare 
  num_users integer;
begin
   SELECT count(*) 
     into num_users
   FROM pg_user
   WHERE usename = 'my_user';

   IF num_users = 0 THEN
      CREATE ROLE my_user LOGIN PASSWORD 'my_password';
   END IF;
end
$body$
;

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

Update multiple columns in SQL

I'd like to share with you how I address this kind of question. My case is slightly different as the result of table2 is dynamic and the column numbers may be less than that of table1. But the concept is the same.

First, get the result of table2.

enter image description here

Next, unpivot it.

enter image description here

Then write the update query using dynamic SQL. Sample code is written for testing 2 simple tables - tblA and tblB

--CREATE TABLE tblA(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--CREATE TABLE tblB(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--INSERT INTO tblA(id, col1, col2, col3, col4)
--VALUES(1,'A1','A2','A3','A4')
--INSERT INTO tblB(id, col1, col2, col3, col4)
--VALUES(1,'B1','B2','B3','B4')

DECLARE @id VARCHAR(10) = 1, @TSQL NVARCHAR(MAX)
DECLARE @tblPivot TABLE(    
    colName VARCHAR(255),
    val VARCHAR(255)
)

INSERT INTO @tblPivot
SELECT colName, val
FROM tblB
UNPIVOT
(
    val
    FOR colName IN (col1, col2, col3, col4)
) unpiv
WHERE id = @id

SELECT @TSQL = COALESCE(@TSQL + '''
,','') + colName + ' = ''' + val
FROM @tblPivot

SET @TSQL = N'UPDATE tblA
SET ' + @TSQL + ''' 
WHERE id = ' + @id
PRINT @TSQL
--EXEC SP_EXECUTESQL @TSQL

PRINT @TSQL result:

enter image description here

Beamer: How to show images as step-by-step images

This is what I did:

\begin{frame}{series of images}
\begin{center}
\begin{overprint}

\only<2>{\includegraphics[scale=0.40]{image1.pdf}}
\hspace{-0.17em}\only<3>{\includegraphics[scale=0.40]{image2.pdf}}
\hspace{-0.34em}\only<4>{\includegraphics[scale=0.40]{image3.pdf}}
\hspace{-0.17em}\only<5>{\includegraphics[scale=0.40]{image4.pdf}}

\only<2-5>{\mbox{\structure{Figure:} something}}

\end{overprint}
\end{center}
\end{frame}

What does the DOCKER_HOST variable do?

Ok, I think I got it.

The client is the docker command installed into OS X.

The host is the Boot2Docker VM.

The daemon is a background service running inside Boot2Docker.

This variable tells the client how to connect to the daemon.

When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST set, so that's why docker commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.

Failing to set it gives a message like this:

$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create: 
dial unix /var/run/docker.sock: no such file or directory

One way to fix that would be to simply do this:

$ export DOCKER_HOST=tcp://192.168.59.103:2375

But, as pointed out by others, it's better to do this:

$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]

To spell out this possibly non-intuitive Bash command, running boot2docker shellinit returns a set of Bash commands that set environment variables:

export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1

Hence running $(boot2docker shellinit) generates those commands, and then runs them.

Save plot to image file instead of displaying it using Matplotlib

I used the following:

import matplotlib.pyplot as plt

p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")  
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")  
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05),        ncol=2, fancybox=True, shadow=True)

plt.savefig('data.png')  
plt.show()  
f.close()
plt.close()

I found very important to use plt.show after saving the figure, otherwise it won't work.figure exported in png

Getting full URL of action in ASP.NET MVC

This may be just me being really, really picky, but I like to only define constants once. If you use any of the approaches defined above, your action constant will be defines multiple times.

To avoid this, you can do the following:

    public class Url
    {
        public string LocalUrl { get; }

        public Url(string localUrl)
        {
            LocalUrl = localUrl;
        }

        public override string ToString()
        {
            return LocalUrl;
        }
    }

    public abstract class Controller
    {
        public Url RootAction => new Url(GetUrl());

        protected abstract string Root { get; }

        public Url BuildAction(string actionName)
        {
            var localUrl = GetUrl() + "/" + actionName;
            return new Url(localUrl);
        }

        private string GetUrl()
        {
            if (Root == "")
            {
                return "";
            }

            return "/" + Root;
        }

        public override string ToString()
        {
            return GetUrl();
        }
    }

Then create your controllers, say for example the DataController:

    public static readonly DataController Data = new DataController();
    public class DataController : Controller
    {
        public const string DogAction = "dog";
        public const string CatAction = "cat";
        public const string TurtleAction = "turtle";

        protected override string Root => "data";

        public Url Dog => BuildAction(DogAction);
        public Url Cat => BuildAction(CatAction);
        public Url Turtle => BuildAction(TurtleAction);
    }

Then just use it like:

    // GET: Data/Cat
    [ActionName(ControllerRoutes.DataController.CatAction)]
    public ActionResult Etisys()
    {
        return View();
    }

And from your .cshtml (or any code)

<ul>
    <li><a href="@ControllerRoutes.Data.Dog">Dog</a></li>
    <li><a href="@ControllerRoutes.Data.Cat">Cat</a></li>
</ul>

This is definitely a lot more work, but I rest easy knowing compile time validation is on my side.

Find out where MySQL is installed on Mac OS X

If you run SHOW VARIABLES from a mysql console you can look for basedir.

When I run the following:

mysql> SHOW VARIABLES WHERE `Variable_name` = 'basedir';

on my system I get /usr/local/mysql as the Value returned. (I am not using MAMP - I installed MySQL with homebrew.

mysqldon my machine is in /usr/local/mysql/bin so the basedir is where most everything will be installed to.

Also util:

mysql> SHOW VARIABLES WHERE `Variable_name` = 'datadir'; 

To find where the DBs are stored.

For more: http://dev.mysql.com/doc/refman/5.0/en/show-variables.html

and http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_basedir

Fastest way to copy a file in Node.js

Well, usually it is good to avoid asynchronous file operations. Here is the short (i.e. no error handling) sync example:

var fs = require('fs');
fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));

Difference between abstract class and interface in Python

What is the difference between abstract class and interface in Python?

An interface, for an object, is a set of methods and attributes on that object.

In Python, we can use an abstract base class to define and enforce an interface.

Using an Abstract Base Class

For example, say we want to use one of the abstract base classes from the collections module:

import collections
class MySet(collections.Set):
    pass

If we try to use it, we get an TypeError because the class we created does not support the expected behavior of sets:

>>> MySet()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MySet with abstract methods
__contains__, __iter__, __len__

So we are required to implement at least __contains__, __iter__, and __len__. Let's use this implementation example from the documentation:

class ListBasedSet(collections.Set):
    """Alternate set implementation favoring space over speed
    and not requiring the set elements to be hashable. 
    """
    def __init__(self, iterable):
        self.elements = lst = []
        for value in iterable:
            if value not in lst:
                lst.append(value)
    def __iter__(self):
        return iter(self.elements)
    def __contains__(self, value):
        return value in self.elements
    def __len__(self):
        return len(self.elements)

s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2

Implementation: Creating an Abstract Base Class

We can create our own Abstract Base Class by setting the metaclass to abc.ABCMeta and using the abc.abstractmethod decorator on relevant methods. The metaclass will be add the decorated functions to the __abstractmethods__ attribute, preventing instantiation until those are defined.

import abc

For example, "effable" is defined as something that can be expressed in words. Say we wanted to define an abstract base class that is effable, in Python 2:

class Effable(object):
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def __str__(self):
        raise NotImplementedError('users must define __str__ to use this base class')

Or in Python 3, with the slight change in metaclass declaration:

class Effable(object, metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def __str__(self):
        raise NotImplementedError('users must define __str__ to use this base class')

Now if we try to create an effable object without implementing the interface:

class MyEffable(Effable): 
    pass

and attempt to instantiate it:

>>> MyEffable()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyEffable with abstract methods __str__

We are told that we haven't finished the job.

Now if we comply by providing the expected interface:

class MyEffable(Effable): 
    def __str__(self):
        return 'expressable!'

we are then able to use the concrete version of the class derived from the abstract one:

>>> me = MyEffable()
>>> print(me)
expressable!

There are other things we could do with this, like register virtual subclasses that already implement these interfaces, but I think that is beyond the scope of this question. The other methods demonstrated here would have to adapt this method using the abc module to do so, however.

Conclusion

We have demonstrated that the creation of an Abstract Base Class defines interfaces for custom objects in Python.

How to do ToString for a possibly null object?

I might get beat up for my answer but here goes anyway:

I would simply write

string s = ""
if (myObj != null) {
   x = myObj.toString();
}

Is there a payoff in terms of performance for using the ternary operator? I don't know off the top of my head.

And clearly, as someone above mentioned, you can put this behavior into a method such as safeString(myObj) that allows for reuse.

'Syntax Error: invalid syntax' for no apparent reason

You're missing a close paren in this line:

fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494

There are three ( and only two ).
I hope This will help you.

Python: Get HTTP headers from urllib2.urlopen call?

def _GetHtmlPage(self, addr):
  headers = { 'User-Agent' : self.userAgent,
            '  Cookie' : self.cookies}

  req = urllib2.Request(addr)
  response = urllib2.urlopen(req)

  print "ResponseInfo="
  print response.info()

  resultsHtml = unicode(response.read(), self.encoding)
  return resultsHtml  

Replace Multiple String Elements in C#

Another option using linq is

[TestMethod]
public void Test()
{
  var input = "it's worth a lot of money, if you can find a buyer.";
  var expected = "its worth a lot of money if you can find a buyer";
  var removeList = new string[] { ".", ",", "'" };
  var result = input;

  removeList.ToList().ForEach(o => result = result.Replace(o, string.Empty));

  Assert.AreEqual(expected, result);
}

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Source="../Bilder/sas.png"
       Width="350" />  

EDIT

Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
       x:Name="MyImage"/>

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
{
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
    {
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());
    }

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
    {
          throw new NotImplementedException();
    }
}

Now as you set a different data context, Image would be automatically loaded at runtime.

How to set up a PostgreSQL database in Django

Also make sure you have the PostgreSQL development package installed. On Ubuntu you need to do something like this:

$ sudo apt-get install libpq-dev

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

As far as I can tell, both syntaxes are equivalent. The first is SQL standard, the second is MySQL's extension.

So they should be exactly equivalent performance wise.

http://dev.mysql.com/doc/refman/5.6/en/insert.html says:

INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms of the statement insert rows based on explicitly specified values. The INSERT ... SELECT form inserts rows selected from another table or tables.

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

C# "as" cast vs classic cast

In some cases, it's easily to deal with a null than an exception. In particular, the coalescing operator is handy:

SomeClass someObject = (obj as SomeClass) ?? new SomeClass();

It also simplifies code where you are (not using polymorphism, and) branching based on the type of an object:

ClassA a;
ClassB b;
if ((a = obj as ClassA) != null)
{
    // use a
}
else if ((b = obj as ClassB) != null)
{
    // use b
}

As specified on the MSDN page, the as operator is equivalent to:

expression is type ? (type)expression : (type)null

which avoids the exception completely in favour of a faster type test, but also limits its use to types that support null (reference types and Nullable<T>).

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

Shortcut to comment out a block of code with sublime text

In mac I did this

  • type your comment and press command + D to select the text
  • and then press Alt + Command + / to comment out the selected text.

node.js, socket.io with SSL

This is my nginx config file and iosocket code. Server(express) is listening on port 9191. It works well: nginx config file:

server {
    listen       443 ssl;
    server_name  localhost;
    root   /usr/share/nginx/html/rdist;

    location /user/ {
        proxy_pass   http://localhost:9191;
    }
    location /api/ {
        proxy_pass   http://localhost:9191;
    }
    location /auth/ {
        proxy_pass   http://localhost:9191;
    }

    location / {
        index  index.html index.htm;
        if (!-e $request_filename){
          rewrite ^(.*)$ /index.html break;
        }
    }
    location /socket.io/ {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_pass   http://localhost:9191/socket.io/;
    }


    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    ssl_certificate /etc/nginx/conf.d/sslcert/xxx.pem;
    ssl_certificate_key /etc/nginx/conf.d/sslcert/xxx.key;

}

Server:

const server = require('http').Server(app)
const io = require('socket.io')(server)
io.on('connection', (socket) => {
    handleUserConnect(socket)

  socket.on("disconnect", () => {
   handleUserDisConnect(socket)
  });
})

server.listen(9191, function () {
  console.log('Server listening on port 9191')
})

Client(react):

    const socket = io.connect('', { secure: true, query: `userId=${this.props.user._id}` })

        socket.on('notifications', data => {
            console.log('Get messages from back end:', data)
            this.props.mergeNotifications(data)
        })

What is the list of valid @SuppressWarnings warning names in Java?

All values are permitted (unrecognized ones are ignored). The list of recognized ones is compiler specific.

In The Java Tutorials unchecked and deprecation are listed as the two warnings required by The Java Language Specification, therefore, they should be valid with all compilers:

Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked.

The specific sections inside The Java Language Specification where they are defined is not consistent across versions. In the Java SE 8 Specification unchecked and deprecation are listed as compiler warnings in sections 9.6.4.5. @SuppressWarnings and 9.6.4.6 @Deprecated, respectively.

For Sun's compiler, running javac -X gives a list of all values recognized by that version. For 1.5.0_17, the list appears to be:

  • all
  • deprecation
  • unchecked
  • fallthrough
  • path
  • serial
  • finally

Fatal error: Class 'PHPMailer' not found

Just download composer and install phpMailler autoloader.php

https://github.com/PHPMailer/PHPMailer/blob/master/composer.json

once composer is loaded use below code:

    require_once("phpMailer/class.phpmailer.php");
    require_once("phpMailer/PHPMailerAutoload.php");

    $mail = new PHPMailer(true); 
            $mail->SMTPDebug = true;
            $mail->SMTPSecure = "tls";
            $mail->SMTPAuth   = true;
            $mail->Username   = 'youremail id';
            $mail->Password   = 'youremail password';
            $mail_from        = "youremail id";
            $subject          = "Your Subject";
            $body             = "email body";
            $mail_to          = "receiver_email";
            $mail->IsSMTP(); 
            try {
                  $mail->Host= "smtp.your.com";
                  $mail->Port = "Your SMTP Port No";// ssl port :465, 
                  $mail->Debugoutput = 'html';
                  $mail->AddAddress($mail_to, "receiver_name");
                  $mail->SetFrom($mail_from,'AmpleChat Team'); 
                  $mail->Subject = $subject;
                  $mail->MsgHTML($body);
                  $mail->Send();
                 $emailreturn = 200;
                } catch (phpmailerException $e) {
                  $emailreturn = $e->errorMessage();             
                } catch (Exception $e) {
                 $emailreturn = $e->getMessage();
                }
    echo $emailreturn;

Hope this will work.

How do you post to the wall on a facebook page (not profile)

Get PHP SDK from github and run the following code:

<?php
$attachment = array(
    'message' => 'this is my message',
    'name' => 'This is my demo Facebook application!',
    'caption' => "Caption of the Post",
    'link' => 'http://mylink.com',
    'description' => 'this is a description',
    'picture' => 'http://mysite.com/pic.gif',
    'actions' => array(
        array(
            'name' => 'Get Search',
            'link' => 'http://www.google.com'
        )
    )
);

$result = $facebook->api('/me/feed/', 'post', $attachment);

the above code will Post the message on to your wall... and if you want to post onto your friends or others wall then replace me with the Facebook User Id of that user..for further information look out the API Documentation.

Use dynamic variable names in JavaScript

This is an alternative for those who need to export a dynamically named variable

export {
  [someVariable]: 'some value',
  [anotherVariable]: 'another value',
}

// then.... import from another file like this:
import * as vars from './some-file'

Another alternative is to simply create an object whose keys are named dynamically

const vars = { [someVariable]: 1, [otherVariable]: 2 };

// consume it like this
vars[someVariable];

ListBox with ItemTemplate (and ScrollBar!)

Thnaks for answer. I tried it myself too to an Empty Project and - lo behold allmighty creator of heaven and seven seas - it worked. I originally had ListBox inside which was inside of root . For some reason ListBox doesn't like being inside of StackPanel, at all! =)

-pom-

Wi-Fi Direct and iOS Support

According to this thread:

The peer-to-peer Wi-Fi implemented by iOS (and recent versions of OS X) is not compatible with Wi-Fi Direct. Note Just as an aside, you can access peer-to-peer Wi-Fi without using Multipeer Connectivity. The underlying technology is Bonjour + TCP/IP, and you can access that directly from your app. The WiTap sample code shows how.

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

This Error hit me after installing RVM correctly. Solution: re-boot Terminal.

Reference RailsCast's RVM Install tutorial.

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

For SDK 29 :

String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}

public static void createTextFile(String sBody, String FileName, String Where) {
    try {
        File gpxfile = new File(Where, FileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then you can save your file like this :

createTextFile("This is Content","file.txt",str1);

Changing upload_max_filesize on PHP

You can use also in the php file like this

<?php ini_set('upload_max_filesize', '200M'); ?>

How do I execute a program from Python? os.system fails due to spaces in path

I suspect it's the same problem as when you use shortcuts in Windows... Try this:

import os;
os.system("\"C:\\Temp\\a b c\\Notepad.exe\" C:\\test.txt");

Rails: FATAL - Peer authentication failed for user (PG::Error)

If you get that error message (Peer authentication failed for user (PG::Error)) when running unit tests, make sure the test database exists.

Concatenate String in String Objective-c

Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:

@"first" @"second"

And it will result in:

@"firstsecond"

You can not use it with NSString objects, only with literals, but it can be useful in some cases.

Delete all rows in an HTML table

const table = document.querySelector('table'); table.innerHTML === ' ' ? null : table.innerHTML = ' '; the above javascript worked fine for me. It checks to see if the table contains any data and then clears everything including the header.

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

How can I measure the similarity between two images?

Use a normalised colour histogram. (Read the section on applications here), they are commonly used in image retrieval/matching systems and are a standard way of matching images that is very reliable, relatively fast and very easy to implement.

Essentially a colour histogram will capture the colour distribution of the image. This can then be compared with another image to see if the colour distributions match.

This type of matching is pretty resiliant to scaling (once the histogram is normalised), and rotation/shifting/movement etc.

Avoid pixel-by-pixel comparisons as if the image is rotated/shifted slightly it may lead to a large difference being reported.

Histograms would be straightforward to generate yourself (assuming you can get access to pixel values), but if you don't feel like it, the OpenCV library is a great resource for doing this kind of stuff. Here is a powerpoint presentation that shows you how to create a histogram using OpenCV.

What is a singleton in C#?

E.X You can use Singleton for global information that needs to be injected.

In my case, I was keeping the Logged user detail(username, permissions etc.) in Global Static Class. And when I tried to implement the Unit Test, there was no way I could inject dependency into Controller classes. Thus I have changed my Static Class to Singleton pattern.

public class SysManager
{
    private static readonly SysManager_instance = new SysManager();

    static SysManager() {}

    private SysManager(){}

    public static SysManager Instance
    {
        get {return _instance;}
    }
}

http://csharpindepth.com/Articles/General/Singleton.aspx#cctor

iOS: present view controller programmatically

Try the following:

NextViewController *nextView = [self.storyboard instantiateViewControllerWithIdentifier:@"nextView"];
[self presentViewController:nextView animated:YES completion:NULL];

Using sed to split a string with a delimiter

This might work for you (GNU sed):

sed 'y/:/\n/' file

or perhaps:

sed y/:/$"\n"/ file

How to detect if a string contains at least a number?

  1. You could use CLR based UDFs or do a CONTAINS query using all the digits on the search column.

Appending a list to a list of lists in R

There are two other solutions which involve assigning to an index one past the end of the list. Here is a solution that does use append.

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

outlist <- list(resultsa)
outlist <- append(outlist, list(resultsb))
outlist <- append(outlist, list(resultsc))

which gives your requested format

> str(outlist)
List of 3
 $ :List of 5
  ..$ : num 1
  ..$ : num 2
  ..$ : num 3
  ..$ : num 4
  ..$ : num 5
 $ :List of 5
  ..$ : num 6
  ..$ : num 7
  ..$ : num 8
  ..$ : num 9
  ..$ : num 10
 $ :List of 5
  ..$ : num 11
  ..$ : num 12
  ..$ : num 13
  ..$ : num 14
  ..$ : num 15

SQL injection that gets around mysql_real_escape_string()

The short answer is yes, yes there is a way to get around mysql_real_escape_string(). #For Very OBSCURE EDGE CASES!!!

The long answer isn't so easy. It's based off an attack demonstrated here.

The Attack

So, let's start off by showing the attack...

mysql_query('SET NAMES gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:

  1. Selecting a Character Set

    mysql_query('SET NAMES gbk');
    

    For this attack to work, we need the encoding that the server's expecting on the connection both to encode ' as in ASCII i.e. 0x27 and to have some character whose final byte is an ASCII \ i.e. 0x5c. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5, cp932, gb2312, gbk and sjis. We'll select gbk here.

    Now, it's very important to note the use of SET NAMES here. This sets the character set ON THE SERVER. If we used the call to the C API function mysql_set_charset(), we'd be fine (on MySQL releases since 2006). But more on why in a minute...

  2. The Payload

    The payload we're going to use for this injection starts with the byte sequence 0xbf27. In gbk, that's an invalid multibyte character; in latin1, it's the string ¿'. Note that in latin1 and gbk, 0x27 on its own is a literal ' character.

    We have chosen this payload because, if we called addslashes() on it, we'd insert an ASCII \ i.e. 0x5c, before the ' character. So we'd wind up with 0xbf5c27, which in gbk is a two character sequence: 0xbf5c followed by 0x27. Or in other words, a valid character followed by an unescaped '. But we're not using addslashes(). So on to the next step...

  3. mysql_real_escape_string()

    The C API call to mysql_real_escape_string() differs from addslashes() in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1 for the connection, because we never told it otherwise. We did tell the server we're using gbk, but the client still thinks it's latin1.

    Therefore the call to mysql_real_escape_string() inserts the backslash, and we have a free hanging ' character in our "escaped" content! In fact, if we were to look at $var in the gbk character set, we'd see:

    ?' OR 1=1 /*

    Which is exactly what the attack requires.

  4. The Query

    This part is just a formality, but here's the rendered query:

    SELECT * FROM test WHERE name = '?' OR 1=1 /*' LIMIT 1
    

Congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

It gets worse. PDO defaults to emulating prepared statements with MySQL. That means that on the client side, it basically does a sprintf through mysql_real_escape_string() (in the C library), which means the following will result in a successful injection:

$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Now, it's worth noting that you can prevent this by disabling emulated prepared statements:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version).

The Ugly

I said at the very beginning that we could have prevented all of this if we had used mysql_set_charset('gbk') instead of SET NAMES gbk. And that's true provided you are using a MySQL release since 2006.

If you're using an earlier MySQL release, then a bug in mysql_real_escape_string() meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20, 5.0.22 and 5.1.11.

But the worst part is that PDO didn't expose the C API for mysql_set_charset() until 5.3.6, so in prior versions it cannot prevent this attack for every possible command! It's now exposed as a DSN parameter.

The Saving Grace

As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4 is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8, which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane.

Alternatively, you can enable the NO_BACKSLASH_ESCAPES SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string(). With this mode enabled, 0x27 will be replaced with 0x2727 rather than 0x5c27 and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27 is still 0xbf27 etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode.

Safe Examples

The following examples are safe:

mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because the server's expecting utf8...

mysql_set_charset('gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because we've properly set the character set so the client and the server match.

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've turned off emulated prepared statements.

$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've set the character set properly.

$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

Because MySQLi does true prepared statements all the time.

Wrapping Up

If you:

  • Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) AND mysql_set_charset() / $mysqli->set_charset() / PDO's DSN charset parameter (in PHP = 5.3.6)

OR

  • Don't use a vulnerable character set for connection encoding (you only use utf8 / latin1 / ascii / etc)

You're 100% safe.

Otherwise, you're vulnerable even though you're using mysql_real_escape_string()...

What is a Windows Handle?

Think of the window in Windows as being a struct that describes it. This struct is an internal part of Windows and you don't need to know the details of it. Instead, Windows provides a typedef for pointer to struct for that struct. That's the "handle" by which you can get hold on the window.,

How do I set specific environment variables when debugging in Visual Studio?

As environments are inherited from the parent process, you could write an add-in for Visual Studio that modifies its environment variables before you perform the start. I am not sure how easy that would be to put into your process.

How to get row number in dataframe in Pandas?

 len(df[df["Lastname"]=="Smith"].values)

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

@DanielLittle has the easiest and most elegant answer to the specific question. However, if you are interested in converting to a specific timezone AND taking into account DST (Daylight Savings Time), the following works well:

CAST(DATEADD(S, [UnixTimestamp], '1970-01-01') AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS Datetime)

Note: This solution only works on SQL Server 2016 and above (and Azure).

To create a function:

CREATE FUNCTION dbo.ConvertUnixTime (@input INT)
RETURNS Datetime
AS BEGIN
    DECLARE @Unix Datetime

    SET @Unix = CAST(DATEADD(S, @Input, '1970-01-01') AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS Datetime)

    RETURN @Unix
END

You can call the function like so:

SELECT   dbo.ConvertUnixTime([UnixTimestamp])
FROM     YourTable

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

How to efficiently use try...catch blocks in PHP

When an exception is thrown, execution is immediately halted and continues at the catch{} block. This means that, if you place the database calls in the same try{} block and $tableAresults = $dbHandler->doSomethingWithTableA(); throws an exception, $tableBresults = $dbHandler->doSomethingElseWithTableB(); will not occur. With your second option, $tableBresults = $dbHandler->doSomethingElseWithTableB(); will still occur since it is after the catch{} block, when execution has resumed.

There is no ideal option for every situation; if you want the second operation to continue regardless, then you must use two blocks. If it is acceptable (or desirable) to have the second operation not occur, then you should use only one.

Folder structure for a Node.js project

There is a discussion on GitHub because of a question similar to this one: https://gist.github.com/1398757

You can use other projects for guidance, search in GitHub for:

  • ThreeNodes.js - in my opinion, seems to have a specific structure not suitable for every project;
  • lighter - an more simple structure, but lacks a bit of organization;

And finally, in a book (http://shop.oreilly.com/product/0636920025344.do) suggests this structure:

+-- index.html
+-- js/
¦   +-- main.js
¦   +-- models/
¦   +-- views/
¦   +-- collections/
¦   +-- templates/
¦   +-- libs/
¦       +-- backbone/
¦       +-- underscore/
¦       +-- ...
+-- css/
+-- ...

Where is the Docker daemon log?

Add ways to find docker daemon log in windows:

try

When using docker machine on Windows and Mac OSX, the daemon runs inside a virtual machine.

First, find your active Docker machine.

docker-machine ls Find the name of the active docker machine under the NAME column in the output.

You can copy the docker daemon log file to your local directory for analysis:

docker-machine scp default:/var/log/docker.log ./ Where default is the name of active your docker machine.

How do I iterate over a JSON structure?

mootools example:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});

How do I load an org.w3c.dom.Document from XML in a string?

This works for me in Java 1.5 - I stripped out specific exceptions for readability.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;

public Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

PHP - add 1 day to date format mm-dd-yyyy

use http://www.php.net/manual/en/datetime.add.php like

$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('1 days'));
echo date_format($date, 'Y-m-d');

output

2000-01-2

Laravel Blade html image

Change /img/stuvi-logo.png to img/stuvi-logo.png

{{ HTML::image('img/stuvi-logo.png', 'alt text', array('class' => 'css-class')) }}

Which produces the following HTML.

<img src="http://your.url/img/stuvi-logo.png" class="css-class" alt="alt text">

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

Can be done in one line:

-- the following expression calculates ==> max(@val1, @val2)
SELECT 0.5 * ((@val1 + @val2) + ABS(@val1 - @val2)) 

Edit: If you're dealing with very large numbers you'll have to convert the value variables into bigint in order to avoid an integer overflow.

jQuery check if Cookie exists, if not create it

 $(document).ready(function() {

     var CookieSet = $.cookie('cookietitle', 'yourvalue');

     if (CookieSet == null) {
          // Do Nothing
     }
     if (jQuery.cookie('cookietitle')) {
          // Reactions
     }
 });

How to compile c# in Microsoft's new Visual Studio Code?

Install the extension "Code Runner". Check if you can compile your program with csc (ex.: csc hello.cs). The command csc is shipped with Mono. Then add this to your VS Code user settings:

"code-runner.executorMap": {
        "csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
        // "csharp": "echo '# calling dotnet run\n' && dotnet run"
    }

Open your C# file and use the execution key of Code Runner.

Edit: also added dotnet run, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console, dotnet restore).

Toggle Checkboxes on/off

Here is a jQuery way to toggle checkboxes without having to select a checkbox with html5 & labels:

 <div class="checkbox-list margin-auto">
    <label class="">Compare to Last Year</label><br>
    <label class="normal" for="01">
       <input id="01" type="checkbox" name="VIEW" value="01"> Retail units
    </label>
    <label class="normal" for="02">
          <input id="02" type="checkbox" name="VIEW" value="02">  Retail Dollars
    </label>
    <label class="normal" for="03">
          <input id="03" type="checkbox" name="VIEW" value="03">  GP Dollars
    </label>
    <label class="normal" for="04">
          <input id="04" type="checkbox" name="VIEW" value="04">  GP Percent
    </label>
</div>

  $("input[name='VIEW']:checkbox").change(function() {
    if($(this).is(':checked')) {  
         $("input[name='VIEW']:checkbox").prop("checked", false);
     $("input[name='VIEW']:checkbox").parent('.normal').removeClass("checked");
         $(this).prop("checked", true);
         $(this).parent('.normal').addClass('checked');
    }
    else{
         $("input[name='VIEW']").prop("checked", false);
         $("input[name='VIEW']").parent('.normal').removeClass('checked');
    }    
});

http://www.bootply.com/A4h6kAPshx

Changing one character in a string

new = text[:1] + 'Z' + text[2:]

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

Or you can debug by CTRL+F5 this will open ConsoleWindow waits after last line executed untill you press key.

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

This issue occurred when I switched to Android Studio 3.4 with Android Gradle plugin 3.4.0. which works with the R8 compiler.

The Android Gradle plugin includes additional predefined ProGuard rules files, but it is recommended that you use proguard-android-optimize.txt. More info here.

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile(
          'proguard-android-optimize.txt'),
          // List additional ProGuard rules for the given build type here. By default,
          // Android Studio creates and includes an empty rules file for you (located
          // at the root directory of each module).
          'proguard-rules.pro'
    }
}

Alternate output format for psql

Also be sure to check out \H, which toggles HTML output on/off. Not necessarily easy to read at the console, but interesting for dumping into a file (see \o) or pasting into an editor/browser window for viewing, especially with multiple rows of relatively complex data.

Node package ( Grunt ) installed but not available

If you did have installed Grunt package by running npm install -g grunt and it still say's No command 'grunt' found or grunt: command not found, a quick and dirty way to get this working is linking node binaries to your $PATH manually.

On MacOSX/Linux you can add this line to your ~/.bash_profile or ~/.bashrc file.

PATH=$PATH:/usr/local/Cellar/node/HEAD/bin # Add NPM binaries

You probably should replace /usr/local/Cellar/node/HEAD/bin by the path where your node binaries could be found.

If this is quick and dirty to me, it's because everything should work without doing this, but for an unknown reason, a link seem broken. As nobody on IRC could tell me why this happened, I found my own way to make it (grunt) work.

PS: This should help you make grunt works, this answer is not jquery-ui related.

Update 02/2013 : You should take a look at @tom-p's answer which explains better what is going on. Tom gives us the real solution instead of hacking your bashrc file : both should work, but you should try installing grunt-cli first.

Log.INFO vs. Log.DEBUG

Also remember that all info(), error(), and debug() logging calls provide internal documentation within any application.

What's a quick way to comment/uncomment lines in Vim?

You can use vim-commentary by tpope (https://github.com/tpope/vim-commentary) you can use it as following:

Enter visual mode by pressing

'v'

Then press

'j' repeatedly or e.g 4j to select 4 row

Now all you have to do with the selection is enter keys:

'gc'

This will comment out all the selection, to uncomment repead keys:

'gc'

Saving a text file on server using JavaScript

It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.

However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:

http://api.jquery.com/jQuery.post/

And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!

File uploading (most of this applies if sending plain text too if javascript can choose the name of the file) http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security https://www.owasp.org/index.php/Unrestricted_File_Upload

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

How can I return pivot table output in MySQL?

A stardard-SQL version using boolean logic:

SELECT company_name
     , COUNT(action = 'EMAIL' OR NULL) AS "Email"
     , COUNT(action = 'PRINT' AND pagecount = 1 OR NULL) AS "Print 1 pages"
     , COUNT(action = 'PRINT' AND pagecount = 2 OR NULL) AS "Print 2 pages"
     , COUNT(action = 'PRINT' AND pagecount = 3 OR NULL) AS "Print 3 pages"
FROM   tbl
GROUP  BY company_name;

SQL Fiddle.

How?

TRUE OR NULL yields TRUE.
FALSE OR NULL yields NULL.
NULL OR NULL yields NULL.
And COUNT only counts non-null values. Voilá.

HTML5 Video Stop onClose

Starting Video with different browsers

For Opera 12

window.navigator.getUserMedia(param, function(stream) {
                            video.src =window.URL.createObjectURL(stream);
                        }, videoError );

For Firefox Nightly 18.0

window.navigator.mozGetUserMedia(param, function(stream) {
                            video.mozSrcObject = stream;
                        }, videoError );

For Chrome 22

window.navigator.webkitGetUserMedia(param, function(stream) {
                            video.src =window.webkitURL.createObjectURL(stream);
                        },  videoError );

Stopping video with different browsers

For Opera 12

video.pause();
video.src=null;

For Firefox Nightly 18.0

video.pause();
video.mozSrcObject=null;

For Chrome 22

video.pause();
video.src="";

sed with literal string--not input file

Works like you want:

echo "A,B,C" | sed s/,/\',\'/g

How to get the size of a JavaScript object?

function sizeOf(parent_data, size)
{
    for (var prop in parent_data)
    {
        let value = parent_data[prop];

        if (typeof value === 'boolean')
        {
            size += 4;
        }
        else if (typeof value === 'string')
        {
            size += value.length * 2;
        }
        else if (typeof value === 'number')
        {
             size += 8;
        }
        else
        {      
            let oldSize = size;
            size += sizeOf(value, oldSize) - oldSize;
        }
    }

    return size;
}


function roughSizeOfObject(object)
{   
    let size = 0;
    for each (let prop in object)
    {    
        size += sizeOf(prop, 0);
    } // for..
    return size;
}

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

WPF Application that only has a tray icon

I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

  • Rich ToolTips rather than text
  • WPF context menus and popups
  • Command support and routed events
  • Flexible data binding
  • Rich balloon messages rather than the default messages provides by the OS

Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

How to print a groupby object

to print all (or arbitrarily many) lines of the grouped df:

import pandas as pd
pd.set_option('display.max_rows', 500)

grouped_df = df.group(['var1', 'var2'])
print(grouped_df)

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Try

$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ")or die(mysql_error());

and check if this throw any error.

Then use while($rows = mysql_fetch_assoc($query)):

And finally display it as

echo $name . "<br/>" . $address . "<br/>" . $email . "<br/>" . $subject . "<br/>" . $comment . "<br/><br/>" . ;

Do not user mysql_* as its deprecated.

What is correct media query for IPad Pro?

For those who want to target an iPad Pro 11" the device-width is 834px, device-height is 1194px and the device-pixel-ratio is 2. Source: screen.width, screen.height and devicePixelRatio reported by Safari on iOS Simulator.

Exact media query for portrait: (device-height: 1194px) and (device-width: 834px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

You can use case in update and SWAP as many as you want

update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

Export MySQL database using PHP only

Try the following.

Execute a database backup query from PHP file. Below is an example of using SELECT INTO OUTFILE query for creating table backup:

<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";

$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
  die('Connection failed [' . $con->connect_error . ']');
}

$tableName  = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
?>

To restore the backup you just need to run LOAD DATA INFILE query like this:

<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";

$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
  die('Connection failed [' . $con->connect_error . ']');
}

$tableName  = 'yourtable';
$backupFile = 'yourtable.sql';
$query      = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
?>

git push rejected

Actually I got the same error but the below comment worked for me

git push -f origin master

How does one parse XML files?

In Addition you can use XPath selector in the following way (easy way to select specific nodes):

XmlDocument doc = new XmlDocument();
doc.Load("test.xml");

var found = doc.DocumentElement.SelectNodes("//book[@title='Barry Poter']"); // select all Book elements in whole dom, with attribute title with value 'Barry Poter'

// Retrieve your data here or change XML here:
foreach (XmlNode book in nodeList)
{
  book.InnerText="The story began as it was...";
}

Console.WriteLine("Display XML:");
doc.Save(Console.Out);

the documentation

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

i was trying the same, so i downloaded the .7zip version of XAMPP with php 5.6.33 from https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/5.6.33/

then followed the steps below: 1. rename c:\xampp\php to c:\xampp\php7 2. raname C:\xampp\apache\conf\extra\httpd-xampp.conf to httpd-xampp7.OLD 3. copy php folder from XAMPP_5.6 7zip archive to c:\xampp\ 4. copy file httpd-xampp.conf from XAMPP_5.6 7zip archive to C:\xampp\apache\conf\extra\

open xampp control panel and start Apache and then visit ( i am using port 82 instead of default 80) http://localhost and then click PHPInfo to see if it is working as expected.

Opening localhost shows dashboard

Opening phpinfo shows version 5.6

Download file and automatically save it to folder

Why not just bypass the WebClient's file handling pieces altogether. Perhaps something similar to this:

    private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
    {
        e.Cancel = true;
        WebClient client = new WebClient();

        client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);

        client.DownloadDataAsync(e.Url);
    }

    void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        string filepath = textBox1.Text;
        File.WriteAllBytes(filepath, e.Result);
        MessageBox.Show("File downloaded");
    }

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The Adjusted R-squared is close to, but different from, the value of R2. Instead of being based on the explained sum of squares SSR and the total sum of squares SSY, it is based on the overall variance (a quantity we do not typically calculate), s2T = SSY/(n - 1) and the error variance MSE (from the ANOVA table) and is worked out like this: adjusted R-squared = (s2T - MSE) / s2T.

This approach provides a better basis for judging the improvement in a fit due to adding an explanatory variable, but it does not have the simple summarizing interpretation that R2 has.

If I haven't made a mistake, you should verify the values of adjusted R-squared and R-squared as follows:

s2T <- sum(anova(v.lm)[[2]]) / sum(anova(v.lm)[[1]])
MSE <- anova(v.lm)[[3]][2]
adj.R2 <- (s2T - MSE) / s2T

On the other side, R2 is: SSR/SSY, where SSR = SSY - SSE

attach(v)
SSE <- deviance(v.lm) # or SSE <- sum((epm - predict(v.lm,list(n_days)))^2)
SSY <- deviance(lm(epm ~ 1)) # or SSY <- sum((epm-mean(epm))^2)
SSR <- (SSY - SSE) # or SSR <- sum((predict(v.lm,list(n_days)) - mean(epm))^2)
R2 <- SSR / SSY 

print call stack in C or C++

You can use Poppy for this. It is normally used to gather the stack trace during a crash but it can also output it for a running program as well.

Now here's the good part: it can output the actual parameter values for each function on the stack, and even local variables, loop counters, etc.

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

You are sending one parameter incorrectly; it should be a dictionary object:

  • Wrong: func(a=r)

  • Correct: func(a={'x':y})

Replace all occurrences of a string in a data frame

If you are only looking to replace all occurrences of "< " (with space) with "<" (no space), then you can do an lapply over the data frame, with a gsub for replacement:

> data <- data.frame(lapply(data, function(x) {
+                  gsub("< ", "<", x)
+              }))
> data
  name var1 var2
1    a   <2   <3
2    a   <2   <3
3    a   <2   <3
4    b   <2   <3
5    b   <2   <3
6    b   <2   <3
7    c   <2   <3
8    c   <2   <3
9    c   <2   <3

LINQ select in C# dictionary

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.

Passing HTML input value as a JavaScript Function Parameter

You can get the values with use of ID. But ID should be Unique.

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="b"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    a = $('#a').val();
    b = $('#b').val();
    var sum = a + b;
    alert(sum);
  }
</script>
</body>

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

How to use protractor to check if an element is visible?

This should do it:

expect($('[ng-show=saving].icon-spin').isDisplayed()).toBe(true);

Remember protractor's $ isn't jQuery and :visible is not yet a part of available CSS selectors + pseudo-selectors

More info at https://stackoverflow.com/a/13388700/511069

Safely casting long to int in Java

A new method has been added with Java 8 to do just that.

import static java.lang.Math.toIntExact;

long foo = 10L;
int bar = toIntExact(foo);

Will throw an ArithmeticException in case of overflow.

See: Math.toIntExact(long)

Several other overflow safe methods have been added to Java 8. They end with exact.

Examples:

  • Math.incrementExact(long)
  • Math.subtractExact(long, long)
  • Math.decrementExact(long)
  • Math.negateExact(long),
  • Math.subtractExact(int, int)

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

Increment variable value by 1 ( shell programming)

you can use bc as it can also do floats

var=$(echo "1+2"|bc)

How to access environment variable values?

import os
for a in os.environ:
    print('Var: ', a, 'Value: ', os.getenv(a))
print("all done")

That will print all of the environment variables along with their values.

How can I remove the "No file chosen" tooltip from a file input in Chrome?

I know it is a bit of a hack, but all I required was to set the color to transparent in the style sheet - inline would look like this style="color:transparent;".

Make a dictionary in Python from input values

This is what we ended up using:

n = 3
d = dict(raw_input().split() for _ in range(n))
print d

Input:

A1023 CRT
A1029 Regulator
A1030 Therm

Output:

{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

curl.h no such file or directory

To those who use centos and have stumbled upon this post :

 $ yum install curl-devel

and when compiling your program example.cpp, link to the curl library:

 $ g++ example.cpp -lcurl -o example

"-o example" creates the executable example instead of the default a.out.

The next line runs example:

 $ ./example

Changing Locale within the app itself

In Android M the top solution won't work. I've written a helper class to fix that which you should call from your Application class and all Activities (I would suggest creating a BaseActivity and then make all the Activities inherit from it.

Note: This will also support properly RTL layout direction.

Helper class:

public class LocaleUtils {

    private static Locale sLocale;

    public static void setLocale(Locale locale) {
        sLocale = locale;
        if(sLocale != null) {
            Locale.setDefault(sLocale);
        }
    }

    public static void updateConfig(ContextThemeWrapper wrapper) {
        if(sLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Configuration configuration = new Configuration();
            configuration.setLocale(sLocale);
            wrapper.applyOverrideConfiguration(configuration);
        }
    }

    public static void updateConfig(Application app, Configuration configuration) {
        if (sLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            //Wrapping the configuration to avoid Activity endless loop
            Configuration config = new Configuration(configuration);
            // We must use the now-deprecated config.locale and res.updateConfiguration here,
            // because the replacements aren't available till API level 24 and 17 respectively.
            config.locale = sLocale;
            Resources res = app.getBaseContext().getResources();
            res.updateConfiguration(config, res.getDisplayMetrics());
        }
    }
}

Application:

public class App extends Application {
    public void onCreate(){
        super.onCreate();

        LocaleUtils.setLocale(new Locale("iw"));
        LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        LocaleUtils.updateConfig(this, newConfig);
    }
}

BaseActivity:

public class BaseActivity extends Activity {
    public BaseActivity() {
        LocaleUtils.updateConfig(this);
    }
}

How can I set the aspect ratio in matplotlib?

This answer is based on Yann's answer. It will set the aspect ratio for linear or log-log plots. I've used additional information from https://stackoverflow.com/a/16290035/2966723 to test if the axes are log-scale.

def forceAspect(ax,aspect=1):
    #aspect is width/height
    scale_str = ax.get_yaxis().get_scale()
    xmin,xmax = ax.get_xlim()
    ymin,ymax = ax.get_ylim()
    if scale_str=='linear':
        asp = abs((xmax-xmin)/(ymax-ymin))/aspect
    elif scale_str=='log':
        asp = abs((scipy.log(xmax)-scipy.log(xmin))/(scipy.log(ymax)-scipy.log(ymin)))/aspect
    ax.set_aspect(asp)

Obviously you can use any version of log you want, I've used scipy, but numpy or math should be fine.

What is the difference between a data flow diagram and a flow chart?

Although my experience with DFD diagrams is limited I can tell you that a DFD shows you how the data moves (flows) between the various modules. Furthermore a DFD can be partitioned in levels, that is in the Initial Level you see the system (say, a System to Rent a Movie) as a whole (called the Context Level). That level could be broken down into another Level that contains activities (say, rent a movie, return a movie) and how the data flows into those activities (could be a name, number of days, whatever). Now you can make a sublevel for each activity detailing the many tasks or scenarios of those activities. And so on, so forth. Remember that the data is always passing between levels.

Now as for the flowchart just remember that a flowchart describes an algorithm!

Specify path to node_modules in package.json

Yarn supports this feature:

# .yarnrc file in project root
--modules-folder /node_modules

But your experience can vary depending on which packages you use. I'm not sure you'd want to go into that rabbit hole.

Flushing footer to bottom of the page, twitter bootstrap

Here you'll find the approach in HAML ( http://haml.info ) with navbar on top and footer at the bottom of the page:

%body
  #main{:role => "main"}
    %header.navbar.navbar-fixed-top
      %nav.navbar-inner
        .container
          /HEADER
      .container
        /BODY
    %footer.navbar.navbar-fixed-bottom
      .container
        .row
          /FOOTER

How can I disable all views inside the layout?

Although not quite the same as disabling views within a layout, it is worth mentioning that you can prevent all children from receiving touches (without having to recurse the layout hierarchy) by overriding the ViewGroup#onInterceptTouchEvent(MotionEvent) method:

public class InterceptTouchEventFrameLayout extends FrameLayout {

    private boolean interceptTouchEvents;

    // ...

    public void setInterceptTouchEvents(boolean interceptTouchEvents) {
        this.interceptTouchEvents = interceptTouchEvents;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return interceptTouchEvents || super.onInterceptTouchEvent(ev);
    }

}

Then you can prevent children from receiving touch events:

InterceptTouchEventFrameLayout layout = (InterceptTouchEventFrameLayout) findViewById(R.id.layout);
layout.setInterceptTouchEvents(true);

If you have a click listener set on layout, it will still be triggered.

Conversion from List<T> to array T[]

list.ToArray()

Will do the tric. See here for details.

How do I remove blank elements from an array?

Shortest way cities.select(&:present?)

How to link html pages in same or different folders?

Use

../

For example if your file, lets say image is in folder1 in folder2 you locate it this way

../folder1/folder2/image

SVN upgrade working copy

from eclipse, you can select on the project, right click->team->upgrade

What is the color code for transparency in CSS?

There are now 8-digit hex codes in CSS4 (CSS Color Module Level 4), the last two digit (or in case of the abbreviation, the last of the 4 digits) represents alpha, 00 meaning fully transparent and ff meaning fully opaque, 7f representing an opacity of 0.5 etc.

The format is '#rrggbbaa' or the shorthand, '#rgba'.

Support is lacking for MS browsers, they might be less cooperative or just slower than the other developers, either or both of which actually sealed IE's fate: https://caniuse.com/#feat=css-rrggbbaa

Test a weekly cron job

Aside from that you can also use:

http://pypi.python.org/pypi/cronwrap

to wrap up your cron to send you an email upon success or failure.

Method has the same erasure as another method in type

This is because Java Generics are implemented with Type Erasure.

Your methods would be translated, at compile time, to something like:

Method resolution occurs at compile time and doesn't consider type parameters. (see erickson's answer)

void add(Set ii);
void add(Set ss);

Both methods have the same signature without the type parameters, hence the error.

JavaScript Promises - reject vs. throw

There is no advantage of using one vs the other, but, there is a specific case where throw won't work. However, those cases can be fixed.

Any time you are inside of a promise callback, you can use throw. However, if you're in any other asynchronous callback, you must use reject.

For example, this won't trigger the catch:

_x000D_
_x000D_
new Promise(function() {
  setTimeout(function() {
    throw 'or nah';
    // return Promise.reject('or nah'); also won't work
  }, 1000);
}).catch(function(e) {
  console.log(e); // doesn't happen
});
_x000D_
_x000D_
_x000D_

Instead you're left with an unresolved promise and an uncaught exception. That is a case where you would want to instead use reject. However, you could fix this in two ways.

  1. by using the original Promise's reject function inside the timeout:

_x000D_
_x000D_
new Promise(function(resolve, reject) {
  setTimeout(function() {
    reject('or nah');
  }, 1000);
}).catch(function(e) {
  console.log(e); // works!
});
_x000D_
_x000D_
_x000D_

  1. by promisifying the timeout:

_x000D_
_x000D_
function timeout(duration) { // Thanks joews
  return new Promise(function(resolve) {
    setTimeout(resolve, duration);
  });
}

timeout(1000).then(function() {
  throw 'worky!';
  // return Promise.reject('worky'); also works
}).catch(function(e) {
  console.log(e); // 'worky!'
});
_x000D_
_x000D_
_x000D_

How to display default text "--Select Team --" in combo box on pageload in WPF?

  1. Put a label on top of the combobox.

  2. Bind the content of the label to to the combobox Text property.

  3. Set the opacity of the combobox to zero , Opacity=0.

  4. Write default text in the combobox Text property

          <ComboBox Name="cb"
            Text="--Select Team--" Opacity="0" 
            Height="40" Width="140" >
             <ComboBoxItem Content="Manchester United" />
             <ComboBoxItem Content="Lester" />
         </ComboBox>
     </Grid>
    

dplyr mutate with conditional values

With dplyr 0.7.2, you can use the very useful case_when function :

x=read.table(
 text="V1 V2 V3 V4
 1  1  2  3  5
 2  2  4  4  1
 3  1  4  1  1
 4  4  5  1  3
 5  5  5  5  4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
                 x$V2==4 & x$V3!=1 ~ 2,
                 TRUE ~ 0)

Expressed with dplyr::mutate, it gives:

x = x %>% mutate(
     V5 = case_when(
         V1==1 & V2!=4 ~ 1,
         V2==4 & V3!=1 ~ 2,
         TRUE ~ 0
     )
)

Please note that NA are not treated specially, as it can be misleading. The function will return NA only when no condition is matched. If you put a line with TRUE ~ ..., like I did in my example, the return value will then never be NA.

Therefore, you have to expressively tell case_when to put NA where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_. Hint: the dplyr::coalesce() function can be really useful here sometimes!

Moreover, please note that NA alone will usually not work, you have to put special NA values : NA_integer_, NA_character_ or NA_real_.

What is the "-->" operator in C/C++?

Here -- is the unary post decrement operator.

 while (x-- > 0) // x goes to 0
 {
     printf("%d ", x);
 }
  • In the beginning, the condition will evaluate as (x > 0) // 10 > 0
  • Now because the condition is true, it will go into the loop with a decremented value x-- // x = 9
  • That's why the first printed value is 9
  • And so on. In the last loop x=1, so the condition is true. As per the unary operator, the value changed to x = 0 at the time of print.
  • Now, x = 0, which evaluates the condition (x > 0 ) as false and the while loop exits.

Example: Communication between Activity and Service using Messaging

Message msg = Message.obtain(null, 2, 0, 0);
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    bundle.putString("names", names);
                    bundle.putString("captions",captions); 
                    msg.setData(bundle);

So you send it to the service. Afterward receive.

How do I apply the for-each loop to every character in a String?

You can also use a lambda in this case.

    String s = "xyz";
    IntStream.range(0, s.length()).forEach(i -> {
        char c = s.charAt(i);
    });

How to use __doPostBack()

This is how I do it

    public void B_ODOC_OnClick(Object sender, EventArgs e)
    {
        string script="<script>__doPostBack(\'fileView$ctl01$OTHDOC\',\'{\"EventArgument\":\"OpenModal\",\"EncryptedData\":null}\');</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(),"JsOtherDocuments",script);               
    }

jQuery detect if string contains something

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
   alert(str2 + " found");
}

Java - No enclosing instance of type Foo is accessible

Thing is an inner class with an automatic connection to an instance of Hello. You get a compile error because there is no instance of Hello for it to attach to. You can fix it most easily by changing it to a static nested class which has no connection:

static class Thing

Convert hex to binary

Convert hex to binary

I have ABC123EFFF.

I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).

Short answer:

The new f-strings in Python 3.6 allow you to do this using very terse syntax:

>>> f'{0xABC123EFFF:0>42b}'
'001010101111000001001000111110111111111111'

or to break that up with the semantics:

>>> number, pad, rjust, size, kind = 0xABC123EFFF, '0', '>', 42, 'b'
>>> f'{number:{pad}{rjust}{size}{kind}}'
'001010101111000001001000111110111111111111'

Long answer:

What you are actually saying is that you have a value in a hexadecimal representation, and you want to represent an equivalent value in binary.

The value of equivalence is an integer. But you may begin with a string, and to view in binary, you must end with a string.

Convert hex to binary, 42 digits and leading zeros?

We have several direct ways to accomplish this goal, without hacks using slices.

First, before we can do any binary manipulation at all, convert to int (I presume this is in a string format, not as a literal):

>>> integer = int('ABC123EFFF', 16)
>>> integer
737679765503

alternatively we could use an integer literal as expressed in hexadecimal form:

>>> integer = 0xABC123EFFF
>>> integer
737679765503

Now we need to express our integer in a binary representation.

Use the builtin function, format

Then pass to format:

>>> format(integer, '0>42b')
'001010101111000001001000111110111111111111'

This uses the formatting specification's mini-language.

To break that down, here's the grammar form of it:

[[fill]align][sign][#][0][width][,][.precision][type]

To make that into a specification for our needs, we just exclude the things we don't need:

>>> spec = '{fill}{align}{width}{type}'.format(fill='0', align='>', width=42, type='b')
>>> spec
'0>42b'

and just pass that to format

>>> bin_representation = format(integer, spec)
>>> bin_representation
'001010101111000001001000111110111111111111'
>>> print(bin_representation)
001010101111000001001000111110111111111111

String Formatting (Templating) with str.format

We can use that in a string using str.format method:

>>> 'here is the binary form: {0:{spec}}'.format(integer, spec=spec)
'here is the binary form: 001010101111000001001000111110111111111111'

Or just put the spec directly in the original string:

>>> 'here is the binary form: {0:0>42b}'.format(integer)
'here is the binary form: 001010101111000001001000111110111111111111'

String Formatting with the new f-strings

Let's demonstrate the new f-strings. They use the same mini-language formatting rules:

>>> integer = 0xABC123EFFF
>>> length = 42
>>> f'{integer:0>{length}b}'
'001010101111000001001000111110111111111111'

Now let's put this functionality into a function to encourage reusability:

def bin_format(integer, length):
    return f'{integer:0>{length}b}'

And now:

>>> bin_format(0xABC123EFFF, 42)
'001010101111000001001000111110111111111111'    

Aside

If you actually just wanted to encode the data as a string of bytes in memory or on disk, you can use the int.to_bytes method, which is only available in Python 3:

>>> help(int.to_bytes)
to_bytes(...)
    int.to_bytes(length, byteorder, *, signed=False) -> bytes
...

And since 42 bits divided by 8 bits per byte equals 6 bytes:

>>> integer.to_bytes(6, 'big')
b'\x00\xab\xc1#\xef\xff'

How to pass event as argument to an inline event handler in JavaScript?

to pass the event object:

<p id="p" onclick="doSomething(event)">

to get the clicked child element (should be used with event parameter:

function doSomething(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    console.log(target);
}

to pass the element itself (DOMElement):

<p id="p" onclick="doThing(this)">

see live example on jsFiddle.

You can specify the name of the event as above, but alternatively your handler can access the event parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.

Absolute position of an element on the screen using jQuery

See .offset() here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset() and .position() confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop() and .scrollLeft() values to account for the scrolled position.

Here's an excerpt from the doc:

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

To combine these:

var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft(); 

You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I was having the same issue implementing in Angular 9. These are the two steps I did:

  1. Change your YouTube URL from https://youtube.com/your_code to https://youtube.com/embed/your_code.

  2. And then pass the URL through DomSanitizer of Angular.

    import { Component, OnInit } from "@angular/core";
    import { DomSanitizer } from '@angular/platform-browser';
    
    @Component({
      selector: "app-help",
      templateUrl: "./help.component.html",
      styleUrls: ["./help.component.scss"],
    })
    export class HelpComponent implements OnInit {
    
      youtubeVideoLink: any = 'https://youtube.com/embed/your_code'
    
      constructor(public sanitizer: DomSanitizer) {
        this.sanitizer = sanitizer;   
      }
    
      ngOnInit(): void {}
    
      getLink(){
        return this.sanitizer.bypassSecurityTrustResourceUrl(this.youtubeVideoLink);
      }
    
    }
    
    <iframe width="420" height="315" [src]="getLink()" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
    

TypeError: 'int' object is not subscriptable

If you want to sum the digit of a number, one way to do it is using sum() + a generator expression:

sum(int(i) for i in str(155))

I modified a little your code using sum(), maybe you want to take a look at it:

birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = sum(int(i) for i in birthday[0:2])
sumd = sum(int(i) for i in birthday[3:5])
sumy = sum(int(i) for i in birthday[6:10])
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = sum(int(c) for c in str(sumall)))
print "Your lucky number is", sumln

How to call URL action in MVC with javascript function?

I'm going to give you 2 way's to call an action from the client side

first

If you just want to navigate to an action you should call just use the follow

window.location = "/Home/Index/" + youid

Notes: that you action need to handle a get type called

Second

If you need to render a View you could make the called by ajax

//this if you want get the html by get
public ActionResult Foo()
{
    return View(); //this return the render html   
}

And the client called like this "Assuming that you're using jquery"

$.get('your controller path', parameters to the controler , function callback)

or

$.ajax({
    type: "GET",
    url: "your controller path",
    data: parameters to the controler
    dataType: "html",
    success: your function
});

or

$('your selector').load('your controller path') 

Update

In your ajax called make this change to pass the data to the action

function onDropDownChange(e) {
var url = '/Home/Index' 
$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            //put your code here
        }
    });
}

UPDATE 2

You cannot do this in your callback 'windows.location ' if you want it's go render a view, you need to put a div in your view and do something like this

in the view where you are that have the combo in some place

<div id="theNewView"> </div> <---you're going to load the other view here

in the javascript client

$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

With this i think that you solve your problem

How to predict input image using trained model in Keras?

You can use model.predict() to predict the class of a single image as follows [doc]:

# load_model_sample.py
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os


def load_image(img_path, show=False):

    img = image.load_img(img_path, target_size=(150, 150))
    img_tensor = image.img_to_array(img)                    # (height, width, channels)
    img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
    img_tensor /= 255.                                      # imshow expects values in the range [0, 1]

    if show:
        plt.imshow(img_tensor[0])                           
        plt.axis('off')
        plt.show()

    return img_tensor


if __name__ == "__main__":

    # load model
    model = load_model("model_aug.h5")

    # image path
    img_path = '/media/data/dogscats/test1/3867.jpg'    # dog
    #img_path = '/media/data/dogscats/test1/19.jpg'      # cat

    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)

In this example, a image is loaded as a numpy array with shape (1, height, width, channels). Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).

Not able to change TextField Border Color

That is not changing due to the default theme set to the screen.

So just change them for the widget you are drawing by wrapping your TextField with new ThemeData()

child: new Theme(
          data: new ThemeData(
            primaryColor: Colors.redAccent,
            primaryColorDark: Colors.red,
          ),
          child: new TextField(
            decoration: new InputDecoration(
                border: new OutlineInputBorder(
                    borderSide: new BorderSide(color: Colors.teal)),
                hintText: 'Tell us about yourself',
                helperText: 'Keep it short, this is just a demo.',
                labelText: 'Life story',
                prefixIcon: const Icon(
                  Icons.person,
                  color: Colors.green,
                ),
                prefixText: ' ',
                suffixText: 'USD',
                suffixStyle: const TextStyle(color: Colors.green)),
          ),
        ));

enter image description here

Favicon dimensions?

2020 standards thanks to faviconit

I use faviconit.com for the best browser and device support possible. You upload an image and this site gives you the code, the converted images and a browserconfig file.


We could simply upload a favicon manually to our website of 16x16 and it will probably show up in almost any browser.

But when you will mark it as one of your favorites on your smartphone or tablet, we will need larger images (60x60 to 144x144).

And lets say one of our users creates a shortcut on their desktop. In that case a 196x196 looks better!


Example code of what faviconit would give you, next to all the converted images:

<!-- place this in your <head></head> -->
<link rel="shortcut icon" href="/favicon.ico">
<link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico">
<link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png">
<link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png">
<link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png">
<link rel="apple-touch-icon" href="/favicon-57.png">
<link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png">
<link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png">
<link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png">
<link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png">
<link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png">
<link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png">
<link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png">

Since Windows 8

But that is not all. Since windows 8 we are able to create shortcuts to websites with tiles!

<!-- place this in your <head></head> -->
<meta name="msapplication-TileColor" content="#FFFFFF">
<meta name="msapplication-TileImage" content="/favicon-144.png">
<meta name="msapplication-config" content="/browserconfig.xml">

Browserconfig.xml

Upload a file named browserconfig.xml (to enable the tiles in windows >8)

<browserconfig>
    <msapplication>
        <tile>
            <square70x70logo src="/favicon-70.png"/>
            <square150x150logo src="/favicon-150.png"/>
            <square310x310logo src="/favicon-310.png"/>
            <TileColor>#FFFFFF</TileColor>
        </tile>
    </msapplication>
</browserconfig>

How to create a date object from string in javascript

First extract the string like this

var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

Then,

var d = new Date( dateString[3], dateString[2]-1, dateString[1] );

How can I set the Secure flag on an ASP.NET Session Cookie?

secure - This attribute tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS. This will help protect the cookie from being passed over unencrypted requests. If the application can be accessed over both HTTP and HTTPS, then there is the potential that the cookie can be sent in clear text.