Programs & Examples On #Embedded sql

Embedded SQL is the term used for a method of inlining SQL statements with the source code of another programming language, called host language.

How to find the operating system version using JavaScript?

I started to write a Script to read OS and browser version that can be tested on Fiddle. Feel free to use and extend.
Breaking Change:
Since September 2020 the new Edge gets detected. So 'Microsoft Edge' is the new version based on Chromium and the old Edge is now detected as 'Microsoft Legacy Edge'!

/**
 * JavaScript Client Detection
 * (C) viazenetti GmbH (Christian Ludwig)
 */
(function (window) {
    {
        var unknown = '-';

        // screen
        var screenSize = '';
        if (screen.width) {
            width = (screen.width) ? screen.width : '';
            height = (screen.height) ? screen.height : '';
            screenSize += '' + width + " x " + height;
        }

        // browser
        var nVer = navigator.appVersion;
        var nAgt = navigator.userAgent;
        var browser = navigator.appName;
        var version = '' + parseFloat(navigator.appVersion);
        var majorVersion = parseInt(navigator.appVersion, 10);
        var nameOffset, verOffset, ix;

        // Opera
        if ((verOffset = nAgt.indexOf('Opera')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 6);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // Opera Next
        if ((verOffset = nAgt.indexOf('OPR')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 4);
        }
        // Legacy Edge
        else if ((verOffset = nAgt.indexOf('Edge')) != -1) {
            browser = 'Microsoft Legacy Edge';
            version = nAgt.substring(verOffset + 5);
        } 
        // Edge (Chromium)
        else if ((verOffset = nAgt.indexOf('Edg')) != -1) {
            browser = 'Microsoft Edge';
            version = nAgt.substring(verOffset + 4);
        }
        // MSIE
        else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
        }
        // Chrome
        else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
            browser = 'Chrome';
            version = nAgt.substring(verOffset + 7);
        }
        // Safari
        else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
            browser = 'Safari';
            version = nAgt.substring(verOffset + 7);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // Firefox
        else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
            browser = 'Firefox';
            version = nAgt.substring(verOffset + 8);
        }
        // MSIE 11+
        else if (nAgt.indexOf('Trident/') != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(nAgt.indexOf('rv:') + 3);
        }
        // Other browsers
        else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
            browser = nAgt.substring(nameOffset, verOffset);
            version = nAgt.substring(verOffset + 1);
            if (browser.toLowerCase() == browser.toUpperCase()) {
                browser = navigator.appName;
            }
        }
        // trim the version string
        if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

        majorVersion = parseInt('' + version, 10);
        if (isNaN(majorVersion)) {
            version = '' + parseFloat(navigator.appVersion);
            majorVersion = parseInt(navigator.appVersion, 10);
        }

        // mobile version
        var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

        // cookie
        var cookieEnabled = (navigator.cookieEnabled) ? true : false;

        if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
            document.cookie = 'testcookie';
            cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
        }

        // system
        var os = unknown;
        var clientStrings = [
            {s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 3.11', r:/Win16/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Chrome OS', r:/CrOS/},
            {s:'Linux', r:/(Linux|X11(?!.*CrOS))/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];
        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(nAgt)) {
                os = cs.s;
                break;
            }
        }

        var osVersion = unknown;

        if (/Windows/.test(os)) {
            osVersion = /Windows (.*)/.exec(os)[1];
            os = 'Windows';
        }

        switch (os) {
            case 'Mac OS':
            case 'Mac OS X':
            case 'Android':
                osVersion = /(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                break;
        }
        
        // flash (you'll need to include swfobject)
        /* script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" */
        var flashVersion = 'no check';
        if (typeof swfobject != 'undefined') {
            var fv = swfobject.getFlashPlayerVersion();
            if (fv.major > 0) {
                flashVersion = fv.major + '.' + fv.minor + ' r' + fv.release;
            }
            else  {
                flashVersion = unknown;
            }
        }
    }

    window.jscd = {
        screen: screenSize,
        browser: browser,
        browserVersion: version,
        browserMajorVersion: majorVersion,
        mobile: mobile,
        os: os,
        osVersion: osVersion,
        cookies: cookieEnabled,
        flashVersion: flashVersion
    };
}(this));

alert(
    'OS: ' + jscd.os +' '+ jscd.osVersion + '\n' +
    'Browser: ' + jscd.browser +' '+ jscd.browserMajorVersion +
      ' (' + jscd.browserVersion + ')\n' + 
    'Mobile: ' + jscd.mobile + '\n' +
    'Flash: ' + jscd.flashVersion + '\n' +
    'Cookies: ' + jscd.cookies + '\n' +
    'Screen Size: ' + jscd.screen + '\n\n' +
    'Full User Agent: ' + navigator.userAgent
);

Use a.any() or a.all()

You comment:

valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....

If you are interested in each term, then write the code so it deals with each. For example.

for b in valeur<=0.6:
    if b:
        print ("this works")
    else:   
        print ("valeur is too high")

This will write 2 lines.

The error is produced by numpy code when you try to use it a context that expects a single, scalar, value. if b:... can only do one thing. It does not, by itself, iterate through the elements of b doing a different thing for each.

You could also cast that iteration as list comprehension, e.g.

['yes' if b else 'no' for b in np.array([True, False, True])]

How do you create vectors with specific intervals in R?

In R the equivalent function is seq and you can use it with the option by:

seq(from = 5, to = 100, by = 5)
# [1]   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100

In addition to by you can also have other options such as length.out and along.with.

length.out: If you want to get a total of 10 numbers between 0 and 1, for example:

seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1

along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).

seq(along.with=c(10,20,30))
# [1] 1 2 3

Although, instead of using the along.with option, it is recommended to use seq_along in this case. From the documentation for ?seq

seq is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to use seq_along in that case.

seq_along: Instead of seq(along.with(.))

seq_along(c(10,20,30))
# [1] 1 2 3

Hope this helps.

Date only from TextBoxFor()

Just add next to your model.

[DataType(DataType.Date)]
public string dtArrivalDate { get; set; }

How do I apply a diff patch on Windows?

I know you said you would prefer a GUI, but the commandline tools will do the work nicely. See GnuWin for a port of unix tools to Windows. You'd need the patch command, obviously ;-)

You might run into a problem with the line termination, though. The GnuWin port will assume that the patchfile has DOS style line termination (CR/LF). Try to open the patchfile in a reasonably smart editor and it will convert it for you.

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I never managed to get git to work completely in Powershell. But in the git bash shell I did not have any permission related issues, and I did not need to set chmod etc... After adding the ssh to Github I was up and running.

What are the dark corners of Vim your mom never told you about?

% is also good when you want to diff files across two different copies of a project without wearing out the pinkies (from root of project1):

:vert diffs /project2/root/%

check if a std::vector contains a certain object?

See question: How to find an item in a std::vector?

You'll also need to ensure you've implemented a suitable operator==() for your object, if the default one isn't sufficient for a "deep" equality test.

Can I catch multiple Java exceptions in the same catch clause?

In pre-7 how about:

  Boolean   caught = true;
  Exception e;
  try {
     ...
     caught = false;
  } catch (TransformerException te) {
     e = te;
  } catch (SocketException se) {
     e = se;
  } catch (IOException ie) {
     e = ie;
  }
  if (caught) {
     someCode(); // You can reference Exception e here.
  }

SQLAlchemy create_all() does not create tables

You should put your model class before create_all() call, like this:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

If your models are declared in a separate module, import them before calling create_all().

Say, the User model is in a file called models.py,

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

# See important note below
from models import User

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

Important note: It is important that you import your models after initializing the db object since, in your models.py _you also need to import the db object from this module.

Crop image in android

hope you are doing well. you can use my code to crop image.you just have to make a class and use this class into your XMl and java classes. Crop image. you can crop your selected image into circle and square into many of option. hope fully it will works for you.because this is totally manageable for you and you can change it according to you.

enjoy your work :)

Overwriting txt file in java

Add one more line after initializing file object

File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();

How can I solve the error 'TS2532: Object is possibly 'undefined'?

For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci.certificateStatus = "";
    }
  }

And because dataToSend.naci cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci!.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci!.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci!.certificateStatus = "";
    }
  }

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

How do I call an Angular 2 pipe with multiple arguments?

Since beta.16 the parameters are not passed as array to the transform() method anymore but instead as individual parameters:

{{ myData | date:'fullDate':'arg1':'arg2' }}


export class DatePipe implements PipeTransform {    
  transform(value:any, arg1:any, arg2:any):any {
        ...
}

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

pipes now take a variable number of arguments, and not an array that contains all arguments.

Convert named list to vector with values only

This can be done by using unlist before as.vector. The result is the same as using the parameter use.names=FALSE.

as.vector(unlist(myList))

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

"Error: Main method not found in class MyClass, please define the main method as..."

I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a

java.lang.NoSuchMethodError: No virtual method

How to set size for local image using knitr for markdown?

Here's some options that keep the file self-contained without retastering the image:

Wrap the image in div tags

<div style="width:300px; height:200px">
![Image](path/to/image)
</div>

Use a stylesheet

test.Rmd

---
title: test
output: html_document
css: test.css
---

## Page with an image {#myImagePage}

![Image](path/to/image)

test.css

#myImagePage img {
  width: 400px;
  height: 200px;
}

If you have more than one image you might need to use the nth-child pseudo-selector for this second option.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

Take a look at WordUtils in the Apache Commons lang library:

Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job:

String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, new char[]{'_'}).replaceAll("_", ""));

Green bar!

How to get the entire document HTML as a string?

document.documentElement.outerHTML

How to get the new value of an HTML input after a keypress has modified it?

You can try this code (requires jQuery):

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#foo').keyup(function(e) {
                var v = $('#foo').val();
                $('#debug').val(v);
            })
        });
    </script>
</head>
<body>
    <form>
        <input type="text" id="foo" value="bar"><br>
        <textarea id="debug"></textarea>
    </form>
</body>
</html>

What's the use of ob_start() in php?

I prefer:

ob_start();
echo("Hello there!");
$output = ob_get_clean(); //Get current buffer contents and delete current output buffer

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

python NameError: global name '__file__' is not defined

if you are using jupyter notebook like:

MODEL_NAME = os.path.basename(file)[:-3]

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-f391bbbab00d> in <module>
----> 1 MODEL_NAME = os.path.basename(__file__)[:-3]

NameError: name '__file__' is not defined

you should place a ' ! ' in front like this

!MODEL_NAME = os.path.basename(__file__)[:-3]

/bin/bash: -c: line 0: syntax error near unexpected token `('
/bin/bash: -c: line 0: `MODEL_NAME = os.path.basename(__file__)[:-3]'

done.....

How to discard local commits in Git?

I had to do a :

git checkout -b master

as git said that it doesn't exists, because it's been wipe with the

git -D master

Assigning multiple styles on an HTML element

The syntax you used is problematic. In html, an attribute (ex: style) has a value delimited by double quotes. In that case, the value of the style attribute is a css list of selectors. Try this:

<h2 style="text-align:center; font-family:tahoma">TITLE</h2>

How to set proxy for wget?

For all users of the system via the /etc/wgetrc or for the user only with the ~/.wgetrc file:

use_proxy=yes
http_proxy=127.0.0.1:8080
https_proxy=127.0.0.1:8080

or via -e options placed after the URL:

wget ... -e use_proxy=yes -e http_proxy=127.0.0.1:8080 ...

