Programs & Examples On #Adornerlayer

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

How to remove a newline from a string in Bash

Under , there are some bashisms:

The tr command could be replaced by // bashism:

COMMAND=$'\nREBOOT\r   \n'
echo "|${COMMAND}|"
|
   OOT
|

echo "|${COMMAND//[$'\t\r\n']}|"
|REBOOT   |

echo "|${COMMAND//[$'\t\r\n ']}|"
|REBOOT|

See Parameter Expansion and QUOTING in bash's man page:

man -Pless\ +/\/pattern bash
man -Pless\ +/\\\'string\\\' bash

man -Pless\ +/^\\\ *Parameter\\\ Exp bash
man -Pless\ +/^\\\ *QUOTING bash

Further...

As asked by @AlexJordan, this will suppress all specified characters. So what if $COMMAND do contain spaces...

COMMAND=$'         \n        RE BOOT      \r           \n'
echo "|$COMMAND|"
|
           BOOT      
|

CLEANED=${COMMAND//[$'\t\r\n']}
echo "|$CLEANED|"
|                 RE BOOT                 |

shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}

CLEANED=${CLEANED%%*( )}
echo "|$CLEANED|"
|                 RE BOOT|

CLEANED=${CLEANED##*( )}
echo "|$CLEANED|"
|RE BOOT|

Shortly:

COMMAND=$'         \n        RE BOOT      \r           \n'
CLEANED=${COMMAND//[$'\t\r\n']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"
|RE BOOT|

Note: have extglob option to be enabled (shopt -s extglob) in order to use *(...) syntax.

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

NLTK and Stopwords Fail #lookuperror

If you want to manually install NLTK Corpus.

1) Go to http://www.nltk.org/nltk_data/ and download your desired NLTK Corpus file.

2) Now in a Python shell check the value of nltk.data.path

3) Choose one of the path that exists on your machine, and unzip the data files into the corpora sub directory inside.

4) Now you can import the data from nltk.corpos import stopwords

Reference: https://medium.com/@satorulogic/how-to-manually-download-a-nltk-corpus-f01569861da9

How do you Change a Package's Log Level using Log4j?

set the system property log4j.debug=true. Then you can determine where your configuration is running amuck.

Javascript window.open pass values using POST

Even though this question was long time ago, thanks all for the inputs that helping me out a similar problem. I also made a bit modification based on the others' answers here and making multiple inputs/valuables into a Single Object (json); and hope this helps someone.

js:

//example: params={id:'123',name:'foo'};

mapInput.name = "data";
mapInput.value = JSON.stringify(params); 

php:

$data=json_decode($_POST['data']); 

echo $data->id;
echo $data->name;

How do I return to an older version of our code in Subversion?

I think this is most suited:

Do the merging backward, for instance, if the committed code contains the revision from rev 5612 to 5616, just merge it backwards. It works in my end.

For instance:

svn merge -r 5616:5612 https://<your_svn_repository>/

It would contain a merged code back to former revision, then you could commit it.

How do I copy directories recursively with gulp?

If you want to copy the entire contents of a folder recursively into another folder, you can execute the following windows command from gulp:

xcopy /path/to/srcfolder /path/to/destfolder /s /e /y

The /y option at the end is to suppress the overwrite confirmation message.

In Linux, you can execute the following command from gulp:

cp -R /path/to/srcfolder /path/to/destfolder

you can use gulp-exec or gulp-run plugin to execute system commands from gulp.

Related Links:

  1. xcopy usage

  2. gulp-exec and gulp-run

How can I get the application's path in a .NET console application?

Another solution is using relative paths pointing to the current path:

Path.GetFullPath(".")

Chrome desktop notification example

I like: http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examples but it uses old variables, so the demo doesn't work anymore. webkitNotifications is now Notification.

Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

hash function for string

Wikipedia shows a nice string hash function called Jenkins One At A Time Hash. It also quotes improved versions of this hash.

uint32_t jenkins_one_at_a_time_hash(char *key, size_t len)
{
    uint32_t hash, i;
    for(hash = i = 0; i < len; ++i)
    {
        hash += key[i];
        hash += (hash << 10);
        hash ^= (hash >> 6);
    }
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    return hash;
}

How to check whether the user uploaded a file in PHP?

You should use $_FILES[$form_name]['error']. It returns UPLOAD_ERR_NO_FILE if no file was uploaded. Full list: PHP: Error Messages Explained

function isUploadOkay($form_name, &$error_message) {
    if (!isset($_FILES[$form_name])) {
        $error_message = "No file upload with name '$form_name' in form.";
        return false;
    }
    $error = $_FILES[$form_name]['error'];

    // List at: http://php.net/manual/en/features.file-upload.errors.php
    if ($error != UPLOAD_ERR_OK) {
        switch ($error) {
            case UPLOAD_ERR_INI_SIZE:
                $error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
                break;

            case UPLOAD_ERR_FORM_SIZE:
                $error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
                break;

            case UPLOAD_ERR_PARTIAL:
                $error_message = 'The uploaded file was only partially uploaded.';
                break;

            case UPLOAD_ERR_NO_FILE:
                $error_message = 'No file was uploaded.';
                break;

            case UPLOAD_ERR_NO_TMP_DIR:
                $error_message = 'Missing a temporary folder.';
                break;

            case UPLOAD_ERR_CANT_WRITE:
                $error_message = 'Failed to write file to disk.';
                break;

            case UPLOAD_ERR_EXTENSION:
                $error_message = 'A PHP extension interrupted the upload.';
                break;

            default:
                $error_message = 'Unknown error';
            break;
        }
        return false;
    }

    $error_message = null;
    return true;
}

How to rename array keys in PHP?

Very simple approach to replace keys in a multidimensional array, and maybe even a bit dangerous, but should work fine if you have some kind of control over the source array:

$array = [ 'oldkey' => [ 'oldkey' => 'wow'] ];
$new_array = json_decode(str_replace('"oldkey":', '"newkey":', json_encode($array)));
print_r($new_array); // [ 'newkey' => [ 'newkey' => 'wow'] ]

UIButton Image + Text IOS

Make UIImageView and UILabel, and set image and text to both of this....then Place a custom button over imageView and Label....

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search.png"]];
    imageView.frame = CGRectMake(x, y, imageView.frame.size.width, imageView.frame.size.height);
    [self.view addSubview:imageView];

UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y,a,b)];
yourLabel.text = @"raj";
[self.view addSubview:yourLabel];

UIButton * yourBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[yourBtn setFrame:CGRectMake(x, y,c,d)];
[yourBtn addTarget:self action:@selector(@"Your Action") forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourBtn];  

react button onClick redirect page

A simple click handler on the button, and setting window.location.hash will do the trick, assuming that your destination is also within the app.

You can listen to the hashchange event on window, parse the URL you get, call this.setState(), and you have your own simple router, no library needed.

class LoginLayout extends Component {
    constuctor() {
      this.handlePageChange = this.handlePageChange.bind(this);
      this.handleRouteChange = this.handleRouteChange.bind(this);
      this.state = { page_number: 0 }
    }

  handlePageChange() {
    window.location.hash = "#/my/target/url";
  }

  handleRouteChange(event) {
    const destination = event.newURL;
    // check the URL string, or whatever other condition, to determine
    // how to set internal state.
    if (some_condition) {
      this.setState({ page_number: 1 });
    }
  }

  componentDidMount() {
    window.addEventListener('hashchange', this.handleRouteChange, false);
  }

  render() {
    // @TODO: check this.state.page_number and render the correct page.
    return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
                <Row>
                  <Col xs="6">                      
                    <Button 
                       color="primary"
                       className="px-4"
                       onClick={this.handlePageChange}
                    >
                        Login
                     </Button>
                  </Col>
                  <Col xs="6" className="text-right">
                    <Button color="link" className="px-0">Forgot password </Button>
                  </Col>
                </Row>
           ...
        </Container>
      </div>
    );
  }
}

Random number between 0 and 1 in python

you can use use numpy.random module, you can get array of random number in shape of your choice you want

>>> import numpy as np
>>> np.random.random(1)[0]
0.17425892129128229
>>> np.random.random((3,2))
array([[ 0.7978787 ,  0.9784473 ],
       [ 0.49214277,  0.06749958],
       [ 0.12944254,  0.80929816]])
>>> np.random.random((3,1))
array([[ 0.86725993],
       [ 0.36869585],
       [ 0.2601249 ]])
>>> np.random.random((4,1))
array([[ 0.87161403],
       [ 0.41976921],
       [ 0.35714702],
       [ 0.31166808]])
>>> np.random.random_sample()
0.47108547995356098

How do I set the proxy to be used by the JVM

As is pointed out in other answers, if you need to use Authenticated proxies, there's no reliable way to do this purely using command-line variables - which is annoying if you're using someone else's application and don't want to mess with the source code.

Will Iverson makes the helpful suggestion over at Using HttpProxy to connect to a host with preemtive authentication to use a Proxy-management tool such as Proxifier ( http://www.proxifier.com/ for Mac OS X and Windows) to handle this.

For example with Proxifier you can set it up to only intercept java commands to be managed and redirected through its (authenticated) proxy. You're going to want to set the proxyHost and proxyPort values to blank in this case though, e.g. pass in -Dhttp.proxyHost= -Dhttp.proxyPort= to your java commands.

getch and arrow codes

Actually, to read arrow keys one need to read its scan code. Following are the scan code generated by arrow keys press (not key release)

When num Lock is off

  • Left E0 4B
  • Right E0 4D
  • Up E0 48
  • Down E0 50

When Num Lock is on these keys get preceded with E0 2A

  • Byte E0 is -32
  • Byte 48 is 72 UP
  • Byte 50 is 80 DOWN

    user_var=getch();
    if(user_var == -32)
    {
        user_var=getch();
        switch(user_var)
        {
        case 72:
            cur_sel--;
            if (cur_sel==0)
                cur_sel=4;
            break;
        case 80:
            cur_sel++;
            if(cur_sel==5)
                cur_sel=1;
            break;
    
        }
    }
    

In the above code I have assumed programmer wants to move 4 lines only.

How can I convert a date to GMT?

After searching for an hour or two ,I've found a simple solution below.

const date = new Date(`${date from client} GMT`);

inside double ticks, there is a date from client side plust GMT.

I'm first time commenting, constructive criticism will be welcomed.

Black transparent overlay on image hover with only CSS?

You were close. This will work:

.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }

You needed to put the :hover on image, and make the .overlay cover the whole image by adding right:0; and bottom:0.

jsfiddle: http://jsfiddle.net/Zf5am/569/

CSS: Hover one element, effect for multiple elements?

You'd need to use JavaScript to accomplish this, I think.

jQuery:

$(function(){
   $("#innerContainer").hover(
        function(){
            $("#innerContainer").css('border-color','#FFF');
            $("#outerContainer").css('border-color','#FFF');
        },
        function(){
            $("#innerContainer").css('border-color','#000');
            $("#outerContainer").css('border-color','#000');
        }
    );
});

Adjust the values and element id's accordingly :)

How I could add dir to $PATH in Makefile?

By design make parser executes lines in a separate shell invocations, that's why changing variable (e.g. PATH) in one line, the change may not be applied for the next lines (see this post).

One way to workaround this problem, is to convert multiple commands into a single line (separated by ;), or use One Shell special target (.ONESHELL, as of GNU Make 3.82).

Alternatively you can provide PATH variable at the time when shell is invoked. For example:

PATH  := $(PATH):$(PWD)/bin:/my/other/path
SHELL := env PATH=$(PATH) /bin/bash

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

In my case,I was getting error while refreshing gradle ('View'->Tool Windows->Gradle) tab and hit "refresh" and getting this error no such property gradleversion for class jetgradleplugin.

Had to install latest intellij compatible with gradle 5+

Disable output buffering

# reopen stdout file descriptor with write mode
# and 0 as the buffer size (unbuffered)
import io, os, sys
try:
    # Python 3, open as binary, then wrap in a TextIOWrapper with write-through.
    sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)
    # If flushing on newlines is sufficient, as of 3.7 you can instead just call:
    # sys.stdout.reconfigure(line_buffering=True)
except TypeError:
    # Python 2
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Credits: "Sebastian", somewhere on the Python mailing list.

Working Copy Locked

You can fix it with only one step.

Step 1 : Open terminal and go to your project then fire command "svn cleanup" then "svn update"

How to pass data between fragments

I'm working on a similar project and I guess my code may help in the above situation

Here is the overview of what i'm doing

My project Has two fragments Called "FragmentA" and "FragmentB"

-FragmentA Contains one list View,when you click an item in FragmentA It's INDEX is passed to FragmentB using Communicator interface

  • The design pattern is totally based on the concept of java interfaces that says "interface reference variables can refer to a subclass object"
  • Let MainActivity implement the interface provided by fragmentA(otherwise we can't make interface reference variable to point to MainActivity)
  • In the below code communicator object is made to refer to MainActivity's object by using "setCommunicator(Communicatot c)" method present in fragmentA.
  • I'm triggering respond() method of interface from FrgamentA using the MainActivity's reference.

    Interface communcator is defined inside fragmentA, this is to provide least access previlage to communicator interface.

below is my complete working code

FragmentA.java

public class FragmentA extends Fragment implements OnItemClickListener {

ListView list;
Communicator communicater;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragmenta, container,false);
}

