Programs & Examples On #Networkcredentials

Part of Microsoft's .NET Framework that provides a base class for supplying credentials for password based authentication schemes such as basic, digest, NTLM or Kerberos.

How to set username and password for SmtpClient object in .NET?

The SmtpClient can be used by code:

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");

how to kill hadoop jobs

An unhandled exception will (assuming it's repeatable like bad data as opposed to read errors from a particular data node) eventually fail the job anyway.

You can configure the maximum number of times a particular map or reduce task can fail before the entire job fails through the following properties:

  • mapred.map.max.attempts - The maximum number of attempts per map task. In other words, framework will try to execute a map task these many number of times before giving up on it.
  • mapred.reduce.max.attempts - Same as above, but for reduce tasks

If you want to fail the job out at the first failure, set this value from its default of 4 to 1.

how to "execute" make file

You don't tend to execute the make file itself, rather you execute make, giving it the make file as an argument:

make -f pax.mk

If your make file is actually one of the standard names (like makefile or Makefile), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make man page to see which takes precedence).

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

I added TO_DATE and it resolved issue.

Before modification - due to below condition i got this error

record_update_dt>='05-May-2017'

After modification - after adding to_date, issue got resolved.

record_update_dt>=to_date('05-May-2017','DD-Mon-YYYY')

How do I catch a PHP fatal (`E_ERROR`) error?

There are certain circumstances in which even fatal errors should be caught (you might need to do some clean up before exiting gracefully and don’t just die..).

I have implemented a pre_system hook in my CodeIgniter applications so that I can get my fatal errors through emails, and this helped me finding bugs that were not reported (or were reported after they were fixed, as I already knew about them :)).

Sendemail checks if the error has already been reported so that it does not spam you with known errors multiple times.

class PHPFatalError {

    public function setHandler() {
        register_shutdown_function('handleShutdown');
    }
}

function handleShutdown() {
    if (($error = error_get_last())) {
        ob_start();
        echo "<pre>";
        var_dump($error);
        echo "</pre>";
        $message = ob_get_clean();
        sendEmail($message);
        ob_start();
        echo '{"status":"error","message":"Internal application error!"}';
        ob_flush();
        exit();
    }
}

UML diagram shapes missing on Visio 2013

Microsoft is moving away from software and database diagramming using Visio and instead transitioning into Visual Studio. See the "Modeling" Projects. Component Diagrams, Sequence Diagrams, Use Cases, Layer Diagrams are all part of the modeling project. While I am experimenting with it (but question its viability), you can generate code from the models creating in the code generation sense.

See also this post Pet Shop Models as well as the MSDN documentation: Modeling the Architectural

Here's what I have available in vs2013 ultimate Pet Shop Project

Python convert csv to xlsx

Adding an answer that exclusively uses the pandas library to read in a .csv file and save as a .xlsx file. This example makes use of pandas.read_csv (Link to docs) and pandas.dataframe.to_excel (Link to docs).

The fully reproducible example uses numpy to generate random numbers only, and this can be removed if you would like to use your own .csv file.

import pandas as pd
import numpy as np

# Creating a dataframe and saving as test.csv in current directory
df = pd.DataFrame(np.random.randn(100000, 3), columns=list('ABC'))
df.to_csv('test.csv', index = False)

# Reading in test.csv and saving as test.xlsx

df_new = pd.read_csv('test.csv')
writer = pd.ExcelWriter('test.xlsx')
df_new.to_excel(writer, index = False)
writer.save()

How to reposition Chrome Developer Tools

As of october 2014, Version 39.0.2171.27 beta (64-bit)

I needed to go in the Chrome Web Developper pan into "Settings" and uncheck Split panels vertically when docked to right

IF function with 3 conditions

You can do it this way:

=IF(E9>21,"Text 1",IF(AND(E9>=5,E9<=21),"Test 2","Text 3"))

Note I assume you meant >= and <= here since your description skipped the values 5 and 21, but you can adjust these inequalities as needed.

Or you can do it this way:

=IF(E9>21,"Text 1",IF(E9<5,"Text 3","Text 2"))

How to change the type of a field?

You can easily convert the string data type to numerical data type.
Don't forget to change collectionName & FieldName.
for ex : CollectionNmae : Users & FieldName : Contactno.

Try this query..

db.collectionName.find().forEach( function (x) {
x.FieldName = parseInt(x.FieldName);
db.collectionName.save(x);
});

How to download/checkout a project from Google Code in Windows?

If you have a github account and don't want to download software, you can export to github, then download a zip from github.

How can I verify a Google authentication API access token?

Here's an example using Guzzle:

/**
 * @param string $accessToken JSON-encoded access token as returned by \Google_Client->getAccessToken() or raw access token
 * @return array|false False if token is invalid or array in the form
 * 
 * array (
 *   'issued_to' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
 *   'audience' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
 *   'scope' => 'https://www.googleapis.com/auth/calendar',
 *   'expires_in' => 3350,
 *   'access_type' => 'offline',
 * )
 */
public static function tokenInfo($accessToken) {
    if(!strlen($accessToken)) {
        return false;
    }

    if($accessToken[0] === '{') {
        $accessToken = json_decode($accessToken)->access_token;
    }

    $guzzle = new \GuzzleHttp\Client();

    try {
        $resp = $guzzle->get('https://www.googleapis.com/oauth2/v1/tokeninfo', [
            'query' => ['access_token' => $accessToken],
        ]);
    } catch(ClientException $ex) {
        return false;
    }

    return $resp->json();
}

How to disable compiler optimizations in gcc?

For gcc you want to omit any -O1 -O2 or -O3 options passed to the compiler or if you already have them you can append the -O0 option to turn it off again. It might also help you to add -g for debug so that you can see the c source and disassembled machine code in your debugger.

See also: http://sourceware.org/gdb/onlinedocs/gdb/Optimized-Code.html

Total Number of Row Resultset getRow Method

The best way to get number of rows from resultset is using count function query for database access and then rs.getInt(1) method to get number of rows. from my code look it:

    String query = "SELECT COUNT() FROM table";
ResultSet rs = new DatabaseConnection().selectData(query);
rs.getInt(1);

this will return int value number of rows fetched from database. Here DatabaseConnection().selectData() is my code for accessing database. I was also stuck here but then solved...

Make a borderless form movable?

Let's not make things any more difficult than they need to be. I've come across so many snippets of code that allow you to drag a form around (or another Control). And many of them have their own drawbacks/side effects. Especially those ones where they trick Windows into thinking that a Control on a form is the actual form.

That being said, here is my snippet. I use it all the time. I'd also like to note that you should not use this.Invalidate(); as others like to do because it causes the form to flicker in some cases. And in some cases so does this.Refresh. Using this.Update, I have not had any flickering issues:

private bool mouseDown;
private Point lastLocation;

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        mouseDown = true;
        lastLocation = e.Location;
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if(mouseDown)
        {
            this.Location = new Point(
                (this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);

            this.Update();
        }
    }

    private void Form1_MouseUp(object sender, MouseEventArgs e)
    {
        mouseDown = false;
    }

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

How to remove all ListBox items?

I think it would be better to actually bind your listBoxes to a datasource, since it looks like you are adding the same elements to each listbox. A simple example would be something like this:

    private List<String> _weight = new List<string>() { "kilogram", "pound" };
    private List<String> _height = new List<string>() { "foot", "inch", "meter" };

    public Window1()
    {            
        InitializeComponent();
    }        

    private void Weight_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _weight;
        listBox2.ItemsSource = _weight;
    }

    private void Height_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _height;
        listBox2.ItemsSource = _height;
    }

How do I programmatically set the value of a select box element using JavaScript?

Not answering the question, but you can also select by index, where i is the index of the item you wish to select:

var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;

You can also loop through the items to select by display value with a loop:

for (var i = 0, len < formObj.leaveCode.length; i < len; i++) 
    if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;

How can I access getSupportFragmentManager() in a fragment?

You can use childFragmentManager inside Fragments.

Coding Conventions - Naming Enums

As already stated, enum instances should be uppercase according to the docs on the Oracle website (http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html).