How to check if an environment variable exists and get its value?

There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.

You can check if a variable is defined:

if [ -z "$a" ]
then
    echo "not defined"
else 
    echo "defined"
fi

and then set a default value for undefined variables or do something else.

The -z checks for a zero-length (i.e. empty) string. See man bash and look for the CONDITIONAL EXPRESSIONS section.

You can also use set -u at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.

How do I remove duplicates from a C# array?

Add all the strings to a dictionary and get the Keys property afterwards. This will produce each unique string, but not necessarily in the same order your original input had them in.

If you require the end result to have the same order as the original input, when you consider the first occurance of each string, use the following algorithm instead:

  1. Have a list (final output) and a dictionary (to check for duplicates)
  2. For each string in the input, check if it exists in the dictionary already
  3. If not, add it both to the dictionary and to the list

At the end, the list contains the first occurance of each unique string.

Make sure you consider things like culture and such when constructing your dictionary, to make sure you handle duplicates with accented letters correctly.

Can you get the number of lines of code from a GitHub repository?

There is an extension for Google Chrome browser - GLOC which works for public and private repos.

Counts the number of lines of code of a project from:

  • project detail page
  • user's repositories
  • organization page
  • search results page
  • trending page
  • explore page

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

The accounts property is defined like this:

"accounts":{"github":"sergiotapia"}

Your POCO states this:

public List<Account> Accounts { get; set; }

Try using this Json:

"accounts":[{"github":"sergiotapia"}]

An array of items (which is going to be mapped to the list) is always enclosed in square brackets.

Edit: The Account Poco will be something like this:

class Account {
    public string github { get; set; }
}

and maybe other properties.

Edit 2: To not have an array use the property as follows:

public Account Accounts { get; set; }

with something like the sample class I've posted in the first edit.

Detect if an element is visible with jQuery

There's no need, just use fadeToggle() on the element:

$('#testElement').fadeToggle('fast');

Here's a demo.

Using intents to pass data between activities

In FirstActivity:

Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);

In SecondActivity

In onCreate()

String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");

stringstream, string, and char* conversion confusion

What you're doing is creating a temporary. That temporary exists in a scope determined by the compiler, such that it's long enough to satisfy the requirements of where it's going.

As soon as the statement const char* cstr2 = ss.str().c_str(); is complete, the compiler sees no reason to keep the temporary string around, and it's destroyed, and thus your const char * is pointing to free'd memory.

Your statement string str(ss.str()); means that the temporary is used in the constructor for the string variable str that you've put on the local stack, and that stays around as long as you'd expect: until the end of the block, or function you've written. Therefore the const char * within is still good memory when you try the cout.

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

I just got the same error, when I didn't use the correct case. I could checkout out 'integration'. Git told me to perform a git pull to update my branch. I did that, but received the mentioned error. The correct branch name is 'Integration' with a capital 'I'. When I checked out that branch and pulled, it worked without problem.

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

Java String declaration

First one will create new String object in heap and str will refer it. In addition literal will also be placed in String pool. It means 2 objects will be created and 1 reference variable.

Second option will create String literal in pool only and str will refer it. So only 1 Object will be created and 1 reference. This option will use the instance from String pool always rather than creating new one each time it is executed.

How to read the last row with SQL Server

You'll need some sort of uniquely identifying column in your table, like an auto-filling primary key or a datetime column (preferably the primary key). Then you can do this:

SELECT * FROM table_name ORDER BY unique_column DESC LIMIT 1

The ORDER BY column tells it to rearange the results according to that column's data, and the DESC tells it to reverse the results (thus putting the last one first). After that, the LIMIT 1 tells it to only pass back one row.

How to convert SQL Query result to PANDAS Data Structure?

pandas.io.sql.write_frame is DEPRECATED. https://pandas.pydata.org/pandas-docs/version/0.15.2/generated/pandas.io.sql.write_frame.html

Should change to use pandas.DataFrame.to_sql https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html

There is another solution. PYODBC to Pandas - DataFrame not working - Shape of passed values is (x,y), indices imply (w,z)

As of Pandas 0.12 (I believe) you can do:

import pandas
import pyodbc

sql = 'select * from table'
cnn = pyodbc.connect(...)

data = pandas.read_sql(sql, cnn)

Prior to 0.12, you could do:

import pandas
from pandas.io.sql import read_frame
import pyodbc

sql = 'select * from table'
cnn = pyodbc.connect(...)

data = read_frame(sql, cnn)

How to get full REST request body using Jersey?

Turns out you don't have to do much at all.

See below - the parameter x will contain the full HTTP body (which is XML in our case).

@POST
public Response go(String x) throws IOException {
    ...
}

How to call a MySQL stored procedure from within PHP code?

I now found solution by using mysqli instead of mysql.

<?php 

// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to database
$connection = mysqli_connect("hostname", "user", "password", "db", "port");

//run the store proc
$result = mysqli_query($connection, "CALL StoreProcName");

//loop the result set
while ($row = mysqli_fetch_array($result)){     
  echo $row[0] . " - " . + $row[1]; 
}

I found that many people seem to have a problem with using mysql_connect, mysql_query and mysql_fetch_array.

How to send POST request in JSON using HTTPClient in Android?

There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.

/**
 * This method is used to process GET requests to the server.
 * 
 * @param url 
 * @return String
 * @throws IOException
 */
public static String connect(String url) throws IOException {

    HttpGet httpget = new HttpGet(url);
    HttpResponse response;
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    try {

        response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            //instream.close();
        }
    } 
    catch (ClientProtocolException e) {
        Utilities.showDLog("connect","ClientProtocolException:-"+e);
    } catch (IOException e) {
        Utilities.showDLog("connect","IOException:-"+e); 
    }
    return result;
}


 /**
 * This method is used to send POST requests to the server.
 * 
 * @param URL
 * @param paramenter
 * @return result of server response
 */
static public String postHTPPRequest(String URL, String paramenter) {       

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(URL);
    httppost.setHeader("Content-Type", "application/json");
    try {
        if (paramenter != null) {
            StringEntity tmp = null;
            tmp = new StringEntity(paramenter, "UTF-8");
            httppost.setEntity(tmp);
        }
        HttpResponse httpResponse = null;
        httpResponse = httpclient.execute(httppost);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            InputStream input = null;
            input = entity.getContent();
            String res = convertStreamToString(input);
            return res;
        }
    } 
     catch (Exception e) {
        System.out.print(e.toString());
    }
    return null;
}

Batch - If, ElseIf, Else

@echo off

set "language=de"

IF "%language%" == "de" (
    goto languageDE
) ELSE (
    IF "%language%" == "en" (
        goto languageEN
    ) ELSE (
    echo Not found.
    )
)

:languageEN
:languageDE

echo %language%

This works , but not sure how your language variable is defined.Does it have spaces in its definition.

Getting the first and last day of a month, using a given DateTime object

DateTime dCalcDate = DateTime.Now;
dtpFromEffDate.Value = new DateTime(dCalcDate.Year, dCalcDate.Month, 1);
dptToEffDate.Value = new DateTime(dCalcDate.Year, dCalcDate.Month, DateTime.DaysInMonth(dCalcDate.Year, dCalcDate.Month));

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

How do I raise an exception in Rails so it behaves like other Rails exceptions?

If you need an easier way to do it, and don't want much fuss, a simple execution could be:

raise Exception.new('something bad happened!')

This will raise an exception, say e with e.message = something bad happened!

and then you can rescue it as you are rescuing all other exceptions in general.

Is it possible to force row level locking in SQL Server?

Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:

ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);

pandas groupby sort descending order

This kind of operation is covered under hierarchical indexing. Check out the examples here

When you groupby, you're making new indices. If you also pass a list through .agg(). you'll get multiple columns. I was trying to figure this out and found this thread via google.

It turns out if you pass a tuple corresponding to the exact column you want sorted on.

Try this:

# generate toy data 
ex = pd.DataFrame(np.random.randint(1,10,size=(100,3)), columns=['features', 'AUC', 'recall'])

# pass a tuple corresponding to which specific col you want sorted. In this case, 'mean' or 'AUC' alone are not unique. 
ex.groupby('features').agg(['mean','std']).sort_values(('AUC', 'mean'))

This will output a df sorted by the AUC-mean column only.

Could not resolve this reference. Could not locate the assembly

In my case I had the following warnings:

Could not resolve this reference. Could not locate the assembly "x". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

No way to resolve conflict between "x, Version=1.0.0.248, Culture=neutral, PublicKeyToken=null" and "x". Choosing "x, Version=1.0.0.248

The path to the dll was correct in my .csproj file but I had it referenced twice and the second reference was with another version. Once I deleted the unnecessary reference, the warning disappeared.

Laravel 4: Redirect to a given url

Both Redirect::to() and Redirect::away() should work.

Difference

Redirect::to() does additional URL checks and generations. Those additional steps are done in Illuminate\Routing\UrlGenerator and do the following, if the passed URL is not a fully valid URL (even with protocol):

Determines if URL is secure
rawurlencode() the URL
trim() URL

src : https://medium.com/@zwacky/laravel-redirect-to-vs-redirect-away-dd875579951f

array filter in python?

>>> a = set([6, 7, 8, 9, 10, 11, 12])
>>> sub_a = set([6, 9, 12])
>>> a - sub_a
set([8, 10, 11, 7])

Laravel Eloquent compare date from datetime field

If you're still wondering how to solve it.

I use

$protected $dates = ['created_at','updated_at','aired'];

In my model and in my where i do

where('aired','>=',time())

So just use the unix to compaire in where.

In views on the otherhand you have to use the date object.

Hope it helps someone!

Converting integer to digit list

There are already great methods already mentioned on this page, however it does seem a little obscure as to which to use. So I have added some mesurements so you can more easily decide for yourself:


A large number has been used (for overhead) 1111111111111122222222222222222333333333333333333333

Using map(int, str(num)):

import timeit

def method():
    num = 1111111111111122222222222222222333333333333333333333
    return map(int, str(num))

print(timeit.timeit("method()", setup="from __main__ import method", number=10000)

Output: 0.018631496999999997

Using list comprehension:

import timeit

def method():
    num = 1111111111111122222222222222222333333333333333333333
    return [int(x) for x in str(num)]

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.28403817900000006

Code taken from this answer

The results show that the first method involving inbuilt methods is much faster than list comprehension.

The "mathematical way":

import timeit

def method():
    q = 1111111111111122222222222222222333333333333333333333
    ret = []
    while q != 0:
        q, r = divmod(q, 10) # Divide by 10, see the remainder
        ret.insert(0, r) # The remainder is the first to the right digit
    return ret

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.38133582499999996

Code taken from this answer

The list(str(123)) method (does not provide the right output):

import timeit

def method():
    return list(str(1111111111111122222222222222222333333333333333333333))
    
print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.028560138000000013

Code taken from this answer

The answer by Duberly González Molinari:

import timeit

def method():
    n = 1111111111111122222222222222222333333333333333333333
    l = []
    while n != 0:
        l = [n % 10] + l
        n = n // 10
    return l

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.37039988200000007

Code taken from this answer

Remarks:

In all cases the map(int, str(num)) is the fastest method (and is therefore probably the best method to use). List comprehension is the second fastest (but the method using map(int, str(num)) is probably the most desirable of the two.

Those that reinvent the wheel are interesting but are probably not so desirable in real use.

Angular 2 - Checking for server errors from subscribe

As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.

For reference:

  1. [onNext] (Function): Function to invoke for each element in the observable sequence.
  2. [onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
  3. [onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.

Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).

this.httpService.makeRequest()
    .subscribe(
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
      }
    );

As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).

Rx.Observable.prototype.finally(action)

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

For instance, here is a basic example:

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';

// ...

this.httpService.getRequest()
    .finally(() => {
      // Execute after graceful or exceptionally termination
      console.log('Handle logging logic...');
    })
    .subscribe (
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // No errors, route to new page
      }
    );