public void setCommunicator(Communicator c){
    communicater=c;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    communicater=(Communicator) getActivity();
    list = (ListView) getActivity().findViewById(R.id.lvModularListView);
    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.items, android.R.layout.simple_list_item_1);
    list.setAdapter(adapter);
    list.setOnItemClickListener(this);

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
communicater.respond(index);

}

public interface Communicator{
    public void respond(int index);
}

}

fragmentB.java

public class FragmentA extends Fragment implements OnItemClickListener {

ListView list;
Communicator communicater;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragmenta, container,false);
}

public void setCommunicator(Communicator c){
    communicater=c;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    communicater=(Communicator) getActivity();
    list = (ListView) getActivity().findViewById(R.id.lvModularListView);
    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.items, android.R.layout.simple_list_item_1);
    list.setAdapter(adapter);
    list.setOnItemClickListener(this);

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
communicater.respond(index);

}

public interface Communicator{
    public void respond(int index);
}

}

MainActivity.java

public class MainActivity extends Activity implements FragmentA.Communicator {
FragmentManager manager=getFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentA fragA=(FragmentA) manager.findFragmentById(R.id.fragmenta);
    fragA.setCommunicator(this);


}

@Override
public void respond(int i) {
    // TODO Auto-generated method stub

FragmentB FragB=(FragmentB) manager.findFragmentById(R.id.fragmentb);
FragB.changetext(i);
}



}

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX is only supported by IE - the other browsers use a plugin architecture called NPAPI. However, there's a cross-browser plugin framework called Firebreath that you might find useful.

How to use hex color values

RGBA Version Swift 3/4

I like @Luca's answer as i think it's the most elegant.

However I don't want my colours specified in ARGB. I'd rather RGBA + also i needed to hack in the case of dealing with strings that specify 1 character for each of the channels "#FFFA".

This version also adds error throwing + strips the '#' character if it's included in the string. Here is my modified form for Swift.

public enum ColourParsingError: Error
{
    
    case invalidInput(String)
}
extension UIColor {
    public convenience init(hexString: String) throws
    {
        let hexString = hexString.replacingOccurrences(of: "#", with: "")
        let hex = hexString.trimmingCharacters(in:NSCharacterSet.alphanumerics.inverted)
        var int = UInt32()
        Scanner(string: hex).scanHexInt32(&int)
        let a, r, g, b: UInt32
        switch hex.count 
        {
        case 3: // RGB (12-bit)
            (r, g, b,a) = ((int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17,255)
        //iCSS specification in the form of #F0FA
        case 4: // RGB (24-bit)
            (r, g, b,a) = ((int >> 12) * 17, (int >> 8 & 0xF) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (r, g, b, a) = (int >> 16, int >> 8 & 0xFF, int & 0xFF,255)
        case 8: // ARGB (32-bit)
            (r, g, b, a) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            throw ColourParsingError.invalidInput("String is not a valid hex colour string: \(hexString)")
        }
        self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
    }
}

How to check the multiple permission at single request in Android M?

I faced the same problem and below is the workaround I came up with:

public boolean checkForPermission(final String[] permissions, final int permRequestCode, int msgResourceId) {
        final List<String> permissionsNeeded = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            final String perm = permissions[i];
            if (ContextCompat.checkSelfPermission(getActivity(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(permissions[i])) {
                    final AlertDialog dialog = AlertDialog.newInstance( getResources().getString(R.string.permission_title), getResources().getString(msgResourceId) );
                    dialog.setPositiveButton("OK", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // add the request.
                            permissionsNeeded.add(perm);
                            dialog.dismiss();
                        }
                    });
                    dialog.show( getActivity().getSupportFragmentManager(), "HCFAlertDialog" );
                } else {
                    // add the request.
                    permissionsNeeded.add(perm);
                }
            }
        }

        if (permissionsNeeded.size() > 0) {
            // go ahead and request permissions
            requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
            return false;
        } else {
            // no permission need to be asked so all good...we have them all.
            return true;
        }
    }

And you call the above method like this:

if ( checkForPermission( new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, 
Manifest.permission.CAMERA}, REQUEST_PERMISSION_EXTERNAL_STORAGE_RESULT, R.string.permission_image) ) {
                        // DO YOUR STUFF

                    }

Why would you use Expression<Func<T>> rather than Func<T>?

LINQ is the canonical example (for example, talking to a database), but in truth, any time you care more about expressing what to do, rather than actually doing it. For example, I use this approach in the RPC stack of protobuf-net (to avoid code-generation etc) - so you call a method with:

string result = client.Invoke(svc => svc.SomeMethod(arg1, arg2, ...));

This deconstructs the expression tree to resolve SomeMethod (and the value of each argument), performs the RPC call, updates any ref/out args, and returns the result from the remote call. This is only possible via the expression tree. I cover this more here.

Another example is when you are building the expression trees manually for the purpose of compiling to a lambda, as done by the generic operators code.

How to delete a workspace in Perforce (using p4v)?

From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.

To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.

In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

If you've tried to change target to a previous GooglePlayServices or AppCompatv7 version and it doesn't work, check if you have any project-libraries dependency, this project will be targeting the latest version of any of these libraries. It happened to me with the Google Maps Utils Library project:

replace:

compile 'com.google.android.gms:play-services:+'

to

compile 'com.google.android.gms:play-services:8.3.0'

Then you can continue full targeting API 22

If it still doesn't compile, sometimes is useful to set compileSdkVersion API to 23 and targetSdkVersion to 22.

raw_input function in Python

raw_input is a form of input that takes the argument in the form of a string whereas the input function takes the value depending upon your input. Say, a=input(5) returns a as an integer with value 5 whereas a=raw_input(5) returns a as a string of "5"

Open existing file, append a single line

Choice one! But the first is very simple. The last maybe util for file manipulation:

//Method 1 (I like this)
File.AppendAllLines(
    "FileAppendAllLines.txt", 
    new string[] { "line1", "line2", "line3" });

//Method 2
File.AppendAllText(
    "FileAppendAllText.txt",
    "line1" + Environment.NewLine +
    "line2" + Environment.NewLine +
    "line3" + Environment.NewLine);

//Method 3
using (StreamWriter stream = File.AppendText("FileAppendText.txt"))
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}

//Method 4
using (StreamWriter stream = new StreamWriter("StreamWriter.txt", true))
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}

//Method 5
using (StreamWriter stream = new FileInfo("FileInfo.txt").AppendText())
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}

How to write subquery inside the OUTER JOIN Statement

You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.

SELECT
       cs.CUSID
       ,dp.DEPID
FROM
    CUSTMR cs
        LEFT OUTER JOIN (
            SELECT
                    DEPID
                    ,DEPNAME
                FROM
                    DEPRMNT 
                WHERE
                    dp.DEPADDRESS = 'TOKYO'
        ) ss
            ON (
                ss.DEPID = cs.CUSID
                AND ss.DEPNAME = cs.CUSTNAME
            )
WHERE
    cs.CUSID != '' 

Is there a css cross-browser value for "width: -moz-fit-content;"?

I use these:

.right {display:table; margin:-18px 0 0 auto;}
.center {display:table; margin:-18px auto 0 auto;}

How to overcome TypeError: unhashable type: 'list'

Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.

Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.

Internally, hash() method calls __hash__() method of an object which are set by default for any object.

Converting a nested list to a set

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

Explicitly hashing a nested list

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

The solution to avoid this error is to restructure the list to have nested tuples instead of lists.

What is the purpose of the "final" keyword in C++11 for functions?

The final keyword allows you to declare a virtual method, override it N times, and then mandate that 'this can no longer be overridden'. It would be useful in restricting use of your derived class, so that you can say "I know my super class lets you override this, but if you want to derive from me, you can't!".

struct Foo
{
   virtual void DoStuff();
}

struct Bar : public Foo
{
   void DoStuff() final;
}

struct Babar : public Bar
{
   void DoStuff(); // error!
}

As other posters pointed out, it cannot be applied to non-virtual functions.

One purpose of the final keyword is to prevent accidental overriding of a method. In my example, DoStuff() may have been a helper function that the derived class simply needs to rename to get correct behavior. Without final, the error would not be discovered until testing.

Javascript / Chrome - How to copy an object from the webkit inspector as code

Right click on data which you want to store

  • Firstly, Right click on data which you want to store -> select "Store as global variable" And the new temp variable appear like bellow: (temp3 variable): New temp variable appear in console
  • Second use command copy(temp_variable_name) like picture: enter image description here After that, you can paste data to anywhere you want. hope useful/

Authentication plugin 'caching_sha2_password' is not supported

Using MySql 8 I got the same error when connecting my code to the DB, using the pip install mysql-connector-python did solve this error.

Add st, nd, rd and th (ordinal) suffix to a number

From Shopify

_x000D_
_x000D_
function getNumberWithOrdinal(n) {_x000D_
  var s = ["th", "st", "nd", "rd"],_x000D_
      v = n % 100;_x000D_
  return n + (s[(v - 20) % 10] || s[v] || s[0]);_x000D_
}_x000D_
_x000D_
[-4,-1,0,1,2,3,4,10,11,12,13,14,20,21,22,100,101,111].forEach(_x000D_
  n => console.log(n + ' -> ' + getNumberWithOrdinal(n))_x000D_
);
_x000D_
_x000D_
_x000D_

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

Decompile .smali files on an APK

There is a new cross plateform (java) and open source tool, that enable you to do that, just checkout https://bytecodeviewer.com

enter image description here

=========

EDIT: As of April 2017, there is a new open source tool developed by google, that is meant to do just what we have been looking for => https://github.com/google/android-classyshark

How to check which locks are held on a table

To add to the other responses, sp_lock can also be used to dump full lock information on all running processes. The output can be overwhelming, but if you want to know exactly what is locked, it's a valuable one to run. I usually use it along with sp_who2 to quickly zero in on locking problems.

There are multiple different versions of "friendlier" sp_lock procedures available online, depending on the version of SQL Server in question.

In your case, for SQL Server 2005, sp_lock is still available, but deprecated, so it's now recommended to use the sys.dm_tran_locks view for this kind of thing. You can find an example of how to "roll your own" sp_lock function here.

Convert .pfx to .cer

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

Get list of Excel files in a folder using VBA

If all you want is the file name without file extension

Dim fileNamesCol As New Collection
Dim MyFile As Variant  'Strings and primitive data types aren't allowed with collection

filePath = "c:\file directory" + "\"
MyFile = Dir$(filePath & "*.xlsx")
Do While MyFile <> ""
    fileNamesCol.Add (Replace(MyFile, ".xlsx", ""))
    MyFile = Dir$
Loop

To output to excel worksheet

Dim myWs As Worksheet: Set myWs = Sheets("SheetNameToDisplayTo")
Dim ic As Integer: ic = 1

For Each MyFile In fileNamesCol
    myWs.Range("A" & ic).Value = fileNamesCol(ic)
    ic = ic + 1
Next MyFile

Primarily based on the technique detailed here: https://wordmvp.com/FAQs/MacrosVBA/ReadFilesIntoArray.htm

assigning column names to a pandas series

You can also use the .to_frame() method.

If it is a Series, I assume 'Gene' is already the index, and will remain the index after converting it to a DataFrame. The name argument of .to_frame() will name the column.

x = x.to_frame('count')

If you want them both as columns, you can reset the index:

x = x.to_frame('count').reset_index()

Maven: How to run a .java file from command line passing arguments

Adding a shell script e.g. run.sh makes it much more easier:

#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"

Then you are able to execute:

./run.sh arg1 arg2 arg3

Where is the visual studio HTML Designer?

Go to [Tools, Options], section "Web Forms Designer" and enable the option "Enable Web Forms Designer". That should give you the Design and Split option again.

access denied for user @ 'localhost' to database ''

You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).

Force IE8 Into IE7 Compatiblity Mode

There is an HTTP header you can set that will force IE8 to use IE7-compatibility mode.

How can I set the color of a selected row in DataGrid

The above solution left blue border around each cell in my case.

This is the solution that worked for me. It is very simple, just add this to your DataGrid. You can change it from a SolidColorBrush to any other brush such as linear gradient.

<DataGrid.Resources>
  <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
                   Color="#FF0000"/>
</DataGrid.Resources>

Validate date in dd/mm/yyyy format using JQuery Validate

I encountered a similar problem in my project. After struggling a lot, I found this solution:

if ($.datepicker.parseDate("dd/mm/yy","17/06/2015") > $.datepicker.parseDate("dd/mm/yy","20/06/2015"))
    // do something

You DO NOT NEED plugins like jQuery Validate or Moment.js for this issue. Hope this solution helps.

Visual Studio 64 bit?

Is there any 64 bit Visual Studio at all?

Yes literally there is one called "Visual Studio" and is 64bit, but well,, on Mac not on Windows

Why not?

Decision making is electro-chemical reaction made in our brain and that have an activation point (Nerdest answer I can come up with, but follow). Same situation happened in history: Windows 64!...

So in order to answer this fully I want you to remember old days. Imagine reasons for "why not we see 64bit Windows" are there at the time. I think at the time for Windows64 they had exact same reasons others have enlisted here about "reasons why not 64bit VS on windows" were on "reasons why not 64bit Windows" too. Then why they did start development for Windows 64bit? Simple! If they didn't succeed in making 64bit Windows I bet M$ would have been a history nowadays. If same reasons forcing M$ making 64bit Windows starts to appear on need for 64Bit VS then I bet we will see 64bit VS, even though very same reasons everyone else here enlisted will stay same! In time the limitations of 32bit may hit VS as well, so most likely something like below start to happen:

  • Visual Studio will drop 32bit support and become 64bit,
  • Visual Studio Code will take it's place instead,
  • Visual Studio will have similar functionality like WOW64 for old extensions which is I believe unlikely to happen.