However, while looking through a JavaEE7 tutorial on the Oracle website (http://www.oracle.com/technetwork/java/javaee/downloads/index.html), I stumbled across the "Duke's bookstore" tutorial and in a class (tutorial\examples\case-studies\dukes-bookstore\src\main\java\javaeetutorial\dukesbookstore\components\AreaComponent.java), I found the following enum definition:

private enum PropertyKeys {
    alt, coords, shape, targetImage;
}

According to the conventions, it should have looked like:

public enum PropertyKeys {
    ALT("alt"), COORDS("coords"), SHAPE("shape"), TARGET_IMAGE("targetImage");

    private final String val;

    private PropertyKeys(String val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return val;
    }
}

So it seems even the guys at Oracle sometimes trade convention with convenience.

Using a batch to copy from network drive to C: or D: drive

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

How to resolve the C:\fakepath?

seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path

Visual Studio 2012 Web Publish doesn't copy files

For what it's worth, I eventually gave up on fighting with Web Deploy to get it to do what I wanted (copy deployable files and nothing else), so I scripted it in PowerShell and am really happy with the result. It's much faster than anything I tried through MSBuild/Web Publish, presumably because those methods were still doing things I didn't need.

Here's the gist (literally):

function copy-deployable-web-files($proj_path, $deploy_dir) {
  # copy files where Build Action = "Content" 
  $proj_dir = split-path -parent $proj_path
  [xml]$xml = get-content $proj_path
  $xml.Project.ItemGroup | % { $_.Content } | % { $_.Include } | ? { $_ } | % {
    $from = "$proj_dir\$_"
    $to = split-path -parent "$deploy_dir\$_"
    if (!(test-path $to)) { md $to }
    cp $from $to
  }

  # copy everything in bin
  cp "$proj_dir\bin" $deploy_dir -recurse
}

In my case I'm calling this in a CI environment (TeamCity), but it could easily be hooked into a post-build event as well.

How to strip HTML tags from string in JavaScript?

I know this question has an accepted answer, but I feel that it doesn't work in all cases.

For completeness and since I spent too much time on this, here is what we did: we ended up using a function from php.js (which is a pretty nice library for those more familiar with PHP but also doing a little JavaScript every now and then):

http://phpjs.org/functions/strip_tags:535

It seemed to be the only piece of JavaScript code which successfully dealt with all the different kinds of input I stuffed into my application. That is, without breaking it – see my comments about the <script /> tag above.

Generate a random date between two other dates

  1. Convert your input dates to numbers (int, float, whatever is best for your usage)
  2. Choose a number between your two date numbers.
  3. Convert this number back to a date.

Many algorithms for converting date to and from numbers are already available in many operating systems.

Adding subscribers to a list using Mailchimp's API v3

If it helps anyone, here is what I got working in Python using the Python Requests library instead of CURL.

As explained by @staypuftman above, you will need your API Key and List ID from MailChimp and make sure your API Key suffix and URL prefix (i.e. us5) match.

Python:

#########################################################################################
# To add a single contact to MailChimp (using MailChimp v3.0 API), requires:
#   + MailChimp API Key
#   + MailChimp List Id for specific list
#   + MailChimp API URL for adding a single new contact
#
# Note: the API URL has a 3/4 character location subdomain at the front of the URL string. 
# It can vary depending on where you are in the world. To determine yours, check the last 
# 3/4 characters of your API key. The API URL location subdomain must match API Key 
# suffix e.g. us5, us13, us19 etc. but in this example, us5.
# (suggest you put the following 3 values in 'settings' or 'secrets' file)
#########################################################################################
MAILCHIMP_API_KEY = 'your-api-key-here-us5'
MAILCHIMP_LIST_ID = 'your-list-id-here'
MAILCHIMP_ADD_CONTACT_TO_LIST_URL = 'https://us5.api.mailchimp.com/3.0/lists/' + MAILCHIMP_LIST_ID + '/members/'

    # Create new contact data and convert into JSON as this is what MailChimp expects in the API
    # I've hardcoded some test data but use what you get from your form as appropriate
    new_contact_data_dict = {
        "email_address": "[email protected]",              # 'email_address' is a mandatory field
        "status": "subscribed",                           # 'status' is a mandatory field
        "merge_fields": {                                 # 'merge_fields' are optional:
            "FNAME": "John",                  
            "LNAME": "Smith"
        }
    }
    new_contact_data_json = json.dumps(new_contact_data_dict)

    # Create the new contact using MailChimp API using Python 'Requests' library
    req = requests.post(
        MAILCHIMP_ADD_CONTACT_TO_LIST_URL,
        data=new_contact_data_json,
        auth=('user', MAILCHIMP_API_KEY),
        headers={"content-type": "application/json"}
    )

    # debug info if required - .text and .json also list the 'merge_fields' names for use in contact JSON above
    # print req.status_code
    # print req.text
    # print req.json()

    if req.status_code == 200:
        # success - do anything you need to do
    else:
        # fail - do anything you need to do - but here is a useful debug message
        mailchimp_fail = 'MailChimp call failed calling this URL: {0}\n' \
                         'Returned this HTTP status code: {1}\n' \
                         'Returned this response text: {2}' \
                         .format(req.url, str(req.status_code), req.text)

How can I give an imageview click effect like a button on Android?

I think the easiest way is creating a new XML file. In this case, let's call it "example.xml" in the drawable folder, and put in the follow code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/blue"
          android:state_pressed="true" />

</selector>

But before that you have to set the colors in the colors.xml file, in the values folder, like this:

<resources>
    <color name="blue">#0000FF</color>
</resources>

That made, you just set the Button / ImageButton to use the new layout, like this:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/example"
/>

Then when you click that image, it will change to the color set in

<item android:drawable="@color/blue"
      android:state_pressed="true" />

giving the feedback that you want...

Oracle JDBC intermittent Connection Issue

A "connection reset" error message generally means that the other side has aborted the connection during the attempt to create a connection (the handshake). This has a lot of possible causes. A bug in the JDBC driver, a timeout at the DB side, a restart of the database, the DB being run out of available connections, poor network quality, bad virusscanner/firewall/proxy, etc.

As it happens intermittely, a bug in the JDBC driver can be less or more excluded. Left behind the remaining possible causes. I suggest to start with looking in the logs of the DB server.

jquery: how to get the value of id attribute?

$('.select_continent').click(function () {
    alert($(this).attr('value'));
});

Sending JWT token in the headers with Postman

In Postman latest version(7++) may be there is no Bearer field in Authorization So go to Header tab

select key as Authorization and in value write JWT

C++ deprecated conversion from string constant to 'char*'

Maybe you can try this:

void foo(const char* str) 
{
    // Do something
}

foo("Hello")

It works for me

Can I get div's background-image url?

I have slightly improved answer, which handles extended CSS definitions like:

background-image: url(http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png), -webkit-linear-gradient(top, rgb(81, 127, 164), rgb(48, 96, 136))

JavaScript code:

var bg = $("div").css("background-image")
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')

Result:

"http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png"

How to prevent page scrolling when scrolling a DIV element?

just offering this up as a possible solution if you don't think the user will have a negative experience on the obvious change. I simply changed the body's class of overflow to hidden when the mouse was over the target div; then I changed the body's div to hidden overflow when the mouse leaves.

Personally I don't think it looks bad, my code could use toggle to make it cleaner, and there are obvious benefits for making this effect possible without the user being aware. So this is probably the hackish-last-resort answer.

//listen mouse on and mouse off for the button
pxMenu.addEventListener("mouseover", toggleA1);
pxOptContainer.addEventListener("mouseout", toggleA2);
//show / hide the pixel option menu
function toggleA1(){
  pxOptContainer.style.display = "flex";
  body.style.overflow = "hidden";
}
function toggleA2(){
  pxOptContainer.style.display = "none";
  body.style.overflow = "hidden scroll";
}

Integrating CSS star rating into an HTML form

Here is how to integrate CSS star rating into an HTML form without using javascript (only html and css):

CSS:

.txt-center {
    text-align: center;
}
.hide {
    display: none;
}

.clear {
    float: none;
    clear: both;
}

.rating {
    width: 90px;
    unicode-bidi: bidi-override;
    direction: rtl;
    text-align: center;
    position: relative;
}

.rating > label {
    float: right;
    display: inline;
    padding: 0;
    margin: 0;
    position: relative;
    width: 1.1em;
    cursor: pointer;
    color: #000;
}

.rating > label:hover,
.rating > label:hover ~ label,
.rating > input.radio-btn:checked ~ label {
    color: transparent;
}

.rating > label:hover:before,
.rating > label:hover ~ label:before,
.rating > input.radio-btn:checked ~ label:before,
.rating > input.radio-btn:checked ~ label:before {
    content: "\2605";
    position: absolute;
    left: 0;
    color: #FFD700;
}

HTML:

<div class="txt-center">
    <form>
        <div class="rating">
            <input id="star5" name="star" type="radio" value="5" class="radio-btn hide" />
            <label for="star5">?</label>
            <input id="star4" name="star" type="radio" value="4" class="radio-btn hide" />
            <label for="star4">?</label>
            <input id="star3" name="star" type="radio" value="3" class="radio-btn hide" />
            <label for="star3">?</label>
            <input id="star2" name="star" type="radio" value="2" class="radio-btn hide" />
            <label for="star2">?</label>
            <input id="star1" name="star" type="radio" value="1" class="radio-btn hide" />
            <label for="star1">?</label>
            <div class="clear"></div>
        </div>
    </form>
</div>

Please check the demo

Keylistener in Javascript

Did you check the small Mousetrap library?

Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

This is the minimal stuff I keep for day to day Android development (including production code). Latest versions from API 25 to API 27 (Nougat to Android P) included only, and you can work great with it.

  • To minimize even more, just keep any one of the below versions as same and keep a lower versions i.e. API 16 with same files downloaded as below.

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

phc allows you to compile PHP programs into shared libraries, which can be uploaded to the server. The PHP program is compiled into binaries. It's done in such a way as to support evals, includes, and the entire PHP standard library.

Copy multiple files in Python

def recursive_copy_files(source_path, destination_path, override=False):
    """
    Recursive copies files from source  to destination directory.
    :param source_path: source directory
    :param destination_path: destination directory
    :param override if True all files will be overridden otherwise skip if file exist
    :return: count of copied files
    """
    files_count = 0
    if not os.path.exists(destination_path):
        os.mkdir(destination_path)
    items = glob.glob(source_path + '/*')
    for item in items:
        if os.path.isdir(item):
            path = os.path.join(destination_path, item.split('/')[-1])
            files_count += recursive_copy_files(source_path=item, destination_path=path, override=override)
        else:
            file = os.path.join(destination_path, item.split('/')[-1])
            if not os.path.exists(file) or override:
                shutil.copyfile(item, file)
                files_count += 1
    return files_count

How to change xampp localhost to another folder ( outside xampp folder)?

just in case someone looks for this, the path to the file on Sourav answer (httpd.conf) in linux is /opt/lampp/etc/httpd.conf

How can I get the current page name in WordPress?

We just need to use the "post" global variable:

global $post;
echo $post->post_title;

This will echo the current page/post title.

How to set the environmental variable LD_LIBRARY_PATH in linux

Alternatively you can execute program with specified library dir:

/lib/ld-linux.so.2 --library-path PATH EXECUTABLE

Read more here.

Laravel PHP Command Not Found

Solution on link http://tutsnare.com/laravel-command-not-found-ubuntu-mac/

In terminal

# download installer
composer global require "laravel/installer=~1.1"
#setting up path
export PATH="~/.composer/vendor/bin:$PATH" 
# check laravel command
laravel 

# download installer
composer global require "laravel/installer=~1.1"

nano ~/.bashrc

#add

alias laravel='~/.composer/vendor/bin/laravel'

source ~/.bashrc

laravel

# going to html dir to create project there
cd /var/www/html/
# install project in blog dir.
laravel new blog

Get file size before uploading

Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.

ActiveX warning

If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).

function getFileSize(fileInputElement){
    if (!fileInputElement.value ||
        typeof fileInputElement.files === 'undefined' ||
        typeof fileInputElement.files[0] === 'undefined' ||
        typeof fileInputElement.files[0].size !== 'number'
    ) {
        // File size is undefined.
        return undefined;
    }

    return fileInputElement.files[0].size;
}

What is the string concatenation operator in Oracle?

DECLARE
     a      VARCHAR2(30);
     b      VARCHAR2(30);
     c      VARCHAR2(30);
 BEGIN
      a  := ' Abc '; 
      b  := ' def ';
      c  := a || b;
 DBMS_OUTPUT.PUT_LINE(c);  
   END;

output:: Abc def

Default optional parameter in Swift function

It is little tricky when you try to combine optional parameter and default value for that parameter. Like this,

func test(param: Int? = nil)

These two are completely opposite ideas. When you have an optional type parameter but you also provide default value to it, it is no more an optional type now since it has a default value. Even if the default is nil, swift simply removes the optional binding without checking what the default value is.

So it is always better not to use nil as default value.

Does not contain a definition for and no extension method accepting a first argument of type could be found

There are two cases in which this error is raised.

  1. You didn't declare the variable which is used
  2. You didn't create the instances of the class

How to run a single test with Mocha?

Consolidate all your tests in one test.js file & your package json add scripts as:

  "scripts": {
  "api:test": "node_modules/.bin/mocha --timeout 10000 --recursive api_test/"
},

Type command on your test directory:

npm run api:test

HTML: Changing colors of specific words in a string of text

You could use the longer boringer way

_x000D_
_x000D_
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">Enter the competition by</p><p style="font-size:14px; color:#ff00; font-weight:bold; font-style:italic;">summer</p> 
_x000D_
_x000D_
_x000D_

you get the point for the rest

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

Find text in string with C#

If you know that you always want the string between "my" and "is", then you can always perform the following:

string message = "This is an example string and my data is here";

//Get the string position of the first word and add two (for it's length)
int pos1 = message.IndexOf("my") + 2;

//Get the string position of the next word, starting index being after the first position
int pos2 = message.IndexOf("is", pos1);

//use substring to obtain the information in between and store in a new string
string data = message.Substring(pos1, pos2 - pos1).Trim();

Meaning of - <?xml version="1.0" encoding="utf-8"?>

This is the XML optional preamble.

  • version="1.0" means that this is the XML standard this file conforms to
  • encoding="utf-8" means that the file is encoded using the UTF-8 Unicode encoding

Extract the first (or last) n characters of a string

Make it simple and use R basic functions:

# To get the LEFT part:
> substr(a, 1, 4)
[1] "left"
> 
# To get the MIDDLE part:
> substr(a, 3, 7)
[1] "ftrig"
> 
# To get the RIGHT part:
> substr(a, 5, 10)
[1] "right"

The substr() function tells you where start and stop substr(x, start, stop)

find difference between two text files with one item per line

A tried a slight variation on Luca's answer and it worked for me.

diff file1 file2 | grep ">" | sed 's/^> //g' > diff_file

Note that the searched pattern in sed is a > followed by a space.

Sum of two input value by jquery