How to change background color in the Notepad++ text editor?

There seems to have been an update some time in the past 3 years which changes the location of where to place themes in order to get them working.

Previosuly, themes were located in the Notepad++ installation folder. Now they are located in AppData:

C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes

My answer is an update to @Amit-IO's answer about manually copying the themes.

  1. In Explorer, browse to: %AppData%\Notepad++.
  2. If a folder called themes does not exist, create it.
  3. Download your favourite theme from wherever (see Amit-IO's answer for a good list) and save it to %AppData%\Notepad++\themes.
  4. Restart Notepad++ and then use Settings -> Style Configurator. The new theme(s) will appear in the list.

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

Leave only two decimal places after the dot

double amount = 31.245678;
amount = Math.Floor(amount * 100) / 100;

keyCode values for numeric keypad?

The answer by @.A. Morel I find to be the best easy to understand solution with a small footprint. Just wanted to add on top if you want a smaller code amount this solution which is a modification of Morel works well for not allowing letters of any sort including inputs notorious 'e' character.

function InputTypeNumberDissallowAllCharactersExceptNumeric() {
  let key = Number(inputEvent.key);
  return !isNaN(key);
}

I get exception when using Thread.sleep(x) or wait()

When using Android (the only time when I use Java) I would recommend using a handler instead putting the thread to sleep.

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Log.i(TAG, "I've waited for two hole seconds to show this!");

        }
    }, 2000);

Reference: http://developer.android.com/reference/android/os/Handler.html

Iterate all files in a directory using a 'for' loop

I use the xcopy command with the /L option to get the file names. So if you want to get either a directory or all the files in the subdirectory you could do something like this:

for /f "delims=" %%a IN ('xcopy "D:\*.pdf" c:\ /l') do echo %%a

I just use the c:\ as the destination because it always exists on windows systems and it is not copying so it does not matter. if you want the subdirectories too just use /s option on the end. You can also use the other switches of xcopy if you need them for other reasons.

How to center text vertically with a large font-awesome icon?

When using a flexbox, vertical alignment of font awesome icons next to text can be very difficult. I tried margins and padding, but that moved all items. I tried different flex alignments like center, start, baseline, etc, to no avail. The easiest and cleanest way to adjust only the icon was to set it's containing div to position: relative; top: XX; This did the job perfectly.

ReferenceError: $ is not defined

jQuery is a JavaScript library, The purpose of jQuery is to make code much easier to use JavaScript.

The jQuery syntax is tailor-made for selecting, A $ sign to define/access jQuery.

Its in declaration sequence must be on top then any other script included which uses jQuery

Correct position to jQuery declaration :

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    console.log('hi from jQuery!');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
_x000D_
_x000D_
_x000D_

Above example will work perfectly because jQuery library is initialized before any other library which is using jQuery functions, including $

But if you apply it somewhere else, jQuery functions will not initialize in browser DOM and it will not able to identify any code related to jQuery, and its code starts with $ sign, so you will receive $ is not a function error.

Incorrect position for jQuery declaration:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    console.log('hi from jQuery!');_x000D_
});
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Above code will not work because, jQuery is not declared on the top of any library which uses jQuery ready function.

How to get multiple selected values from select box in JSP?

It would seem overkill but Spring Forms handles this elegantly. That is of course if you are already using Spring MVC and you want to take advantage of the Spring Forms feature.

// jsp form
    <form:select path="friendlyNumber" items="${friendlyNumberItems}" />

    // the command class
    public class NumberCmd {
      private String[] friendlyNumber;
    }

    // in your Spring MVC controller submit method
    @RequestMapping(method=RequestMethod.POST)
    public String manageOrders(@ModelAttribute("nbrCmd") NumberCmd nbrCmd){

       String[] selectedNumbers = nbrCmd.getFriendlyNumber();

    }

How can I do DNS lookups in Python, including referring to /etc/hosts?

I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:

#!/usr/bin/python

def expand_dnsname(dnsname):
    from socket import getaddrinfo
    from dns import reversename, resolver
    namelist = [ ]
    # expand hostname into dict of ip addresses
    iplist = dict()
    for answer in getaddrinfo(dnsname, 80):
        ipa = str(answer[4][0])
        iplist[ipa] = 0
    # run through the list of IP addresses to get hostnames
    for ipaddr in sorted(iplist):
        rev_name = reversename.from_address(ipaddr)
        # run through all the hostnames returned, ignoring the dnsname
        for answer in resolver.query(rev_name, "PTR"):
            name = str(answer)
            if name != dnsname:
                # add it to the list of answers
                namelist.append(name)
                break
    # if no other choice, return the dnsname
    if len(namelist) == 0:
        namelist.append(dnsname)
    # return the sorted namelist
    namelist = sorted(namelist)
    return namelist

namelist = expand_dnsname('google.com.')
for name in namelist:
    print name

Which, when I run it, lists a few 1e100.net hostnames:

How do I upgrade to Python 3.6 with conda?

Anaconda has not updated python internally to 3.6.

a) Method 1

  1. If you wanted to update you will type conda update python
  2. To update anaconda type conda update anaconda
  3. If you want to upgrade between major python version like 3.5 to 3.6, you'll have to do

    conda install python=$pythonversion$
    

b) Method 2 - Create a new environment (Better Method)

conda create --name py36 python=3.6

c) To get the absolute latest python(3.6.5 at time of writing)

conda create --name py365 python=3.6.5 --channel conda-forge

You can see all this from here

Also, refer to this for force upgrading

EDIT: Anaconda now has a Python 3.6 version here

Git diff says subproject is dirty

Also removing the submodule and then running git submodule init and git submodule update will obviously do the trick, but may not always be appropriate or possible.

How to use WHERE IN with Doctrine 2

I struggled with this same scenario where I had to do a query against an array of values.

The following worked for me:

http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/dql-doctrine-query-language.html#where-clause

->andWhereIn("[fieldname]", [array[]])

Array data example (worked with strings and integers):

$ids = array(1, 2, 3, 4);

Query example (Adapt to where you need it):

$q = dataTable::getInstance()
    ->createQuery()
    ->where("name = ?",'John')
    ->andWhereIn("image_id", $ids)
    ->orderBy('date_created ASC')
    ->limit(100);

$q->execute();

How to configure encoding in Maven?

It seems people mix a content encoding with a built files/resources encoding. Having only maven properties is not enough. Having -Dfile.encoding=UTF8 not effective. To avoid having issues with encoding you should follow the following simple rules

  1. Set maven encoding, as described above:
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  1. Always set encoding explicitly, when work with files, strings, IO in your code. If you do not follow this rule, your application depend on the environment. The -Dfile.encoding=UTF8 exactly is responsible for run-time environment configuration, but we should not depend on it. If you have thousands of clients, it takes more effort to configure systems and to find issues because of it. You just have an additional dependency on it which you can avoid by setting it explicitly. Most methods in Java that use a default encoding are marked as deprecated because of it.

  2. Make sure the content, you are working with, also is in the same encoding, that you expect. If it is not, the previous steps do not matter! For instance a file will not be processed correctly, if its encoding is not UTF8 but you expect it. To check file encoding on Linux:

$ file --mime F_PRDAUFT.dsv

  1. Force clients/server set encoding explicitly in requests/responses, here are examples:
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")

Hope this will be useful to someone.

How do you initialise a dynamic array in C++?

The array form of new-expression accepts only one form of initializer: an empty (). This, BTW, has the same effect as the empty {} in your non-dynamic initialization.


The above applies to pre-C++11 language. Starting from C++11 one can use uniform initialization syntax with array new-expressions

char* c = new char[length]{};
char* d = new char[length]{ 'a', 'b', 'c' };

Combining C++ and C - how does #ifdef __cplusplus work?

  1. extern "C" doesn't change the presence or absence of the __cplusplus macro. It just changes the linkage and name-mangling of the wrapped declarations.

  2. You can nest extern "C" blocks quite happily.

  3. If you compile your .c files as C++ then anything not in an extern "C" block, and without an extern "C" prototype will be treated as a C++ function. If you compile them as C then of course everything will be a C function.

  4. Yes

  5. You can safely mix C and C++ in this way.

NameError: uninitialized constant (rails)

Some things to try:

  1. Restart the rails console; changes to your models will only get picked up by a rails console that is already open if you do > reload! (although I have found this to be unpredictable), or by restarting the console.

  2. Is your model file called "phone_number.rb" and is it in "/app/models"?

  3. You should double-check the "--sandbox" option on your rails console command. AFAIK, this prevents changes. Try it without the switch.

Installation Issue with matplotlib Python

Problem Cause

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

Solution

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

From this link you can try different diagrams.

How can I account for period (AM/PM) using strftime?

format = '%Y-%m-%d %H:%M %p'

The format is using %H instead of %I. Since %H is the "24-hour" format, it's likely just discarding the %p information. It works just fine if you change the %H to %I.

Converting a number with comma as decimal point to float

Assuming they are in a file or array just do the replace as a batch (i.e. on all at once):

$input = str_replace(array('.', ','), array('', '.'), $input); 

and then process the numbers from there taking full advantage of PHP's loosely typed nature.

one line if statement in php

use the ternary operator ?:

change this

<?php if ($requestVars->_name == '') echo $redText; ?>

with

<?php echo ($requestVars->_name == '') ? $redText : ''; ?>

In short

// (Condition)?(thing's to do if condition true):(thing's to do if condition false);

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

What is unexpected T_VARIABLE in PHP?

It could be some other line as well. PHP is not always that exact.

Probably you are just missing a semicolon on previous line.

How to reproduce this error, put this in a file called a.php:

<?php
  $a = 5
  $b = 7;        // Error happens here.
  print $b;
?>

Run it:

eric@dev ~ $ php a.php

PHP Parse error:  syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3

Explanation:

The PHP parser converts your program to a series of tokens. A T_VARIABLE is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.

In the simple case above with variable $b, the parser tried to process this:

$a = 5 $b = 7;

The PHP parser looks at the $b after the 5 and says "that is unexpected".

Regular Expression to match every new line character (\n) inside a <content> tag

Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:

<!-- <content> blah </content> -->

You can take two approaches here:

  1. Strip all comments out first. Then use the regex approach.
  2. Do not use regular expressions and use a context sensitive parsing approach that can keep track of whether or not you are nested in a comment.

Be careful.

I am also not so sure you can match all new lines at once. @Quartz suggested this one:

<content>([^\n]*\n+)+</content>

This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:

<content>.*</content>

BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.

I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.

I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...

UPDATE 1:

Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):

To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.

Similarly, to search for content tags, use: .*?

Also, You may be able to try this out, and access each newline character with the match objects groups():

<content>(.*?(\n))+.*?</content>

I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.

UPDATE 2:

So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:

#!/usr/bin/python

import re