I put my bets on Visual Studio Code taking the place in time; I guess bifurcation point for it will be some CPU manufacturer X starts to compete x86_64 architecture taking its place on mainstream market for laptop and/or workstation,

Get the year from specified date php

You can achieve your goal by using php date() & explode() functions:

$date = date("2068-06-15");

$date_arr = explode("-", $date);

$yr = $date_arr[0];

echo $yr;

That is it. Happy coding :)

How to change Hash values?

Since ruby 2.4.0 you can use native Hash#transform_values method:

hash = {"a" => "b", "c" => "d"}
new_hash = hash.transform_values(&:upcase)
# => {"a" => "B", "c" => "D"}

There is also destructive Hash#transform_values! version.

How do I change the default location for Git Bash on Windows?

the only way that worked for me on windows 10:

  1. right-click gitbash shortcut -> proporties
  2. change target as: "C:\Program Files\Git\git-bash.exe" --cd=C:\Users\test\Desktop\

This will always open desktop path

Ruby function to remove all white spaces?

Related answer:

"   clean up my edges    ".strip

returns

"clean up my edges"

Server.Transfer Vs. Response.Redirect

There are many differences as specified above. Apart from above all, there is one more difference. Response.Redirect() can be used to redirect user to any page which is not part of the application but Server.Transfer() can only be used to redirect user within the application.

//This will work.
Response.Redirect("http://www.google.com");

//This will not work.
Server.Transfer("http://www.google.com");

How to generate an MD5 file hash in JavaScript?

Simplified and minified version (about 3.5k) of this nice implementation http://pajhome.org.uk/crypt/md5/md5.html

will be (stripped utf-8 conversion, upper/lowercase change the array). This is the smallest size I could get, still perfect for embedded web servers.

function md5(d){return rstr2hex(binl2rstr(binl_md5(rstr2binl(d),8*d.length)))}function rstr2hex(d){for(var _,m="0123456789ABCDEF",f="",r=0;r<d.length;r++)_=d.charCodeAt(r),f+=m.charAt(_>>>4&15)+m.charAt(15&_);return f}function rstr2binl(d){for(var _=Array(d.length>>2),m=0;m<_.length;m++)_[m]=0;for(m=0;m<8*d.length;m+=8)_[m>>5]|=(255&d.charCodeAt(m/8))<<m%32;return _}function binl2rstr(d){for(var _="",m=0;m<32*d.length;m+=8)_+=String.fromCharCode(d[m>>5]>>>m%32&255);return _}function binl_md5(d,_){d[_>>5]|=128<<_%32,d[14+(_+64>>>9<<4)]=_;for(var m=1732584193,f=-271733879,r=-1732584194,i=271733878,n=0;n<d.length;n+=16){var h=m,t=f,g=r,e=i;f=md5_ii(f=md5_ii(f=md5_ii(f=md5_ii(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_ff(f=md5_ff(f=md5_ff(f=md5_ff(f,r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+0],7,-680876936),f,r,d[n+1],12,-389564586),m,f,d[n+2],17,606105819),i,m,d[n+3],22,-1044525330),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+4],7,-176418897),f,r,d[n+5],12,1200080426),m,f,d[n+6],17,-1473231341),i,m,d[n+7],22,-45705983),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+8],7,1770035416),f,r,d[n+9],12,-1958414417),m,f,d[n+10],17,-42063),i,m,d[n+11],22,-1990404162),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+12],7,1804603682),f,r,d[n+13],12,-40341101),m,f,d[n+14],17,-1502002290),i,m,d[n+15],22,1236535329),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+1],5,-165796510),f,r,d[n+6],9,-1069501632),m,f,d[n+11],14,643717713),i,m,d[n+0],20,-373897302),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+5],5,-701558691),f,r,d[n+10],9,38016083),m,f,d[n+15],14,-660478335),i,m,d[n+4],20,-405537848),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+9],5,568446438),f,r,d[n+14],9,-1019803690),m,f,d[n+3],14,-187363961),i,m,d[n+8],20,1163531501),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+13],5,-1444681467),f,r,d[n+2],9,-51403784),m,f,d[n+7],14,1735328473),i,m,d[n+12],20,-1926607734),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+5],4,-378558),f,r,d[n+8],11,-2022574463),m,f,d[n+11],16,1839030562),i,m,d[n+14],23,-35309556),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+1],4,-1530992060),f,r,d[n+4],11,1272893353),m,f,d[n+7],16,-155497632),i,m,d[n+10],23,-1094730640),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+13],4,681279174),f,r,d[n+0],11,-358537222),m,f,d[n+3],16,-722521979),i,m,d[n+6],23,76029189),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+9],4,-640364487),f,r,d[n+12],11,-421815835),m,f,d[n+15],16,530742520),i,m,d[n+2],23,-995338651),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+0],6,-198630844),f,r,d[n+7],10,1126891415),m,f,d[n+14],15,-1416354905),i,m,d[n+5],21,-57434055),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+12],6,1700485571),f,r,d[n+3],10,-1894986606),m,f,d[n+10],15,-1051523),i,m,d[n+1],21,-2054922799),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+8],6,1873313359),f,r,d[n+15],10,-30611744),m,f,d[n+6],15,-1560198380),i,m,d[n+13],21,1309151649),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+4],6,-145523070),f,r,d[n+11],10,-1120210379),m,f,d[n+2],15,718787259),i,m,d[n+9],21,-343485551),m=safe_add(m,h),f=safe_add(f,t),r=safe_add(r,g),i=safe_add(i,e)}return Array(m,f,r,i)}function md5_cmn(d,_,m,f,r,i){return safe_add(bit_rol(safe_add(safe_add(_,d),safe_add(f,i)),r),m)}function md5_ff(d,_,m,f,r,i,n){return md5_cmn(_&m|~_&f,d,_,r,i,n)}function md5_gg(d,_,m,f,r,i,n){return md5_cmn(_&f|m&~f,d,_,r,i,n)}function md5_hh(d,_,m,f,r,i,n){return md5_cmn(_^m^f,d,_,r,i,n)}function md5_ii(d,_,m,f,r,i,n){return md5_cmn(m^(_|~f),d,_,r,i,n)}function safe_add(d,_){var m=(65535&d)+(65535&_);return(d>>16)+(_>>16)+(m>>16)<<16|65535&m}function bit_rol(d,_){return d<<_|d>>>32-_}

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

What is the difference between aggregation, composition and dependency?

Containment :- Here to access inner object we have to use outer object. We can reuse the contained object. Aggregation :- Here we can access inner object again and again without using outer object.

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.

To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.

Example for manual parsing:

var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));

Example using date.js:

var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");

HTML table with 100% width, with vertical scroll inside tbody

In following solution, table occupies 100% of the parent container, no absolute sizes required. It's pure CSS, flex layout is used.

Here is how it looks: enter image description here

Possible disadvantages:

  • vertical scrollbar is always visible, regardless of whether it's required;
  • table layout is fixed - columns do not resize according to the content width (you still can set whatever column width you want explicitly);
  • there is one absolute size - the width of the scrollbar, which is about 0.9em for the browsers I was able to check.

HTML (shortened):

<div class="table-container">
    <table>
        <thead>
            <tr>
                <th>head1</th>
                <th>head2</th>
                <th>head3</th>
                <th>head4</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>content1</td>
                <td>content2</td>
                <td>content3</td>
                <td>content4</td>
            </tr>
            <tr>
                <td>content1</td>
                <td>content2</td>
                <td>content3</td>
                <td>content4</td>
            </tr>
            ...
        </tbody>
    </table>
</div>

CSS, with some decorations omitted for clarity:

.table-container {
    height: 10em;
}
table {
    display: flex;
    flex-flow: column;
    height: 100%;
    width: 100%;
}
table thead {
    /* head takes the height it requires, 
    and it's not scaled when table is resized */
    flex: 0 0 auto;
    width: calc(100% - 0.9em);
}
table tbody {
    /* body takes all the remaining available space */
    flex: 1 1 auto;
    display: block;
    overflow-y: scroll;
}
table tbody tr {
    width: 100%;
}
table thead, table tbody tr {
    display: table;
    table-layout: fixed;
}

full code on jsfiddle

Same code in LESS so you can mix it in:

.table-scrollable() {
  @scrollbar-width: 0.9em;
  display: flex;
  flex-flow: column;

  thead,
  tbody tr {
    display: table;
    table-layout: fixed;
  }

  thead {
    flex: 0 0 auto;
    width: ~"calc(100% - @{scrollbar-width})";
  }

  tbody {
    display: block;
    flex: 1 1 auto;
    overflow-y: scroll;

    tr {
      width: 100%;
    }
  }
}

How to get the Android device's primary e-mail address

Sadly accepted answer isn't working.

I'm late, but here's the solution for internal Android Email application unless the content uri is changed by provider:

Uri EMAIL_ACCOUNTS_DATABASE_CONTENT_URI = 
              Uri.parse("content://com.android.email.provider/account");

public ArrayList<String> GET_EMAIL_ADDRESSES ()
{
    ArrayList<String> names = new ArrayList<String>();
    ContentResolver cr      = m_context.getContentResolver();
    Cursor cursor           = cr.query(EMAIL_ACCOUNTS_DATABASE_CONTENT_URI ,null, 
                             null, null, null);

    if (cursor == null) {
        Log.e("TEST", "Cannot access email accounts database");
        return null;
    }

    if (cursor.getCount() <= 0) {
        Log.e("TEST", "No accounts");
        return null;
    }

    while (cursor.moveToNext()) {
        names.add(cursor.getString(cursor.getColumnIndex("emailAddress")));
        Log.i("TEST", cursor.getString(cursor.getColumnIndex("emailAddress")));
    }
    return names;
}

How to set user environment variables in Windows Server 2008 R2 as a normal user?

Step by step instructions:

  • Go to Control Panel \System and Security\System
  • Click on Change Settings
  • Go to “Advance” tab
  • Click on Environment Variables

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

Oracle comparing timestamp with date

to_date format worked for me. Please consider the date formats: MON-, MM, ., -.

t.start_date >= to_date('14.11.2016 04:01:39', 'DD.MM.YYYY HH24:MI:SS')
t.start_date <=to_date('14.11.2016 04:10:07', 'DD.MM.YYYY HH24:MI:SS')

Correct way to push into state array

You can use .concat method to create copy of your array with new data:

this.setState({ myArray: this.state.myArray.concat('new value') })

But beware of special behaviour of .concat method when passing arrays - [1, 2].concat(['foo', 3], 'bar') will result in [1, 2, 'foo', 3, 'bar'].

Winforms TableLayoutPanel adding rows programmatically

It's a weird design, but the TableLayoutPanel.RowCount property doesn't reflect the count of the RowStyles collection, and similarly for the ColumnCount property and the ColumnStyles collection.

What I've found I needed in my code was to manually update RowCount/ColumnCount after making changes to RowStyles/ColumnStyles.

Here's an example of code I've used:

    /// <summary>
    /// Add a new row to our grid.
    /// </summary>
    /// The row should autosize to match whatever is placed within.
    /// <returns>Index of new row.</returns>
    public int AddAutoSizeRow()
    {
        Panel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
        Panel.RowCount = Panel.RowStyles.Count;
        mCurrentRow = Panel.RowCount - 1;
        return mCurrentRow;
    }

Other thoughts

  • I've never used DockStyle.Fill to make a control fill a cell in the Grid; I've done this by setting the Anchors property of the control.

  • If you're adding a lot of controls, make sure you call SuspendLayout and ResumeLayout around the process, else things will run slow as the entire form is relaid after each control is added.

Why is document.write considered a "bad practice"?

Pro:

  • It's the easiest way to embed inline content from an external (to your host/domain) script.
  • You can overwrite the entire content in a frame/iframe. I used to use this technique a lot for menu/navigation pieces before more modern Ajax techniques were widely available (1998-2002).

Con:

  • It serializes the rendering engine to pause until said external script is loaded, which could take much longer than an internal script.
  • It is usually used in such a way that the script is placed within the content, which is considered bad-form.

Complex CSS selector for parent of active child

I actually ran into the same issue as the original poster. There is a simple solution of just using .parent() jQuery selector. My problem was, I was using .parent instead of .parent(). Stupid mistake I know.