Your code is correct, except you are adding (concatenating) strings, not adding integers. Just change your code into:

function compute() {
    if ( $('input[name=type]:checked').val() != undefined ) {
        var a = parseInt($('input[name=service_price]').val());
        var b = parseInt($('input[name=modem_price]').val());
        var total = a+b;
        $('#total_price').val(a+b);
    }
}

and this should work.

Here is some working example that updates the sum when the value when checkbox is checked (and if this is checked, the value is also updated when one of the fields is changed): jsfiddle.

JAVA_HOME and PATH are set but java -version still shows the old one

update-java-alternatives

The java executable is not found with your JAVA_HOME, it only depends on your PATH.

update-java-alternatives is a good way to manage it for the entire system is through:

update-java-alternatives -l

Sample output:

java-7-oracle 1 /usr/lib/jvm/java-7-oracle
java-8-oracle 2 /usr/lib/jvm/java-8-oracle

Choose one of the alternatives:

sudo update-java-alternatives -s java-7-oracle

Like update-alternatives, it works through symlink management. The advantage is that is manages symlinks to all the Java utilities at once: javac, java, javap, etc.

I am yet to see a JAVA_HOME effect on the JDK. So far, I have only seen it used in third-party tools, e.g. Maven.

Java Switch Statement - Is "or"/"and" possible?

Above, you mean OR not AND. Example of AND: 110 & 011 == 010 which is neither of the things you're looking for.

For OR, just have 2 cases without the break on the 1st. Eg:

case 'a':
case 'A':
  // do stuff
  break;

Pass mouse events through absolutely-positioned element

If all you need is mousedown, you may be able to make do with the document.elementFromPoint method, by:

  1. removing the top layer on mousedown,
  2. passing the x and y coordinates from the event to the document.elementFromPoint method to get the element underneath, and then
  3. restoring the top layer.

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

In order to resolve this on an operating system level in an Ubuntu installation check the following:

$ locale charmap

If you get

locale: Cannot set LC_CTYPE to default locale: No such file or directory

instead of

UTF-8

then set LC_CTYPE and LC_ALL like this:

$ export LC_ALL="en_US.UTF-8"
$ export LC_CTYPE="en_US.UTF-8"

jquery draggable: how to limit the draggable area?

See excerpt from official documentation for containment option:

containment

Default: false

Constrains dragging to within the bounds of the specified element or region.
Multiple types supported:

  • Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
  • Element: The draggable element will be contained to the bounding box of this element.
  • String: Possible values: "parent", "document", "window".
  • Array: An array defining a bounding box in the form [ x1, y1, x2, y2 ].

Code examples:
Initialize the draggable with the containment option specified:

$( ".selector" ).draggable({
    containment: "parent" 
}); 

Get or set the containment option, after initialization:

// Getter
var containment = $( ".selector" ).draggable( "option", "containment" );
// Setter
$( ".selector" ).draggable( "option", "containment", "parent" );

How to convert a private key to an RSA private key?

Newer versions of OpenSSL say BEGIN PRIVATE KEY because they contain the private key + an OID that identifies the key type (this is known as PKCS8 format). To get the old style key (known as either PKCS1 or traditional OpenSSL format) you can do this:

openssl rsa -in server.key -out server_new.key

Alternately, if you have a PKCS1 key and want PKCS8:

openssl pkcs8 -topk8 -nocrypt -in privkey.pem

How to check if a line is blank using regex

Full credit to bchr02 for this answer. However, I had to modify it a bit to catch the scenario for lines that have */ (end of comment) followed by an empty line. The regex was matching the non empty line with */.

New: (^(\r\n|\n|\r)$)|(^(\r\n|\n|\r))|^\s*$/gm

All I did is add ^ as second character to signify the start of line.

How to set radio button selected value using jquery

A clean approach I find is by giving an ID for each radio button and then setting it by using the following statement:

document.getElementById('publicedit').checked = true;

Dynamically adding properties to an ExpandoObject

i think this add new property in desired type without having to set a primitive value, like when property defined in class definition

var x = new ExpandoObject();
x.NewProp = default(string)

How to use OAuth2RestTemplate?

I have different approach if you want access token and make call to other resource system with access token in header

Spring Security comes with automatic security: oauth2 properties access from application.yml file for every request and every request has SESSIONID which it reads and pull user info via Principal, so you need to make sure inject Principal in OAuthUser and get accessToken and make call to resource server

This is your application.yml, change according to your auth server:

security:
  oauth2:
    client:
      clientId: 233668646673605
      clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
      accessTokenUri: https://graph.facebook.com/oauth/access_token
      userAuthorizationUri: https://www.facebook.com/dialog/oauth
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
    resource:
      userInfoUri: https://graph.facebook.com/me

@Component
public class OAuthUser implements Serializable {

private static final long serialVersionUID = 1L;

private String authority;

@JsonIgnore
private String clientId;

@JsonIgnore
private String grantType;
private boolean isAuthenticated;
private Map<String, Object> userDetail = new LinkedHashMap<String, Object>();

@JsonIgnore
private String sessionId;

@JsonIgnore
private String tokenType;

@JsonIgnore
private String accessToken;

@JsonIgnore
private Principal principal;

public void setOAuthUser(Principal principal) {
    this.principal = principal;
    init();
}

public Principal getPrincipal() {
    return principal;
}

private void init() {
    if (principal != null) {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
        if (oAuth2Authentication != null) {
            for (GrantedAuthority ga : oAuth2Authentication.getAuthorities()) {
                setAuthority(ga.getAuthority());
            }
            setClientId(oAuth2Authentication.getOAuth2Request().getClientId());
            setGrantType(oAuth2Authentication.getOAuth2Request().getGrantType());
            setAuthenticated(oAuth2Authentication.getUserAuthentication().isAuthenticated());

            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) oAuth2Authentication
                    .getDetails();
            if (oAuth2AuthenticationDetails != null) {
                setSessionId(oAuth2AuthenticationDetails.getSessionId());
                setTokenType(oAuth2AuthenticationDetails.getTokenType());

            // This is what you will be looking for 
                setAccessToken(oAuth2AuthenticationDetails.getTokenValue());
            }

    // This detail is more related to Logged-in User
            UsernamePasswordAuthenticationToken userAuthenticationToken = (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();
            if (userAuthenticationToken != null) {
                LinkedHashMap<String, Object> detailMap = (LinkedHashMap<String, Object>) userAuthenticationToken.getDetails();
                if (detailMap != null) {
                    for (Map.Entry<String, Object> mapEntry : detailMap.entrySet()) {
                        //System.out.println("#### detail Key = " + mapEntry.getKey());
                        //System.out.println("#### detail Value = " + mapEntry.getValue());
                        getUserDetail().put(mapEntry.getKey(), mapEntry.getValue());
                    }

                }

            }

        }

    }
}


public String getAuthority() {
    return authority;
}

public void setAuthority(String authority) {
    this.authority = authority;
}

public String getClientId() {
    return clientId;
}

public void setClientId(String clientId) {
    this.clientId = clientId;
}

public String getGrantType() {
    return grantType;
}

public void setGrantType(String grantType) {
    this.grantType = grantType;
}

public boolean isAuthenticated() {
    return isAuthenticated;
}

public void setAuthenticated(boolean isAuthenticated) {
    this.isAuthenticated = isAuthenticated;
}

public Map<String, Object> getUserDetail() {
    return userDetail;
}

public void setUserDetail(Map<String, Object> userDetail) {
    this.userDetail = userDetail;
}

public String getSessionId() {
    return sessionId;
}

public void setSessionId(String sessionId) {
    this.sessionId = sessionId;
}

public String getTokenType() {
    return tokenType;
}

public void setTokenType(String tokenType) {
    this.tokenType = tokenType;
}

public String getAccessToken() {
    return accessToken;
}

public void setAccessToken(String accessToken) {
    this.accessToken = accessToken;
}

@Override
public String toString() {
    return "OAuthUser [clientId=" + clientId + ", grantType=" + grantType + ", isAuthenticated=" + isAuthenticated
            + ", userDetail=" + userDetail + ", sessionId=" + sessionId + ", tokenType="
            + tokenType + ", accessToken= " + accessToken + " ]";
}

@RestController
public class YourController {

@Autowired
OAuthUser oAuthUser;

// In case if you want to see Profile of user then you this 
@RequestMapping(value = "/profile", produces = MediaType.APPLICATION_JSON_VALUE)
public OAuthUser user(Principal principal) {
    oAuthUser.setOAuthUser(principal);

    // System.out.println("#### Inside user() - oAuthUser.toString() = " + oAuthUser.toString());

    return oAuthUser;
}


@RequestMapping(value = "/createOrder",
        method = RequestMethod.POST,
        headers = {"Content-type=application/json"},
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public FinalOrderDetail createOrder(@RequestBody CreateOrder createOrder) {

    return postCreateOrder_restTemplate(createOrder, oAuthUser).getBody();
}


private ResponseEntity<String> postCreateOrder_restTemplate(CreateOrder createOrder, OAuthUser oAuthUser) {

String url_POST = "your post url goes here";

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Authorization", String.format("%s %s", oAuthUser.getTokenType(), oAuthUser.getAccessToken()));
    headers.add("Content-Type", "application/json");

    RestTemplate restTemplate = new RestTemplate();
    //restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpEntity<String> request = new HttpEntity<String>(createOrder, headers);

    ResponseEntity<String> result = restTemplate.exchange(url_POST, HttpMethod.POST, request, String.class);
    System.out.println("#### post response = " + result);

    return result;
}


}

Select all where [first letter starts with B]

This will work for MYSQL

SELECT Name FROM Employees WHERE Name REGEXP '^[B].*$'

In this REGEXP stands for regular expression

and

this is for T-SQL

SELECT Name FROM Employees WHERE Name LIKE '[B]%'

How to clean node_modules folder of packages that are not in package.json?

Due to its folder nesting Windows can’t delete the folder as its name is too long. To solve this, install RimRaf:

npm install rimraf -g

rimraf node_modules

Using Helvetica Neue in a Website

They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).

In your example "HelveticaNeue-Light" will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light" and finally "Helvetica Neue".

As far as I'm aware "Helvetica Neue" isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif" or "sans-serif" as a final default position.

In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.

A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.

How to get a variable name as a string in PHP?

I was looking for this but just decided to pass the name in, I usually have the name in the clipboard anyway.

function VarTest($my_var,$my_var_name){
    echo '$'.$my_var_name.': '.$my_var.'<br />';
}

$fruit='apple';
VarTest($fruit,'fruit');

ImportError: Cannot import name X

You have circular dependent imports. physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing. Remove the dependency to physics from entity module.

Setting Inheritance and Propagation flags with set-acl and powershell

Here's some succinct Powershell code to apply new permissions to a folder by modifying it's existing ACL (Access Control List).

# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path 'C:\DemoFolder'

# Set the permissions that you want to apply to the folder
$permissions = $env:username, 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'

# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions

# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)

# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path 'C:\DemoFolder'

Each of the values in the $permissions variable list pertain to the parameters of this constructor for the FileSystemAccessRule class.

Courtesy of this page.

How to draw a filled triangle in android canvas?

You probably need to do something like :

Paint red = new Paint();

red.setColor(android.graphics.Color.RED);
red.setStyle(Paint.Style.FILL);

And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.

Tell me if it works please !

Testing pointers for validity (C/C++)

AFAIK there is no way. You should try to avoid this situation by always setting pointers to NULL after freeing memory.

Remove an array element and shift the remaining ones

If you are most concerned about code size and/or performance (also for WCET analysis, if you need one), I think this is probably going to be one of the more transparent solutions (for finding and removing elements):

unsigned int l=0, removed=0;

for( unsigned int i=0; i<count; i++ ) {
    if( array[i] != to_remove )
        array[l++] = array[i];
    else
        removed++;
}

count -= removed;

Why use deflate instead of gzip for text files served by Apache?

On Ubuntu with Apache2 and the deflate module already installed (which it is by default), you can enable deflate gzip compression in two easy steps:

a2enmod deflate
/etc/init.d/apache2 force-reload

And you're away! I found pages I served over my adsl connection loaded much faster.

Edit: As per @GertvandenBerg's comment, this enables gzip compression, not deflate.

Oracle SQL Developer - tables cannot be seen

The answer about going under "Other Users" was close, but not nearly explicit enough, so I felt the need to add this answer, below.

In Oracle, it will only show you tables that belong to schemas (databases in MS SQL Server) that are owned by the account you are logged in with. If the account owns/has created nothing, you will see nothing, even if you have rights/permissions to everything in the database! (This is contrary to MS SQL Server Management Studio, where you can see anything you have rights on and the owner is always "dbo", barring some admin going in and changing it for some unforeseeable reason.)

The owner will be the only one who will see those tables under "Tables" in the tree. If you do not see them because you are not their owner, you will have to go under "Other Users" and expand each user until you find out who created/owns that schema, if you do not know it, already. It will not matter if your account has permissions to the tables or not, you still have to go under "Other Users" and find that user that owns it to see it, under "Tables"!

One thing that can help you: when you write queries, you actually specify in the nomenclature who that owner is, ex.

Select * from admin.mytable

indicates that "admin" is the user that owns it, so you go under "Other Users > Admin" and expand "Tables" and there it is.

In PHP how can you clear a WSDL cache?

I recommend using a cache-buster in the wsdl url.

In our apps we use a SVN Revision id in the wsdl url so the client immediately knows of changing structures. This works on our app because, everytime we change the server-side, we also need to adjust the client accordingly.

$client = new SoapClient('http://somewhere.com/?wsdl&rev=$Revision$');

This requires svn to be configured properly. Not on all repositories this is enabled by default.

In case you are not responsible for both components (server,client) or you don't use SVN you may find another indicator which can be utilised as a cache-buster in your wsdl url.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

I had a similar problem but all answers here didn't help me.

For me the problem was a failing test. If you are doing test driven development than a failing / not implemented test shouldn't break the build. I still want my project to build.

To solve this I added a configuration to surefire so that it ignores a failing test.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <testFailureIgnore>true</testFailureIgnore>
    </configuration>
</plugin>

How do I use the nohup command without getting nohup.out?

Have you tried redirecting all three I/O streams:

nohup ./yourprogram > foo.out 2> foo.err < /dev/null &

How to declare a variable in SQL Server and use it in the same Stored Procedure

What's going wrong with what you have? What error do you get, or what result do or don't you get that doesn't match your expectations?

I can see the following issues with that SP, which may or may not relate to your problem:

  • You have an extraneous ) after @BrandName in your SELECT (at the end)
  • You're not setting @CategoryID or @BrandName to anything anywhere (they're local variables, but you don't assign values to them)

Edit Responding to your comment: The error is telling you that you haven't declared any parameters for the SP (and you haven't), but you called it with parameters. Based on your reply about @CategoryID, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:

CREATE PROCEDURE AddBrand
   @BrandName nvarchar(50),
   @CategoryID int
AS
BEGIN
   DECLARE @BrandID int

   SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName

   INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
END

You would then call this like this:

EXEC AddBrand 'Gucci', 23

...assuming the brand name was 'Gucci' and category ID was 23.

How do I add space between two variables after a print in Python

Alternatively you can use ljust/rjust to make the formatting nicer.

print "%s%s" % (str(count).rjust(10), conv)

or

print str(count).ljust(10), conv

Git pull after forced update

This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:

git checkout some-branch   # where some-branch can be replaced by any other branch
git branch base-branch -D  # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch  # recreating branch with correct commits

Note: You can combine these all by putting && between them

Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?

Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.

Ex:

git checkout feature-old  # some branch with the extra commits
git log                   # gives commits (write down the id of the ones you want)
git checkout base-branch  # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd   # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch

Now feature-new is your branch without the extra (possibly bad) commits!

bash echo number of lines of file given in a bash variable without the file name

wc can't get the filename if you don't give it one.

wc -l < "$JAVA_TAGS_FILE"

Merge / convert multiple PDF files into one PDF

pdfunite is fine to merge entire PDFs. If you want, for example, pages 2-7 from file1.pdf and pages 1,3,4 from file2.pdf, you have to use pdfseparate to split the files into separate PDFs for each page to give to pdfunite.

At that point you probably want a program with more options. qpdf is the best utility I've found for manipulating PDFs. pdftk is bigger and slower and Red Hat/Fedora don't package it because of its dependency on gcj. Other PDF utilities have Mono or Python dependencies. I found qpdf produced a much smaller output file than using pdfseparate and pdfunite to assemble pages into a 30-page output PDF, 970kB vs. 1,6450 kB. Because it offers many more options, qpdf's command line is not as simple; the original request to merge file1 and file2 can be performed with

qpdf --empty --pages file1.pdf file2.pdf -- merged.pdf

Switch statement for string matching in JavaScript

var token = 'spo';

switch(token){
    case ( (token.match(/spo/) )? token : undefined ) :
       console.log('MATCHED')    
    break;;
    default:
       console.log('NO MATCH')
    break;;
}


--> If the match is made the ternary expression returns the original token
----> The original token is evaluated by case

--> If the match is not made the ternary returns undefined
----> Case evaluates the token against undefined which hopefully your token is not.

The ternary test can be anything for instance in your case

( !!~ base_url_string.indexOf('xxx.dev.yyy.com') )? xxx.dev.yyy.com : undefined 

===========================================

(token.match(/spo/) )? token : undefined ) 

is a ternary expression.

The test in this case is token.match(/spo/) which states the match the string held in token against the regex expression /spo/ ( which is the literal string spo in this case ).

If the expression and the string match it results in true and returns token ( which is the string the switch statement is operating on ).

Obviously token === token so the switch statement is matched and the case evaluated

It is easier to understand if you look at it in layers and understand that the turnery test is evaluated "BEFORE" the switch statement so that the switch statement only sees the results of the test.

Program "make" not found in PATH

Probably there are some files inside C:\cygwin\bin called xxxxxmake.exe, try renaming it to make.exe

How to serve an image using nodejs

I like using Restify for REST services. In my case, I had created a REST service to serve up images and then if an image source returned 404/403, I wanted to return an alternative image. Here's what I came up with combining some of the stuff here:

function processRequest(req, res, next, url) {
    var httpOptions = {
        hostname: host,
        path: url,
        port: port,
        method: 'GET'
    };

    var reqGet = http.request(httpOptions, function (response) {
        var statusCode = response.statusCode;

        // Many images come back as 404/403 so check explicitly
        if (statusCode === 404 || statusCode === 403) {
            // Send default image if error
            var file = 'img/user.png';
            fs.stat(file, function (err, stat) {
                var img = fs.readFileSync(file);
                res.contentType = 'image/png';
                res.contentLength = stat.size;
                res.end(img, 'binary');
            });

        } else {
            var idx = 0;
            var len = parseInt(response.header("Content-Length"));
            var body = new Buffer(len);

            response.setEncoding('binary');

            response.on('data', function (chunk) {
                body.write(chunk, idx, "binary");
                idx += chunk.length;
            });

            response.on('end', function () {
                res.contentType = 'image/jpg';
                res.send(body);
            });

        }
    });

    reqGet.on('error', function (e) {
        // Send default image if error
        var file = 'img/user.png';
        fs.stat(file, function (err, stat) {
            var img = fs.readFileSync(file);
            res.contentType = 'image/png';
            res.contentLength = stat.size;
            res.end(img, 'binary');
        });
    });

    reqGet.end();

    return next();
}

How to get all of the IDs with jQuery?

HTML

<div id="mydiv">
 <span id='span1'>
 <span id='span2'>
</div>

JQuery

var IDs = [];
$("#mydiv").find("span").each(function(){ IDs.push($(this).attr("id")); });

Base64 encoding and decoding in client-side Javascript

Short and fast Base64 JavaScript Decode Function without Failsafe:

function decode_base64 (s)
{
    var e = {}, i, k, v = [], r = '', w = String.fromCharCode;
    var n = [[65, 91], [97, 123], [48, 58], [43, 44], [47, 48]];

    for (z in n)
    {
        for (i = n[z][0]; i < n[z][1]; i++)
        {
            v.push(w(i));
        }
    }
    for (i = 0; i < 64; i++)
    {
        e[v[i]] = i;
    }

    for (i = 0; i < s.length; i+=72)
    {
        var b = 0, c, x, l = 0, o = s.substring(i, i+72);
        for (x = 0; x < o.length; x++)
        {
            c = e[o.charAt(x)];
            b = (b << 6) + c;
            l += 6;
            while (l >= 8)
            {
                r += w((b >>> (l -= 8)) % 256);
            }
         }
    }
    return r;
}

How to implement class constants?

You can mark properties with readonly modifier in your declaration:

export class MyClass {
  public static readonly MY_PUBLIC_CONSTANT = 10;
  private static readonly myPrivateConstant = 5;
}

@see TypeScript Deep Dive book - Readonly

Passing additional variables from command line to make

From the manual:

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment.

So you can do (from bash):

FOOBAR=1 make

resulting in a variable FOOBAR in your Makefile.

How good is Java's UUID.randomUUID?

I'm not an expert, but I'd assume that enough smart people looked at Java's random number generator over the years. Hence, I'd also assume that random UUIDs are good. So you should really have the theoretical collision probability (which is about 1 : 3 × 10^38 for all possible UUIDs. Does anybody know how this changes for random UUIDs only? Is it 1/(16*4) of the above?)

From my practical experience, I've never seen any collisions so far. I'll probably have grown an astonishingly long beard the day I get my first one ;)

encapsulation vs abstraction real world example

Abstraction : you'll never buy a "device", but always buy something more specific : iPhone, GSII, Nokia 3310... Here, iPhone, GSII and N3310 are concrete things, device is abstract.

Encapsulation : you've got several devices, all of them have got a USB port. You don't know what kind of printed circuit there's back, you just have to know you'll be able to plug a USB cable into it.

Abstraction is a concept, which is allowed by encapsulation. My example wasn't the best one (there's no real link between the two blocks).

You can do encapsulation without using abstraction, but if you wanna use some abstraction in your projects, you'll need encapsulation.

C++, copy set to vector

here's another alternative using vector::assign:

theVector.assign(theSet.begin(), theSet.end());

PHP add elements to multidimensional array with array_push

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);

Find the nth occurrence of substring in a string

The replace one liner is great but only works because XX and bar have the same lentgh

A good and general def would be:

def findN(s,sub,N,replaceString="XXX"):
    return s.replace(sub,replaceString,N-1).find(sub) - (len(replaceString)-len(sub))*(N-1)

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

jus do this import { shallow, mount } from "enzyme";

const store = mockStore({
  startup: { complete: false }
});