def FindContentNewlines(xml_text):
    # May want to compile these regexes elsewhere, but I do it here for brevity
    comments = re.compile(r"<!--.*?-->", re.DOTALL)
    content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
    newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)

    # strip comments: this actually may not be reliable for "nested comments"
    # How does xml handle <!--  <!-- --> -->. I am not sure. But that COULD
    # be trouble.
    xml_text = re.sub(comments, "", xml_text)

    result = []
    all_contents = re.findall(content, xml_text)
    for c in all_contents:
        result.extend(re.findall(newlines, c))

    return result

if __name__ == "__main__":
    example = """

<!-- This stuff
ought to be omitted
<content>
  omitted
</content>
-->

This stuff is good
<content>
<p>
  haha!
</p>
</content>

This is not found
"""
    print FindContentNewlines(example)

This program prints the result:

 ['', '<p>', '  haha!', '</p>', '']

The first and last empty strings come from the newline chars immediately preceeding the first <p> and the one coming right after the </p>. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.

Hope this helps :-).

PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.

What is meant by the term "hook" in programming?

Essentially it's a place in code that allows you to tap in to a module to either provide different behavior or to react when something happens.

Download files in laravel using Response::download

Quite a few of these solutions suggest referencing the public_path() of the Laravel application in order to locate the file. Sometimes you'll want to control access to the file or offer real-time monitoring of the file. In this case, you'll want to keep the directory private and limit access by a method in a controller class. The following method should help with this:

public function show(Request $request, File $file) {

    // Perform validation/authentication/auditing logic on the request

    // Fire off any events or notifiations (if applicable)

    return response()->download(storage_path('app/' . $file->location));
}

There are other paths that you could use as well, described on Laravel's helper functions documentation

How to design RESTful search/filtering?

It seems that resource filtering/searching can be implemented in a RESTful way. The idea is to introduce a new endpoint called /filters/ or /api/filters/.

Using this endpoint filter can be considered as a resource and hence created via POST method. This way - of course - body can be used to carry all the parameters as well as complex search/filter structures can be created.

After creating such filter there are two possibilities to get the search/filter result.

  1. A new resource with unique ID will be returned along with 201 Created status code. Then using this ID a GET request can be made to /api/users/ like:

    GET /api/users/?filterId=1234-abcd
    
  2. After new filter is created via POST it won't reply with 201 Created but at once with 303 SeeOther along with Location header pointing to /api/users/?filterId=1234-abcd. This redirect will be automatically handled via underlying library.

In both scenarios two requests need to be made to get the filtered results - this may be considered as a drawback, especially for mobile applications. For mobile applications I'd use single POST call to /api/users/filter/.

How to keep created filters?

They can be stored in DB and used later on. They can also be stored in some temporary storage e.g. redis and have some TTL after which they will expire and will be removed.

What are the advantages of this idea?

Filters, filtered results are cacheable and can be even bookmarked.

Ignore self-signed ssl cert using Jersey Client

Just adding the same code with the imports. Also contains the unimplemented code that is needed for compilation. I initially had trouble finding out what was imported for this code. Also adding the right package for the X509Certificate. Got this working with trial and error:

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import javax.ws.rs.core.MultivaluedMap;

 TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

     public java.security.cert.X509Certificate[] getAcceptedIssuers() {
         java.security.cert.X509Certificate[] chck = null;
         ;
         return chck;
     }

     public void checkServerTrusted(X509Certificate[] arg0, String arg1)
             throws CertificateException {
         // TODO Auto-generated method stub

     }

     public void checkClientTrusted(X509Certificate[] arg0, String arg1)
             throws CertificateException {

     }

     public void checkClientTrusted(
             java.security.cert.X509Certificate[] arg0, String arg1)
                     throws java.security.cert.CertificateException {
         // TODO Auto-generated method stub

     }

     public void checkServerTrusted(
             java.security.cert.X509Certificate[] arg0, String arg1)
                     throws java.security.cert.CertificateException {
         // TODO Auto-generated method stub

     }
 } };

 // Install the all-trusting trust manager
 try {
     SSLContext sc = SSLContext.getInstance("TLS");
     sc.init(null, trustAllCerts, new SecureRandom());
     HttpsURLConnection
     .setDefaultSSLSocketFactory(sc.getSocketFactory());
 } catch (Exception e) {
     ;
 }

How to convert a UTF-8 string into Unicode?

If you have a UTF-8 string, where every byte is correct ('Ö' -> [195, 0] , [150, 0]), you can use the following:

public static string Utf8ToUtf16(string utf8String)
{
    /***************************************************************
     * Every .NET string will store text with the UTF-16 encoding, *
     * known as Encoding.Unicode. Other encodings may exist as     *
     * Byte-Array or incorrectly stored with the UTF-16 encoding.  *
     *                                                             *
     * UTF-8 = 1 bytes per char                                    *
     *    ["100" for the ansi 'd']                                 *
     *    ["206" and "186" for the russian '?']                    *
     *                                                             *
     * UTF-16 = 2 bytes per char                                   *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["186, 3" for the russian '?']                           *
     *                                                             *
     * UTF-8 inside UTF-16                                         *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["206, 0" and "186, 0" for the russian '?']              *
     *                                                             *
     * First we need to get the UTF-8 Byte-Array and remove all    *
     * 0 byte (binary 0) while doing so.                           *
     *                                                             *
     * Binary 0 means end of string on UTF-8 encoding while on     *
     * UTF-16 one binary 0 does not end the string. Only if there  *
     * are 2 binary 0, than the UTF-16 encoding will end the       *
     * string. Because of .NET we don't have to handle this.       *
     *                                                             *
     * After removing binary 0 and receiving the Byte-Array, we    *
     * can use the UTF-8 encoding to string method now to get a    *
     * UTF-16 string.                                              *
     *                                                             *
     ***************************************************************/

    // Get UTF-8 bytes and remove binary 0 bytes (filler)
    List<byte> utf8Bytes = new List<byte>(utf8String.Length);
    foreach (byte utf8Byte in utf8String)
    {
        // Remove binary 0 bytes (filler)
        if (utf8Byte > 0) {
            utf8Bytes.Add(utf8Byte);
        }
    }

    // Convert UTF-8 bytes to UTF-16 string
    return Encoding.UTF8.GetString(utf8Bytes.ToArray());
}

In my case the DLL result is a UTF-8 string too, but unfortunately the UTF-8 string is interpreted with UTF-16 encoding ('Ö' -> [195, 0], [19, 32]). So the ANSI '–' which is 150 was converted to the UTF-16 '–' which is 8211. If you have this case too, you can use the following instead:

public static string Utf8ToUtf16(string utf8String)
{
    // Get UTF-8 bytes by reading each byte with ANSI encoding
    byte[] utf8Bytes = Encoding.Default.GetBytes(utf8String);

    // Convert UTF-8 bytes to UTF-16 bytes
    byte[] utf16Bytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, utf8Bytes);

    // Return UTF-16 bytes as UTF-16 string
    return Encoding.Unicode.GetString(utf16Bytes);
}

Or the Native-Method:

[DllImport("kernel32.dll")]
private static extern Int32 MultiByteToWideChar(UInt32 CodePage, UInt32 dwFlags, [MarshalAs(UnmanagedType.LPStr)] String lpMultiByteStr, Int32 cbMultiByte, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpWideCharStr, Int32 cchWideChar);

public static string Utf8ToUtf16(string utf8String)
{
    Int32 iNewDataLen = MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, null, 0);
    if (iNewDataLen > 1)
    {
        StringBuilder utf16String = new StringBuilder(iNewDataLen);
        MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, utf16String, utf16String.Capacity);

        return utf16String.ToString();
    }
    else
    {
        return String.Empty;
    }
}

If you need it the other way around, see Utf16ToUtf8. Hope I could be of help.

Pass values of checkBox to controller action in asp.net mvc4

I did had a problem with the most of solutions, since I was trying to use a checkbox with a specific style. I was in need of the values of the checkbox to send them to post from a list, once the values were collected, needed to save it. I did manage to work it around after a while.

Hope it helps someone. Here's the code below:

Controller:

    [HttpGet]
    public ActionResult Index(List<Model> ItemsModelList)
    {

        ItemsModelList = new List<Model>()
        {                
            //example two values
            //checkbox 1
            new Model{ CheckBoxValue = true},
            //checkbox 2
            new Model{ CheckBoxValue = false}

        };

        return View(new ModelLists
        {
            List = ItemsModelList

        });


    }

    [HttpPost]
    public ActionResult Index(ModelLists ModelLists)
    {
        //Use a break point here to watch values
        //Code... (save for example)
        return RedirectToAction("Index", "Home");

    }

Model 1:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace waCheckBoxWithModel.Models
    {
        public class Model
{

    public bool CheckBoxValue { get; set; }

}
    }

Model 2:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace waCheckBoxWithModel.Models
    {
        public class ModelLists
{

    public List<Model> List { get; set; }

}
    }

View (Index):

    @{
ViewBag.Title = "Index";

@model waCheckBoxWithModel.Models.ModelLists
    }
    <style>

.checkBox {
    display: block;
    position: relative;
    margin-bottom: 12px;
    cursor: pointer;
    font-size: 22px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

    /* hide default checkbox*/
    .checkBox input {
        position: absolute;
        opacity: 0;
        cursor: pointer;
    }

/* checkmark */
.checkmark {
    position: absolute;
    top: 0;
    left: 0;
    height: 25px;
    width: 25px;
    background: #fff;
    border-radius: 4px;
    border-width: 1px;
    box-shadow: inset 0px 0px 10px #ccc;
}

/* On mouse-over change backgroundcolor */
.checkBox:hover input ~ .checkmark {
    /*background-color: #ccc;*/
}

/* background effect */
.checkBox input:checked ~ .checkmark {
    background-color: #fff;
}

/* checkmark (hide when not checked) */
.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

/* show checkmark (checked) */
.checkBox input:checked ~ .checkmark:after {
    display: block;
}

/* Style checkmark */
.checkBox .checkmark:after {
    left: 9px;
    top: 7px;
    width: 5px;
    height: 10px;
    border: solid #1F4788;
    border-width: 0 2px 2px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}
   </style>

    @using (Html.BeginForm())
    {

    <div>

@{
    int cnt = Model.List.Count;
    int i = 0;

}

@foreach (var item in Model.List)
{

    {
        if (cnt >= 1)
        { cnt--; }
    }

    @Html.Label("Example" + " " + (i + 1))

    <br />

    <label class="checkBox">
        @Html.CheckBoxFor(m => Model.List[i].CheckBoxValue)
        <span class="checkmark"></span>
    </label>

    { i++;}

    <br />

}

<br />
<input type="submit" value="Go to Post Index" />    

    </div>

    }

fork and exec in bash

How about:

(sleep 5; echo "Hello World") &

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

DFS is more space-efficient than BFS, but may go to unnecessary depths.

Their names are revealing: if there's a big breadth (i.e. big branching factor), but very limited depth (e.g. limited number of "moves"), then DFS can be more preferrable to BFS.


On IDDFS

It should be mentioned that there's a less-known variant that combines the space efficiency of DFS, but (cummulatively) the level-order visitation of BFS, is the iterative deepening depth-first search. This algorithm revisits some nodes, but it only contributes a constant factor of asymptotic difference.

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

How can I make git show a list of the files that are being tracked?

If you want to list all the files currently being tracked under the branch master, you could use this command:

git ls-tree -r master --name-only

If you want a list of files that ever existed (i.e. including deleted files):

git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'

How do I read a large csv file with pandas?

You can read in the data as chunks and save each chunk as pickle.

import pandas as pd 
import pickle

in_path = "" #Path where the large file is
out_path = "" #Path to save the pickle files to
chunk_size = 400000 #size of chunks relies on your available memory
separator = "~"

reader = pd.read_csv(in_path,sep=separator,chunksize=chunk_size, 
                    low_memory=False)    


for i, chunk in enumerate(reader):
    out_file = out_path + "/data_{}.pkl".format(i+1)
    with open(out_file, "wb") as f:
        pickle.dump(chunk,f,pickle.HIGHEST_PROTOCOL)

In the next step you read in the pickles and append each pickle to your desired dataframe.

import glob
pickle_path = "" #Same Path as out_path i.e. where the pickle files are

data_p_files=[]
for name in glob.glob(pickle_path + "/data_*.pkl"):
   data_p_files.append(name)


df = pd.DataFrame([])
for i in range(len(data_p_files)):
    df = df.append(pd.read_pickle(data_p_files[i]),ignore_index=True)

rails 3 validation on uniqueness on multiple attributes

In Rails 2, I would have written:

validates_uniqueness_of :zipcode, :scope => :recorded_at

In Rails 3:

validates :zipcode, :uniqueness => {:scope => :recorded_at}

For multiple attributes:

validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}