Bind the events (in this case since my tabs are in Modal I needed to bind them with .live instead of a basic .click.

$('#testTab1 .tabLink').live('click', function() {
    $('#modal ul.tabs li').removeClass("current"); //Remove any "current" class
    $(this).parent().addClass("current"); //Add "current" class to selected tab
    $('#modal div#testTab1 .tabContent').hide();
    $(this).next('.tabContent').fadeIn();   
    return false;
})
$('#testTab2 .tabLink').live('click', function() {
    $('#modal ul.tabs li').removeClass("current"); //Remove any "current" class
    $(this).parent().addClass("current"); //Add "current" class to selected tab
    $('#modal div#testTab2 .tabContent').hide();
    $(this).next('.tabContent').fadeIn();   
    return false;
})

Here is the HTML..

<div id="tabView1" style="display:none;">
  <!-- start: the code for tabView 1 -->
  <div id="testTab1" style="width:1080px; height:640px; position:relative;">
    <h1 class="Bold_Gray_45px">Modal Header</h1>
    <div class="tabBleed"></div>
    <ul class="tabs">
      <li class="current"> <a href="#" class="tabLink" id="link1">Tab Title Link</a>
        <div class="tabContent" id="tabContent1-1">
          <div class="modalCol">
            <p>Your Tab Content</p>
            <p><a href="#" class="tabShopLink">tabBased Anchor Link</a> </p>
          </div>
          <div class="tabsImg"> </div>
        </div>
      </li>
      <li> <a href="#" class="tabLink" id="link2">Tab Title Link</a>
        <div class="tabContent" id="tabContent1-2">
          <div class="modalCol">
            <p>Your Tab Content</p>
            <p><a href="#" class="tabShopLink">tabBased Anchor Link</a> </p>
          </div>
          <div class="tabsImg"> </div>
        </div>
      </li>
    </ul>
  </div>
</div>

Of course you can repeat that pattern..with more LI's

CSS transition with visibility not working

Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337

You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0 only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden, you can eliminate this problem:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:20px;_x000D_
}_x000D_
.menu {_x000D_
    visibility:hidden;_x000D_
    opacity:0;_x000D_
    transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
    _x000D_
    background:#eee;_x000D_
    width:100px;_x000D_
    margin:0;_x000D_
    padding:5px;_x000D_
    list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
    visibility:visible;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="#">Open Menu</a>_x000D_
  <ul class="menu">_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Close Window from ViewModel

I know this is an old post, probably no one would scroll this far, I know I didn't. So, after hours of trying different stuff, I found this blog and dude killed it. Simplest way to do this, tried it and it works like a charm.

Blog

In the ViewModel:

...

public bool CanClose { get; set; }

private RelayCommand closeCommand;
public ICommand CloseCommand
{
    get
    {
        if(closeCommand == null)
        (
            closeCommand = new RelayCommand(param => Close(), param => CanClose);
        )
    }
}

public void Close()
{
    this.Close();
}

...

add an Action property to the ViewModel, but define it from the View’s code-behind file. This will let us dynamically define a reference on the ViewModel that points to the View.

On the ViewModel, we’ll simply add:

public Action CloseAction { get; set; }

And on the View, we’ll define it as such:

public View()
{
    InitializeComponent() // this draws the View
    ViewModel vm = new ViewModel(); // this creates an instance of the ViewModel
    this.DataContext = vm; // this sets the newly created ViewModel as the DataContext for the View
    if ( vm.CloseAction == null )
        vm.CloseAction = new Action(() => this.Close());
}

Download TS files from video stream

1) Please read instructions by @aalhanane (after "paste URL m3u8" step you have to type name for the file, eg "video" then click on "hand" icon next to "quality" and only after that you should select "one on one" and "download").

2) The stream splits video and audio, so you need to download them separately and then use the same m3u8x to join them https://youtu.be/he-tDNiVl2M (optionally convert to mp4).

3) m3u8x can download video without any issues but in my case it cannot extract audio links. So I simply downloaded the *.m3u8 file and searched for line which contains GROUP-ID="audio-0" and then scroll right and copied the link (!including token!) and paste it straight into "Quality URL" field of m3u8x app. Then "one on one" and download it similar to video stream.

Once I had both video and audio, I joined and success =)

p.s. in case automatic extraction will stop working in the future, you can use the same method to extract video links manually.

SQL Order By Count

Try using below Query:

SELECT
    GROUP,
    COUNT(*) AS Total_Count
FROM
    TABLE
GROUP BY
    GROUP
ORDER BY
    Total_Count DESC

How to display Woocommerce Category image?

Add code in /wp-content/plugins/woocommerce/templates/ loop path

    <?php
        if ( is_product_category() ){

            global $wp_query;
            $cat = $wp_query->get_queried_object();    
            $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true ); 
            $image = wp_get_attachment_url( $thumbnail_id ); 
            echo "<img src='{$image}' alt='' />";
        }
    ?>

Run Android studio emulator on AMD processor

Open Android AVD Manager: Tools -> Android -> AVD Manager and create an emulator:

  • Create Virtual Device
  • Choose any hardware
  • Now in system image you need to click on the "Other Images" tab
  • Select an image to install. IMPORTANT: Notice that for AMD in the "ABI" column it has to say: ARM EABI v7a or ARM 64 v8a
  • Install it and restart Android Studio

This works for me.

Find distance between two points on map using Google Map API V2

All this answers will give you the distance in a straight line. If you need to get the distance by road, you have to parse the JSON that Google sends you back after calling his service. You can use this method:

public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){
    String parsedDistance;
    String response;
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
                    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");

                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray array = jsonObject.getJSONArray("routes");
                    JSONObject routes = array.getJSONObject(0);
                    JSONArray legs = routes.getJSONArray("legs");
                    JSONObject steps = legs.getJSONObject(0);
                    JSONObject distance = steps.getJSONObject("distance");
                    parsedDistance=distance.getString("text");

                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return parsedDistance;
}

lat1 and lon1 are coordinates of origin, lat2 and lon2 are coordinates of destination.

Android Design Support Library expandable Floating Action Button(FAB) menu

When I tried to create something simillar to inbox floating action button i thought about creating own custom component.

It would be simple frame layout with fixed height (to contain expanded menu) containing FAB button and 3 more placed under the FAB. when you click on FAB you just simply animate other buttons to translate up from under the FAB.

There are some libraries which do that (for example https://github.com/futuresimple/android-floating-action-button), but it's always more fun if you create it by yourself :)

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you consider using fastjson, you can solve your problem, note the version

 <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.56</version>
 </dependency>

Hide console window from Process.Start C#

I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:

Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process

matplotlib: how to change data points color based on some variable

This is what matplotlib.pyplot.scatter is for.

As a quick example:

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)

plt.scatter(t,x,c=y)
plt.show()

enter image description here

Boolean vs boolean in Java

One observation: (though this can be thought of side effect)

boolean being a primitive can either say yes or no.

Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)

Learning Regular Expressions

The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

Start simple

Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

Order from the menu

Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

The pattern . is special: rather than matching a literal dot only, it matches any character. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

Think of character classes as menus: pick just one.

Helpful shortcuts

Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

Once is not enough

From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

  • * (zero or more times)
  • + (one or more times)
  • {n} (exactly n times)
  • {n,} (at least n times)
  • {n,m} (at least n times but no more than m times)

Putting some of these blocks together, the pattern [Nn]*ick matches all of

  • ick
  • Nick
  • nick
  • Nnick
  • nNick
  • nnick
  • (and so on)

The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

A few other useful examples:

  • [0-9]+ (and its equivalent \d+) matches any non-negative integer
  • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

Grouping

A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

Alternation

Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

Escaping

Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

Greediness

Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

For example, say the input is

"Hello," she said, "How are you?"

You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

(As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

Anchors

Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

Say you want to match comments of the form

-- This is a comment --

you'd write ^--\s+(.+)\s+--$.

Build your own

Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

Tools for writing and debugging regexes:

Books

Free resources

Footnote

†: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

While trace flag 272 may work for many, it definitely won't work for hosted Sql Server Express installations. So, I created an identity table, and use this through an INSTEAD OF trigger. I'm hoping this helps someone else, and/or gives others an opportunity to improve my solution. The last line allows returning the last identity column added. Since I typically use this to add a single row, this works to return the identity of a single inserted row.

The identity table:

CREATE TABLE [dbo].[tblsysIdentities](
[intTableId] [int] NOT NULL,
[intIdentityLast] [int] NOT NULL,
[strTable] [varchar](100) NOT NULL,
[tsConcurrency] [timestamp] NULL,
CONSTRAINT [PK_tblsysIdentities] PRIMARY KEY CLUSTERED 
(
    [intTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

and the insert trigger:

-- INSERT --
IF OBJECT_ID ('dbo.trgtblsysTrackerMessagesIdentity', 'TR') IS NOT NULL
   DROP TRIGGER dbo.trgtblsysTrackerMessagesIdentity;
GO
CREATE TRIGGER trgtblsysTrackerMessagesIdentity
ON dbo.tblsysTrackerMessages
INSTEAD OF INSERT AS 
BEGIN
    DECLARE @intTrackerMessageId INT
    DECLARE @intRowCount INT

    SET @intRowCount = (SELECT COUNT(*) FROM INSERTED)

    SET @intTrackerMessageId = (SELECT intIdentityLast FROM tblsysIdentities WHERE intTableId=1)
    UPDATE tblsysIdentities SET intIdentityLast = @intTrackerMessageId + @intRowCount WHERE intTableId=1

    INSERT INTO tblsysTrackerMessages( 
    [intTrackerMessageId],
    [intTrackerId],
    [strMessage],
    [intTrackerMessageTypeId],
    [datCreated],
    [strCreatedBy])
    SELECT @intTrackerMessageId + ROW_NUMBER() OVER (ORDER BY [datCreated]) AS [intTrackerMessageId], 
    [intTrackerId],
   [strMessage],
   [intTrackerMessageTypeId],
   [datCreated],
   [strCreatedBy] FROM INSERTED;

   SELECT TOP 1 @intTrackerMessageId + @intRowCount FROM INSERTED;
END

How do I check for a network connection?

Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:

  1. NCSI performs a DNS lookup on www.msftncsi.com, then requests http://www.msftncsi.com/ncsi.txt. This file is a plain-text file and contains only the text 'Microsoft NCSI'.
  2. NCSI sends a DNS lookup request for dns.msftncsi.com. This DNS address should resolve to 131.107.255.255. If the address does not match, then it is assumed that the internet connection is not functioning correctly.

Getting a timestamp for today at midnight?

If you are using Carbon you can do the following. You could also format this date to set an Expire HTTP Header.

Carbon::parse('tomorrow midnight')->format(Carbon::RFC7231_FORMAT)

How to display multiple notifications in android

declare class member
static int i = 0;

mNotificationManager.notify(++i, mBuilder.build());

Java: How to check if object is null?

if (yourObject instanceof yourClassName) will evaluate to false if yourObject is null.

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

The name 'controlname' does not exist in the current context

I had the same problem. It turns out that I had both "MyPage.aspx" and "Copy of MyPage.aspx" in my project.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

I had a similar problem, trying to add a background image with inline css. No need to specify the images folder due to the way asset sync works.

This worked for me:

background-image: url('/assets/image.jpg');

How to remove all the occurrences of a char in c++ string

I guess the method std:remove works but it was giving some compatibility issue with the includes so I ended up writing this little function:

string removeCharsFromString(const string str, char* charsToRemove )
{
    char c[str.length()+1]; // + terminating char
    const char *p = str.c_str();
    unsigned int z=0, size = str.length();
    unsigned int x;
    bool rem=false;

    for(x=0; x<size; x++)
    {
        rem = false;
        for (unsigned int i = 0; charsToRemove[i] != 0; i++)
        {
            if (charsToRemove[i] == p[x])
            {
                rem = true;
                break;
            }
        }
        if (rem == false) c[z++] = p[x];
    }

    c[z] = '\0';
    return string(c);
}

Just use as

myString = removeCharsFromString(myString, "abc\r");

and it will remove all the occurrence of the given char list.

This might also be a bit more efficient as the loop returns after the first match, so we actually do less comparison.

Powershell get ipv4 address into a variable

(Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DefaultIPGateway -ne $null}).IPAddress | select-object -first 1

Celery Received unregistered task of type (run example)

The answer to your problem lies in THE FIRST LINE of the output you provided in your question: /usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and is available to Python. "is available to Python." % (configname, ))). Without the right configuration Celery is not able to do anything.

Reason why it can't find the celeryconfig is most likely it is not in your PYTHONPATH.

Performing Inserts and Updates with Dapper

We are looking at building a few helpers, still deciding on APIs and if this goes in core or not. See: https://code.google.com/archive/p/dapper-dot-net/issues/6 for progress.

In the mean time you can do the following

val = "my value";
cnn.Execute("insert into Table(val) values (@val)", new {val});

cnn.Execute("update Table set val = @val where Id = @id", new {val, id = 1});

etcetera

See also my blog post: That annoying INSERT problem

Update

As pointed out in the comments, there are now several extensions available in the Dapper.Contrib project in the form of these IDbConnection extension methods:

T Get<T>(id);
IEnumerable<T> GetAll<T>();
int Insert<T>(T obj);
int Insert<T>(Enumerable<T> list);
bool Update<T>(T obj);
bool Update<T>(Enumerable<T> list);
bool Delete<T>(T obj);
bool Delete<T>(Enumerable<T> list);
bool DeleteAll<T>();

How to get just the responsive grid from Bootstrap 3?

Checkout zirafa/bootstrap-grid-only. It contains only the bootstrap grid and responsive utilities that you need (no reset or anything), and simplifies the complexity of working directly with the LESS files.

Making an iframe responsive

Fully responsive iFrame for situations where aspect ratio is unknown and content in the iFrame is fully responsive.

None of the above solutions worked for my need, which was to create a fully responsive iFrame that had fully responsive dynamic content inside of it. Maintaining any kind of aspect ratio was not an option.

  1. Get height of your navigation bar and any content ABOVE or BELOW the iFrame. In my case I only needed to subtract the top navbar and I wanted the iFrame to fill all the way down to the bottom of the screen.

Code:

function getWindowHeight() {
        console.log('Get Window Height Called')
        var currentWindowHeight = $(window).height()

        var iFrame = document.getElementById("myframe")
        var frameHeight = currentWindowHeight - 95

        iFrame.height = frameHeight; 

    }
//Timeout to prevent function from repeatedly firing
    var doit;
    window.onresize = function(){
      clearTimeout(doit);
      doit = setTimeout(resizedw, 100);
    };

I also created a timeout so that on resize the function wouldn't get called a million times.

NameError: name 'self' is not defined

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

What are file descriptors, explained in simple terms?

File descriptors are nothing but references for any open resource. As soon as you open a resource the kernel assumes you will be doing some operations on it. All the communication via your program and the resource happens over an interface and this interface is provided by the file-descriptor.

Since a process can open more than one resource, it is possible for a resource to have more than one file-descriptors.
You can view all file-descriptors linked to the process by simply running, ls -li /proc/<pid>/fd/ here pid is the process-id of your process

random.seed(): What does it do?

Imho, it is used to generate same random course result when you use random.seed(samedigit) again.

In [47]: random.randint(7,10)

Out[47]: 9


In [48]: random.randint(7,10)

Out[48]: 9


In [49]: random.randint(7,10)

Out[49]: 7


In [50]: random.randint(7,10)

Out[50]: 10


In [51]: random.seed(5)


In [52]: random.randint(7,10)

Out[52]: 9


In [53]: random.seed(5)


In [54]: random.randint(7,10)

Out[54]: 9

Command prompt won't change directory to another drive

The directory you're switching to is on another drive, you need to switch to that drive using :

C:\...\Admin> d:

then you can cd into the directory you want.

C:\...\Admin> d:
D:\>cd "Docs\Java"

D:\Docs\Java>

How to remove first 10 characters from a string?

You Can Remove Char using below Line ,

:- First check That String has enough char to remove ,like

   string temp="Hello Stack overflow";
   if(temp.Length>10)
   {
    string textIWant = temp.Remove(0, 10);
   }

NGinx Default public www location?

Dump the configuration:

$ nginx -T
...
server {
    ...
    location / {
        root   /usr/share/nginx/html;
        ...
    }
    ...
}

What you get might be different since it depends on how your nginx was configured/installed.

References:

Update: There's some confusion on the issue of if/when the -T option was added to nginx. It was documented in the man page by vl-homutov on 2015 June 16, which became part of the v1.9.2 release. It's even mentioned in the release notes. The -T option has been present in every nginx release since, including the one available on Ubuntu 16.04.1 LTS:

root@23cc8e58640e:/# nginx -h    
nginx version: nginx/1.10.0 (Ubuntu)
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/share/nginx/)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