describe("==== Testing App ======", () => {
  const setUpFn = props => {
    return mount(
      <Provider store={store}>
        <App />
      </Provider>
    );
  };

  let wrapper;
  beforeEach(() => {
    wrapper = setUpFn();
  });

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

You can simply pass to "default" instead of "ON". Seems more adherent to Apple logic.

(but all the other comments about the use of @obj remains valid.)

What should a JSON service return on failure / error

The HTTP status code you return should depend on the type of error that has occurred. If an ID doesn't exist in the database, return a 404; if a user doesn't have enough privileges to make that Ajax call, return a 403; if the database times out before being able to find the record, return a 500 (server error).

jQuery automatically detects such error codes, and runs the callback function that you define in your Ajax call. Documentation: http://api.jquery.com/jQuery.ajax/

Short example of a $.ajax error callback:

$.ajax({
  type: 'POST',
  url: '/some/resource',
  success: function(data, textStatus) {
    // Handle success
  },
  error: function(xhr, textStatus, errorThrown) {
    // Handle error
  }
});

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

The term 'Get-ADUser' is not recognized as the name of a cmdlet

If you don't see the Active Directory, it's because you did not install AD LS Users and Computer Feature. Go to Manage - Add Roles & Features. Within Add Roles and Features Wizard, on Features tab, select Remote Server Administration Tools, select - Role Admininistration Tools - Select AD DS and DF LDS Tools.

After that, you can see the PS Active Directory package.

Getting list of tables, and fields in each, in a database

Tables ::

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

columns ::

SELECT * FROM INFORMATION_SCHEMA.COLUMNS 

or

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='your_table_name'

Convert string to symbol-able in ruby

"Book Author Title".parameterize('_').to_sym
=> :book_author_title

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize

parameterize is a rails method, and it lets you choose what you want the separator to be. It is a dash "-" by default.

How can I insert values into a table, using a subquery with more than one result?

the sub query looks like

 insert into table_name (col1,col2,....) values (select col1,col2,... FROM table_2 ...)

hope this help

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

Python loop to run for certain amount of seconds

If I understand you, you can do it with a datetime.timedelta -

import datetime

endTime = datetime.datetime.now() + datetime.timedelta(minutes=15)
while True:
  if datetime.datetime.now() >= endTime:
    break
  # Blah
  # Blah

How can I make one python file run another?

There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):

  1. Treat it like a module: import file. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is called file.py, your import should not include the .py extension at the end.
  2. The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.
    • execfile('file.py') in Python 2
    • exec(open('file.py').read()) in Python 3
  3. Spawn a shell process: os.system('python file.py'). Use when desperate.

How to get start and end of day in Javascript?

I prefer to use date-fns library for date manipulating. It is really great modular and consistent tool. You can get start and end of the day this way:

_x000D_
_x000D_
var startOfDay = dateFns.startOfDay;_x000D_
var endOfDay = dateFns.endOfDay;_x000D_
_x000D_
console.log('start of day ==> ', startOfDay(new Date('2015-11-11')));_x000D_
console.log('end of day ==> ', endOfDay(new Date('2015-11-11')));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
_x000D_
_x000D_
_x000D_

how to get files from <input type='file' .../> (Indirect) with javascript

Above answers are pretty sufficient. Additional to the onChange, if you upload a file using drag and drop events, you can get the file in drop event by accessing eventArgs.dataTransfer.files.

Unknown SSL protocol error in connection

You can get more information with

# Windows
set GIT_CURL_VERBOSE=1
set GIT_TRACE_PACKET=2

# Unix
export GIT_CURL_VERBOSE=1
export GIT_TRACE_PACKET=2

And then try a git push.

Double-check your proxy settings if you have one.

Note: git 2.8 (March 2016) adds more information on an error 35:

See commit 0054045 (14 Feb 2016) by Shawn Pearce (spearce).
(Merged by Junio C Hamano -- gitster -- in commit 97c49af, 24 Feb 2016)

remote-curl: include curl_errorstr on SSL setup failures

For curl error 35 (CURLE_SSL_CONNECT_ERROR) users need the additional text stored in CURLOPT_ERRORBUFFER to debug why the connection did not start.
This is curl_errorstr inside of http.c, so include that in the message if it is non-empty.


Also check out the common causes for that message:

If it was working before, and not working today, it is possible the SSL private key has expired on the BitBucket side (see below, reason #3), but that doesn't seem to be the case here (the certificate is valid until 12/03/2014).


The Destination Site Does Not Like the Protocol

Firing off a request like the following, results in the Unknown SSL Protocol error:

curl --sslv2 https://techstacks-tools.appspot.com/

Why? Well, in this case it is because the techstacks tools site does not support SSLv2, thus, generating the curl (35) error.

The Destination Site Does Not Like the Cipher

You could be trying to connect to the site using an ssl cipher that the site is configured to reject.
For example, anonymous ciphers are typically disabled on ssl-encrypted sites that are customer-facing. (Many of us set a blanket rejection policy on any SSL-encrypted web site—regardless of it's purpose.)
The following command string "can" also result in the curl (35) error:

curl --ciphers ADH-RC4-MD5 https://some_web_site.some_domain.com/

Unfortunately, the type of error response you can get from curl depends largely upon the ssl server. On some sites, you'll receive the Unknown SSL Protocol error but on my techstacks-tools site, I get:

curl: (35) error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure

Kudos to Google because this particular error is a bit more descriptive than the one my websites at work generate because this at least tells you that a ssl socket was started but because of handshake failures, the socket was never able to complete.

Try connecting to the site with a cipher that the site supports. Not sure which cipher to use? Well, let me introduce my cryptonark ssl cipher tester...

The SSL Private Key Has Expired

I came across this one earlier today working with an old WebSeAL site.
In IBM GSKit, you can specify how long the private key password is valid. After reaching a certain date, you will still be able to get webseal started and listening on port 443 (or whatever you set your https-port value to) but you will not be able to successfully negotiate an SSL session.
In today's case, the old WebSEAL instance was using long-expired kdb file with a long expired private key password. Once replaced with the correct, more-up-to-date version, everything worked again.

Improper redirection

Some ISP's and DNS providers like to intercept your failed DNS queries in order to redirect you to a search engine results-style page offering you alternative URLs or "Did you mean...?" counter-query results.
If you see an error like this:

 error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol, 

it could be due to you typing the hostname incorrectly or the hostname is not yet tabled in your DNS. You can verify that with a simple "host" or "nslookup".


Note (August 2015): Git 2.6+ (Q3 2015) will allow to specify the SSL version explicitly:

http: add support for specifying the SSL version

See commit 01861cb (14 Aug 2015) by Elia Pinto (devzero2000).
Helped-by: Eric Sunshine (sunshineco).
(Merged by Junio C Hamano -- gitster -- in commit ed070a4, 26 Aug 2015)

http.sslVersion

The SSL version to use when negotiating an SSL connection, if you want to force the default.
The available and default version depend on whether libcurl was built against NSS or OpenSSL and the particular configuration of the crypto library in use. Internally this sets the 'CURLOPT_SSL_VERSION' option; see the libcurl documentation for more details on the format of this option and for the ssl version supported.
Actually the possible values of this option are:

  • sslv2
  • sslv3
  • tlsv1
  • tlsv1.0
  • tlsv1.1
  • tlsv1.2

Can be overridden by the 'GIT_SSL_VERSION' environment variable.
To force git to use libcurl's default ssl version and ignore any explicit http.sslversion option, set 'GIT_SSL_VERSION' to the empty string.

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

You can, if uploading an entire folder is an option for you

<input type="file" webkitdirectory directory multiple/>

change event will contain:

.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"

What is the difference between statically typed and dynamically typed languages?

http://en.wikipedia.org/wiki/Type_system

Static typing

A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time. In static typing, types are associated with variables not values. Statically typed languages include Ada, C, C++, C#, JADE, Java, Fortran, Haskell, ML, Pascal, Perl (with respect to distinguishing scalars, arrays, hashes and subroutines) and Scala. Static typing is a limited form of program verification (see type safety): accordingly, it allows many type errors to be caught early in the development cycle. Static type checkers evaluate only the type information that can be determined at compile time, but are able to verify that the checked conditions hold for all possible executions of the program, which eliminates the need to repeat type checks every time the program is executed. Program execution may also be made more efficient (i.e. faster or taking reduced memory) by omitting runtime type checks and enabling other optimizations.

Because they evaluate type information during compilation, and therefore lack type information that is only available at run-time, static type checkers are conservative. They will reject some programs that may be well-behaved at run-time, but that cannot be statically determined to be well-typed. For example, even if an expression always evaluates to true at run-time, a program containing the code

if <complex test> then 42 else <type error>

will be rejected as ill-typed, because a static analysis cannot determine that the else branch won't be taken.[1] The conservative behaviour of static type checkers is advantageous when evaluates to false infrequently: A static type checker can detect type errors in rarely used code paths. Without static type checking, even code coverage tests with 100% code coverage may be unable to find such type errors. Code coverage tests may fail to detect such type errors because the combination of all places where values are created and all places where a certain value is used must be taken into account.

The most widely used statically typed languages are not formally type safe. They have "loopholes" in the programming language specification enabling programmers to write code that circumvents the verification performed by a static type checker and so address a wider range of problems. For example, Java and most C-style languages have type punning, and Haskell has such features as unsafePerformIO: such operations may be unsafe at runtime, in that they can cause unwanted behaviour due to incorrect typing of values when the program runs.

Dynamic typing

A programming language is said to be dynamically typed, or just 'dynamic', when the majority of its type checking is performed at run-time as opposed to at compile-time. In dynamic typing, types are associated with values not variables. Dynamically typed languages include Groovy, JavaScript, Lisp, Lua, Objective-C, Perl (with respect to user-defined types but not built-in types), PHP, Prolog, Python, Ruby, Smalltalk and Tcl. Compared to static typing, dynamic typing can be more flexible (e.g. by allowing programs to generate types and functionality based on run-time data), though at the expense of fewer a priori guarantees. This is because a dynamically typed language accepts and attempts to execute some programs which may be ruled as invalid by a static type checker.

Dynamic typing may result in runtime type errors—that is, at runtime, a value may have an unexpected type, and an operation nonsensical for that type is applied. This operation may occur long after the place where the programming mistake was made—that is, the place where the wrong type of data passed into a place it should not have. This makes the bug difficult to locate.

Dynamically typed language systems, compared to their statically typed cousins, make fewer "compile-time" checks on the source code (but will check, for example, that the program is syntactically correct). Run-time checks can potentially be more sophisticated, since they can use dynamic information as well as any information that was present during compilation. On the other hand, runtime checks only assert that conditions hold in a particular execution of the program, and these checks are repeated for every execution of the program.

Development in dynamically typed languages is often supported by programming practices such as unit testing. Testing is a key practice in professional software development, and is particularly important in dynamically typed languages. In practice, the testing done to ensure correct program operation can detect a much wider range of errors than static type-checking, but conversely cannot search as comprehensively for the errors that both testing and static type checking are able to detect. Testing can be incorporated into the software build cycle, in which case it can be thought of as a "compile-time" check, in that the program user will not have to manually run such tests.

References

  1. Pierce, Benjamin (2002). Types and Programming Languages. MIT Press. ISBN 0-262-16209-1.

Eclipse interface icons very small on high resolution screen in Windows 8.1

Best effortless solution is to go for Eclipse Neon. All bugs are fixed as a part of this release. https://bugs.eclipse.org/bugs/show_bug.cgi?id=421383

How can I check if the current date/time is past a set date/time?

There's also the DateTime class which implements a function for comparison operators.

// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');

if ( $dtA > $dtB ) {
  echo 'dtA > dtB';
}
else {
  echo 'dtA <= dtB';
}

how to download file using AngularJS and calling MVC API?

Here you have the angularjs http request to the API that any client will have to do. Just adapt the WS url and params (if you have) to your case. It's a mixture between Naoe's answer and this one:

$http({
    url: '/path/to/your/API',
    method: 'POST',
    params: {},
    headers: {
        'Content-type': 'application/pdf',
    },
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    // TODO when WS success
    var file = new Blob([data], {
        type: 'application/csv'
    });
    //trick to download store a file having its URL
    var fileURL = URL.createObjectURL(file);
    var a = document.createElement('a');
    a.href = fileURL;
    a.target = '_blank';
    a.download = 'yourfilename.pdf';
    document.body.appendChild(a); //create the link "a"
    a.click(); //click the link "a"
    document.body.removeChild(a); //remove the link "a"
}).error(function (data, status, headers, config) {
    //TODO when WS error
});

Explanation of the code:

  1. Angularjs request a file.pdf at the URL: /path/to/your/API.
  2. Success is received on the response
  3. We execute a trick with JavaScript on the front-end:
    • Create an html link ta: <a>.
    • Click the hyperlink <a> tag, using the JS click() function
  4. Remove the html <a> tag, after its click.

Rolling back local and remote git repository by 1 commit

For Windows Machines, use:

git reset HEAD~1  #Remove Commit Locally

How to get the focused element with jQuery?

If you want to confirm if focus is with an element then

if ($('#inputId').is(':focus')) {
    //your code
}

Git blame -- prior commits?

Amber's answer is correct but I found it unclear; The syntax is:

git blame {commit_id} -- {path/to/file}

Note: the -- is used to separate the tree-ish sha1 from the relative file paths. 1

For example:

git blame master -- index.html

Full credit to Amber for knowing all the things! :)

JQuery - $ is not defined

That error can only be caused by one of three things:

  1. Your JavaScript file is not being properly loaded into your page
  2. You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
  3. You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.

First of all, ensure, what script is call properly, it should looks like

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

and shouldn't have attributes async or defer.

Then you should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.

Make sure all jQuery javascript code is being run inside a code block such as:

$(document).ready(function () {
  //your code here
});

This will ensure that your code is being loaded after jQuery has been initialized.

One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.

Note: If you're loading code which does not require jQuery to run it does not need to be placed inside the jQuery ready handler. That code may be separated using document.readyState.

Spring JPA and persistence.xml

I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.

Windows.history.back() + location.reload() jquery

Try these ...

Option1

window.location=document.referrer;

Option2

window.location.reload(history.back());

Check if a column contains text using SQL

Leaving database modeling issues aside. I think you can try

SELECT * FROM STUDENTS WHERE ISNUMERIC(STUDENTID) = 0

But ISNUMERIC returns 1 for any value that seems numeric including things like -1.0e5

If you want to exclude digit-only studentids, try something like

SELECT * FROM STUDENTS WHERE STUDENTID LIKE '%[^0-9]%'

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

This Worked for me

In Web.config add below script

_x000D_
_x000D_
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="WebDAVModule"/>
  </modules>
  <handlers accessPolicy="Read, Execute, Script">
    <remove name="WebDAV" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />

    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*."
         verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
         type="System.Web.Handlers.TransferRequestHandler"
         preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
 </system.webServer>
_x000D_
_x000D_
_x000D_

Also in RouteConfig.cs

Change

settings.AutoRedirectMode = RedirectMode.Permanent;

To

settings.AutoRedirectMode = RedirectMode.Off;

Hope it helps you or some one :)

Access the css ":after" selector with jQuery

If you use jQuery built-in after() with empty value it will create a dynamic object that will match your :after CSS selector.

$('.active').after().click(function () {
    alert('clickable!');
});

See the jQuery documentation.

ng-change not working on a text input

When you want to edit something in Angular you need to insert an ngModel in your html

try this in your sample:

    <input type="text" name="abc" class="color" ng-model="myStyle.color">

You don't need to watch the change at all!

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

Using Git, show all commits that are in one branch, but not the other(s)

I'd like to count the commits too, so here's how to do that:

Count how many commits are on the current branch (HEAD), but NOT on master:

git log --oneline ^master HEAD | wc -l

wc -l means "word count"--count the number of 'l'ines.

And of course to see the whole log messages, as other answers have given:

git log ^master HEAD

...or in a condensed --oneline form:

git log --oneline ^master HEAD

If you don't want to count merge commits either, you can exclude those with --no-merges:

git log --oneline --no-merges ^master HEAD | wc -l

etc.

How to access remote server with local phpMyAdmin client?

Follow this blog post. You can do it very easily. https://wadsashika.wordpress.com/2015/01/06/manage-remote-mysql-database-locally-using-phpmyadmin/

The file config.inc.php contains the configuration settings for your phpMyAdmin installation. It uses an array to store sets of config options for every server it can connect to and by default there is only one, your own machine, or localhost. In order to connect to another server, you would have to add another set of config options to the config array. You have to edit this configuration file.

First open config.inc.php file held in phpMyAdmin folder. In wamp server, you can find it in wamp\apps\phpmyadmin folder. Then add following part to that file.

$i++;
$cfg['Servers'][$i]['host']          = 'hostname/Ip Adress';
$cfg['Servers'][$i]['port']          = '';
$cfg['Servers'][$i]['socket']        = '';
$cfg['Servers'][$i]['connect_type']  = 'tcp';
$cfg['Servers'][$i]['extension']     = 'mysql';
$cfg['Servers'][$i]['compress']      = FALSE;
$cfg['Servers'][$i]['auth_type']     = 'config';
$cfg['Servers'][$i]['user']          = 'username';
$cfg['Servers'][$i]['password']      = 'password';

Let’s see what is the meaning of this variables.

$i++ :- Incrementing variable for each server
$cfg[‘Servers’][$i][‘host’] :- Server host name or IP adress
$cfg[‘Servers’][$i][‘port’] :- MySQL port (Leave a blank for default port. Default MySQL port is 3306)
$cfg[‘Servers’][$i][‘socket’] :- Path to the socket (Leave a blank for default socket)
$cfg[‘Servers’][$i][‘connect_type’] :- How to connect to MySQL server (‘tcp’ or ‘socket’)
$cfg[‘Servers’][$i][‘extension’] :- php MySQL extension to use (‘mysql’ or ‘msqli’)
$cfg[‘Servers’][$i][‘compress’] :- Use compressed protocol for the MySQL connection (requires PHP >= 4.3.0)
$cfg[‘Servers’][$i][‘auth_type’] :- Method of Authentication
$cfg[‘Servers’][$i][‘username’] :- Username to the MySQL database in remote server
$cfg[‘Servers’][$i][‘password’] :- Password to the MySQL database int he remote server

After adding this configuration part, restart you server and now your phpMyAdmin home page will change and it will show a field to select the server.

Now you can select you server and access your remote database by entering username and password for that database.

How to add a line to a multiline TextBox?

Just put a line break into your text.

You don't add lines as a method. Multiline just supports the use of line breaks.

Get String in YYYYMMDD format from JS date object?

Answering another for Simplicity & readability.
Also, editing existing predefined class members with new methods is not encouraged:

function getDateInYYYYMMDD() {
    let currentDate = new Date();

    // year
    let yyyy = '' + currentDate.getFullYear();

    // month
    let mm = ('0' + (currentDate.getMonth() + 1));  // prepend 0 // +1 is because Jan is 0
    mm = mm.substr(mm.length - 2);                  // take last 2 chars

    // day
    let dd = ('0' + currentDate.getDate());         // prepend 0
    dd = dd.substr(dd.length - 2);                  // take last 2 chars

    return yyyy + "" + mm + "" + dd;
}

var currentDateYYYYMMDD = getDateInYYYYMMDD();
console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);