How to get the top 10 values in postgresql?

Note that if there are ties in top 10 values, you will only get the top 10 rows, not the top 10 values with the answers provided. Ex: if the top 5 values are 10, 11, 12, 13, 14, 15 but your data contains 10, 10, 11, 12, 13, 14, 15 you will only get 10, 10, 11, 12, 13, 14 as your top 5 with a LIMIT

Here is a solution which will return more than 10 rows if there are ties but you will get all the rows where some_value_column is technically in the top 10.

select
  *
from
  (select
     *,
     rank() over (order by some_value_column desc) as my_rank
  from mytable) subquery
where my_rank <= 10

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

How to host google web fonts on my own server?

Great solution is google-webfonts-helper .

It allows you to select more than one font variant, which saves a lot of time.

Changing background colour of tr element on mouseover

I had the same problem:

tr:hover { background: #000 !important; }

allone did not work, but adding

tr:hover td { background: transparent; }

to the next line of my css did the job for me!! My problem was that some of the TDs already had a background-color assigned and I did not know that I have to set that to TRANSPARENT to make the tr:hover work.

Actually, I used it with a classnames:

.trclass:hover { background: #000 !important; }
.trclass:hover td { background: transparent; }

Thanks for these answers, they made my day!! :)

Storing Python dictionaries

Minimal example, writing directly to a file:

import json
json.dump(data, open(filename, 'wb'))
data = json.load(open(filename))

or safely opening / closing:

import json
with open(filename, 'wb') as outfile:
    json.dump(data, outfile)
with open(filename) as infile:
    data = json.load(infile)

If you want to save it in a string instead of a file:

import json
json_str = json.dumps(data)
data = json.loads(json_str)

How to add a progress bar to a shell script?

You can implement this by overwriting a line. Use \r to go back to the beginning of the line without writing \n to the terminal.

Write \n when you're done to advance the line.

Use echo -ne to:

  1. not print \n and
  2. to recognize escape sequences like \r.

Here's a demo:

echo -ne '#####                     (33%)\r'
sleep 1
echo -ne '#############             (66%)\r'
sleep 1
echo -ne '#######################   (100%)\r'
echo -ne '\n'

In a comment below, puk mentions this "fails" if you start with a long line and then want to write a short line: In this case, you'll need to overwrite the length of the long line (e.g., with spaces).

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

Adding this answer partially because it fixed my problem of the same issue and so I can bookmark this question myself.

I was able to fix it by doing the following:

sudo apt-get install gcc-multilib g++-multilib

If you've installed a version of gcc / g++ that doesn't ship by default (such as g++-4.8 on lucid) you'll want to match the version as well:

sudo apt-get install gcc-4.8-multilib g++-4.8-multilib

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

you may use this - https://github.com/chanakyachatterjee/JSLightGrid ..JSLightGrid. have a look.. I found this one really very useful. Good performance, very light weight, all important browser friendly and fluid in itself, so you don't really need bootstrap for the grid.

ImportError: No Module Named bs4 (BeautifulSoup)

You might want to try install bs4 with

pip install --ignore-installed BeautifulSoup4

if the methods above didn't work for you.

Is there a way to detect if a browser window is not currently active?

I create a Comet Chat for my app, and when I receive a message from another user I use:

if(new_message){
    if(!document.hasFocus()){
        audio.play();
        document.title="Have new messages";
    }
    else{
        audio.stop();
        document.title="Application Name";
    } 
}

Are email addresses case sensitive?

From RFC 5321, section 2.3.11:

The standard mailbox naming convention is defined to be "local-part@domain"; contemporary usage permits a much broader set of applications than simple "user names". Consequently, and due to a long history of problems when intermediate hosts have attempted to optimize transport by modifying them, the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address.

So yes, the part before the "@" could be case-sensitive, since it is entirely under the control of the host system. In practice though, no widely used mail systems distinguish different addresses based on case.

The part after the @ sign however is the domain and according to RFC 1035, section 3.1,

"Name servers and resolvers must compare [domains] in a case-insensitive manner"

In short, you are safe to treat email addresses as case-insensitive.

How do I retrieve the number of columns in a Pandas data frame?

Alternative:

df.shape[1]

(df.shape[0] is the number of rows)

Get raw POST body in Python Flask regardless of Content-Type header

I created a WSGI middleware that stores the raw body from the environ['wsgi.input'] stream. I saved the value in the WSGI environ so I could access it from request.environ['body_copy'] within my app.

This isn't necessary in Werkzeug or Flask, as request.get_data() will get the raw data regardless of content type, but with better handling of HTTP and WSGI behavior.

This reads the entire body into memory, which will be an issue if for example a large file is posted. This won't read anything if the Content-Length header is missing, so it won't handle streaming requests.

from io import BytesIO

class WSGICopyBody(object):
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        length = int(environ.get('CONTENT_LENGTH') or 0)
        body = environ['wsgi.input'].read(length)
        environ['body_copy'] = body
        # replace the stream since it was exhausted by read()
        environ['wsgi.input'] = BytesIO(body)
        return self.application(environ, start_response)

app.wsgi_app = WSGICopyBody(app.wsgi_app)
request.environ['body_copy']

How to remove all .svn directories from my application directories

You almost had it. If you want to pass the output of a command as parameters to another one, you'll need to use xargs. Adding -print0 makes sure the script can handle paths with whitespace:

find . -type d -name .svn -print0|xargs -0 rm -rf

How can Perl's print add a newline by default?

You can use the -l option in the she-bang header:

#!/usr/bin/perl -l

$text = "hello";

print $text;
print $text;

Output:

hello
hello

How to split a string between letters and digits (or between digits and letters)?

Use two different patterns: [0-9]* and [a-zA-Z]* and split twice by each of them.

Best TCP port number range for internal applications

I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.

Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.

Total   Start   End
829     29170   29998
815     38866   39680
710     41798   42507
681     43442   44122
661     46337   46997
643     35358   36000
609     36866   37474
596     38204   38799
592     33657   34248
571     30261   30831
563     41231   41793
542     21011   21552
528     28590   29117
521     14415   14935
510     26490   26999

Source (via the CSV download button):

http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

Alternate output format for psql

You have so many choices, how could you be confused :-)? The main controls are:

# \pset format
# \H
# \x
# \pset pager off

Each has options and interactions with the others. The most automatic options are:

# \x off;\pset format wrapped
# \x auto

The newer "\x auto" option switches to line-by-line display only "if needed".

-[ RECORD 1 ]---------------
id          | 6
description | This is a gallery of oilve oil brands.
authority   | I love olive oil, and wanted to create a place for
reviews and comments on various types.
-[ RECORD 2 ]---------------
id          | 19
description | XXX Test A 
authority   | Testing

The older "\pset format wrapped" is similar in that it tries to fit the data neatly on screen, but falls back to unaligned if the headers won't fit. Here's an example of wrapped:

 id |          description           |            authority            
----+--------------------------------+---------------------------------
  6 | This is a gallery of oilve     | I love olive oil, and wanted to
    ; oil brands.                    ;  create a place for reviews and
    ;                                ;  comments on various types.
 19 | Test Test A                    | Testing

T-SQL loop over query results

You could do something like this:

create procedure test
as
BEGIN

    create table #ids
    (
        rn int,
        id int
    )

    insert into #ids (rn, id)
    select distinct row_number() over(order by id) as rn, id
    from table

    declare @id int
    declare @totalrows int = (select count(*) from #ids)
    declare @currentrow int = 0

    while @currentrow <  @totalrows  
    begin 
        set @id = (select id from #ids where rn = @currentrow)

        exec stored_proc @varName=@id, @otherVarName='test'

        set @currentrow = @currentrow +1
    end  

END

Random alpha-numeric string in JavaScript?

Nice and simple, and not limited to a certain number of characters:

let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);

get all characters to right of last dash

You can get the position of the last - with str.LastIndexOf('-'). So the next step is obvious:

var result = str.Substring(str.LastIndexOf('-') + 1);

Correction:

As Brian states below, using this on a string with no dashes will result in the same string being returned.

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

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

The jQuery documentation is your friend.

How do I find where JDK is installed on my windows machine?

Have you tried looking at your %PATH% variable. That's what Windows uses to find any executable.

What is an unhandled promise rejection?

Promises can be "handled" after they are rejected. That is, one can call a promise's reject callback before providing a catch handler. This behavior is a little bothersome to me because one can write...

var promise = new Promise(function(resolve) {
kjjdjf(); // this function does not exist });

... and in this case, the Promise is rejected silently. If one forgets to add a catch handler, code will continue to silently run without errors. This could lead to lingering and hard-to-find bugs.

In the case of Node.js, there is talk of handling these unhandled Promise rejections and reporting the problems. This brings me to ES7 async/await. Consider this example:

async function getReadyForBed() {
  let teethPromise = brushTeeth();
  let tempPromise = getRoomTemperature();

  // Change clothes based on room temperature
  let temp = await tempPromise;
  // Assume `changeClothes` also returns a Promise
  if(temp > 20) {
    await changeClothes("warm");
  } else {
    await changeClothes("cold");
  }

  await teethPromise;
}

In the example above, suppose teethPromise was rejected (Error: out of toothpaste!) before getRoomTemperature was fulfilled. In this case, there would be an unhandled Promise rejection until await teethPromise.

My point is this... if we consider unhandled Promise rejections to be a problem, Promises that are later handled by an await might get inadvertently reported as bugs. Then again, if we consider unhandled Promise rejections to not be problematic, legitimate bugs might not get reported.

Thoughts on this?

This is related to the discussion found in the Node.js project here:

Default Unhandled Rejection Detection Behavior

if you write the code this way:

function getReadyForBed() {
  let teethPromise = brushTeeth();
  let tempPromise = getRoomTemperature();

  // Change clothes based on room temperature
  return Promise.resolve(tempPromise)
    .then(temp => {
      // Assume `changeClothes` also returns a Promise
      if (temp > 20) {
        return Promise.resolve(changeClothes("warm"));
      } else {
        return Promise.resolve(changeClothes("cold"));
      }
    })
    .then(teethPromise)
    .then(Promise.resolve()); // since the async function returns nothing, ensure it's a resolved promise for `undefined`, unless it's previously rejected
}

When getReadyForBed is invoked, it will synchronously create the final (not returned) promise - which will have the same "unhandled rejection" error as any other promise (could be nothing, of course, depending on the engine). (I find it very odd your function doesn't return anything, which means your async function produces a promise for undefined.

If I make a Promise right now without a catch, and add one later, most "unhandled rejection error" implementations will actually retract the warning when i do later handle it. In other words, async/await doesn't alter the "unhandled rejection" discussion in any way that I can see.

to avoid this pitfall please write the code this way:

async function getReadyForBed() {
  let teethPromise = brushTeeth();
  let tempPromise = getRoomTemperature();

  // Change clothes based on room temperature
  var clothesPromise = tempPromise.then(function(temp) {
    // Assume `changeClothes` also returns a Promise
    if(temp > 20) {
      return changeClothes("warm");
    } else {
      return changeClothes("cold");
    }
  });
  /* Note that clothesPromise resolves to the result of `changeClothes`
     due to Promise "chaining" magic. */

  // Combine promises and await them both
  await Promise.all(teethPromise, clothesPromise);
}

Note that this should prevent any unhandled promise rejection.

How to test if a string is basically an integer in quotes using Ruby

You can use regular expressions. Here is the function with @janm's suggestions.

class String
    def is_i?
       !!(self =~ /\A[-+]?[0-9]+\z/)
    end
end

An edited version according to comment from @wich:

class String
    def is_i?
       /\A[-+]?\d+\z/ === self
    end
end

In case you only need to check positive numbers

  if !/\A\d+\z/.match(string_to_check)
      #Is not a positive number
  else
      #Is all good ..continue
  end  

Change drawable color programmatically

Try this:

Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, R.drawable.my_drawable); 
Drawable wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
DrawableCompat.setTint(wrappedDrawable, Color.RED);    

Using DrawableCompat is important because it provides backwards compatibility and bug fixes on API 22 devices and earlier.

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

Gmail: OAuth

  • Goto the link
  • Login with your gmail username password
  • Click on the google menu at the top left
  • Click API Manager
  • Click on Credentials
  • Click Create Credentials and select OAuth Client
  • Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of Client ID and Secret ID. Finally click OK to close the credentials pop up.
  • Next important step is to enable the Google API. Click on Overview in the left pane.
  • Click on the Google API under Social APIs section.
  • Click Enable.

That’s all from the Google part.

Come back to your application, open App_start/Startup.Auth.cs and uncomment the following snippet

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = ""
        });

Update the ClientId and ClientSecret with the values from Google API credentials which you have created already.

  • Run your application
  • Click Login
  • You will see the Google button under ‘Use Another Section to log in’ section
  • Click on the Google button
  • Application will prompt you to enter the username and password
  • Enter the gmail username and password and click Sign In
  • This will perform the OAuth and come back to your application and prompting you to register with the Gmail id.
  • Click register to register the Gmail id into your application database.
  • You will see the Identity details appear in the top as normal registration
  • Try logout and login again thru Gmail. This will automatically logs you into the app.

Deploy a project using Git push

We use capistrano for managing deploy. We build capistrano to deploy on a staging server, and then running a rsync with all of ours server.

cap deploy
cap deploy:start_rsync (when the staging is ok)

With capistrano, we can made easy rollback in case of bug

cap deploy:rollback
cap deploy:start_rsync

Scheduling Python Script to run every hour accurately

Run the script every 15 minutes of the hour. For example, you want to receive 15 minute stock price quotes, which are updated every 15 minutes.

while True:
    print("Update data:", datetime.now())
    sleep = 15 - datetime.now().minute % 15
    if sleep == 15:
        run_strategy()
        time.sleep(sleep * 60)
    else:
        time.sleep(sleep * 60)

PostgreSQL: export resulting data from SQL query to Excel/CSV

In PostgreSQL 9.4 to create to file CSV with the header in Ubuntu:

COPY (SELECT * FROM tbl) TO '/home/user/Desktop/result_sql.csv' WITH CSV HEADER;

Note: The folder must be writable.

Plotting histograms from grouped data in a pandas DataFrame

Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist() it's trying to make a histogram of both columns hence the str error.

This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.

df.reset_index().pivot('index','Letter','N').hist()

The reset_index() is just to shove the current index into a column called index. Then pivot will take your data frame, collect all of the values N for each Letter and make them a column. The resulting data frame as 400 rows (fills missing values with NaN) and three columns (A, B, C). hist() will then produce one histogram per column and you get format the plots as needed.

SQL Server: IF EXISTS ; ELSE

EDIT

I want to add the reason that your IF statement seems to not work. When you do an EXISTS on an aggregate, it's always going to be true. It returns a value even if the ID doesn't exist. Sure, it's NULL, but its returning it. Instead, do this:

if exists(select 1 from table where id = 4)

and you'll get to the ELSE portion of your IF statement.


Now, here's a better, set-based solution:

update b
  set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
  on b.id = a.id
where
  b.id = yourid

This has the benefit of being able to run on the entire table rather than individual ids.

What is the function of the push / pop instructions used on registers in x86 assembly?

Where is it pushed on?

esp - 4. More precisely:

  • esp gets subtracted by 4
  • the value is pushed to esp

pop reverses this.

The System V ABI tells Linux to make rsp point to a sensible stack location when the program starts running: What is default register state when program launches (asm, linux)? which is what you should usually use.

How can you push a register?

Minimal GNU GAS example:

.data
    /* .long takes 4 bytes each. */
    val1:
        /* Store bytes 0x 01 00 00 00 here. */
        .long 1
    val2:
        /* 0x 02 00 00 00 */
        .long 2
.text
    /* Make esp point to the address of val2.
     * Unusual, but totally possible. */
    mov $val2, %esp

    /* eax = 3 */
    mov $3, %ea 

    push %eax
    /*
    Outcome:
    - esp == val1
    - val1 == 3
    esp was changed to point to val1,
    and then val1 was modified.
    */

    pop %ebx
    /*
    Outcome:
    - esp == &val2
    - ebx == 3
    Inverses push: ebx gets the value of val1 (first)
    and then esp is increased back to point to val2.
    */

The above on GitHub with runnable assertions.

Why is this needed?

It is true that those instructions could be easily implemented via mov, add and sub.

They reason they exist, is that those combinations of instructions are so frequent, that Intel decided to provide them for us.

The reason why those combinations are so frequent, is that they make it easy to save and restore the values of registers to memory temporarily so they don't get overwritten.

To understand the problem, try compiling some C code by hand.

A major difficulty, is to decide where each variable will be stored.

Ideally, all variables would fit into registers, which is the fastest memory to access (currently about 100x faster than RAM).

But of course, we can easily have more variables than registers, specially for the arguments of nested functions, so the only solution is to write to memory.

We could write to any memory address, but since the local variables and arguments of function calls and returns fit into a nice stack pattern, which prevents memory fragmentation, that is the best way to deal with it. Compare that with the insanity of writing a heap allocator.

Then we let compilers optimize the register allocation for us, since that is NP complete, and one of the hardest parts of writing a compiler. This problem is called register allocation, and it is isomorphic to graph coloring.

When the compiler's allocator is forced to store things in memory instead of just registers, that is known as a spill.

Does this boil down to a single processor instruction or is it more complex?

All we know for sure is that Intel documents a push and a pop instruction, so they are one instruction in that sense.

Internally, it could be expanded to multiple microcodes, one to modify esp and one to do the memory IO, and take multiple cycles.

But it is also possible that a single push is faster than an equivalent combination of other instructions, since it is more specific.

This is mostly un(der)documented:

Ascending and Descending Number Order in java

public static void main(String[] args) {
          Scanner input =new Scanner(System.in);
          System.out.print("enter how many:");
         int num =input.nextInt();
    int[] arr= new int [num];
    for(int b=0;b<arr.length;b++){
   System.out.print("enter no." + (b+1) +"=");
   arr[b]=input.nextInt();
    }

    for (int i=0; i<arr.length;i++) {
        for (int k=i;k<arr.length;k++) {

        if(arr[i] > arr[k]) {

        int temp=arr[k];
        arr[k]=arr[i];
        arr[i]=temp;
        }
            }

    }
    System.out.println("******************\n output\t accending order");


    for (int i : arr){
        System.out.println(i);
    }
}
}

Undefined Reference to

Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:

foo.h:

namespace foo {
    void bar();
}

foo.cc:

namespace foo {
    namespace {  // wrong
        void bar() { cout << "hello"; };
    }
}

other.cc file:

#include "foo.h"

void baz() {
    foo::bar();
}

Language Books/Tutorials for popular languages

For Java, I highly recommend Core Java. It's a large tome (or two large tomes), but I've found it to be one of the best references on Java I've read.

Execute a shell script in current shell with sudo permission

The answers here explain why it happens but I thought I'd add my simple way around the issue. First you can cat the file into a variable with sudo permissions. Then you can evaluate the variable to execute the code in the file in your current shell.

Here is an example of reading and executing an .env file (ex Docker)

 sensitive_stuff=$(sudo cat ".env")
 eval "${sensitive_stuff}"
 echo $ADMIN_PASSWORD 

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

The issue was resolved as I was having a JDK pointing to 1.7 and JRE pointing to 1.8. Check in the command prompt by typing

java -version

and

javac -version

Both should be same.  

Correct way to remove plugin from Eclipse

Correct way to remove install plug-in from Eclipse/STS :

Go to install folder of eclipse ----> plugin --> select required plugin and remove it.

Ex-

Step 1. 
E:\springsource\sts-3.4.0.RELEASE\plugins

Step 2. 
select and remove related plugins jars.

Bootstrap 3: pull-right for col-lg only

.pull-right-not-xs, .pull-right-not-sm, .pull-right-not-md, .pull-right-not-lg{
    float: right;
}

.pull-left-not-xs, .pull-left-not-sm, .pull-left-not-md, .pull-left-not-lg{
    float: left;
}
@media (max-width: 767px) {    
    .pull-right-not-xs, .pull-left-not-xs{
        float: none;
    }
    .pull-right-xs {
        float: right;
    }
    .pull-left-xs {
        float: left;
    }
}
@media (min-width: 768px) and (max-width: 991px) {
    .pull-right-not-sm, .pull-left-not-sm{
        float: none;
    }
    .pull-right-sm {
        float: right;
    }
    .pull-left-sm {
        float: left;
    }
}
@media (min-width: 992px) and (max-width: 1199px) {
    .pull-right-not-md, .pull-left-not-md{
        float: none;
    }
    .pull-right-md {
        float: right;
    }
    .pull-left-md {
        float: left;
    }
}
@media (min-width: 1200px) {
    .pull-right-not-lg, .pull-left-not-lg{
        float: none;
    }
    .pull-right-lg {
        float: right;
    }
    .pull-left-lg {
        float: left;
    }
}

What is the !! (not not) operator in JavaScript?

Some operators in JavaScript perform implicit type conversions, and are sometimes used for type conversion.

The unary ! operator converts its operand to a boolean and negates it.

This fact lead to the following idiom that you can see in your source code:

!!x // Same as Boolean(x). Note double exclamation mark

How to set the height of table header in UITableView?