How to sort a list of strings numerically?

If you want to use strings of the numbers better take another list as shown in my code it will work fine.

list1=["1","10","3","22","23","4","2","200"]

k=[]    
for item in list1:    
    k.append(int(item))

k.sort()
print(k)
# [1, 2, 3, 4, 10, 22, 23, 200]

How to set Java SDK path in AndroidStudio?

Go to File>Project Structure>JDK location: Here, you have to set the directory path exactly same, in which you have installed the java version. Also, you have to mention the paths of SDK for project run on emulator successfully.

Why This Problem Occurs: It is due to the unsynchronized java version directory that should be available to Android Studio for java code compilance.

Check if selected dropdown value is empty using jQuery

Try this it will work --

if($('#EventStartTimeMin').val() === " ") {

    alert("Please enter start time!");

}

Bootstrap 3: Offset isn't working?

There is no col-??-offset-0. All "rows" assume there is no offset unless it has been specified. I think you are wanting 3 rows on a small screen and 1 row on a medium screen.

To get the result I believe you are looking for try this:

<div class="container">
    <div class="row">
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
    </div>
  </div>

Keep in mind you will only see a difference on a small tablet with what you described. Medium, large, and extra small screens the columns are spanning 12.

Hope this helps.

Query to get only numbers from a string

For the hell of it...

This solution is different to all earlier solutions, viz:

  • There is no need to create a function
  • There is no need to use pattern matching
  • There is no need for a temporary table
  • This solution uses a recursive common table expression (CTE)

But first - note the question does not specify where such strings are stored. In my solution below, I create a CTE as a quick and dirty way to put these strings into some kind of "source table".

Note also - this solution uses a recursive common table expression (CTE) - so don't get confused by the usage of two CTEs here. The first is simply to make the data avaliable to the solution - but it is only the second CTE that is required in order to solve this problem. You can adapt the code to make this second CTE query your existing table, view, etc.

Lastly - my coding is verbose, trying to use column and CTE names that explain what is going on and you might be able to simplify this solution a little. I've added in a few pseudo phone numbers with some (expected and atypical, as the case may be) formatting for the fun of it.

with SOURCE_TABLE as (
    select '003Preliminary Examination Plan' as numberString
    union all select 'Coordination005' as numberString
    union all select 'Balance1000sheet' as numberString
    union all select '1300 456 678' as numberString
    union all select '(012) 995 8322  ' as numberString
    union all select '073263 6122,' as numberString
),
FIRST_CHAR_PROCESSED as (
    select
        len(numberString) as currentStringLength,
        isNull(cast(try_cast(replace(left(numberString, 1),' ','z') as tinyint) as nvarchar),'') as firstCharAsNumeric,
        cast(isNull(cast(try_cast(nullIf(left(numberString, 1),'') as tinyint) as nvarchar),'') as nvarchar(4000)) as newString,
        cast(substring(numberString,2,len(numberString)) as nvarchar) as remainingString
    from SOURCE_TABLE
    union all
    select
        len(remainingString) as currentStringLength,
        cast(try_cast(replace(left(remainingString, 1),' ','z') as tinyint) as nvarchar) as firstCharAsNumeric,
        cast(isNull(newString,'') as nvarchar(3999)) + isNull(cast(try_cast(nullIf(left(remainingString, 1),'') as tinyint) as nvarchar(1)),'') as newString,
        substring(remainingString,2,len(remainingString)) as remainingString
    from FIRST_CHAR_PROCESSED fcp2
    where fcp2.currentStringLength > 1
)
select 
    newString
    ,* -- comment this out when required
from FIRST_CHAR_PROCESSED 
where currentStringLength = 1

So what's going on here?

Basically in our CTE we are selecting the first character and using try_cast (see docs) to cast it to a tinyint (which is a large enough data type for a single-digit numeral). Note that the type-casting rules in SQL Server say that an empty string (or a space, for that matter) will resolve to zero, so the nullif is added to force spaces and empty strings to resolve to null (see discussion) (otherwise our result would include a zero character any time a space is encountered in the source data).

The CTE also returns everything after the first character - and that becomes the input to our recursive call on the CTE; in other words: now let's process the next character.

Lastly, the field newString in the CTE is generated (in the second SELECT) via concatenation. With recursive CTEs the data type must match between the two SELECT statements for any given column - including the column size. Because we know we are adding (at most) a single character, we are casting that character to nvarchar(1) and we are casting the newString (so far) as nvarchar(3999). Concatenated, the result will be nvarchar(4000) - which matches the type casting we carry out in the first SELECT.

If you run this query and exclude the WHERE clause, you'll get a sense of what's going on - but the rows may be in a strange order. (You won't necessarily see all rows relating to a single input value grouped together - but you should still be able to follow).

Hope it's an interesting option that may help a few people wanting a strictly expression-based solution.

C - freeing structs

Simple answer : free(testPerson) is enough .

Remember you can use free() only when you have allocated memory using malloc, calloc or realloc.

In your case you have only malloced memory for testPerson so freeing that is sufficient.

If you have used char * firstname , *last surName then in that case to store name you must have allocated the memory and that's why you had to free each member individually.

Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free() it first then free the pointer to object.

Freeing each element you can see the demo shown below:

typedef struct Person
{
char * firstname , *last surName;
}Person;
Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct
ptrobj->firstname = malloc(n); // memory allocation for firstname
ptrobj->surName = malloc(m); // memory allocation for surName

.
. // do whatever you want

free(ptrobj->surName);
free(ptrobj->firstname);
free(ptrobj);

The reason behind this is, if you free the ptrobj first, then there will be memory leaked which is the memory allocated by firstname and suName pointers.

How to download and save an image in Android

it might help you..

Button download_image = (Button)bigimagedialog.findViewById(R.id.btn_downloadimage);
                    download_image.setOnClickListener(new View.OnClickListener()
                    {
                        public void onClick(View v)
                        {
                            boolean success = (new File("/sdcard/dirname")).mkdir(); 
                            if (!success)
                            {
                                Log.w("directory not created", "directory not created");
                            }

                            try
                            {
                                URL url = new URL("YOUR_URL");
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                connection.setDoInput(true);
                                connection.connect();
                                InputStream input = connection.getInputStream();
                                Bitmap myBitmap = BitmapFactory.decodeStream(input);

                                String data1 = String.valueOf(String.format("/sdcard/dirname/%d.jpg",System.currentTimeMillis()));

                                FileOutputStream stream = new FileOutputStream(data1);

                                ByteArrayOutputStream outstream = new ByteArrayOutputStream();
                                myBitmap.compress(Bitmap.CompressFormat.JPEG, 85, outstream);
                                byte[] byteArray = outstream.toByteArray();

                                stream.write(byteArray);
                                stream.close();

                                Toast.makeText(getApplicationContext(), "Downloading Completed", Toast.LENGTH_SHORT).show();
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                    });

Edit a specific Line of a Text File in C#

You need to Open the output file for write access rather than using a new StreamReader, which always overwrites the output file.

StreamWriter stm = null;
fi = new FileInfo(@"C:\target.xml");
if (fi.Exists)
   stm = fi.OpenWrite();

Of course, you will still have to seek to the correct line in the output file, which will be hard since you can't read from it, so unless you already KNOW the byte offset to seek to, you probably really want read/write access.

FileStream stm = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);

with this stream, you can read until you get to the point where you want to make changes, then write. Keep in mind that you are writing bytes, not lines, so to overwrite a line you will need to write the same number of characters as the line you want to change.

Java random number with given length

To generate a 6-digit number:

Use Random and nextInt as follows:

Random rnd = new Random();
int n = 100000 + rnd.nextInt(900000);

Note that n will never be 7 digits (1000000) since nextInt(900000) can at most return 899999.

So how do I randomize the last 5 chars that can be either A-Z or 0-9?

Here's a simple solution:

// Generate random id, for example 283952-V8M32
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random rnd = new Random();
StringBuilder sb = new StringBuilder((100000 + rnd.nextInt(900000)) + "-");
for (int i = 0; i < 5; i++)
    sb.append(chars[rnd.nextInt(chars.length)]);

return sb.toString();

String is immutable. What exactly is the meaning?

A string is a char[] containing a series of UTF-16 code units, an int offset into that array, and an int length.

For example.

String s

It creates space for a string reference. Assigning copies references around but does not modify the objects to which those references refer.

You should also be aware that

new String(s)

doesn't really do anything useful. It merely creates another instance backed by the same array, offset, and length as s. There is very rarely a reason to do this so it is considered bad practice by most Java programmers.

Java double quoted strings like "my string" are really references to interned String instances so "bar" is a reference to the same String instance regardless of how many times it appears in your code.


The "hello" creates one instance that is pooled, and the new String(...) creates a non-pooled instance. Try System.out.println(("hello" == "hello") + "," + (new String("hello") == "hello") + "," + (new String("hello") == new String("hello"))); and you should see true,false,false

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

HTML5: Slider with two inputs possible?

Coming late, but noUiSlider avoids having a jQuery-ui dependency, which the accepted answer does not. Its only "caveat" is IE support is for IE9 and newer, if legacy IE is a deal breaker for you.

It's also free, open source and can be used in commercial projects without restrictions.

Installation: Download noUiSlider, extract the CSS and JS file somewhere in your site file system, and then link to the CSS from head and to JS from body:

<!-- In <head> -->
<link href="nouislider.min.css" rel="stylesheet">

<!-- In <body> -->
<script src="nouislider.min.js"></script>

Example usage: Creates a slider which goes from 0 to 100, and starts set to 20-80.

HTML:

<div id="slider">
</div>

JS:

var slider = document.getElementById('slider');

noUiSlider.create(slider, {
    start: [20, 80],
    connect: true,
    range: {
        'min': 0,
        'max': 100
    }
});

Real-world examples of recursion

I think that this really depends upon the language. In some languages, Lisp for example, recursion is often the natural response to a problem (and often with languages where this is the case, the compiler is optimized to deal with recursion).

The common pattern in Lisp of performing an operation on the first element of a list and then calling the function on the rest of the list in order to either accumulate a value or a new list is quite elegant and most natural way to do a lot of things in that language. In Java, not so much.

phpMyAdmin + CentOS 6.0 - Forbidden

I tried all answers provided here: editing phpMyAdmin.conf, changing selinux context for phpmyadmin folder, disabling selinux... but I still got a 'Forbidden' from the web server.

I finally found what I was missing in Edouard Thiel post here :

$ yum install php

then restart httpd :

$ service httpd restart => for centos 6 hots

$ systemctl restart httpd => for centos 7 hosts

What has me amazed is why php is not installed as dependency for phpmyadmin in the first place.

Regards, Fred

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

For Python 3.7, use subprocess.call. Use raw string to simplify the Windows paths:

import subprocess
subprocess.call([r'C:\Temp\Example\Notepad.exe', 'C:\test.txt'])

Check that a input to UITextField is numeric only

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(string.length > 0)
    {
        NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];

        BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
        return stringIsValid;
    }
    return YES;
}

Why are the Level.FINE logging messages not showing?

I found my actual problem and it was not mentioned in any answer: some of my unit-tests were causing logging initialization code to be run multiple times within the same test suite, messing up the logging on the later tests.

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