What is Func, how and when is it used

Both C# and Java don't have plain functions only member functions (aka methods). And the methods are not first-class citizens. First-class functions allow us to create beautiful and powerful code, as seen in F# or Clojure languages. (For instance, first-class functions can be passed as parameters and can return functions.) Java and C# ameliorate this somewhat with interfaces/delegates.

Func<int, int, int> randInt = (n1, n2) => new Random().Next(n1, n2); 

So, Func is a built-in delegate which brings some functional programming features and helps reduce code verbosity.

How to set Linux environment variables with Ansible

There are multiple ways to do this and from your question it's nor clear what you need.

1. If you need environment variable to be defined PER TASK ONLY, you do this:

- hosts: dev
  tasks:
    - name: Echo my_env_var
      shell: "echo $MY_ENV_VARIABLE"
      environment:
        MY_ENV_VARIABLE: whatever_value

    - name: Echo my_env_var again
      shell: "echo $MY_ENV_VARIABLE"

Note that MY_ENV_VARIABLE is available ONLY for the first task, environment does not set it permanently on your system.

TASK: [Echo my_env_var] ******************************************************* 
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": "whatever_value"}

TASK: [Echo my_env_var again] ************************************************* 
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": ""}

Hopefully soon using environment will also be possible on play level, not only task level as above. There's currently a pull request open for this feature on Ansible's GitHub: https://github.com/ansible/ansible/pull/8651

UPDATE: It's now merged as of Jan 2, 2015.

2. If you want permanent environment variable + system wide / only for certain user

You should look into how you do it in your Linux distribution / shell, there are multiple places for that. For example in Ubuntu you define that in files like for example:

  • ~/.profile
  • /etc/environment
  • /etc/profile.d directory
  • ...

You will find Ubuntu docs about it here: https://help.ubuntu.com/community/EnvironmentVariables

After all for setting environment variable in ex. Ubuntu you can just use lineinfile module from Ansible and add desired line to certain file. Consult your OS docs to know where to add it to make it permanent.

SQL Query for Student mark functionality

I like the simple solution using windows functions:

select t.*
from (select student.*, su.subname, max(mark) over (partition by subid) as maxmark
      from marks m join
           students st
           on m.stid = st.stid join
           subject su
           on m.subid = su.subid
     ) t
where t.mark = maxmark

Or, alternatively:

select t.*
from (select student.*, su.subname, rank(mark) over (partition by subid order by mark desc) as markseqnum
      from marks m join
           students st
           on m.stid = st.stid join
           subject su
           on m.subid = su.subid
     ) t
where markseqnum = 1

Comma separated results in SQL

Use FOR XML PATH('') - which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result

SELECT  STUFF((SELECT  ',' + INSTITUTIONNAME
            FROM EDUCATION EE
            WHERE  EE.STUDENTNUMBER=E.STUDENTNUMBER
            ORDER BY sortOrder
        FOR XML PATH('')), 1, 1, '') AS listStr

FROM EDUCATION E
GROUP BY E.STUDENTNUMBER

Here is the FIDDLE

How do I write a backslash (\) in a string?

Just escape the "\" by using + "\\Tasks" or use a verbatim string like @"\Tasks"

How can I calculate an md5 checksum of a directory?

If you want really independance from the filesystem attributes and from the bit-level differences of some tar versions, you could use cpio:

cpio -i -e theDirname | md5sum

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

clientHeight/clientWidth returning different values on different browsers

The equivalent of offsetHeight and offsetWidth in jQuery is $(window).width(), $(window).height() It's not the clientHeight and clientWidth

How to create a signed APK file using Cordova command line interface?

For Windows, I've created a build.cmd file:

(replace the keystore path and alias)

For Cordova:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

And for Ionic:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

Save it in the ptoject's directory, you can double click or open it with cmd.

What is better, adjacency lists or adjacency matrices for graph problems in C++?

If you use a hash table instead of either adjacency matrix or list, you'll get better or same big-O run-time and space for all operations (checking for an edge is O(1), getting all adjacent edges is O(degree), etc.).

There's some constant factor overhead though for both run-time and space (hash table isn't as fast as linked list or array lookup, and takes a decent amount extra space to reduce collisions).

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Your receiver:

public class MyReceiver extends BroadcastReceiver {   

    @Override
    public void onReceive(Context context, Intent intent) {

     Intent myIntent = new Intent(context, YourService.class);
     context.startService(myIntent);

    }
}

Your AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.broadcast.receiver.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">

        <activity android:name=".BR_Example"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
        <receiver android:name=".MyReceiver" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

    <!-- Adding the permission -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

</manifest>

Concatenate a list of pandas dataframes together

Given that all the dataframes have the same columns, you can simply concat them:

import pandas as pd
df = pd.concat(list_of_dataframes)

IF a == true OR b == true statement

check this Twig Reference.

You can do it that simple:

{% if (a or b) %}
    ...
{% endif %}

Access to the requested object is only available from the local network phpmyadmin

If you see below error message, when try into phpyAdmin:

New XAMPP security concept:
Access to the requested directory is only available from the local network.
This setting can be configured in the file "httpd-xampp.conf".

You can do next (for XAMPP, deployed on the UNIX-system): You can try change configuration for <Directory "/opt/lampp/phpmyadmin">

# vi /opt/lampp/etc/extra/httpd-xampp.conf

and change security settings to

#LoadModule perl_module        modules/mod_perl.so

<Directory "/opt/lampp/phpmyadmin">
    AllowOverride AuthConfig Limit
    Order allow,deny
    Allow from all
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

First - comment pl module, second - change config for node Directory. After it, you should restart httpd daemon

# /opt/lampp/xampp restart

Now you can access http://[server_ip]/phpmyadmin/

Add CSS box shadow around the whole DIV

Use this below code

 border:2px soild #eee;

 margin: 15px 15px;
 -webkit-box-shadow: 2px 3px 8px #eee;
-moz-box-shadow: 2px 3px 8px #eee;
box-shadow: 2px 3px 8px #eee;

Explanation:-

box-shadow requires you to set the horizontal & vertical offsets, you can then optionally set the blur and colour, you can also choose to have the shadow inset instead of the default outset. Colour can be defined as hex or rgba.

box-shadow : inset/outset h-offset v-offset blur spread color;

Explanation of the values...

inset/outset -- whether the shadow is inside or outside the box. If not specified it will default to outset.

h-offset -- the horizontal offset of the shadow (required value)

v-offset -- the vertical offset of the shadow (required value)

blur -- as it says, the blur of the shadow

spread -- moves the shadow away from the box equally on all sides. A positive value causes the shadow to expand, negative causes it to contract. Though this value isn't often used, it is useful with multiple shadows.

color -- as it says, the color of the shadow

Usage

box-shadow:2px 3px 8px #eee; a gray shadow with a horizontal outset of 2px, vertical of 3px and a blur of 8px

Using Jquery Datatable with AngularJs

For AngularJs you have to use "angular-datatables.min.js" file for datatable settings. You will get this from http://l-lin.github.io/angular-datatables/#/welcome.

After that you can write code like below,

<script>
     var app = angular.module('AngularWayApp', ['datatables']);
</script>

<div ng-app="AngularWayApp" ng-controller="AngularWayCtrl">
  <table id="example" datatable="ng" class="table">
                                    <thead>
                                        <tr>
                                            <th><b>UserID</b></th>
                                            <th><b>Firstname</b></th>
                                            <th><b>Lastname</b></th>
                                            <th><b>Email</b></th>
                                            <th><b>Actions</b></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr ng-repeat="user in users" ng-click="testingClick(user)">
                                            <td>
                                                {{user.UserId}}
                                            </td>
                                            <td>
                                                {{user.FirstName}}
                                            </td>
                                            <td>
                                                {{user.Lastname}}
                                            </td>
                                            <td>
                                                {{user.Email}}
                                            </td>
                                            <td>
                                                <span ng-click="editUser(user)" style="color:blue;cursor: pointer; font-weight:500; font-size:15px" class="btnAdd" data-toggle="modal" data-target="#myModal">Edit</span> &nbsp;&nbsp; | &nbsp;&nbsp;
                                                <span ng-click="deleteUser(user)" style="color:red; cursor: pointer; font-weight:500; font-size:15px" class="btnRed">Delete</span>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                                </div>

How to delete all instances of a character in a string in python?

Try str.replace():

string = "it is icy"
print string.replace("i", "")

"Gradle Version 2.10 is required." Error

For people who are using Ionic/Cordova framework, we need to change the distributionUrl in GradleBuilder.js file to var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'http\\://services.gradle.org/distributions/gradle-2.10-all.zip';

The GradleBuilder.js locates at project/platforms/android/cordova/lib/builders/GradleBuilder.js

Proper use cases for Android UserManager.isUserAGoat()?

I don't know if this was "the" official use case, but the following produces a warning in Java (that can further produce compile errors if mixed with return statements, leading to unreachable code):

while (1 == 2) { // Note that "if" is treated differently
    System.out.println("Unreachable code");
}

However this is legal:

while (isUserAGoat()) {
    System.out.println("Unreachable but determined at runtime, not at compile time");
}

So I often find myself writing a silly utility method for the quickest way to dummy out a code block, then in completing debugging find all calls to it, so provided the implementation doesn't change this can be used for that.

JLS points out if (false) does not trigger "unreachable code" for the specific reason that this would break support for debug flags, i.e., basically this use case (h/t @auselen). (static final boolean DEBUG = false; for instance).

I replaced while for if, producing a more obscure use case. I believe you can trip up your IDE, like Eclipse, with this behavior, but this edit is 4 years into the future, and I don't have an Eclipse environment to play with.

Algorithm to generate all possible permutations of a list?

Java version

/**
 * @param uniqueList
 * @param permutationSize
 * @param permutation
 * @param only            Only show the permutation of permutationSize,
 *                        else show all permutation of less than or equal to permutationSize.
 */
public static void my_permutationOf(List<Integer> uniqueList, int permutationSize, List<Integer> permutation, boolean only) {
    if (permutation == null) {
        assert 0 < permutationSize && permutationSize <= uniqueList.size();
        permutation = new ArrayList<>(permutationSize);
        if (!only) {
            System.out.println(Arrays.toString(permutation.toArray()));
        }
    }
    for (int i : uniqueList) {
        if (permutation.contains(i)) {
            continue;
        }
        permutation.add(i);
        if (!only) {
            System.out.println(Arrays.toString(permutation.toArray()));
        } else if (permutation.size() == permutationSize) {
            System.out.println(Arrays.toString(permutation.toArray()));
        }
        if (permutation.size() < permutationSize) {
            my_permutationOf(uniqueList, permutationSize, permutation, only);
        }
        permutation.remove(permutation.size() - 1);
    }
}

E.g.

public static void main(String[] args) throws Exception { 
    my_permutationOf(new ArrayList<Integer>() {
        {
            add(1);
            add(2);
            add(3);

        }
    }, 3, null, true);
}

output:

  [1, 2, 3]
  [1, 3, 2]
  [2, 1, 3]
  [2, 3, 1]
  [3, 1, 2]
  [3, 2, 1]

React eslint error missing in props validation

the problem is in flow annotation in handleClick, i removed this and works fine thanks @alik

.NET obfuscation tools/strategy

Back with .Net 1.1 obfuscation was essential: decompiling code was easy, and you could go from assembly, to IL, to C# code and have it compiled again with very little effort.

Now with .Net 3.5 I'm not at all sure. Try decompiling a 3.5 assembly; what you get is a long long way from compiling.

Add the optimisations from 3.5 (far better than 1.1) and the way anonymous types, delegates and so on are handled by reflection (they are a nightmare to recompile). Add lambda expressions, compiler 'magic' like Linq-syntax and var, and C#2 functions like yield (which results in new classes with unreadable names). Your decompiled code ends up a long long way from compilable.

A professional team with lots of time could still reverse engineer it back again, but then the same is true of any obfuscated code. What code they got out of that would be unmaintainable and highly likely to be very buggy.

I would recommend key-signing your assemblies (meaning if hackers can recompile one they have to recompile all) but I don't think obfuscation's worth it.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

TortoiseSVN icons not showing up under Windows 7

Have you tried to change in Tortoise Settings the status cache to 'Default'? I had this problem with the overlay icon on folders because I had this option in 'Shell'. The option is in Settings -> Icons overlay.

Maybe this could help you http://tortoisesvn.net/node/97

How do I syntax check a Bash script without running it?

bash -n scriptname

Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello instead of echo hello.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

An example to help you get off the ground.

for f in *.jpg; do mv "$f" "$(echo "$f" | sed s/IMG/VACATION/)"; done

In this example, I am assuming that all your image files contain the string IMG and you want to replace IMG with VACATION.

The shell automatically evaluates *.jpg to all the matching files.

The second argument of mv (the new name of the file) is the output of the sed command that replaces IMG with VACATION.

If your filenames include whitespace pay careful attention to the "$f" notation. You need the double-quotes to preserve the whitespace.

Style child element when hover on parent

you can use this too

_x000D_
_x000D_
.parent:hover * {
   /* ... */
}
_x000D_
_x000D_
_x000D_

TypeError : Unhashable type

You are creating a set via set(...) call, and set needs hashable items. You can't have set of lists. Because list's arent hashable.

[[(a,b) for a in range(3)] for b in range(3)] is a list. It's not a hashable type. The __hash__ you saw in dir(...) isn't a method, it's just None.

A list comprehension returns a list, you don't need to explicitly use list there, just use:

>>> [[(a,b) for a in range(3)] for b in range(3)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]

Try those:

>>> a = {1, 2, 3}
>>> b= [1, 2, 3]
>>> type(a)
<class 'set'>
>>> type(b)
<class 'list'>
>>> {1, 2, []}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> print([].__hash__)
None
>>> [[],[],[]] #list of lists
[[], [], []]
>>> {[], [], []} #set of lists
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Best place to insert the Google Analytics code

As google says:

Paste it into your web page, just before the closing </head> tag.

One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the <head> section, and we recommend placing the snippet at the bottom of the <head> section for best performance

How to truncate string using SQL server

You can use

LEFT(column, length)

or

SUBSTRING(column, start index, length)

sqlite copy data from one table to another

If you have data already present in both the tables and you want to update a table column values based on some condition then use this

UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)

SELECT INTO using Oracle

select into is used in pl/sql to set a variable to field values. Instead, use

create table new_table as select * from old_table

The name 'model' does not exist in current context in MVC3

Update: If you are using a newer version of MVC, the same process applies, just be sure to use the correct version number in the web.config's <host> line.

Well, I found myself experiencing the same thing you did, and after a bit further research, I found out what the problem is!

You need to include the default MVC3 web.config for the Views folder. MVC3 has two: one in the root for your application, and one for the views folder. This has a section for included namespaces. Be sure that yours looks something like this:

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

I suggest that you create a new MVC3 project, then just copy the web.config created for you into your views folder.

Important Once you've done that, you need to close the file and reopen it. Voila! Intellisense!

How do I capture the output of a script if it is being ran by the task scheduler?

Example how to run program and write stdout and stderr to file with timestamp:

cmd /c ""C:\Program Files (x86)\program.exe" -param fooo >> "c:\dir space\Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1"

Key part is to double quote whole part behind cmd /c and inside it use double quotes as usual. Also note that date is locale dependent, this example works using US locale.

How to deserialize a list using GSON or another JSON library in Java?

Another way is to use an array as a type, e.g.:

Video[] videoArray = gson.fromJson(json, Video[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list, e.g.:

List<Video> videoList = Arrays.asList(videoArray);

IMHO this is much more readable.


In Kotlin this looks like this:

Gson().fromJson(jsonString, Array<Video>::class.java)

To convert this array into List, just use .toList() method

What is the difference between a web API and a web service?

Difference between Web Service and Web API nicely explained here:

https://softwareengineering.stackexchange.com/questions/38691/difference-between-web-api-and-web-service

Text from the link:

Web Services - that's standard defined by W3C, so they can be accessed semi-automatically or automatically (WSDL / UDDI). The whole thing is based on XML, so anyone can call it. And every aspect of the service is very well defined. There's parameters description standard, parameter passing standard, response standard, discovery standard, etc. etc. You could probably write 2000 pages book that'd describe the standard. There are even some "additional" standards for doing "standard" things, like authentication.

Despite the fact that automatic invoking and discovery is barely working because clients are rather poor, and you have no real guarantee that any service can be called from any client.

Web API is typically done as HTTP/REST, nothing is defined, output can be for eg. JSON/XML, input can be XML/JSON/or plain data. There are no standards for anything => no automatic calling and discovery. You can provide some description in text file or PDF, you can return the data in Windows-1250 instead of unicode, etc. For describing the standard it'd be 2 pages brochure with some simple info and you'll define everything else.

Web is switching towards Web API / REST. Web Services are really no better than Web API. Very complicated to develop and they eat much more resources (bandwidth and RAM)... and because of all data conversions (REQUEST->XML->DATA->RESPONSE->XML->VALIDATION->CONVERSION->DATA) are very slow.

Eg. In WebAPI you can pack the data, send it compressed and un-compress+un-pack on the client. In SOAP you could only compress HTML request.

Sorting data based on second column of a file

You can use the sort command:

sort -k2 -n yourfile

-n, --numeric-sort compare according to string numerical value

For example:

$ cat ages.txt 
Bob 12
Jane 48
Mark 3
Tashi 54

$ sort -k2 -n ages.txt 
Mark 3
Bob 12
Jane 48
Tashi 54

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

How to export library to Jar in Android Studio?

We can export a jar file for Android library project without resource files by Android studio. It is also requirement what I met recently.

1. Config your build.gradle file

    // Task to delete old jar

    task clearJar(type: Delete){
       delete 'release/lunademo.jar'
    }

    // task to export contents as jar
    task makeJar(type: Copy) {
       from ('build/intermediates/bundles/release/')
       into ('build/libs/')
       include ('classes.jar')
       rename('classes.jar', 'lunademo.jar')
    }
    makeJar.dependsOn(clearJar, build)

2. Run gradlew makeJar under your project root

You will see your libs under dir as build/libs/ if you are luckily.

============================================================

If you met issue as "Socket timeout exception" on command line as below,

enter image description here

You can follow this steps to open Gradle window in the right part and click "makeJar" on Android studio like this,

enter image description here

enter image description here

Then go to build/libs dir, you will see your jar file.

Hope that it is helpful for u.

Good Luck @.@

Luna

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."; 


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

.Contains() on a list of custom class objects

If you are using .NET 3.5 or newer you can use LINQ extension methods to achieve a "contains" check with the Any extension method:

if(CartProducts.Any(prod => prod.ID == p.ID))

This will check for the existence of a product within CartProducts which has an ID matching the ID of p. You can put any boolean expression after the => to perform the check on.

This also has the benefit of working for LINQ-to-SQL queries as well as in-memory queries, where Contains doesn't.

How to delete a character from a string using Python

UserString.MutableString

Mutable way:

import UserString

s = UserString.MutableString("EXAMPLE")

>>> type(s)
<type 'str'>

# Delete 'M'
del s[3]

# Turn it for immutable:
s = str(s)

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

You can set the default value of your Id in your db to newsequentialid() or newid(). Then the identity configuration of EF should work.

String MinLength and MaxLength validation don't work (asp.net mvc)

They do now, with latest version of MVC (and jquery validate packages). mvc51-release-notes#Unobtrusive

Thanks to this answer for pointing it out!

Windows Application has stopped working :: Event Name CLR20r3

This is just because the application is built in non unicode language fonts and you are running the system on unicode fonts. change your default non unicode fonts to arabic by going in regional settings advanced tab in control panel. That will solve your problem.

Changing the cursor in WPF sometimes works, sometimes doesn't

The following worked for me:

ForceCursor = true;
Cursor = Cursors.Wait;

AttributeError: 'datetime' module has no attribute 'strptime'

I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.

Execute an action when an item on the combobox is selected

The simple solution would be to use a ItemListener. When the state changes, you would simply check the currently selected item and set the text accordingly

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

    public static void main(String[] args) {
        new TestComboBox06();
    }

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new String[]{"Item 1", "Item 2"});
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Object item = cb.getSelectedItem();
                    if ("Item 1".equals(item)) {
                        field.setText("20");
                    } else if ("Item 2".equals(item)) {
                        field.setText("30");
                    }
                }
            });
        }

    }

}

A better solution would be to create a custom object that represents the value to be displayed and the value associated with it...

Updated

Now I no longer have a 10 month chewing on my ankles, I updated the example to use a ListCellRenderer which is a more correct approach then been lazy and overriding toString

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

    public static void main(String[] args) {
        new TestComboBox06();
    }

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new Item[]{
                new Item("Item 1", "20"), 
                new Item("Item 2", "30")});
            cb.setRenderer(new ItemCelLRenderer());
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Item item = (Item)cb.getSelectedItem();
                    field.setText(item.getValue());
                }
            });
        }

    }

    public class Item {
        private String value;
        private String text;

        public Item(String text, String value) {
            this.text = text;
            this.value = value;
        }

        public String getText() {
            return text;
        }

        public String getValue() {
            return value;
        }

    }

    public class ItemCelLRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
            if (value instanceof Item) {
                setText(((Item)value).getText());
            }
            return this;
        }

    }

}

How do I find the size of a struct?

This will vary depending on your architecture and how it treats basic data types. It will also depend on whether the system requires natural alignment.

Is it possible to use global variables in Rust?

Look at the const and static section of the Rust book.

You can use something as follows:

const N: i32 = 5; 

or

static N: i32 = 5;

in global space.

But these are not mutable. For mutability, you could use something like:

static mut N: i32 = 5;

Then reference them like:

unsafe {
    N += 1;

    println!("N: {}", N);
}

Listing files in a specific "folder" of a AWS S3 bucket

If your goal is only to take the files and not the folder, the approach I made was to use the file size as a filter. This property is the current size of the file hosted by AWS. All the folders return 0 in that property. The following is a C# code using linq but it shouldn't be hard to translate to Java.

var amazonClient = new AmazonS3Client(key, secretKey, region);
var listObjectsRequest= new ListObjectsRequest
            {
                BucketName = 'someBucketName',
                Delimiter = 'someDelimiter',
                Prefix = 'somePrefix'
            };
var objects = amazonClient.ListObjects(listObjectsRequest);
var objectsInFolder = objects.S3Objects.Where(file => file.Size > 0).ToList();

internal/modules/cjs/loader.js:582 throw err

same happen to me i just resolved by deleting "dist" file and re run the app.

How can I read Chrome Cache files?

The JPEXS Free Flash Decompiler has Java code to do this at in the source tree for both Chrome and Firefox (no support for Firefox's more recent cache2 though).

Checkout another branch when there are uncommitted changes on the current branch

In case you don't want this changes to be committed at all do git reset --hard.

Next you can checkout to wanted branch, but remember that uncommitted changes will be lost.

How do you strip a character out of a column in SQL Server?

Take a look at the following function - REPLACE():

select replace(DataColumn, StringToReplace, NewStringValue)

//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t

http://msdn.microsoft.com/en-us/library/ms186862.aspx

EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:

select replace(DataColumn, 'StringToRemove', '')

PHP Multiple Checkbox Array

Also remember you can include custom indices to the array sent to the server like this

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[4]' value='Option One'>4<br>
    <input type='checkbox' name='checkboxvar[6]' value='Option Two'>6<br>
    <input type='checkbox' name='checkboxvar[9]' value='Option Three'>9
    </td>
</tr>
<input type='submit' class='buttons'>
</form>

This is particularly useful when you want to use the id of individual objects in a server array accounts (for instance) to send data back to the server and recognize same at server

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <?php foreach($accounts as $account) { ?>
        <input type='checkbox' name='accounts[<?php echo $account->id ?>]' value='<?php echo $account->name ?>'>
        <?php echo $account->name ?>
        <br>
    <?php } ?>
    </td>
</tr>
<input type='submit' class='buttons'>
</form>

<?php 
if (isset($_POST['accounts'])) 
{
    print_r($_POST['accounts']); 
}
?>

Java and SQLite

The example code leads to a memory leak in Tomcat (after undeploying the webapp, the classloader still remains in memory) which will cause an outofmemory eventually. The way to solve it is to use the sqlite-jdbc-3.7.8.jar; it's a snapshot, so it doesn't appear for maven yet.

how to show lines in common (reverse diff)?

Easiest way to do is :

awk 'NR==FNR{a[$1]++;next} a[$1] ' file1 file2

Files are not necessary to be sorted.

How to join two tables by multiple columns in SQL?

You should only need to do a single join:

SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

How do I trim whitespace?

If you want to trim the whitespace off just the beginning and end of the string, you can do something like this:

some_string = "    Hello,    world!\n    "
new_string = some_string.strip()
# new_string is now "Hello,    world!"

This works a lot like Qt's QString::trimmed() method, in that it removes leading and trailing whitespace, while leaving internal whitespace alone.

But if you'd like something like Qt's QString::simplified() method which not only removes leading and trailing whitespace, but also "squishes" all consecutive internal whitespace to one space character, you can use a combination of .split() and " ".join, like this:

some_string = "\t    Hello,  \n\t  world!\n    "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"

In this last example, each sequence of internal whitespace replaced with a single space, while still trimming the whitespace off the start and end of the string.

ESLint Parsing error: Unexpected token

Unexpected token errors in ESLint parsing occur due to incompatibility between your development environment and ESLint's current parsing capabilities with the ongoing changes with JavaScripts ES6~7.

Adding the "parserOptions" property to your .eslintrc is no longer enough for particular situations, such as using

static contextTypes = { ... } /* react */

in ES6 classes as ESLint is currently unable to parse it on its own. This particular situation will throw an error of:

error Parsing error: Unexpected token =

The solution is to have ESLint parsed by a compatible parser. babel-eslint is a package that saved me recently after reading this page and i decided to add this as an alternative solution for anyone coming later.

just add:

"parser": "babel-eslint"

to your .eslintrc file and run npm install babel-eslint --save-dev or yarn add -D babel-eslint.

Please note that as the new Context API starting from React ^16.3 has some important changes, please refer to the official guide.

How to remove leading and trailing white spaces from a given html string?

var str = "  my awesome string   "
str.trim();    

for old browsers, use regex

str = str.replace(/^[ ]+|[ ]+$/g,'')
//str = "my awesome string" 

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

Unioning two tables with different number of columns

Add extra columns as null for the table having less columns like

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2

SQL "between" not inclusive

I find that the best solution to comparing a datetime field to a date field is the following:

DECLARE @StartDate DATE = '5/1/2013', 
        @EndDate   DATE = '5/1/2013' 

SELECT * 
FROM   cases 
WHERE  Datediff(day, created_at, @StartDate) <= 0 
       AND Datediff(day, created_at, @EndDate) >= 0 

This is equivalent to an inclusive between statement as it includes both the start and end date as well as those that fall between.

\r\n, \r and \n what is the difference between them?

They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.

As for your replacement, you haven't specified what language you're using, so here's the sketch:

someString.replace("\r\n", "\n").replace("\r", "\n")