It works with me only if I set the footer/header of the tableview to nil first:

self.footer = self.searchTableView.tableFooterView;
CGRect frame = self.footer.frame;
frame.size.height = 200;
self.footer.frame = frame;
self.searchTableView.tableFooterView = nil;
self.searchTableView.tableFooterView = self.footer;

Make sure that self.footer is a strong reference to prevent the footer view from being deallocated

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You can just use the Select() extension method:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

Or in LINQ syntax:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };

var strings = from i in integers
              select i.ToString();

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution

  1. Right click on installer(.exe)
  2. Select properties option.
  3. Click on checkbox to check Unblock at the bottom of Properties.

This solution work for Heroku CLI (heroku-x64) installer(.exe)

kubectl apply vs kubectl create?

Just to give a more straight forward answer, from my understanding:

apply - makes incremental changes to an existing object
create - creates a whole new object (previously non-existing / deleted)


Taking this from a DigitalOcean article which was linked by Kubernetes website:

We use apply instead of create here so that in the future we can incrementally apply changes to the Ingress Controller objects instead of completely overwriting them.

Is there Java HashMap equivalent in PHP?

Depending on what you want you might be interested in the SPL Object Storage class.

http://php.net/manual/en/class.splobjectstorage.php

It lets you use objects as keys, has an interface to count, get the hash and other goodies.

$s = new SplObjectStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o2->foo = 'bar';

$s[$o1] = 'baz';
$s[$o2] = 'bingo';

echo $s[$o1]; // 'baz'
echo $s[$o2]; // 'bingo'

What's the advantage of a Java enum versus a class with public static final fields?

  1. Type safety and value safety.
  2. Guaranteed singleton.
  3. Ability to define and override methods.
  4. Ability to use values in switch statement case statements without qualification.
  5. Built-in sequentialization of values via ordinal().
  6. Serialization by name not by value, which offers a degree of future-proofing.
  7. EnumSet and EnumMap classes.

Convert base-2 binary number string to int

For the record to go back and forth in basic python3:

a = 10
bin(a)
# '0b1010'

int(bin(a), 2)
# 10
eval(bin(a))
# 10

HTML5 record audio to file

Stream audio in realtime without waiting for recording to end: https://github.com/noamtcohen/AudioStreamer

This streams PCM data but you could modify the code to stream mp3 or Speex

What does LINQ return when the results are empty

It will return an empty enumerable. It wont be null. You can sleep sound :)

Convert a byte array to integer in Java and vice versa

Use the classes found in the java.nio namespace, in particular, the ByteBuffer. It can do all the work for you.

byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); // 1

ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num);
byte[] bytes = dbuf.array(); // { 0, 1 }

hexadecimal string to byte array in python

You can use the Codecs module in the Python Standard Library, i.e.

import codecs

codecs.decode(hexstring, 'hex_codec')

Disable back button in android

Apart form these two methods from answer above.

onBackPressed() (API Level 5, Android 2.0)

onKeyDown() (API Level 1, Android 1.0)

You can also override the dispatchKeyEvent()(API Level 1, Android 1.0) like this,

dispatchKeyEvent() (API Level 1, Android 1.0)

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    // TODO Auto-generated method stub
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        return true;
    }
    return super.dispatchKeyEvent(event);
}

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

What is the difference between SQL, PL-SQL and T-SQL?

  • SQL is a query language to operate on sets.

    It is more or less standardized, and used by almost all relational database management systems: SQL Server, Oracle, MySQL, PostgreSQL, DB2, Informix, etc.

  • PL/SQL is a proprietary procedural language used by Oracle

  • PL/pgSQL is a procedural language used by PostgreSQL

  • TSQL is a proprietary procedural language used by Microsoft in SQL Server.

Procedural languages are designed to extend SQL's abilities while being able to integrate well with SQL. Several features such as local variables and string/data processing are added. These features make the language Turing-complete.

They are also used to write stored procedures: pieces of code residing on the server to manage complex business rules that are hard or impossible to manage with pure set-based operations.

if variable contains

If you have a lot of these to check you might want to store a list of the mappings and just loop over that, instead of having a bunch of if/else statements. Something like:

var CODE_TO_LOCATION = {
  'ST1': 'stoke central',
  'ST2': 'stoke north',
  // ...
};

function getLocation(text) {
  for (var code in CODE_TO_LOCATION) {
    if (text.indexOf(code) != -1) {
      return CODE_TO_LOCATION[code];
    }
  }
  return null;
}

This way you can easily add more code/location mappings. And if you want to handle more than one location you could just build up an array of locations in the function instead of just returning the first one you find.

Does Python's time.time() return the local or UTC timestamp?

timestamp is always time in utc, but when you call datetime.datetime.fromtimestamp it returns you time in your local timezone corresponding to this timestamp, so result depend of your locale.

>>> import time, datetime

>>> time.time()
1564494136.0434234

>>> datetime.datetime.now()
datetime.datetime(2019, 7, 30, 16, 42, 3, 899179)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2019, 7, 30, 16, 43, 12, 4610)

There exist nice library arrow with different behaviour. In same case it returns you time object with UTC timezone.

>>> import arrow
>>> arrow.now()
<Arrow [2019-07-30T16:43:27.868760+03:00]>
>>> arrow.get(time.time())
<Arrow [2019-07-30T13:43:56.565342+00:00]>

How to return JSON data from spring Controller using @ResponseBody

Considering @Arpit answer, for me it worked only when I add two jackson dependencies:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>

and configured, of cause, web.xml <mvc:annotation-driven/>.

Original answer that helped me is here: https://stackoverflow.com/a/33896080/3014866

How to build and use Google TensorFlow C++ api

To get started, you should download the source code from Github, by following the instructions here (you'll need Bazel and a recent version of GCC).

The C++ API (and the backend of the system) is in tensorflow/core. Right now, only the C++ Session interface, and the C API are being supported. You can use either of these to execute TensorFlow graphs that have been built using the Python API and serialized to a GraphDef protocol buffer. There is also an experimental feature for building graphs in C++, but this is currently not quite as full-featured as the Python API (e.g. no support for auto-differentiation at present). You can see an example program that builds a small graph in C++ here.

The second part of the C++ API is the API for adding a new OpKernel, which is the class containing implementations of numerical kernels for CPU and GPU. There are numerous examples of how to build these in tensorflow/core/kernels, as well as a tutorial for adding a new op in C++.

Save PHP variables to a text file

Use serialize() on the variable, then save the string to a file. later you will be able to read the serialed var from the file and rebuilt the original var (wether it was a string or an array or an object)

Android Studio Rendering Problems : The following classes could not be found

To use the class ActionBarOverlayLayout you need to include this in the dependencies section of build.gradle file:

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

Sync the project once again and then you will find no problem

pypi UserWarning: Unknown distribution option: 'install_requires'

As far as I can tell, this is a bug in setuptools where it isn't removing the setuptools specific options before calling up to the base class in the standard library: https://bitbucket.org/pypa/setuptools/issue/29/avoid-userwarnings-emitted-when-calling

If you have an unconditional import setuptools in your setup.py (as you should if using the setuptools specific options), then the fact the script isn't failing with ImportError indicates that setuptools is properly installed.

You can silence the warning as follows:

python -W ignore::UserWarning:distutils.dist setup.py <any-other-args>

Only do this if you use the unconditional import that will fail completely if setuptools isn't installed :)

(I'm seeing this same behaviour in a checkout from the post-merger setuptools repo, which is why I'm confident it's a setuptools bug rather than a system config problem. I expect pre-merge distribute would have the same problem)

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

COPY is

Same as 'ADD', but without the tar and remote URL handling.

Reference straight from the source code.

Ubuntu apt-get unable to fetch packages

Just for the sake of any Googlers, if you're getting this error while building a Docker image, preface the failing RUN command with

apt-get update &&

This happens when Docker uses a cached image. Why the cached image wouldn't have the latest repo information the second time around is totally beyond me, but prefacing every single apt-get with an update does solve the problem.

How to set "style=display:none;" using jQuery's attr method?

Why not just use $('#msform').hide()? Behind the scene jQuery's hide and show just set display: none or display: block.

hide() will not change the style if already hidden.

based on the comment below, you are removing all style with removeAttr("style"), in which case call hide() immediately after that.

e.g.

$("#msform").removeAttr("style").hide();

The reverse of this is of course show() as in

$("#msform").show();

Or, more interestingly, toggle(), which effective flips between hide() and show() based on the current state.

'was not declared in this scope' error

Here's a simplified example based on of your problem:

if (test) 
{//begin scope 1
    int y = 1; 
}//end scope 1
else 
{//begin scope 2
    int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope

In the above version you have a variable called y that is confined to scope 1, and another different variable called y that is confined to scope 2. You then try to refer to a variable named y after the end of the if, and not such variable y can be seen because no such variable exists in that scope.

You solve the problem by placing y in the outermost scope which contains all references to it:

int y;
if (test) 
{
    y = 1; 
}
else 
{
    y = 2;
}
int x = y;

I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.

Java, Shifting Elements in an Array

public class Test1 {

    public static void main(String[] args) {

        int[] x = { 1, 2, 3, 4, 5, 6 };
        Test1 test = new Test1();
        x = test.shiftArray(x, 2);
        for (int i = 0; i < x.length; i++) {
            System.out.print(x[i] + " ");
        }
    }

    public int[] pushFirstElementToLast(int[] x, int position) {
        int temp = x[0];
        for (int i = 0; i < x.length - 1; i++) {
            x[i] = x[i + 1];
        }
        x[x.length - 1] = temp;
        return x;
    }

    public int[] shiftArray(int[] x, int position) {
        for (int i = position - 1; i >= 0; i--) {
            x = pushFirstElementToLast(x, position);
        }
        return x;
    }
}

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

How to keep :active css style after clicking an element

The :target-pseudo selector is made for these type of situations: http://reference.sitepoint.com/css/pseudoclass-target

It is supported by all modern browsers. To get some IE versions to understand it you can use something like Selectivizr

Here is a tab example with :target-pseudo selector.

Cannot read property 'map' of undefined

in my case it happens when I try add types to Promise.all handler:

Promise.all([1,2]).then(([num1, num2]: [number, number])=> console.log('res', num1));

If remove : [number, number], the error is gone.

How to create a readonly textbox in ASP.NET MVC3 Razor

 @Html.TextBox("Receivers", Model, new { @class = "form-control", style = "width: 300px", @readonly = "readonly" })

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

Another way of granting permission to the database for the user IIS APPPOOL\ASP.NET v4.0 is as follows.
enter image description here


  1. Add New User with User Name and Login name as IIS APPPOOL\ASP.NET v4.0 with your default schema.
  2. Go to Owner schema and Membership, Check db_datareader, db_datawriter

"column not allowed here" error in INSERT statement

Scanner sc = new Scanner(System.in); 
String name = sc.nextLine();
String surname = sc.nextLine();
Statement statement = connection.createStatement();
String query = "INSERT INTO STUDENT VALUES("+'"name"'+","+'"surname"'+")";
statement.executeQuery();

Do not miss to add '"----"' when concat the string.

how to get vlc logs?

Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...

How to change a DIV padding without affecting the width/height ?

To achieve a consistent result cross browser, you would usually add another div inside the div and give that no explicit width, and a margin. The margin will simulate padding for the outer div.

Convert string (without any separator) to list

A python string is a list of characters. You can iterate over it right now!

justdigits = ""
for char in string:
    if char.isdigit():
        justdigits += str(char)

JavaScript: remove event listener

element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();


HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
    this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};


HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
    for (var i = 0; i < this.myListeners.length; i++) {
        this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
    };
   delete this.myListeners;
};
};