In the examples below the client is the browser and the server is the webserver hosting the website.

Before you can understand these technologies, you have to understand classic HTTP web traffic first.

Regular HTTP:

  1. A client requests a webpage from a server.
  2. The server calculates the response
  3. The server sends the response to the client.

HTTP

Ajax Polling:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server at regular intervals (e.g. 0.5 seconds).
  3. The server calculates each response and sends it back, just like normal HTTP traffic.

Ajax Polling

Ajax Long-Polling:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server.
  3. The server does not immediately respond with the requested information but waits until there's new information available.
  4. When there's new information available, the server responds with the new information.
  5. The client receives the new information and immediately sends another request to the server, re-starting the process.

Ajax Long-Polling

HTML5 Server Sent Events (SSE) / EventSource:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection to the server.
  3. The server sends an event to the client when there's new information available.

HTML5 SSE

HTML5 Websockets:

  1. A client requests a webpage from a server using regular http (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection with the server.
  3. The server and the client can now send each other messages when new data (on either side) is available.

    • Real-time traffic from the server to the client and from the client to the server
    • You'll want to use a server that has an event loop
    • With WebSockets it is possible to connect with a server from another domain.
    • It is also possible to use a third party hosted websocket server, for example Pusher or others. This way you'll only have to implement the client side, which is very easy!
    • If you want to read more, I found these very useful: (article), (article) (tutorial).

HTML5 WebSockets

Comet:

Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.


Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?

You can use PHP with WebSockets, check out Ratchet.

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

How can I use different certificates on specific connections?

I read through LOTS of places online to solve this thing. This is the code I wrote to make it work:

ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());

app.certificateString is a String that contains the Certificate, for example:

static public String certificateString=
        "-----BEGIN CERTIFICATE-----\n" +
        "MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
        "BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
        ... a bunch of characters...
        "5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
        "-----END CERTIFICATE-----";

I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.

Oracle SQL escape character (for a '&')

SELECT 'Free &' || ' Clear' FROM DUAL;

jQuery textbox change event doesn't fire until textbox loses focus?

Try this:

$("#textbox").bind('paste',function() {alert("Change detected!");});

See demo on JSFiddle.

Shuffle DataFrame rows

What is also useful, if you use it for Machine_learning and want to seperate always the same data, you could use:

df.sample(n=len(df), random_state=42)

this makes sure, that you keep your random choice always replicatable

Remove last characters from a string in C#. An elegant way?

Perhaps this:

str = str.Split(",").First();

How to convert string to double with proper cultureinfo

Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture

TryParse does not allway work as we would expect There are change request in .net in this area:

https://github.com/dotnet/runtime/issues/25868

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Safe String to BigDecimal conversion

The code could be cleaner, but this seems to do the trick for different locales.

import java.math.BigDecimal;
import java.text.DecimalFormatSymbols;
import java.util.Locale;


public class Main
{
    public static void main(String[] args)
    {
        final BigDecimal numberA;
        final BigDecimal numberB;

        numberA = stringToBigDecimal("1,000,000,000.999999999999999", Locale.CANADA);
        numberB = stringToBigDecimal("1.000.000.000,999999999999999", Locale.GERMANY);
        System.out.println(numberA);
        System.out.println(numberB);
    }

    private static BigDecimal stringToBigDecimal(final String formattedString,
                                                 final Locale locale)
    {
        final DecimalFormatSymbols symbols;
        final char                 groupSeparatorChar;
        final String               groupSeparator;
        final char                 decimalSeparatorChar;
        final String               decimalSeparator;
        String                     fixedString;
        final BigDecimal           number;

        symbols              = new DecimalFormatSymbols(locale);
        groupSeparatorChar   = symbols.getGroupingSeparator();
        decimalSeparatorChar = symbols.getDecimalSeparator();

        if(groupSeparatorChar == '.')
        {
            groupSeparator = "\\" + groupSeparatorChar;
        }
        else
        {
            groupSeparator = Character.toString(groupSeparatorChar);
        }

        if(decimalSeparatorChar == '.')
        {
            decimalSeparator = "\\" + decimalSeparatorChar;
        }
        else
        {
            decimalSeparator = Character.toString(decimalSeparatorChar);
        }

        fixedString = formattedString.replaceAll(groupSeparator , "");
        fixedString = fixedString.replaceAll(decimalSeparator , ".");
        number      = new BigDecimal(fixedString);

        return (number);
    }
}

how to use font awesome in own css?

Instructions for Drupal 8 / FontAwesome 5

Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)

Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
}
?>

Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.

Make sure you import FontAwesome, add this at the top of the CSS file

@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

then add this in the CSS

input#edit-submit {
    font-family: 'Font Awesome\ 5 Free';
    background-color: transparent;
    border: 0;  
}

FLUSH ALL CACHES AND IT SHOULD WORK FINE

Add Google Font Effects

If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

For this problem, I have finally put a new <i> tag to refresh the select instead. Don't try to trigger an event if the selected option is the same that the one already selected.

enter image description here

If user click on the "refresh" button, I trigger the onchange event of my select with :

const refreshEquipeEl = document.getElementById("refreshEquipe1");

function onClickRefreshEquipe(event){
    let event2 = new Event('change');
    equipesSelectEl.dispatchEvent(event2);
}
refreshEquipeEl.onclick = onClickRefreshEquipe;

This way, I don't need to try select the same option in my select.

Android open camera from button

I know it is a bit late of a reply but you can use the below syntax as it worked with me just fine

Camera=(Button)findViewById(R.id.CameraID);
Camera.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent Intent3=new   Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
            startActivity(Intent3); 
        }
    });

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

in the new actionmailer, "razorengine" is a dependency. The latest version of Razorengine installs the dependency to System.Web.Razor 3.0.0.

If you use an earlier version in your application (i suppose you are using actionmailer in another project and that you reference the mail functionality from another project) than you get this issue of course.

In an earlier application, i had a webapplication MVC that uses system.web.Razor version 2.0.0. Of course, i got the issue to. How to fix? => Simple!

  1. Just uninstall the entire actionmailer in your actionmailer project.
  2. Install a previous version of RazorEngin

    Install-Package RazorEngine -Version 3.3.0 (because version 3.3.0 will reference system.web.razor 2.0.0)

  3. Install actionmailer again (it will not install the latest version of RazorEngin because you allready did that yourselve)
Succes!

Why "no projects found to import"?

I had the same issue when I've modified .project xml-file. When I reverted files to original version the project was created, then I was able to import project. Maybe it helps someone who has the same kind of problem ;)

How to import and export components using React + ES6 + webpack?

I Hope this is Helpfull

Step 1: App.js is (main module) import the Login Module

import React, { Component } from 'react';
import './App.css';
import Login from './login/login';

class App extends Component {
  render() {
    return (
      <Login />
    );
  }
}

export default App;

Step 2: Create Login Folder and create login.js file and customize your needs it automatically render to App.js Example Login.js

import React, { Component } from 'react';
import '../login/login.css';

class Login extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default Login;

How to change default timezone for Active Record in Rails?

If you want to set the timezone to UTC globally, you can do the following in Rails 4:

# Inside config/application.rb
config.time_zone = "UTC"
config.active_record.default_timezone = :utc

Be sure to restart your application or you won't see the changes.

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

and the one for 64 bit WITH the management tools (management studio) is here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Many developers include files by pointing to a remote URL, even if the file is within the local system. For example:

<php include("http://example.com/includes/example_include.php"); ?>

With allow_url_include disabled, this method does not work. Instead, the file must be included with a local path, and there are three methods of doing this:

By using a relative path, such as ../includes/example_include.php. By using an absolute path (also known as relative-from-root), such as /home/username/example.com/includes/example_include.php.

By using the PHP environment variable $_SERVER['DOCUMENT_ROOT'], which returns the absolute path to the web root directory. This is by far the best (and most portable) solution. The following example shows the environment variable in action.

Example Include

<?php include($_SERVER['DOCUMENT_ROOT']."/includes/example_include.php"); ?>

Fastest way to convert string to integer in PHP

More ad-hoc benchmark results:

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = (integer) "-11";}'     

real    2m10.397s
user    2m10.220s
sys     0m0.025s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i += "-11";}'              

real    2m1.724s
user    2m1.635s
sys     0m0.009s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = + "-11";}'             

real    1m21.000s
user    1m20.964s
sys     0m0.007s

Mobile website "WhatsApp" button to send message to a specific number

Format to send a WhatsApp message to a specific number (updated Nov 2018)

<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>

where

whatsappphonenumber is a full phone number in international format

urlencodedtext is the URL-encoded pre-filled message.


Example:

  1. Create a link with a pre-filled message that will automatically appear in the text field of a chat, to be sent to a specific number

    Send I am interested in your car for sale to +001-(555)1234567

    https://wa.me/15551234567?text=I%20am%20interested%20in%20your%20car%20for%20sale

    Note :

    Use: https://wa.me/15551234567

    Don't use: https://wa.me/+001-(555)1234567

  2. Create a link with just a pre-filled message that will automatically appear in the text field of a chat, number will be chosen by the user

    Send I am enquiring about the apartment listing

    https://wa.me/?text=I%20am%20enquiring%20about%20the%20apartment%20listing

    After clicking on the link, user will be shown a list of contacts they can send the pre-filled message to.

For more information, see https://www.whatsapp.com/faq/en/general/26000030

--

P.S : Older format (before updation) for reference

<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>

What is the purpose of Node.js module.exports and how do you use it?

the module.exports property or the exports object allows a module to select what should be shared with the application

enter image description here

I have a video on module_export available here

Why is "except: pass" a bad programming practice?

Simply put, if an exception or error is thrown, something's wrong. It may not be something very wrong, but creating, throwing, and catching errors and exceptions just for the sake of using goto statements is not a good idea, and it's rarely done. 99% of the time, there was a problem somewhere.

Problems need to be dealt with. Just like how it is in life, in programming, if you just leave problems alone and try to ignore them, they don't just go away on their own a lot of times; instead they get bigger and multiply. To prevent a problem from growing on you and striking again further down the road, you either 1) eliminate it and clean up the mess afterwards, or 2) contain it and clean up the mess afterwards.

Just ignoring exceptions and errors and leaving them be like that is a good way to experience memory leaks, outstanding database connections, needless locks on file permissions, etc.

On rare occasions, the problem is so miniscule, trivial, and - aside from needing a try...catch block - self-contained, that there really is just no mess to be cleaned up afterwards. These are the only occasions when this best practice doesn't necessarily apply. In my experience, this has generally meant that whatever the code is doing is basically petty and forgoable, and something like retry attempts or special messages are worth neither the complexity nor holding the thread up on.

At my company, the rule is to almost always do something in a catch block, and if you don't do anything, then you must always place a comment with a very good reason why not. You must never pass or leave an empty catch block when there is anything to be done.

How to use View.OnTouchListener instead of onClick

OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:

myView.setOnTouchListener(new View.OnTouchListener()
{
    // Implementation;
});

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

Abort a git cherry-pick?

For me, the only way to reset the failed cherry-pick-attempt was

git reset --hard HEAD

How do I find the time difference between two datetime objects in python?

Use divmod:

now = int(time.time()) # epoch seconds
then = now - 90000 # some time in the past

d = divmod(now-then,86400)  # days
h = divmod(d[1],3600)  # hours
m = divmod(h[1],60)  # minutes
s = m[1]  # seconds

print '%d days, %d hours, %d minutes, %d seconds' % (d[0],h[0],m[0],s)

Getting full-size profile picture

For Angular:

getUserPicture(userId) {   
FB.api('/' + userId, {fields: 'picture.width(800).height(800)'}, function(response) {
  console.log('getUserPicture',response);
});
}

What is the regex for "Any positive integer, excluding 0"

My pattern is complicated, but it covers exactly "Any positive integer, excluding 0" (1 - 2147483647, not long). It's for decimal numbers and doesn't allow leading zeros.

^((1?[1-9][0-9]{0,8})|20[0-9]{8}|(21[0-3][0-9]{7})|(214[0-6][0-9]{6})
|(2147[0-3][0-9]{5})|(21474[0-7][0-9]{4})|(214748[0-2][0-9]{3})
|(2147483[0-5][0-9]{2})|(21474836[0-3][0-9])|(214748364[0-7]))$

Why can't I initialize non-const static member or static array in class?

It's because there can only be one definition of A::a that all the translation units use.

If you performed static int a = 3; in a class in a header included in all a translation units then you'd get multiple definitions. Therefore, non out-of-line definition of a static is forcibly made a compiler error.

Using static inline or static const remedies this. static inline only concretises the symbol if it is used in the translation unit and ensures the linker only selects and leaves one copy if it's defined in multiple translation units due to it being in a comdat group. const at file scope makes the compiler never emit a symbol because it's always substituted immediately in the code unless extern is used, which is not permitted in a class.

One thing to note is static inline int b; is treated as a definition whereas static const int b or static const A b; are still treated as a declaration and must be defined out-of-line if you don't define it inside the class. Interestingly static constexpr A b; is treated as a definition, whereas static constexpr int b; is an error and must have an initialiser (this is because they now become definitions and like any const/constexpr definition at file scope, they require an initialiser which an int doesn't have but a class type does because it has an implicit = A() when it is a definition -- clang allows this but gcc requires you to explicitly initialise or it is an error. This is not a problem with inline instead). static const A b = A(); is not allowed and must be constexpr or inline in order to permit an initialiser for a static object with class type i.e to make a static member of class type more than a declaration. So yes in certain situations A a; is not the same as explicitly initialising A a = A(); (the former can be a declaration but if only a declaration is allowed for that type then the latter is an error. The latter can only be used on a definition. constexpr makes it a definition). If you use constexpr and specify a default constructor then the constructor will need to be constexpr

#include<iostream>

struct A
{
    int b =2;
    mutable int c = 3; //if this member is included in the class then const A will have a full .data symbol emitted for it on -O0 and so will B because it contains A.
    static const int a = 3;
};

struct B {
    A b;
    static constexpr A c; //needs to be constexpr or inline and doesn't emit a symbol for A a mutable member on any optimisation level
};

const A a;
const B b;

int main()
{
    std::cout << a.b << b.b.b;
    return 0;
}

A static member is an outright file scope declaration extern int A::a; (which can only be made in the class and out of line definitions must refer to a static member in a class and must be definitions and cannot contain extern) whereas a non-static member is part of the complete type definition of a class and have the same rules as file scope declarations without extern. They are implicitly definitions. So int i[]; int i[5]; is a redefinition whereas static int i[]; int A::i[5]; isn't but unlike 2 externs, the compiler will still detect a duplicate member if you do static int i[]; static int i[5]; in the class.

Entity Framework change connection at runtime

I have two extension methods to convert the normal connection string to the Entity Framework format. This version working well with class library projects without copying the connection strings from app.config file to the primary project. This is VB.Net but easy to convert to C#.

Public Module Extensions

    <Extension>
    Public Function ToEntityConnectionString(ByRef sqlClientConnStr As String, ByVal modelFileName As String, Optional ByVal multipleActiceResultSet As Boolean = True)
        Dim sqlb As New SqlConnectionStringBuilder(sqlClientConnStr)
        Return ToEntityConnectionString(sqlb, modelFileName, multipleActiceResultSet)
    End Function

    <Extension>
    Public Function ToEntityConnectionString(ByRef sqlClientConnStrBldr As SqlConnectionStringBuilder, ByVal modelFileName As String, Optional ByVal multipleActiceResultSet As Boolean = True)
        sqlClientConnStrBldr.MultipleActiveResultSets = multipleActiceResultSet
        sqlClientConnStrBldr.ApplicationName = "EntityFramework"

        Dim metaData As String = "metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string='{1}'"
        Return String.Format(metaData, modelFileName, sqlClientConnStrBldr.ConnectionString)
    End Function

End Module

After that I create a partial class for DbContext:

Partial Public Class DlmsDataContext

    Public Shared Property ModelFileName As String = "AvrEntities" ' (AvrEntities.edmx)

    Public Sub New(ByVal avrConnectionString As String)
        MyBase.New(CStr(avrConnectionString.ToEntityConnectionString(ModelFileName, True)))
    End Sub

End Class

Creating a query:

Dim newConnectionString As String = "Data Source=.\SQLEXPRESS;Initial Catalog=DB;Persist Security Info=True;User ID=sa;Password=pass"

Using ctx As New DlmsDataContext(newConnectionString)
    ' ...
    ctx.SaveChanges()
End Using

MVC ajax post to controller action method

It's due to you sending one object, and you're expecting two parameters.

Try this and you'll see:

public class UserDetails
{
   public string username { get; set; }
   public string password { get; set; }
}

public JsonResult Login(UserDetails data)
{
   string error = "";
   //the rest of your code
}

How should you diagnose the error SEHException - External component has thrown an exception

if you are having a problem as describe in this post:

asp.net mvc debugger throwing SEHException

then the solution is:

if you have any application from Trusteer (like rapport or anything ) just uninstall and reboot your system, it'll work fine ... found this solution here:

http://forums.asp.net/t/1704958.aspx/8/10?Re+SEHException+thrown+when+I+run+the+application

onclick open window and specific size

Using function in typescript

openWindow(){
    //you may choose to deduct some value from current screen size
    let height = window.screen.availHeight-100;
    let width = window.screen.availWidth-150;
    window.open("http://your_url",`width=${width},height=${height}`);
}

How to draw a graph in LaTeX?

Aside from the (excellent) suggestion to use TikZ, you could use gastex. I used this before TikZ was available and it did its job too.

Display encoded html with razor

You can also simply use the HtmlString class

    @(new HtmlString(Model.Content))

Fast Bitmap Blur For Android SDK

Android Blur Guide 2016

with Showcase/Benchmark App and Source on Github. Also check out the Blur framework I'm currently working on: Dali.

After experimenting a lot I can now safely give you some solid recommendations that will make your life easier in Android when using the Android Framework.

Load and Use a downscaled Bitmap (for very blurry images)

Never use a the full size of a Bitmap. The bigger the image the more needs to be blurred and also the higher the blur radius needs to be and usually, the higher the blur radius the longer the algorithm takes.

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap blurTemplate = BitmapFactory.decodeResource(getResources(), R.drawable.myImage, options);

This will load the bitmap with inSampleSize 8, so only 1/64 of the original image. Test what inSampleSize suits your needs, but keep it 2^n (2,4,8,...) to avoid degrading quality due to scaling. See Google doc for more

Another really big advantage is that bitmap loading will be really fast. In my early blur testing I figured that the longest time during the whole blur process was the image loading. So to load a 1920x1080 image from disk my Nexus 5 needed 500ms while the blurring only took another 250 ms or so.

Use Renderscript

Renderscript provides ScriptIntrinsicBlur which is a Gaussian blur filter. It has good visual quality and is just the fastest you realistically get on Android. Google claims to be "typically 2-3x faster than a multithreaded C implementation and often 10x+ faster than a Java implementation". Renderscript is really sophisticated (using the fastest processing device (GPU, ISP, etc.), etc.) and there is also the v8 support library for it making it compatible down to 2.2. Well at least in theory, through my own tests and reports from other devs it seems that it is not possible to use Renderscript blindly, since the hardware/driver fragmentation seems to cause problems with some devices, even with higher sdk lvl (e.g. I had troubles with the 4.1 Nexus S) so be careful and test on a lot of devices. Here's a simple example that will get you started:

//define this only once if blurring multiple times
RenderScript rs = RenderScript.create(context);

(...)
//this will blur the bitmapOriginal with a radius of 8 and save it in bitmapOriginal
final Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); //use this constructor for best performance, because it uses USAGE_SHARED mode which reuses memory
final Allocation output = Allocation.createTyped(rs, input.getType());
final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setRadius(8f);
script.setInput(input);
script.forEach(output);
output.copyTo(bitmapOriginal);

When using the v8 support with Gradle, which is specifically recommended by Google "because they include the latest improvements", you only need to add 2 lines to your build script and use android.support.v8.renderscript with current build tools (updated syntax for android Gradle plugin v14+)

android {
    ...
    defaultConfig {
        ...
        renderscriptTargetApi 19
        renderscriptSupportModeEnabled true
    }
}

Simple benchmark on a Nexus 5 - comparing RenderScript with different other java and Renderscript implementations:

The average runtime per blur on different pic sizes The average runtime per blur on different pic sizes

Megapixels per sec that can be blurred Megapixels per sec that can be blurred

Each value is the avg of 250 rounds. RS_GAUSS_FAST is ScriptIntrinsicBlur (and nearly always the fastest), others that start with RS_ are mostly convolve implementations with simple kernels. The details of the algorithms can be found here. This is not purely blurring, since a good portion is garbage collection that is measured. This can be seen in this here (ScriptIntrinsicBlur on a 100x100 image with about 500 rounds)

enter image description here

The spikes are gc.

You can check for yourself, the benchmark app is in the playstore: BlurBenchmark

Reuses Bitmap wherever possible (if prio: performance > memory footprint)

If you need multiple blurs for a live blur or similar and your memory allows it do not load the bitmap from drawables multiple times, but keep it "cached" in a member variable. In this case always try to use the same variables, to keep garbage collecting to a minimum.

Also check out the new inBitmap option when loading from a file or drawable which will reuse the bitmap memory and save garbage collection time.

For blending from sharp to blurry

The simple and naive method is just to use 2 ImageViews, one blurred, and alpha fade them. But if you want a more sophisticated look that smoothly fades from sharp to blurry, then check out Roman Nurik's post about how to do it like in his Muzei app.

Basically he explains that he pre-blurs some frames with different blur extents and uses them as keyframes in an animation that looks really smooth.

Diagram where Nurik exaplains his approach

Sending JSON to PHP using ajax

I believe you could try something like this:

var postData = 
            {
                "bid":bid,
                "location1":"1","quantity1":qty1,"price1":price1,
                "location2":"2","quantity2":qty2,"price2":price2,
                "location3":"3","quantity3":qty3,"price3":price3
            }
$.ajax({
        type: "POST",
        dataType: "json",
        url: "add_cart.php",
        data: postData,
        success: function(data){
            alert('Items added');
        },
        error: function(e){
            console.log(e.message);
        }
});

the json encode should happen automatically, and a dump of your post should give you something like:

array(
    "bid"=>bid,
    "location1"=>"1",
    "quantity1"=>qty1,
    "price1"=>price1,
    "location2"=>"2",
    "quantity2"=>qty2,
    "price2"=>price2,
    "location3"=>"3",
    "quantity3"=>qty3,
    "price3"=>price3
)

Capturing "Delete" Keypress with jQuery

$('html').keyup(function(e){
    if(e.keyCode == 46) {
        alert('Delete key released');
    }
});

Source: javascript char codes key codes from www.cambiaresearch.com

Using number as "index" (JSON)

When a Javascript object property's name doesn't begin with either an underscore or a letter, you cant use the dot notation (like Game.status[0].0), and you must use the alternative notation, which is Game.status[0][0].

One different note, do you really need it to be an object inside the status array? If you're using the object like an array, why not use a real array instead?

Insert the same fixed value into multiple rows

You're looking for UPDATE not insert.

UPDATE mytable
SET    table_column = 'test';

UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).

How to send data to COM PORT using JAVA?

The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html

How can I view live MySQL queries?

Run this convenient SQL query to see running MySQL queries. It can be run from any environment you like, whenever you like, without any code changes or overheads. It may require some MySQL permissions configuration, but for me it just runs without any special setup.

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep';

The only catch is that you often miss queries which execute very quickly, so it is most useful for longer-running queries or when the MySQL server has queries which are backing up - in my experience this is exactly the time when I want to view "live" queries.

You can also add conditions to make it more specific just any SQL query.

e.g. Shows all queries running for 5 seconds or more:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND TIME >= 5;

e.g. Show all running UPDATEs:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND INFO LIKE '%UPDATE %';

For full details see: http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html

Set Colorbar Range in matplotlib

Not sure if this is the most elegant solution (this is what I used), but you could scale your data to the range between 0 to 1 and then modify the colorbar:

import matplotlib as mpl
...
ax, _ = mpl.colorbar.make_axes(plt.gca(), shrink=0.5)
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cm,
                       norm=mpl.colors.Normalize(vmin=-0.5, vmax=1.5))
cbar.set_clim(-2.0, 2.0)

With the two different limits you can control the range and legend of the colorbar. In this example only the range between -0.5 to 1.5 is show in the bar, while the colormap covers -2 to 2 (so this could be your data range, which you record before the scaling).

So instead of scaling the colormap you scale your data and fit the colorbar to that.

How to get number of entries in a Lua table?

seems when the elements of the table is added by insert method, getn will return correctly. Otherwise, we have to count all elements

mytable = {}
element1 = {version = 1.1}
element2 = {version = 1.2}
table.insert(mytable, element1)
table.insert(mytable, element2)
print(table.getn(mytable))

It will print 2 correctly

How to make a flex item not fill the height of the flex container?

The align-items, or respectively align-content attribute controls this behaviour.

align-items defines the items' positioning perpendicularly to flex-direction.

The default flex-direction is row, therfore vertical placement can be controlled with align-items.

There is also the align-self attribute to control the alignment on a per item basis.

_x000D_
_x000D_
#a {_x000D_
  display:flex;_x000D_
_x000D_
  align-items:flex-start;_x000D_
  align-content:flex-start;_x000D_
  }_x000D_
_x000D_
#a > div {_x000D_
  _x000D_
  background-color:red;_x000D_
  padding:5px;_x000D_
  margin:2px;_x000D_
  }_x000D_
 #a > #c {_x000D_
  align-self:stretch;_x000D_
 }
_x000D_
<div id="a">_x000D_
  _x000D_
  <div id="b">left</div>_x000D_
  <div id="c">middle</div>_x000D_
  <div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

css-tricks has an excellent article on the topic. I recommend reading it a couple of times.

BASH Syntax error near unexpected token 'done'

Had similar problems just now and these are two separate instances and solutions that worked for me:

Case 1. Basically, had a space after the last command within my newline-separated for-loop, eg. (imagining that | here represents the carat in a text editor showing where you are writing), this is what I saw when clicking around the end of the line of the last command in the loop:

for f in $pathToFiles
do
   $stuff |
done

Notice the space before before the carat (so far as I know, this is something cat has no option do display visually (one way you could test is with something like od -bc yourscript.sh)). Changing the code to

for f in $pathToFiles
do
   $stuff| <--- notice the carat shows no ending space before the newline
done

fixed the problem.