How to create Java gradle project

Here is what it worked for me.. I wanted to create a hello world java application with gradle with the following requirements.

  1. The application has external jar dependencies
  2. Create a runnable fat jar with all dependent classes copied to the jar
  3. Create a runnable jar with all dependent libraries copied to a directory "dependencies" and add the classpath in the manifest.

Here is the solution :

  • Install the latest gradle ( check gradle --version . I used gradle 6.6.1)
  • Create a folder and open a terminal
  • Execute gradle init --type java-application
  • Add the required data in the command line
  • Import the project into an IDE (IntelliJ or Eclipse)
  • Edit the build.gradle file with the following tasks.

Runnable fat Jar

task fatJar(type: Jar) {
 clean
 println("Creating fat jar")
 manifest {
    attributes 'Main-Class': 'com.abc.gradle.hello.App'
 }
 archiveName "${runnableJar}"
 from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
 } with jar
 println("Fat jar is created")
}

Copy Dependencies

task copyDepends(type: Copy) {
   from configurations.default
   into "${dependsDir}"
}

Create jar with classpath dependecies in manifest

task createJar(type: Jar) {
   println("Cleaning...")
   clean
   manifest {
    attributes('Main-Class': 'com.abc.gradle.hello.App',
            'Class-Path': configurations.default.collect { 'dependencies/' + 
             it.getName() }.join(' ')
    )
}
  from {
      configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  } with jar
  println "${outputJar} created"
}

Here is the complete build.gradle

plugins {
    id 'java'
   id 'application'
}
repositories {
    mavenCentral()
}
dependencies {
  implementation 'org.slf4j:slf4j-api:1.7.30'
  implementation 'ch.qos.logback:logback-classic:1.2.3'
  implementation 'ch.qos.logback:logback-core:1.2.3'
  testImplementation 'junit:junit:4.13'
}
def outputJar = "${buildDir}/libs/${rootProject.name}.jar"
def dependsDir = "${buildDir}/libs/dependencies/"
def runnableJar = "${rootProject.name}_fat.jar";

//Create runnable fat jar
task fatJar(type: Jar) {
   clean
   println("Creating fat jar")
   manifest {
    attributes 'Main-Class': 'com.abc.gradle.hello.App'
  }
  archiveName "${runnableJar}"
  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
  } with jar
  println("Fat jar is created")
}

//Copy dependent libraries to directory.
task copyDepends(type: Copy) {
 from configurations.default
 into "${dependsDir}"
}

//Create runnable jar with dependencies
task createJar(type: Jar) {
 println("Cleaning...")
 clean
 manifest {
    attributes('Main-Class': 'com.abc.gradle.hello.App',
            'Class-Path': configurations.default.collect { 'dependencies/' + 
            it.getName() }.join(' ')
    )
 }
 from {
     configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
 } with jar
  println "${outputJar} created"
}

Gradle build commands
Create fat jar : gradle fatJar
Copy dependencies : gradle copyDepends
Create runnable jar with dependencies : gradle createJar

More details can be read here : https://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d

How do I rename the extension for a bunch of files?

This worked for me on OSX from .txt to .txt_bak

find . -name '*.txt' -exec sh -c 'mv "$0" "${0%.txt}.txt_bak"' {} \;

Matlab: Running an m-file from command-line

A command like this runs the m-file successfully:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m'); exit;"

View/edit ID3 data for MP3 files

I wrapped mp3 decoder library and made it available for .net developers. You can find it here:

http://sourceforge.net/projects/mpg123net/

Included are the samples to convert mp3 file to PCM, and read ID3 tags.

Insert variable into Header Location PHP

header('Location: http://linkhere.com/' . $your_variable);

How to allocate aligned memory only using the standard library?

size =1024;
alignment = 16;
aligned_size = size +(alignment -(size %  alignment));
mem = malloc(aligned_size);
memset_16aligned(mem, 0, 1024);
free(mem);

Hope this one is the simplest implementation, let me know your comments.

How to make the background image to fit into the whole page without repeating using plain css?

try something like

background: url(bgimage.jpg) no-repeat;
background-size: 100%;

Count words in a string method?

public static int countWords(String input) {
        int wordCount = 0;
        boolean isBlankSet = false;
        input = input.trim();

        for (int j = 0; j < input.length(); j++) {
            if (input.charAt(j) == ' ')
                isBlankSet = true;
            else {
                if (isBlankSet) {
                    wordCount++;
                    isBlankSet = false;
                }
            }

        }

        return wordCount + 1;
    }

Spark: subtract two DataFrames

I tried subtract, but the result was not consistent. If I run df1.subtract(df2), not all lines of df1 are shown on the result dataframe, probably due distinct cited on the docs.

This solved my problem: df1.exceptAll(df2)

Insert into C# with SQLCommand

You can use dapper library:

conn2.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) VALUES (@p1,@p2,@p3)", 
                new { p1 = klantId, p2 = klantNaam, p3 = klantVoornaam });

BTW Dapper is a Stack Overflow project :)

UPDATE: I believe you can't do it simpler without something like EF. Also try to use using statements when you are working with database connections. This will close connection automatically, even in case of exception. And connection will be returned to connections pool.

private readonly string _spionshopConnectionString;

private void Form1_Load(object sender, EventArgs e)
{            
    _spionshopConnectionString = ConfigurationManager
          .ConnectionStrings["connSpionshopString"].ConnectionString;
}

private void button4_Click(object sender, EventArgs e)
{
    using(var connection = new SqlConnection(_spionshopConnectionString))
    {
         connection.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) 
                              VALUES (@klantId,@klantNaam,@klantVoornaam)",
                              new { 
                                      klantId = Convert.ToInt32(textBox1.Text), 
                                      klantNaam = textBox2.Text, 
                                      klantVoornaam = textBox3.Text 
                                  });
    }
}

makefiles - compile all c files at once

You need to take out your suffix rule (%.o: %.c) in favour of a big-bang rule. Something like this:

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

OBJ = 64bitmath.o    \
      monotone.o     \
      node_sort.o    \
      planesweep.o   \
      triangulate.o  \
      prim_combine.o \
      welding.o      \
      test.o         \
      main.o

SRCS = $(OBJ:%.o=%.c)

test: $(SRCS)
    gcc -o $@  $(CFLAGS) $(LIBS) $(SRCS)

If you're going to experiment with GCC's whole-program optimization, make sure that you add the appropriate flag to CFLAGS, above.

On reading through the docs for those flags, I see notes about link-time optimization as well; you should investigate those too.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

HTML5 event handling(onfocus and onfocusout) using angular 2

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

works for me from Pardeep Jain

How to create many labels and textboxes dynamically depending on the value of an integer variable?

You can try this:

int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e) 
{
     TextBox txt = new TextBox();
     this.Controls.Add(txt);
     txt.Top = cleft * 40;
     txt.Size = new Size(200, 16);
     txt.Left = 150;
     cleft = cleft + 1;
     Label lbl = new Label();
     this.Controls.Add(lbl);
     lbl.Top = aleft * 40;
     lbl.Size = new Size(100, 16);
     lbl.ForeColor = Color.Blue;
     lbl.Text = "BoxNo/CardNo";
     lbl.Left = 70;
     aleft = aleft + 1;
     return;
}
private void btd_Click(object sender, EventArgs e)
{ 
    //Here you Delete Text Box One By One(int ix for Text Box)
    for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
    //Here you Delete Lable One By One(int ix for Lable)
    for (int x = this.Controls.Count - 2; x >= 0; x--)
    {
        if (this.Controls[ix] is TextBox) 
        this.Controls[ix].Dispose();
        if (this.Controls[x] is Label) 
        this.Controls[x].Dispose();
        return;
    }
}

What is the use of the square brackets [] in sql statements?

They are useful if you are (for some reason) using column names with certain characters for example.

Select First Name From People

would not work, but putting square brackets around the column name would work

Select [First Name] From People

In short, it's a way of explicitly declaring a object name; column, table, database, user or server.

What is the difference between Collection and List in Java?

Java API is the best to answer this

Collection

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

List (extends Collection)

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

How do I center text vertically and horizontally in Flutter?

I think a more flexible option would be to wrap the Text() with Align() like so:

Align(
  alignment: Alignment.center, // Align however you like (i.e .centerRight, centerLeft)
  child: Text("My Text"),
),

Using Center() seems to ignore TextAlign entirely on the Text widget. It will not align TextAlign.left or TextAlign.right if you try, it will remain in the center.

Git commit in terminal opens VIM, but can't get back to terminal

not really the answer to the VIM problem but you could use the command line to also enter the commit message:

git commit -m "This is the first commit"

Delete all rows with timestamp older than x days

DELETE FROM on_search 
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))

Javascript isnull

You could try this:

if(typeof(results) == "undefined") { 
    return 0;
} else {
    return results[1] || 0;
}

Can't bind to 'routerLink' since it isn't a known property

I'll add another case where I was getting the same error but just being a dummy. I had added [routerLinkActiveOptions]="{exact: true}" without yet adding routerLinkActive="active".

My incorrect code was

<a class="nav-link active" routerLink="/dashboard" [routerLinkActiveOptions]="{exact: true}">
  Home
</a>

when it should have been

<a class="nav-link active" routerLink="/dashboard" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
  Home
</a>

Without having routerLinkActive, you can't have routerLinkActiveOptions.

ORA-28040: No matching authentication protocol exception

just install ojdbc-full, That contains the 12.1.0.1 release.

Recover from git reset --hard?

I did git reset --hard on the wrong project by mistake (I know...). I had just worked on one file and it was still open during and after I ran the command.

Even though I had not committed, I was able to retrieve the old file with the simple COMMAND + Z.

How to determine the screen width in terms of dp or dip at runtime in Android?

Get Screen Width and Height in terms of DP with some good decoration:

Step 1: Create interface

public interface ScreenInterface {

   float getWidth();

   float getHeight();

}

Step 2: Create implementer class

public class Screen implements ScreenInterface {
    private Activity activity;

    public Screen(Activity activity) {
        this.activity = activity;
    }

    private DisplayMetrics getScreenDimension(Activity activity) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    private float getScreenDensity(Activity activity) {
        return activity.getResources().getDisplayMetrics().density;
    }

    @Override
    public float getWidth() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.widthPixels / getScreenDensity(activity);
    }

    @Override
    public float getHeight() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.heightPixels / getScreenDensity(activity);
    }
} 

Step 3: Get width and height in activity:

Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();

Python pandas: how to specify data types when reading an Excel file?

You just specify converters. I created an excel spreadsheet of the following structure:

names   ages
bob     05
tom     4
suzy    3

Where the "ages" column is formatted as strings. To load:

import pandas as pd

df = pd.read_excel('Book1.xlsx',sheetname='Sheet1',header=0,converters={'names':str,'ages':str})
>>> df
       names ages
   0   bob   05
   1   tom   4
   2   suzy  3

How to enable relation view in phpmyadmin

first select the table you you would like to make the relation with >> then go to operation , for each table there is difference operation setting, >> inside operation "storage engine" choose innoDB option

innoDB will allow you to view the "relation view" which will help you make the foreign key

enter image description here