Case 2. Was using a pseudo try-catch block for the for-loop (see https://stackoverflow.com/a/22010339/8236733) like

{
for f in $pathToFiles
do
   { $stuff } || { echo "Failed to complete stuff"; exit 255; }
done
} || { echo "Failed to complete loop"; exit 255; }

and apparently bash did not like the nested {}s. Changing to

{
for f in $pathToFiles
do
   $stuff
done
} || { echo "Failed to complete loop"; exit 255; }

fixed the problem in this case. If anyone can further explain either of these cases, please let me know more about them in the comments.

Locking pattern for proper use of .NET MemoryCache

There is an open source library [disclaimer: that I wrote]: LazyCache that IMO covers your requirement with two lines of code:

IAppCache cache = new CachingService();
var cachedResults = cache.GetOrAdd("CacheKey", 
  () => SomeHeavyAndExpensiveCalculation());

It has built in locking by default so the cacheable method will only execute once per cache miss, and it uses a lambda so you can do "get or add" in one go. It defaults to 20 minutes sliding expiration.

There's even a NuGet package ;)

How to implement a lock in JavaScript

Some addition to JoshRiver's answer according to my case;

var functionCallbacks = [];
    var functionLock = false;
    var getData = function (url, callback) {
                   if (functionLock) {
                        functionCallbacks.push(callback);
                   } else {
                       functionLock = true;
                       functionCallbacks.push(callback);
                        $.getJSON(url, function (data) {
                            while (functionCallbacks.length) {
                                var thisCallback = functionCallbacks.pop();
                                thisCallback(data);
                            }
                            functionLock = false;
                        });
                    }
                };

// Usage
getData("api/orders",function(data){
    barChart(data);
});
getData("api/orders",function(data){
  lineChart(data);
});

There will be just one api call and these two function will consume same result.

Create a new object from type parameter in generic class

Not quite answering the question, but, there is a nice library for those kind of problems: https://github.com/typestack/class-transformer (although it won't work for generic types, as they don't really exists at run-time (here all work is done with class names (which are classes constructors)))

For instance:

import {Type, plainToClass, deserialize} from "class-transformer";

export class Foo
{
    @Type(Bar)
    public nestedClass: Bar;

    public someVar: string;

    public someMethod(): string
    {
        return this.nestedClass.someVar + this.someVar;
    }
}

export class Bar
{
    public someVar: string;
}

const json = '{"someVar": "a", "nestedClass": {"someVar": "B"}}';
const optionA = plainToClass(Foo, JSON.parse(json));
const optionB = deserialize(Foo, json);

optionA.someMethod(); // works
optionB.someMethod(); // works

How to count string occurrence in string?

Building upon @Vittim.us answer above. I like the control his method gives me, making it easy to extend, but I needed to add case insensitivity and limit matches to whole words with support for punctuation. (e.g. "bath" is in "take a bath." but not "bathing")

The punctuation regex came from: https://stackoverflow.com/a/25575009/497745 (How can I strip all punctuation from a string in JavaScript using regex?)

function keywordOccurrences(string, subString, allowOverlapping, caseInsensitive, wholeWord)
{

    string += "";
    subString += "";
    if (subString.length <= 0) return (string.length + 1); //deal with empty strings

    if(caseInsensitive)
    {            
        string = string.toLowerCase();
        subString = subString.toLowerCase();
    }

    var n = 0,
        pos = 0,
        step = allowOverlapping ? 1 : subString.length,
        stringLength = string.length,
        subStringLength = subString.length;

    while (true)
    {
        pos = string.indexOf(subString, pos);
        if (pos >= 0)
        {
            var matchPos = pos;
            pos += step; //slide forward the position pointer no matter what

            if(wholeWord) //only whole word matches are desired
            {
                if(matchPos > 0) //if the string is not at the very beginning we need to check if the previous character is whitespace
                {                        
                    if(!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchPos - 1])) //ignore punctuation
                    {
                        continue; //then this is not a match
                    }
                }

                var matchEnd = matchPos + subStringLength;
                if(matchEnd < stringLength - 1)
                {                        
                    if (!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchEnd])) //ignore punctuation
                    {
                        continue; //then this is not a match
                    }
                }
            }

            ++n;                
        } else break;
    }
    return n;
}

Please feel free to modify and refactor this answer if you spot bugs or improvements.

How to use NSJSONSerialization

Your code seems fine except the result is an NSArray, not an NSDictionary, here is an example:

The first two lines just creates a data object with the JSON, the same as you would get reading it from the net.

NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *e;
NSMutableArray *jsonList = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"jsonList: %@", jsonList);

NSLog contents (a list of dictionaries):

jsonList: (
           {
               id = 1;
               name = Aaa;
           },
           {
               id = 2;
               name = Bbb;
           }
           )

How to read data From *.CSV file using javascript?

Don't split on commas -- it won't work for most CSV files, and this question has wayyyy too many views for the asker's kind of input data to apply to everyone. Parsing CSV is kind of scary since there's no truly official standard, and lots of delimited text writers don't consider edge cases.

This question is old, but I believe there's a better solution now that Papa Parse is available. It's a library I wrote, with help from contributors, that parses CSV text or files. It's the only JS library I know of that supports files gigabytes in size. It also handles malformed input gracefully.

1 GB file parsed in 1 minute: Parsed 1 GB file in 1 minute

(Update: With Papa Parse 4, the same file took only about 30 seconds in Firefox. Papa Parse 4 is now the fastest known CSV parser for the browser.)

Parsing text is very easy:

var data = Papa.parse(csvString);

Parsing files is also easy:

Papa.parse(file, {
    complete: function(results) {
        console.log(results);
    }
});

Streaming files is similar (here's an example that streams a remote file):

Papa.parse("http://example.com/bigfoo.csv", {
    download: true,
    step: function(row) {
        console.log("Row:", row.data);
    },
    complete: function() {
        console.log("All done!");
    }
});

If your web page locks up during parsing, Papa can use web workers to keep your web site reactive.

Papa can auto-detect delimiters and match values up with header columns, if a header row is present. It can also turn numeric values into actual number types. It appropriately parses line breaks and quotes and other weird situations, and even handles malformed input as robustly as possible. I've drawn on inspiration from existing libraries to make Papa, so props to other JS implementations.

get the data of uploaded file in javascript

The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.

See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files

In this example, the user selects an HTML file. It uploaded into the <textarea>.

<form enctype="multipart/form-data">
<input id="upload" type=file   accept="text/html" name="files[]" size=30>
</form>

<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>

<script>
function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // use the 1st file from the list
    f = files[0];

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function(theFile) {
        return function(e) {

          jQuery( '#ms_word_filtered_html' ).val( e.target.result );
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsText(f);
  }

  document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

How to uninstall/upgrade Angular CLI?

Regular solution, that does not work always:

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli

Other more drastic solution:

  • Uninstall Angular CLI globally
npm uninstall -g @angular/cli
  • Uninstall Node.js & npm with uninstaller
  • Remove every environment variables related to Node.js & npm
  • Delete folders C:\Users\<user>\AppData\Roaming\npm and C:\Users\<user>\AppData\Roaming\npm-cache
  • Verify these commands are ko:
ng version
npm -v
node -v
npm install -g @angular/cli
  • Finally, check your global Angular CLI version:
ng version

Solving a "communications link failure" with JDBC and MySQL

For Windows :- Goto start menu write , "MySqlserver Instance Configuration Wizard" and reconfigure your mysql server instance. Hope it will solve your problem.

Why does GitHub recommend HTTPS over SSH?

Enabling SSH connections over HTTPS if it is blocked by firewall

Test if SSH over the HTTPS port is possible, run this SSH command:

$ ssh -T -p 443 [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.

If that worked, great! If not, you may need to follow our troubleshooting guide.

If you are able to SSH into [email protected] over port 443, you can override your SSH settings to force any connection to GitHub to run though that server and port.

To set this in your ssh config, edit the file at ~/.ssh/config, and add this section:

Host github.com
  Hostname ssh.github.com
  Port 443

You can test that this works by connecting once more to GitHub:

$ ssh -T [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.

From Authenticating to GitHub / Using SSH over the HTTPS port

function to remove duplicate characters in a string

public static void main(String[] args) {

    char[] str = { 'a', 'b', 'a','b','c','e','c' };

    for (int i = 1; i < str.length; i++) {
        for (int j = 0; j < i; j++) {
            if (str[i] == str[j]) {
                str[i] = ' ';
            }
        }

    }
    System.out.println(str);
}

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

In my case, because I had reinstalled iis, I needed to register iis with dot net 4 using this command:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

How can I force gradle to redownload dependencies?

You can do it like this

https://marschall.github.io/2017/04/17/disabling-gradle-cache.html

To quote from Disabling the Gradle Build Cache

The Gradle build cache may be a great thing when you’re regularly building >large projects with Gradle. However when only occasionally building open source >projects it can quickly become large.

To disable the Gradle build cache add the following line to ~/.gradle/gradle.properties

org.gradle.caching=false

You can clean the existing cache with

rm -rf $HOME/.gradle/caches/
rm -rf $HOME/.gradle/wrapper/

Determine command line working directory when running node bin script

Here's what worked for me:

console.log(process.mainModule.filename);

font-weight is not working properly?

I removed the text-transform: uppercase; and then set it to bold/bolder, and this seemed to work.

How to add to an existing hash in Ruby

my_hash = {:a => 5}
my_hash[:key] = "value"

Fatal error: Call to undefined function pg_connect()

I also had this problem on OSX. The solution was uncommenting the extension = pgsql.so in php.ini.default and deleting the .default suffix, since the file php.ini was not there.

If you are using XAMPP, the php.ini file resides in /XAMPP/xampfiles/etc

Git pushing to remote branch

With modern Git versions, the command to use would be:

git push -u origin <branch_name_test>

This will automatically set the branch name to track from remote and push in one go.

Select only rows if its value in a particular column is less than the value in the other column

df[df$aged <= df$laclen, ] 

Should do the trick. The square brackets allow you to index based on a logical expression.

Can you style an html radio button to look like a checkbox?

Three years after this question is posted and this is almost within reach. In fact, it's completely achievable in Firefox 1+, Chrome 1+, Safari 3+ and Opera 15+ using the CSS3 appearance property.

The result is radio elements that look like checkboxes:

_x000D_
_x000D_
input[type="radio"] {_x000D_
  -webkit-appearance: checkbox; /* Chrome, Safari, Opera */_x000D_
  -moz-appearance: checkbox;    /* Firefox */_x000D_
  -ms-appearance: checkbox;     /* not currently supported */_x000D_
}
_x000D_
<label><input type="radio" name="radio"> Checkbox 1</label>_x000D_
<label><input type="radio" name="radio"> Checkbox 2</label>
_x000D_
_x000D_
_x000D_ jsfiddle: http://jsfiddle.net/mq8Zq/

Note: this was eventually dropped from the CSS3 specification due to a lack of support and conformance from vendors. I'd recommend against implementing it unless you only need to support Webkit or Gecko based browsers.

What is the right way to populate a DropDownList from a database?

You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

For example, if you wanted to use a DataTable:

ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();

EDIT - More complete example

private void LoadSubjects()
{

    DataTable subjects = new DataTable();

    using (SqlConnection con = new SqlConnection(connectionString))
    {

        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
            adapter.Fill(subjects);

            ddlSubject.DataSource = subjects;
            ddlSubject.DataTextField = "SubjectNamne";
            ddlSubject.DataValueField = "SubjectID";
            ddlSubject.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }

    }

    // Add the initial item - you can add this even if the options from the
    // db were not successfully loaded
    ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

}

To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>

You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

from the code-behind, or you'll have two "" items.

"Parser Error Message: Could not load type" in Global.asax

My app was built in an older version of VS, and didn't have a bin folder. I had upgraded it to a newer version, and had a nightmare getting it to deploy. I finally tracked this error down to the Project > Properties > Application. The Target Framework was set to 2.0; changing it on the server to match in the IIS Manager/App Pool solved the issue for me.

Difference between signed / unsigned char

Representation is the same, the meaning is different. e.g, 0xFF, it both represented as "FF". When it is treated as "char", it is negative number -1; but it is 255 as unsigned. When it comes to bit shifting, it is a big difference since the sign bit is not shifted. e.g, if you shift 255 right 1 bit, it will get 127; shifting "-1" right will be no effect.

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

Finally tracked this down with the help of WinDBG and SOS. Access violation was being thrown by some unknown DLL. Turns out a piece of software called "Nvidia Network Manager" was causing the problems. I'd read countless times how this issue can be caused by firewalls or antivirus, neither of which I am using so I dismissed this idea. Also, I was under the assumption that it was not environmental because it occurs on more than 1 server using different hardware. Turns out all the machines I tested this on were running "NVidia Network Manager". I believe it installs with the rest of the motherboard drivers.

Hopefully this helps someone as this issue was plaguing my application for a very long time.

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

You can use the following

new java.sql.Timestamp(System.currentTimeMillis()).getTime()

Result : 1539594988651

Hope this will help. Just my suggestion and not for reward points.

Escape Character in SQL Server

To escape ' you simly need to put another before: ''

As the second answer shows it's possible to escape single quote like this:

select 'it''s escaped'

result will be

it's escaped

If you're concatenating SQL into a VARCHAR to execute (i.e. dynamic SQL), then I'd recommend parameterising the SQL. This has the benefit of helping guard against SQL injection plus means you don't have to worry about escaping quotes like this (which you do by doubling up the quotes).

e.g. instead of doing

DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = ''AAA'''
EXECUTE(@SQL)

try this:

DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = @Field1'
EXECUTE sp_executesql @SQL, N'@Field1 VARCHAR(10)', 'AAA'