Programs & Examples On #Apache commons exec

ImportError: cannot import name NUMPY_MKL

I had the same problem while installing gensim on windows. Gensim is dependent on scipy and scipy on numpy. Making all three work is real pain. It took me a lot of time to make all there work on same time.

Solution: If you are using windows make sure you install numpy+mkl instead of just numpy. If you have already installed scipy and numpy, uninstall then using "pip uninstall scipy" and "pip uninstall numpy"

Then download numpy-1.13.1+mkl-cp34-cp34m-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy and install using pip install numpy-1.13.1+mkl-cp34-cp34m-win32.wh Note: in cp34-cp34m 34 represent the version of python you are using, so download the relevant version.

Now download scipy from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy (appropriate version for your python and system) and install using "pip install scipy-0.19.1-cp34-cp34m-win32.whl"

Your numpy and Scipy both should work now. These binaries by Christoph Gohlke makes it very easy to install python packages on windows. But make sure you download all the dependent packages from there.

What is the easiest way to encrypt a password when I save it to the registry?

If you need more than this, for example securing a connection string (for connection to a database), check this article, as it provides the best "option" for this.

Oli's answer is also good, as it shows how you can create a hash for a string.

Get all column names of a DataTable into string array using (LINQ/Predicate)

Try this (LINQ method syntax):

string[] columnNames = dt.Columns.Cast<DataColumn>()
                                 .Select(x => x.ColumnName)
                                 .ToArray();  

or in LINQ Query syntax:

string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
                        select dc.ColumnName).ToArray();

Cast is required, because Columns is of type DataColumnCollection which is a IEnumerable, not IEnumerable<DataColumn>. The other parts should be obvious.

How do I capture response of form.submit

The non-jQuery vanilla Javascript way, extracted from 12me21's comment:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/your/url/name.php"); 
xhr.onload = function(event){ 
    alert("Success, server responded with: " + event.target.response); // raw response
}; 
// or onerror, onabort
var formData = new FormData(document.getElementById("myForm")); 
xhr.send(formData);

For POST's the default content type is "application/x-www-form-urlencoded" which matches what we're sending in the above snippet. If you want to send "other stuff" or tweak it somehow see here for some nitty gritty details.

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

To fix this issue you need to remove your Google account, then add it again. To do this follow these instructions:

http://support.google.com/android/bin/answer.py?hl=en&answer=1663649

(Or just find the account under Settings > Personal > Accounts and Sync > Click the Google Account > Click Menu button > Click Remove Account > Confirm deletion.)

RabbitMQ / AMQP: single queue, multiple consumers for same message?

If you happen to be using the amqplib library as I am, they have a handy example of an implementation of the Publish/Subscribe RabbitMQ tutorial which you might find handy.

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
      END 
WHERE columnC = 1

Parse String to Date with Different Format in Java

While SimpleDateFormat will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

How do I declare a namespace in JavaScript?

Is there a more elegant or succinct way of doing this?

Yes. For example:

var your_namespace = your_namespace || {};

then you can have

var your_namespace = your_namespace || {};
your_namespace.Foo = {toAlert:'test'};
your_namespace.Bar = function(arg) 
{
    alert(arg);
};
with(your_namespace)
{
   Bar(Foo.toAlert);
}

Decompile Python 2.7 .pyc

In case anyone is still struggling with this, as I was all morning today, I have found a solution that works for me:

Uncompyle

Installation instructions:

git clone https://github.com/gstarnberger/uncompyle.git
cd uncompyle/
sudo ./setup.py install

Once the program is installed (note: it will be installed to your system-wide-accessible Python packages, so it should be in your $PATH), you can recover your Python files like so:

uncompyler.py thank_goodness_this_still_exists.pyc > recovered_file.py

The decompiler adds some noise mostly in the form of comments, however I've found it to be surprisingly clean and faithful to my original code. You will have to remove a little line of text beginning with +++ near the end of the recovered file to be able to run your code.

Where does Chrome store cookies?

Since the expiration time is zero (the third argument, the first false) the cookie is a session cookie, which will expire when the current session ends. (See the setcookie reference).

Therefore it doesn't need to be saved.

Rolling back local and remote git repository by 1 commit

By entering bellow command you can see your git commit history -

$ git log

Let's say your history on that particular branch is like - commit_A, commit_B, commit_C, commit_D. Where, commit_D is the last commit and this is where HEAD remains. Now, to remove your last commit from local and remote, you need to do the following :

Step 1: Remove last commit locally by -

$ git reset --hard HEAD~

This will change your commit HEAD to commit_C

Step 2: Push your change for new HEAD commit to remote

$ git push origin +HEAD

This command will delete the last commit from remote.

P.S. this command is tested on Mac OSX and should work on other operating systems as well (not claiming about other OS though)

What is the difference between private and protected members of C++ classes?

Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ classses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.

Multiple axis line chart in excel

It is possible to get both the primary and secondary axes on one side of the chart by designating the secondary axis for one of the series.

To get the primary axis on the right side with the secondary axis, you need to set to "High" the Axis Labels option in the Format Axis dialog box for the primary axis.

To get the secondary axis on the left side with the primary axis, you need to set to "Low" the Axis Labels option in the Format Axis dialog box for the secondary axis.

I know of no way to get a third set of axis labels on a single chart. You could fake in axis labels & ticks with text boxes and lines, but it would be hard to get everything aligned correctly.

The more feasible route is that suggested by zx8754: Create a second chart, turning off titles, left axes, etc. and lay it over the first chart. See my very crude mockup which hasn't been fine-tuned yet.

three axis labels chart

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

The final solution to your assembly redirect errors

Okay, hopefully this should help resolve any (sane) assembly reference discrepancies ...

  1. Check the error.

Surf to the website

  1. Check web.config after the assembly redirect. Create one if not exists.

Existing web.config assembly redirect

  1. Right-click the reference for the assembly and choose Properties.

Assembly in the Reference list, in the relevant project

  1. Check the Version (not Runtime version) in the Properties table. Copy that.

Properties table showing Version of assembly

  1. Paste into the newVersion attribute.

web.config assembly redirect with updated newVersion

  1. For convenience, change the last part of the oldVersion to something high, round and imaginary.

web.config assembly redirect with updated oldVersion

Rejoice.

Hadoop: «ERROR : JAVA_HOME is not set»

I solved this in my env, without modify hadoop-env.sh

You'd be better using /bin/bash as default shell not /bin/sh

Check these before:

  1. You have already config java and env (success echo $JAVA_HOME)
  2. right config hadoop

echo $SHELL in every node, check if print /bin/bash if not, vi /etc/passwd, add /bin/bash at tail of your username ref

Changing default shell in Linux

https://blog.csdn.net/whitehack/article/details/51705889

How to set div's height in css and html

To write inline styling use:

<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>

Inline styling serves a purpose however, it is not recommended in most situations.

The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.

if you have the file structure:

index.html
>>/css/
>>/css/styles.css

Then in your HTML document between <head> and </head> write:

<link href="css/styles.css" rel="stylesheet" />

Then, change your div structure to be:

<div id="someidname" class="someclassname">
    asdfashdjkfhaskjdf
</div>

In css, you can reference your div from the ID or the CLASS.

To do so write:

.someclassname { height: 100px; }

OR

#someidname { height: 100px; }

Note that if you do both, the one that comes further down the file structure will be the one that actually works.

For example... If you have:

.someclassname { height: 100px; }

.someclassname { height: 150px; }

Then in this situation the height will be 150px.

EDIT:

To answer your secondary question from your edit, probably need overflow: hidden; or overflow: visible; . You could also do this:

<div class="span12">
    <div style="height:100px;">
        asdfashdjkfhaskjdf
    </div>
</div>

Vue.js redirection to another page

If you are using vue-router, you should use router.go(path) to navigate to any particular route. The router can be accessed from within a component using this.$router.

Otherwise, window.location.href = 'some url'; works fine for non single-page apps.

EDIT: router.go() changed in VueJS 2.0. You can use router.push({ name: "yourroutename"}) or just router.push("yourroutename") now to redirect.

Documentation

P.S: In controllers use: this.$router.push({ name: 'routename' })

How do I redirect in expressjs while passing some context?

The easiest way I have found to pass data between routeHandlers to use next() no need to mess with redirect or sessions. Optionally you could just call your homeCtrl(req,res) instead of next() and just pass the req and res

var express  = require('express');
var jade     = require('jade');
var http     = require("http");


var app    = express();
var server = http.createServer(app);

/////////////
// Routing //
/////////////

// Move route middleware into named
// functions
function homeCtrl(req, res) {

    // Prepare the context
    var context = req.dataProcessed;
    res.render('home.jade', context);
}

function categoryCtrl(req, res, next) {

    // Process the data received in req.body
    // instead of res.redirect('/');
    req.dataProcessed = somethingYouDid;
    return next();
    // optionally - Same effect
    // accept no need to define homeCtrl
    // as the last piece of middleware
    // return homeCtrl(req, res, next);
}

app.get('/', homeCtrl);

app.post('/category', categoryCtrl, homeCtrl);

Java: How can I compile an entire directory structure of code ?

There is a way to do this without using a pipe character, which is convenient if you are forking a process from another programming language to do this:

find $JAVA_SRC_DIR -name '*.java' -exec javac -d $OUTPUT_DIR {} +

Though if you are in Bash and/or don't mind using a pipe, then you can do:

find $JAVA_SRC_DIR -name '*.java' | xargs javac -d $OUTPUT_DIR

Two Divs next to each other, that then stack with responsive change

Better late than never!

https://getbootstrap.com/docs/4.5/layout/grid/

<div class="container">
  <div class="row">
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
  </div>
</div>

Expand and collapse with angular js

In html

button ng-click="myMethod()">Videos</button>

In angular

 $scope.myMethod = function () {
         $(".collapse").collapse('hide');    //if you want to hide
         $(".collapse").collapse('toggle');  //if you want toggle
         $(".collapse").collapse('show');    //if you want to show
}

Which JRE am I using?

Git Bash + Windows 10 + Software that came bundled with its own JRE copy:

Do a "Git Bash Here" in the jre/bin folder of the software you installed.

Then use "./java.exe -version" instead of "java -version" to get the information on the software's copy rather than the copy referenced by your PATH environment variable.

Get the version of the software installation: ./java.exe -version

JMIM@DESKTOP-JUDCNDL MINGW64 /c/DEV/PROG/EYE_DB/INST/jre/bin
$ ./java.exe -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

Get the version in your PATH variable: java -version

JMIM@DESKTOP-JUDCNDL MINGW64 /c/DEV/PROG/EYE_DB/INST/jre/bin
$ java -version
java version "10" 2018-03-20
Java(TM) SE Runtime Environment 18.3 (build 10+46)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode)

As for addressing the original question and getting vendor information:

./java.exe -XshowSettings:properties -version ## Software's copy
java       -XshowSettings:properties -version ## Copy in PATH

How can I access getSupportFragmentManager() in a fragment?

Simply get it like this -

getFragmentManager() // This will also give you the SupportFragmentManager or FragmentManager based on which Fragment class you have extended - android.support.v4.app.Fragment OR android.app.Fragment.

OR

getActivity().getSupportFragmentManager();

in your Fragment's onActivityCreated() method and any method that is being called after onActivityCreated().

C++ Object Instantiation

Treat heap as a very important real estate and use it very judiciously. The basic thumb rule is to use stack whenever possible and use heap whenever there is no other way. By allocating the objects on stack you can get many benefits such as:

(1). You need not have to worry about stack unwinding in case of exceptions

(2). You need not worry about memory fragmentation caused by the allocating more space than necessary by your heap manager.

How can I use goto in Javascript?

Actually, I see that ECMAScript (JavaScript) DOES INDEED have a goto statement. However, the JavaScript goto has two flavors!

The two JavaScript flavors of goto are called labeled continue and labeled break. There is no keyword "goto" in JavaScript. The goto is accomplished in JavaScript using the break and continue keywords.

And this is more or less explicitly stated on the w3schools website here http://www.w3schools.com/js/js_switch.asp.

I find the documentation of the labeled continue and labeled break somewhat awkwardly expressed.

The difference between the labeled continue and labeled break is where they may be used. The labeled continue can only be used inside a while loop. See w3schools for some more information.

===========

Another approach that will work is to have a giant while statement with a giant switch statement inside:

while (true)
{
    switch (goto_variable)
    {
        case 1:
            // some code
            goto_variable = 2
            break;
        case 2:
            goto_variable = 5   // case in etc. below
            break;
        case 3:
            goto_variable = 1
            break;

         etc. ...
    }

}

Extracting Nupkg files using command line

You can also use the NuGet command line, by specifying a local host as part of an install. For example if your package is stored in the current directory

nuget install MyPackage -Source %cd% -OutputDirectory packages

will unpack it into the target directory.

This compilation unit is not on the build path of a Java project

If your project is imported as an existing maven project then --> Just right click on project and do maven update. It resolved my similar issue.

What is the best way to paginate results in SQL Server

From SQL Server 2012, we can use OFFSET and FETCH NEXT Clause to achieve the pagination.

Try this, for SQL Server:

In the SQL Server 2012 a new feature was added in the ORDER BY clause, to query optimization of a set data, making work easier with data paging for anyone who writes in T-SQL as well for the entire Execution Plan in SQL Server.

Below the T-SQL script with the same logic used in the previous example.

--CREATING A PAGING WITH OFFSET and FETCH clauses IN "SQL SERVER 2012"
DECLARE @PageNumber AS INT, @RowspPage AS INT
SET @PageNumber = 2
SET @RowspPage = 10 
SELECT ID_EXAMPLE, NM_EXAMPLE, DT_CREATE
FROM TB_EXAMPLE
ORDER BY ID_EXAMPLE
OFFSET ((@PageNumber - 1) * @RowspPage) ROWS
FETCH NEXT @RowspPage ROWS ONLY;

TechNet: Paging a Query with SQL Server

npm install from Git in a specific version

I needed to run two versions of tfjs-core and found that both needed to be built after being installed.

package.json:

"dependencies": {
  "tfjs-core-0.14.3": "git://github.com/tensorflow/tfjs-core#bb0a830b3bda1461327f083ceb3f889117209db2",
  "tfjs-core-1.1.0": "git://github.com/tensorflow/tfjs-core#220660ed8b9a252f9d0847a4f4e3c76ba5188669"
}

Then:

cd node_modules/tfjs-core-0.14.3 && yarn install && yarn build-npm && cd ../../
cd node_modules/tfjs-core-1.1.0  && yarn install && yarn build-npm && cd ../../

And finally, to use the libraries:

import * as tf0143 from '../node_modules/tfjs-core-0.14.3/dist/tf-core.min.js';
import * as tf110 from '../node_modules/tfjs-core-1.1.0/dist/tf-core.min.js';

This worked great but is most certainly #hoodrat

Getting Class type from String

String clsName = "Ex";  // use fully qualified name
Class cls = Class.forName(clsName);
Object clsInstance = (Object) cls.newInstance();

Check the Java Tutorial trail on Reflection at http://java.sun.com/docs/books/tutorial/reflect/TOC.html for further details.

How to transfer data from JSP to servlet when submitting HTML form

http://oreilly.com/catalog/javacook/chapter/ch18.html

Search for :

"Problem

You want to process the data from an HTML form in a servlet. "

How to select between brackets (or quotes or ...) in Vim?

Write a Vim function in .vimrc using the searchpair built-in function:

searchpair({start}, {middle}, {end} [, {flags} [, {skip}
            [, {stopline} [, {timeout}]]]])
    Search for the match of a nested start-end pair.  This can be
    used to find the "endif" that matches an "if", while other
    if/endif pairs in between are ignored.
    [...]

(http://vimdoc.sourceforge.net/htmldoc/eval.html)

Named capturing groups in JavaScript regex?

Don't have ECMAScript 2018?

My goal was to make it work as similar as possible to what we are used to with named groups. Whereas in ECMAScript 2018 you can place ?<groupname> inside the group to indicate a named group, in my solution for older javascript, you can place (?!=<groupname>) inside the group to do the same thing. So it's an extra set of parenthesis and an extra !=. Pretty close!

I wrapped all of it into a string prototype function

Features

  • works with older javascript
  • no extra code
  • pretty simple to use
  • Regex still works
  • groups are documented within the regex itself
  • group names can have spaces
  • returns object with results

Instructions

  • place (?!={groupname}) inside each group you want to name
  • remember to eliminate any non-capturing groups () by putting ?: at the beginning of that group. These won't be named.

arrays.js

// @@pattern - includes injections of (?!={groupname}) for each group
// @@returns - an object with a property for each group having the group's match as the value 
String.prototype.matchWithGroups = function (pattern) {
  var matches = this.match(pattern);
  return pattern
  // get the pattern as a string
  .toString()
  // suss out the groups
  .match(/<(.+?)>/g)
  // remove the braces
  .map(function(group) {
    return group.match(/<(.+)>/)[1];
  })
  // create an object with a property for each group having the group's match as the value 
  .reduce(function(acc, curr, index, arr) {
    acc[curr] = matches[index + 1];
    return acc;
  }, {});
};    

usage

function testRegGroups() {
  var s = '123 Main St';
  var pattern = /((?!=<house number>)\d+)\s((?!=<street name>)\w+)\s((?!=<street type>)\w+)/;
  var o = s.matchWithGroups(pattern); // {'house number':"123", 'street name':"Main", 'street type':"St"}
  var j = JSON.stringify(o);
  var housenum = o['house number']; // 123
}

result of o

{
  "house number": "123",
  "street name": "Main",
  "street type": "St"
}

How can I listen for a click-and-hold in jQuery?

Presumably you could kick off a setTimeout call in mousedown, and then cancel it in mouseup (if mouseup happens before your timeout completes).

However, looks like there is a plugin: longclick.

Get string character by index - Java

Here's the correct code. If you're using zybooks this will answer all the problems.

for (int i = 0; i<passCode.length(); i++)
{
    char letter = passCode.charAt(i);
    if (letter == ' ' )
    {
        System.out.println("Space at " + i);
    }
}

Guid is all 0's (zeros)?

Try this instead:

var responseObject = proxy.CallService(new RequestObject
{
    Data = "misc. data",
    Guid = new Guid.NewGuid()
});

This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).

When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):

Guid g1;                    // g1 is 00000000-0000-0000-0000-000000000000
Guid g2 = new Guid();       // g2 is 00000000-0000-0000-0000-000000000000
Guid g3 = default(Guid);    // g3 is 00000000-0000-0000-0000-000000000000
Guid g4 = Guid.NewGuid();   // g4 is not all zeroes

Compare this to doing the same thing with an int:

int i1;                     // i1 is 0
int i2 = new int();         // i2 is 0
int i3 = default(int);      // i3 is 0

How to make g++ search for header files in a specific directory?

gcc -I/path -L/path
  • -I /path path to include, gcc will find .h files in this path

  • -L /path contains library files, .a, .so

List an Array of Strings in alphabetical order

By alphabetical-order I assume the order to be : A|a < B|b < C|c... Hope this is what @Nick is(or was) looking for and the answer follows the above assumption.

I would suggest to have a class implement compare method of Comparator-interface as :

public int compare(Object o1, Object o2) {
    return o1.toString().compareToIgnoreCase(o2.toString());
}

and from the calling method invoke the Arrays.sort method with custom Comparator as :

Arrays.sort(inputArray, customComparator);

Observed results: input Array : "Vani","Kali", "Mohan","Soni","kuldeep","Arun"

output(Alphabetical-order) is : Arun, Kali, kuldeep, Mohan, Soni, Vani

Output(Natural-order by executing Arrays.sort(inputArray) is : Arun, Kali, Mohan, Soni, Vani, kuldeep

Thus in case of natural ordering, [Vani < kuldeep] which to my understanding of alphabetical-order is not the thing desired.

for more understanding of natural and alphabetical/lexical order visit discussion here

Generating random integer from a range

assume min and max are int values, [ and ] means include this value, ( and ) means not include this value, using above to get the right value using c++ rand()

reference: for ()[] define, visit:

https://en.wikipedia.org/wiki/Interval_(mathematics)

for rand and srand function or RAND_MAX define, visit:

http://en.cppreference.com/w/cpp/numeric/random/rand

[min, max]

int randNum = rand() % (max - min + 1) + min

(min, max]

int randNum = rand() % (max - min) + min + 1

[min, max)

int randNum = rand() % (max - min) + min

(min, max)

int randNum = rand() % (max - min - 1) + min + 1

for-in statement

In Typescript 1.5 and later, you can use for..of as opposed to for..in

var numbers = [1, 2, 3];

for (var number of numbers) {
    console.log(number);
}

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the * operator on a list.

For example:

import math
import numpy as np
alpha = 0.2 
beta=1-alpha
C = (-math.log(1-beta))/alpha

coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C

The error:

    coff *= C 
TypeError: can't multiply sequence by non-int of type 'float'

The solution - convert the list to numpy array:

coff = np.asarray(coff) * C

jQuery UI Dialog Box - does not open after being closed

I believe you can only initialize the dialog one time. The example above is trying to initialize the dialog every time #terms is clicked. This will cause problems. Instead, the initialization should occur outside of the click event. Your example should probably look something like this:

$(document).ready(function() {
    // dialog init
    $('#terms').dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 400,
        height: 450,
        overlay: { backgroundColor: "#000", opacity: 0.5 },
        buttons: { "Close": function() { $(this).dialog('close'); } },
        close: function(ev, ui) { $(this).close(); }
    });
    // click event
    $('#showTerms').click(function(){
        $('#terms').dialog('open').css('display','inline');      
    });
    // date picker
    $('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' });
});

I'm thinking that once you clear that up, it should fix the 'open from link' issue you described.

Django Reverse with arguments '()' and keyword arguments '{}' not found

Resolve is also more straightforward

from django.urls import resolve

resolve('edit_project', project_id=4)

Documentation on this shortcut

Python AttributeError: 'module' object has no attribute 'Serial'

If you are helpless like me, try this:

List all Sub-Modules of "Serial" (or whatever package you are having trouble with) with the method described here: List all the modules that are part of a python package

In my case, the problems solved one after the other.

...looks like a bug to me...

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

How to style the <option> with only CSS?

I've played around with select items before and without overriding the functionality with JavaScript, I don't think it's possible in Chrome. Whether you use a plugin or write your own code, CSS only is a no go for Chrome/Safari and as you said, Firefox is better at dealing with it.

CSS Display an Image Resized and Cropped

Try using the clip-path property:

The clip-path property lets you clip an element to a basic shape or to an SVG source.

Note: The clip-path property will replace the deprecated clip property.

_x000D_
_x000D_
img {_x000D_
  width: 150px;_x000D_
  clip-path: inset(30px 35px);_x000D_
}
_x000D_
<img src="http://i.stack.imgur.com/wPh0S.jpg">
_x000D_
_x000D_
_x000D_

More examples here.

Entity Framework vs LINQ to SQL

I am working for customer that has a big project that is using Linq-to-SQL. When the project started it was the obvious choice, because Entity Framework was lacking some major features at that time and performance of Linq-to-SQL was much better.

Now EF has evolved and Linq-to-SQL is lacking async support, which is great for highly scalable services. We have 100+ requests per second sometimes and despite we have optimized our databases, most queries still take several milliseconds to complete. Because of the synchronous database calls, the thread is blocked and not available for other requests.

We are thinking to switch to Entity Framework, solely for this feature. It's a shame that Microsoft didn't implement async support into Linq-to-SQL (or open-sourced it, so the community could do it).

Addendum December 2018: Microsoft is moving towards .NET Core and Linq-2-SQL isn't support on .NET Core, so you need to move to EF to make sure you can migrate to EF.Core in the future.

There are also some other options to consider, such as LLBLGen. It's a mature ORM solution that exists already a long time and has been proven more future-proof then the MS data solutions (ODBC, ADO, ADO.NET, Linq-2-SQL, EF, EF.core).

How do I comment out a block of tags in XML?

You can use that style of comment across multiple lines (which exists also in HTML)

<detail>
    <band height="20">
    <!--
      Hello,
         I am a multi-line XML comment
         <staticText>
            <reportElement x="180" y="0" width="200" height="20"/>
            <text><![CDATA[Hello World!]]></text>
          </staticText>
      -->
     </band>
</detail>

Keeping session alive with Curl and PHP

Yup, often called a 'cookie jar' Google should provide many examples:

http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/

http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO

Copying that last one here so it does not go away...

Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell

<?php
/*
This script is an example of using curl in php to log into on one page and 
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into 
thinking its netscape and even pass a fake referer, yo look like it surfed 
from a local page.
*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo "<PRE>".htmlentities($buf2);
?>  

What's a .sh file?

Typically a .sh file is a shell script which you can execute in a terminal. Specifically, the script you mentioned is a bash script, which you can see if you open the file and look in the first line of the file, which is called the shebang or magic line.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

What is VanillaJS?

Using "VanillaJS" means using plain JavaScript without any additional libraries like jQuery.

People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries.

Here's a funny site that jokingly talks about this: http://vanilla-js.com/

How to programmatically disable page scrolling with jQuery

I am using the following code to disable scrolling and it works fine

    $('html').css({
      'overflow': 'hidden',
      'height': '100%'
    });

except that on my android tablet, url address bar and top window tags remain visible, and when users scroll up and down, the window also scrolls for about 40px up and down, and shows/hides the url bar and the tags. Is there a way to prevent that and have scrolling fully disabled ?

Get protocol, domain, and port from URL

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

Build error: You must add a reference to System.Runtime

It's an old issue but I faced it today in order to fix a build pipeline on our continuous integration server. Adding

<Reference Include="System.Runtime" />

to my .csproj file solved the problem for me.

A bit of context: the interested project is a full .NET Framework 4.6.1 project, without build problem on the development machines. The problem appears only on the build server, which we can't control, may be due to a different SDK version or something similar.

Adding the proposed <Reference solved the build error, at the price of a missing reference warning (yellow triangle on the added entry in the references tree) in Visual Studio.

Reset/remove CSS styles for element only

BETTER SOLUTION

Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git

Thanks@Milche Patern!
I was really looking for reset/default style properties value. My first try was to copy the computed value from the browser Dev tool of the root(html) element. But as it computed, it would have looked/worked different on every system.
For those who encounter a browser crash when trying to use the asterisk * to reset the style of the children elements, and as I knew it didn't work for you, I have replaced the asterisk "*" with all the HTML tags name instead. The browser didn't crash; I am on Chrome Version 46.0.2490.71 m.
At last, it's good to mention that those properties will reset the style to the default style of topest root element but not to the initial value for each HTML element. ?So to correct this, I have taken the "user-agent" styles of webkit based browser and implemented it under the "reset-this" class.

Useful link:


Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git

User-agent style:
Browsers' default CSS for HTML elements
http://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css

Css specifity (pay attention to specifity) :
https://css-tricks.com/specifics-on-css-specificity/

https://github.com/monmomo04/resetCss.git

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

Broadcast receiver for checking internet connection in android app

It's easier to use https://github.com/JobGetabu/DroidNet

 @Override
    public void onInternetConnectivityChanged(boolean isConnected) {

        if (isConnected) {
            //do Stuff with internet
            netIsOn();
        } else {
            //no internet
            netIsOff();
        }
    }

    private void netIsOn(){...}

    private void netIsOff(){...}

How to give ASP.NET access to a private key in a certificate in the certificate store?

For me, it was nothing more than re-importing the certificate with "Allow private key to be exported" checked.

I guess it is necessary, but it does make me nervous as it is a third party app accessing this certificate.

Bootstrap close responsive menu "on click"

$('.navbar-toggle').trigger('click');

The type or namespace name 'System' could not be found

I attempted to re-create your issue and came up with a similar error when the solution was created in visual studio 2013 and then tried building it in in vs 2015.

I was able to get a successful build once I reinstalled NuGet Package Manager (and closed, then reopened VS 2015).

References / Credit

There are several SO questions relating to build issues via with earlier version of NPM for VS 2015 (i.e. I'm just passing along what I've tried and worked out). Recurring resolution is usually update / reinstall NPM or change execution policy in power shell. I tend to like the update + restart approach to avoid tinkering with the black boxes in windows. one source: https://stackoverflow.com/a/32251092/1158842 There may also be an issue of MSBuild Integrated solutions, in which case migrating away from the NuGet resources in the solution could do the trick.

Source: https://stackoverflow.com/a/31811461/1158842

How to position the Button exactly in CSS

So, the trick here is to use absolute positioning calc like this:

top: calc(50% - XYpx);
left: calc(50% - XYpx);

where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

next - it's like return, but for blocks! (So you can use this in any proc/lambda too.)

That means you can also say next n to "return" n from the block. For instance:

puts [1, 2, 3].map do |e|
  next 42 if e == 2
  e
end.inject(&:+)

This will yield 46.

Note that return always returns from the closest def, and never a block; if there's no surrounding def, returning is an error.

Using return from within a block intentionally can be confusing. For instance:

def my_fun
  [1, 2, 3].map do |e|
    return "Hello." if e == 2
    e
  end
end

my_fun will result in "Hello.", not [1, "Hello.", 2], because the return keyword pertains to the outer def, not the inner block.

What is the difference between max-device-width and max-width for mobile web?

max-width refers to the width of the viewport and can be used to target specific sizes or orientations in conjunction with max-height. Using multiple max-width (or min-width) conditions you could change the page styling as the browser is resized or the orientation changes on a device like an iPhone.

max-device-width refers to the viewport size of the device regardless of orientation, current scale or resizing. This will not change on a device so cannot be used to switch style sheets or CSS directives as the screen is rotated or resized.

pip install - locale.Error: unsupported locale setting

Someone may find it useful. You could put those locale settings in .bashrc file, which usually located in the home directory.
Just add this command in .bashrc:
export LC_ALL=C
then type source .bashrc
Now you don't need to call this command manually every time, when you connecting via ssh for example.

How to append multiple values to a list in Python

If you take a look at the official docs, you'll see right below append, extend. That's what your looking for.

There's also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.

How to make a link open multiple pages when clicked

You might want to arrange your HTML so that the user can still open all of the links even if JavaScript isn’t enabled. (We call this progressive enhancement.) If so, something like this might work well:

HTML

<ul class="yourlinks">
    <li><a href="http://www.google.com/"></li>
    <li><a href="http://www.yahoo.com/"></li>
</ul>

jQuery

$(function() { // On DOM content ready...
    var urls = [];

    $('.yourlinks a').each(function() {
        urls.push(this.href); // Store the URLs from the links...
    });

    var multilink = $('<a href="#">Click here</a>'); // Create a new link...
    multilink.click(function() {
        for (var i in urls) {
            window.open(urls[i]); // ...that opens each stored link in its own window when clicked...
        }
    });

    $('.yourlinks').replaceWith(multilink); // ...and replace the original HTML links with the new link.
});

This code assumes you’ll only want to use one “multilink” like this per page. (I’ve also not tested it, so it’s probably riddled with errors.)

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

Force “landscape” orientation mode

I had the same problem, it was a missing manifest.json file, if not found the browser decide with orientation is best fit, if you don't specify the file or use a wrong path.

I fixed just calling the manifest.json correctly on html headers.

My html headers:

<meta name="application-name" content="App Name">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="manifest" href="manifest.json">
<meta name="msapplication-starturl" content="/">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#">
<meta name="msapplication-TileColor" content="#">
<meta name="msapplication-config" content="browserconfig.xml">
<link rel="icon" type="image/png" sizes="192x192" href="android-chrome-192x192.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
<link rel="mask-icon" href="safari-pinned-tab.svg" color="#ffffff">
<link rel="shortcut icon" href="favicon.ico">

And the manifest.json file content:

{
  "display": "standalone",
  "orientation": "portrait",
  "start_url": "/",
  "theme_color": "#000000",
  "background_color": "#ffffff",
  "icons": [
  {
    "src": "android-chrome-192x192.png",
    "sizes": "192x192",
    "type": "image/png"
  }
}

To generate your favicons and icons use this webtool: https://realfavicongenerator.net/

To generate your manifest file use: https://tomitm.github.io/appmanifest/

My PWA Works great, hope it helps!

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

This seems issue with my node upgrade. How ever I solved it with the following approach.

First uninstall the cli, clear cashe, and reinstall with these commands

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

Then install node-pre-gyp

npm install -g node-pre-gyp

Restart your terminal and see if the issue is solved.

Invalid use side-effecting operator Insert within a function

You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:

User-defined functions cannot be used to perform actions that modify the database state.

"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).

You should be using a stored procedure, not a function.

How does the "view" method work in PyTorch?

I really liked @Jadiel de Armas examples.

I would like to add a small insight to how elements are ordered for .view(...)

  • For a Tensor with shape (a,b,c), the order of it's elements are determined by a numbering system: where the first digit has a numbers, second digit has b numbers and third digit has c numbers.
  • The mapping of the elements in the new Tensor returned by .view(...) preserves this order of the original Tensor.

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

How to parse a JSON and turn its values into an Array?

You can prefer quick-json parser to meet your requirement...

quick-json parser is very straight forward, flexible, very fast and customizable. Try this out

[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -

  • Compliant with JSON specification (RFC4627)

  • High-Performance JSON parser

  • Supports Flexible/Configurable parsing approach

  • Configurable validation of key/value pairs of any JSON Heirarchy

  • Easy to use # Very Less foot print

  • Raises developer friendly and easy to trace exceptions

  • Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered

  • Validating and Non-Validating parser support

  • Support for two types of configuration (JSON/XML) for using quick-json validating parser

  • Require JDK 1.5 # No dependency on external libraries

  • Support for Json Generation through object serialization

  • Support for collection type selection during parsing process

For e.g.

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);

How to store an output of shell script to a variable in Unix?

Suppose you want to store the result of an echo command

echo hello   
x=$(echo hello)  
echo "$x",world!  

output:

hello  
hello,world!

Is there a difference between x++ and ++x in java?

Yes,

int x=5;
System.out.println(++x);

will print 6 and

int x=5;
System.out.println(x++);

will print 5.

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

I had this problem after changing the Application's Default namespace in the Properties dialog.

The ./Views/Web.Config contained a reference to the old namespace

C# try catch continue execution

Why cant you use the finally block?

Like

try {

} catch (Exception e) {

  // THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK

} finally { 

 // THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT

}

EDIT after question amended:

You can do:

int? returnFromFunction2 = null;
    try {
        returnFromFunction2 = function2();
        return returnFromFunction2.value;
        } catch (Exception e) {

          // THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK

        } finally { 

        if (returnFromFunction2.HasValue) { // do something with value }

         // THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT

        }

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

How to calculate the sentence similarity using word2vec model of gensim with python

This is actually a pretty challenging problem that you are asking. Computing sentence similarity requires building a grammatical model of the sentence, understanding equivalent structures (e.g. "he walked to the store yesterday" and "yesterday, he walked to the store"), finding similarity not just in the pronouns and verbs but also in the proper nouns, finding statistical co-occurences / relationships in lots of real textual examples, etc.

The simplest thing you could try -- though I don't know how well this would perform and it would certainly not give you the optimal results -- would be to first remove all "stop" words (words like "the", "an", etc. that don't add much meaning to the sentence) and then run word2vec on the words in both sentences, sum up the vectors in the one sentence, sum up the vectors in the other sentence, and then find the difference between the sums. By summing them up instead of doing a word-wise difference, you'll at least not be subject to word order. That being said, this will fail in lots of ways and isn't a good solution by any means (though good solutions to this problem almost always involve some amount of NLP, machine learning, and other cleverness).

So, short answer is, no, there's no easy way to do this (at least not to do it well).

adding comment in .properties files

The property file task is for editing properties files. It contains all sorts of nice features that allow you to modify entries. For example:

<propertyfile file="build.properties">
    <entry key="build_number"
        type="int"
        operation="+"
        value="1"/>
</propertyfile>

I've incremented my build_number by one. I have no idea what the value was, but it's now one greater than what it was before.

  • Use the <echo> task to build a property file instead of <propertyfile>. You can easily layout the content and then use <propertyfile> to edit that content later on.

Example:

<echo file="build.properties">
# Default Configuration
source.dir=1
dir.publish=1
# Source Configuration
dir.publish.html=1
</echo>
  • Create separate properties files for each section. You're allowed a comment header for each type. Then, use to batch them together into one single file:

Example:

<propertyfile file="default.properties"
    comment="Default Configuration">
    <entry key="source.dir" value="1"/>
    <entry key="dir.publish" value="1"/>
<propertyfile>

<propertyfile file="source.properties"
    comment="Source Configuration">
    <entry key="dir.publish.html" value="1"/>
<propertyfile>
<concat destfile="build.properties">
    <fileset dir="${basedir}">
        <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</concat>

<delete>
    <fileset dir="${basedir}">
         <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</delete>      

Should we pass a shared_ptr by reference or by value?

shared_ptr isn't large enough, nor do its constructor\destructor do enough work for there to be enough overhead from the copy to care about pass by reference vs pass by copy performance.

Date difference in minutes in Python

In case someone doesn't realize it, one way to do this would be to combine Christophe and RSabet's answers:

from datetime import datetime
import time

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)

diff = d2 -d1
diff_minutes = (diff.days * 24 * 60) + (diff.seconds/60)

print(diff_minutes)
> 3043

Create a button programmatically and set a background image

Swift 5 version of accepted answer:

let image = UIImage(named: "image_name")
let button = UIButton(type: UIButton.ButtonType.custom)
button.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: #selector(function), for: .touchUpInside)

//button.backgroundColor = .lightGray
self.view.addSubview(button)

where of course

@objc func function() {...}

The image is aligned to center by default. You can change this by setting button's imageEdgeInsets, like this:

// In this case image is 40 wide and aligned to the left
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: button.frame.width - 45)

Add to python path mac os x

Setting the $PYTHONPATH environment variable does not seem to affect the Spyder IDE's iPython terminals on a Mac. However, Spyder's application menu contains a "PYTHONPATH manager." Adding my path here solved my problem. The "PYTHONPATH manager" is also persistent across application restarts.

This is specific to a Mac, because setting the PYTHONPATH environment variable on my Windows PC gives the expected behavior (modules are found) without using the PYTHONPATH manager in Spyder.

How can I put a ListView into a ScrollView without it collapsing?

Insted of putting ListView inside a ScrollView , we can use ListView as a ScrollView. Things which has to be in ListView can be put inside the ListView. Other layouts on top and bottom of ListView can be put by adding layouts to header and footer of ListView. So the entire ListView will give you an experience of scrolling .

Truncate Decimal number not Round Off

You can use Math.Round:

decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229

Or you can use ToString with the N3 numeric format.

string roundedNumber = number.ToString("N3");

EDIT: Since you don't want rounding, you can easily use Math.Truncate:

Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229

Converting list to *args when calling function

*args just means that the function takes a number of arguments, generally of the same type.

Check out this section in the Python tutorial for more info.

How can I use external JARs in an Android project?

Copying the .jar file into the Android project's folder isn't always possible.
Especially if it's an output of another project in your workspace, and it keeps getting updated.

To solve this you'll have to add the jar as a linked file to your project, instead of importing it (which will copy it locally).

In the UI choose:

Project -> Import -> File System -> yourjar.jar -> (Options area) Advanced -> Create link in workspace.

The link is save in the .project file:

<linkedResources>
    <link>
        <name>yourjar.jar</name>
        <type>1</type>
        <locationURI>PARENT-5-PROJECT_LOC/bin/android_ndk10d_armeabi-v7a/yourjar.jar</locationURI>
    </link>
</linkedResources>

PARENT-5-PROJECT_LOC means relative to the project file, 5 directories up (../../../../../).

Then add it to the libraries:
Project -> Properties -> Java Build Path -> Libraries -> Add Jar -> yourjar.jar

In the same window choose the Order and Export tab and mark your jar so it will be added to the apk.

Concat a string to SELECT * MySql

You simply can't do that in SQL. You have to explicitly list the fields and concat each one:

SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1

If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?

How to create custom spinner like border around the spinner with down triangle on the right side?

This is a simple one.

your_layout.xml

<android.support.v7.widget.AppCompatSpinner
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/spinner_background"
/>

In the drawable folder, spinner_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item><layer-list>
    <item>
        <shape>
            <solid
                android:color="@color/colorWhite">
            </solid>

            <corners android:radius="3dp" />

            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
            <stroke
                android:width="2dp"
                android:color="@color/colorDarkGrey"/>
        </shape>
    </item>
    <item >
        <bitmap android:gravity="bottom|right"
        android:src="@drawable/ic_arrow_drop_down_black_24dp" />
    </item>
  </layer-list></item>
</selector>

Preview:

Spinner example

How to read the last row with SQL Server

I think below query will work for SQL Server with maximum performance without any sortable column

SELECT * FROM table 
WHERE ID not in (SELECT TOP (SELECT COUNT(1)-1 
                             FROM table) 
                        ID 
                 FROM table)

Hope you have understood it... :)

Best Practices for securing a REST API / web service

I want to add(in line with stinkeymatt), simplest solution would be to add SSL certificates to your site. In other words, make sure your url is HTTPS://. That will cover your transport security (bang for the buck). With RESTful url's, idea is to keep it simple (unlike WS* security/SAML), you can use oAuth2/openID connect or even Basic Auth (in simple cases). But you will still need SSL/HTTPS. Please check ASP.NET Web API 2 security here: http://www.asp.net/web-api/overview/security (Articles and Videos)

What is PECS (Producer Extends Consumer Super)?

The principles behind this in computer science is called

  • Covariance: ? extends MyClass,
  • Contravariance: ? super MyClass and
  • Invariance/non-variance: MyClass

The picture below should explain the concept. Picture courtesy: Andrey Tyukin

Covariance vs Contravariance

Using the "animated circle" in an ImageView while loading stuff

This is generally referred to as an Indeterminate Progress Bar or Indeterminate Progress Dialog.

Combine this with a Thread and a Handler to get exactly what you want. There are a number of examples on how to do this via Google or right here on SO. I would highly recommend spending the time to learn how to use this combination of classes to perform a task like this. It is incredibly useful across many types of applications and will give you a great insight into how Threads and Handlers can work together.

I'll get you started on how this works:

The loading event starts the dialog:

//maybe in onCreate
showDialog(MY_LOADING_DIALOG);
fooThread = new FooThread(handler);
fooThread.start();

Now the thread does the work:

private class FooThread extends Thread {
    Handler mHandler;

    FooThread(Handler h) {
        mHandler = h;
    }

    public void run() { 
        //Do all my work here....you might need a loop for this

        Message msg = mHandler.obtainMessage();
        Bundle b = new Bundle();                
        b.putInt("state", 1);   
        msg.setData(b);
        mHandler.sendMessage(msg);
    }
}

Finally get the state back from the thread when it is complete:

final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        int state = msg.getData().getInt("state");
        if (state == 1){
            dismissDialog(MY_LOADING_DIALOG);
            removeDialog(MY_LOADING_DIALOG);
        }
    }
};

How to check if an element is off-screen

There's a jQuery plugin here which allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.

$('#element').visible();

You can also check for partial visibility:

$('#element').visible( true);

One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

I had this issue with gulp. The problem was that gulp added a dependency to my source file and I think npm tried to open it:

{
  "name": "name",
  "version": "2.0.0",
  "description": "",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "appname": "file://gulp",
    "gulp-concat": "^2.6.1",
    "gulp-electron": "^0.1.3",
    "gulp-shell": "^0.5.2",
    "gulp-uglify": "^2.0.0",
    "gulp-util": "^3.0.7",
    "node-7z": "^0.4.0"
  }
}

Make sure that there are no strange references in you package.json file.

Python - Count elements in list

len(myList) should do it.

len works with all the collections, and strings too.

What does "res.render" do, and what does the html file look like?

What does res.render do and what does the html file look like?

res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.


Answering Edit 2 part.

// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `orders` template
response.render("orders", {orders: orders_json});

So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs


Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.

Access denied for user 'test'@'localhost' (using password: YES) except root user

Do not grant all privileges over all databases to a non-root user, it is not safe (and you already have "root" with that role)

GRANT <privileges> ON database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This statement creates a new user and grants selected privileges to it. I.E.:

GRANT INSERT, SELECT, DELETE, UPDATE ON database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

Take a look at the docs to see all privileges detailed

EDIT: you can look for more info with this query (log in as "root"):

select Host, User from mysql.user;

To see what happened

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

Setting public class variables

Add getter and setter method to your class.

public function setValue($new_value)
{
    $this->testvar = $new_value;
}

public function getValue()
{
    return $this->testvar;        
}

How to catch exception correctly from http.request()?

The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"

Then make sure to access the Observable class as Rx.Observable.

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

Joining a WORKGROUP then rejoining the domain fixed this issue for me.

I got this error while using Virtual Box VM's. The issue started to happen when I moved the VM files to a new drive location or computer.

Hope this helps the VM folks.

How to start IIS Express Manually

Once you have IIS Express installed (the easiest way is through Microsoft Web Platform Installer), you will find the executable file in %PROGRAMFILES%\IIS Express (%PROGRAMFILES(x86)%\IIS Express on x64 architectures) and its called iisexpress.exe.

To see all the possible command-line options, just run:

iisexpress /?

and the program detailed help will show up.

If executed without parameters, all the sites defined in the configuration file and marked to run at startup will be launched. An icon in the system tray will show which sites are running.

There are a couple of useful options once you have some sites created in the configuration file (found in %USERPROFILE%\Documents\IISExpress\config\applicationhost.config): the /site and /siteId.

With the first one, you can launch a specific site by name:

iisexpress /site:SiteName

And with the latter, you can launch by specifying the ID:

iisexpress /siteId:SiteId

With this, if IISExpress is launched from the command-line, a list of all the requests made to the server will be shown, which can be quite useful when debugging.

Finally, a site can be launched by specifying the full directory path. IIS Express will create a virtual configuration file and launch the site (remember to quote the path if it contains spaces):

iisexpress /path:FullSitePath

This covers the basic IISExpress usage from the command line.

How to negate the whole regex?

Use negative lookaround: (?!pattern)

Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.

Links to regular-expressions.info

See also

More examples

These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):

import sun.misc.BASE64Encoder results in error compiled in Eclipse

That error is caused by your Eclipse configuration. You can reduce it to a warning. Better still, use a Base64 encoder that isn't part of a non-public API. Apache Commons has one, or when you're already on Java 1.8, then use java.util.Base64.

posting hidden value

Maybe a little late to the party but why don't you use sessions to store your data?

bookingfacilities.php

session_start();
$_SESSION['form_date'] = $date;

successfulbooking.php

session_start();
$date = $_SESSION['form_date']; 

Nobody will see this.

Javascript how to split newline

The problem is that when you initialize ks, the value hasn't been set.

You need to fetch the value when user submits the form. So you need to initialize the ks inside the callback function

(function($){
   $(document).ready(function(){
      $('#data').submit(function(e){
      //Here it will fetch the value of #keywords
         var ks = $('#keywords').val().split("\n");
         ...
      });
   });
})(jQuery);

Using ping in c#

Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress), which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation namespace contains a class called PingReply that has properties designed to translate the ICMP response and deliver useful information about the pinged server such as:

  • IPStatus: Gets the address of the host that sends the Internet Control Message Protocol (ICMP) echo reply.
  • IPAddress: Gets the number of milliseconds taken to send an Internet Control Message Protocol (ICMP) echo request and receive the corresponding ICMP echo reply message.
  • RoundtripTime (System.Int64): Gets the options used to transmit the reply to an Internet Control Message Protocol (ICMP) echo request.
  • PingOptions (System.Byte[]): Gets the buffer of data received in an Internet Control Message Protocol (ICMP) echo reply message.

The following is a simple example using WinForms to demonstrate how ping works in c#. By providing a valid IP address in textBox1 and clicking button1, we are creating an instance of the Ping class, a local variable PingReply, and a string to store the IP or URL address. We assign PingReply to the ping Send method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success status. Finally, we extract from PingReply the information we need to display for the user, which is described above.

    using System;
    using System.Net.NetworkInformation;
    using System.Windows.Forms;

    namespace PingTest1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                Ping p = new Ping();
                PingReply r;
                string s;
                s = textBox1.Text;
                r = p.Send(s);

                if (r.Status == IPStatus.Success)
                {
                    lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
                       + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
                }
            }

            private void textBox1_Validated(object sender, EventArgs e)
            {
                if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
                {
                    MessageBox.Show("Please use valid IP or web address!!");
                }
            }
        }
    }

C char array initialization

Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a struct or union.

Example program:

#include <stdio.h>

struct ccont
{
  char array[32];
};

struct icont
{
  int array[32];
};

int main()
{
  int  cnt;
  char carray[32] = { 'A', 66, 6*11+1 };    // 'A', 'B', 'C', '\0', '\0', ...
  int  iarray[32] = { 67, 42, 25 };

  struct ccont cc = { 0 };
  struct icont ic = { 0 };

  /*  these don't work
  carray = { [0]=1 };           // expected expression before '{' token
  carray = { [0 ... 31]=1 };    // (likewise)
  carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *'
  iarray = (int[32]){ 1 };      // (likewise, but s/char/int/g)
  */

  // but these perfectly work...
  cc = (struct ccont){ .array='a' };        // 'a', '\0', '\0', '\0', ...
  // the following is a gcc extension, 
  cc = (struct ccont){ .array={ [0 ... 2]='a' } };  // 'a', 'a', 'a', '\0', '\0', ...
  ic = (struct icont){ .array={ 42,67 } };      // 42, 67, 0, 0, 0, ...
  // index ranges can overlap, the latter override the former
  // (no compiler warning with -Wall -Wextra)
  ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ...

  for (cnt=0; cnt<5; cnt++)
    printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]);

  return 0;
}

How to read xml file contents in jQuery and display in html elements?

responseText is what you are looking for. Example:

    $.ajax({
...
complete: function(xhr, status) {
alert(xhr.responseText);
}
});

Where xml is your file. Remember this will be your xml in the form form of a string. You can parse it using xmlparse as some of them mentioned.

How to run console application from Windows Service?

I have a Windows service, and I added the following line to the constructor for my service:

using System.Diagnostics;
try {
    Process p = Process.Start(@"C:\Windows\system32\calc.exe");
} catch {
    Debugger.Break();
}

When I tried to run this, the Process.Start() call was made, and no exception occurred. However, the calc.exe application did not show up. In order to make it work, I had edit the properties for my service in the Service Control Manager to enable interaction with the desktop. After doing that, the Process.Start() opened calc.exe as expected.

But as others have said, interaction with the desktop is frowned upon by Microsoft and has essentially been disabled in Vista. So even if you can get it to work in XP, I don't know that you'll be able to make it work in Vista.

Passing references to pointers in C++

I know that it's posible to pass references of pointers, I did it last week, but I can't remember what the syntax was, as your code looks correct to my brain right now. However another option is to use pointers of pointers:

Myfunc(String** s)

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

Compare two files in Visual Studio

If you are working with TFS connected then right click on file which you need to compare (through source control explorer) and it presents you a window like this - enter image description here

Now change path of source file in 'Souce Path:' and you get comparision through VS comparision tool.

Similarly you can compare folder also which compares all files of a folder at once.

What does T&& (double ampersand) mean in C++11?

It denotes an rvalue reference. Rvalue references will only bind to temporary objects, unless explicitly generated otherwise. They are used to make objects much more efficient under certain circumstances, and to provide a facility known as perfect forwarding, which greatly simplifies template code.

In C++03, you can't distinguish between a copy of a non-mutable lvalue and an rvalue.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(const std::string&);

In C++0x, this is not the case.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(std::string&&);

Consider the implementation behind these constructors. In the first case, the string has to perform a copy to retain value semantics, which involves a new heap allocation. However, in the second case, we know in advance that the object which was passed in to our constructor is immediately due for destruction, and it doesn't have to remain untouched. We can effectively just swap the internal pointers and not perform any copying at all in this scenario, which is substantially more efficient. Move semantics benefit any class which has expensive or prohibited copying of internally referenced resources. Consider the case of std::unique_ptr- now that our class can distinguish between temporaries and non-temporaries, we can make the move semantics work correctly so that the unique_ptr cannot be copied but can be moved, which means that std::unique_ptr can be legally stored in Standard containers, sorted, etc, whereas C++03's std::auto_ptr cannot.

Now we consider the other use of rvalue references- perfect forwarding. Consider the question of binding a reference to a reference.

std::string s;
std::string& ref = s;
(std::string&)& anotherref = ref; // usually expressed via template

Can't recall what C++03 says about this, but in C++0x, the resultant type when dealing with rvalue references is critical. An rvalue reference to a type T, where T is a reference type, becomes a reference of type T.

(std::string&)&& ref // ref is std::string&
(const std::string&)&& ref // ref is const std::string&
(std::string&&)&& ref // ref is std::string&&
(const std::string&&)&& ref // ref is const std::string&&

Consider the simplest template function- min and max. In C++03 you have to overload for all four combinations of const and non-const manually. In C++0x it's just one overload. Combined with variadic templates, this enables perfect forwarding.

template<typename A, typename B> auto min(A&& aref, B&& bref) {
    // for example, if you pass a const std::string& as first argument,
    // then A becomes const std::string& and by extension, aref becomes
    // const std::string&, completely maintaining it's type information.
    if (std::forward<A>(aref) < std::forward<B>(bref))
        return std::forward<A>(aref);
    else
        return std::forward<B>(bref);
}

I left off the return type deduction, because I can't recall how it's done offhand, but that min can accept any combination of lvalues, rvalues, const lvalues.

How can I pad an integer with zeros on the left?

Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.

import java.text.NumberFormat;  
public class NumberFormatMain {  

public static void main(String[] args) {  
    int intNumber = 25;  
    float floatNumber = 25.546f;  
    NumberFormat format=NumberFormat.getInstance();  
    format.setMaximumIntegerDigits(6);  
    format.setMaximumFractionDigits(6);  
    format.setMinimumFractionDigits(6);  
    format.setMinimumIntegerDigits(6);  

    System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));  
    System.out.println("Formatted Float   : "+format.format(floatNumber).replace(",",""));  
 }    
}  

Use component from another module

Note that in order to create a so called "feature module", you need to import CommonModule inside it. So, your module initialization code will look like this:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { TaskCardComponent } from './task-card/task-card.component';
import { MdCardModule } from '@angular2-material/card';

@NgModule({
  imports: [
    CommonModule,
    MdCardModule 
  ],
  declarations: [
    TaskCardComponent
  ],
  exports: [
    TaskCardComponent
  ]
})
export class TaskModule { }

More information available here: https://angular.io/guide/ngmodule#create-the-feature-module

How to SSH into Docker?

Firstly you need to install a SSH server in the images you wish to ssh-into. You can use a base image for all your container with the ssh server installed. Then you only have to run each container mapping the ssh port (default 22) to one to the host's ports (Remote Server in your image), using -p <hostPort>:<containerPort>. i.e:

docker run -p 52022:22 container1 
docker run -p 53022:22 container2

Then, if ports 52022 and 53022 of host's are accessible from outside, you can directly ssh to the containers using the ip of the host (Remote Server) specifying the port in ssh with -p <port>. I.e.:

ssh -p 52022 myuser@RemoteServer --> SSH to container1

ssh -p 53022 myuser@RemoteServer --> SSH to container2

Performing Inserts and Updates with Dapper

You can try this:

 string sql = "UPDATE Customer SET City = @City WHERE CustomerId = @CustomerId";             
 conn.Execute(sql, customerEntity);

Less aggressive compilation with CSS3 calc

Less no longer evaluates expression inside calc by default since v3.00.


Original answer (Less v1.x...2.x):

Do this:

body { width: calc(~"100% - 250px - 1.5em"); }

In Less 1.4.0 we will have a strictMaths option which requires all Less calculations to be within brackets, so the calc will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.

wamp server mysql user id and password

Go to phpmyadmin and click on the database you have already created form the left side bar. Then you can see a privilege option at the top.. There you can add a new user..

If you are not having any database yet go to phpmyadmin and select databases and create a database by simply giving database name in the filed and press go.

Get last dirname/filename in a file path argument in Bash

The following approach can be used to get any path of a pathname:

some_path=a/b/c
echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))

Output:

c
b
a

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I was facing the similar type of issue: Code Snippet :

<c:forEach items="${orderList}" var="xx"> ${xx.id} <br>
</c:forEach>

There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.

So make sure about space. They play crucial role sometimes. :p

Problems with a PHP shell script: "Could not open input file"

I know its stupid but in my case i was outside of my project folder i didn't have spark file.

Python: CSV write by column rather than row

Read it in by row and then transpose it in the command line. If you're using Unix, install csvtool and follow the directions in: https://unix.stackexchange.com/a/314482/186237

Android Material and appcompat Manifest merger failed

Follow these steps:

  • Goto Refactor and Click Migrate to AndroidX
  • Click Do Refactor

How to return a value from __init__ in Python?

The __init__ method, like other methods and functions returns None by default in the absence of a return statement, so you can write it like either of these:

class Foo:
    def __init__(self):
        self.value=42

class Bar:
    def __init__(self):
        self.value=42
        return None

But, of course, adding the return None doesn't buy you anything.

I'm not sure what you are after, but you might be interested in one of these:

class Foo:
    def __init__(self):
        self.value=42
    def __str__(self):
        return str(self.value)

f=Foo()
print f.value
print f

prints:

42
42

How do I find out which DOM element has the focus?

I liked the approach used by Joel S, but I also love the simplicity of document.activeElement. I used jQuery and combined the two. Older browsers that don't support document.activeElement will use jQuery.data() to store the value of 'hasFocus'. Newer browsers will use document.activeElement. I assume that document.activeElement will have better performance.

(function($) {
var settings;
$.fn.focusTracker = function(options) {
    settings = $.extend({}, $.focusTracker.defaults, options);

    if (!document.activeElement) {
        this.each(function() {
            var $this = $(this).data('hasFocus', false);

            $this.focus(function(event) {
                $this.data('hasFocus', true);
            });
            $this.blur(function(event) {
                $this.data('hasFocus', false);
            });
        });
    }
    return this;
};

$.fn.hasFocus = function() {
    if (this.length === 0) { return false; }
    if (document.activeElement) {
        return this.get(0) === document.activeElement;
    }
    return this.data('hasFocus');
};

$.focusTracker = {
    defaults: {
        context: 'body'
    },
    focusedElement: function(context) {
        var focused;
        if (!context) { context = settings.context; }
        if (document.activeElement) {
            if ($(document.activeElement).closest(context).length > 0) {
                focused = document.activeElement;
            }
        } else {
            $(':visible:enabled', context).each(function() {
                if ($(this).data('hasFocus')) {
                    focused = this;
                    return false;
                }
            });
        }
        return $(focused);
    }
};
})(jQuery);

'float' vs. 'double' precision

float : 23 bits of significand, 8 bits of exponent, and 1 sign bit.

double : 52 bits of significand, 11 bits of exponent, and 1 sign bit.

Printing string variable in Java

You are printing the wrong value. Instead if the string you print the scanners object. Try this

Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);

Illegal Character when trying to compile java code

That's a byte order mark, as everyone says.

javac does not understand the BOM, not even when you try something like

javac -encoding UTF8 Test.java

You need to strip the BOM or convert your source file to another encoding. Notepad++ can convert a single files encoding, I'm not aware of a batch utility on the Windows platform for this.

The java compiler will assume the file is in your platform default encoding, so if you use this, you don't have to specify the encoding.

Converting NSData to NSString in Objective c

Unsure of data's encoding type? No problem!

Without need to know potential encoding types, in which wrong encoding types will give you nil/null, this should cover all your bases:

NSString *dataString = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];

Done!




Note: In the event this somehow fails, you can unpack your NSData with NSKeyedUnarchiver , then repack the (id)unpacked again via NSKeyedArchiver, and that NSData form should be base64 encodeable.

id unpacked = [NSKeyedUnarchiver unarchiveObjectWithData:data];
data = [NSKeyedArchiver archivedDataWithRootObject:unpacked];

adb shell command to make Android package uninstall dialog appear

Using ADB, you can use any of the following three commands:

adb shell am start -a android.intent.action.UNINSTALL_PACKAGE -d "package:PACKAGE"
adb shell am start -n com.android.packageinstaller/.UninstallerActivity -d "package:PACKAGE"
adb shell am start -a android.intent.action.DELETE -d "package:PACKAGE"

Replace PACKAGE with package name of the installed user app. The app mustn't be a device administrator for the command to work successfully. All of those commands would require user's confirmation for removal of app.

Details of the said command can be known by checking am's usage using adb shell am.

I got the info about those commands using Elixir 2 (use any equivalent app). I used it to show the activities of Package Installer app (the GUI that you see during installation and removal of apps) as well as the related intents. There you go.

The alternative way I used was: I attempted to uninstall the app using GUI until I was shown the final confirmation. I didn't confirm but execute the command

adb shell dumpsys activity recents   # for Android 4.4 and above
adb shell dumpsys activity activities # for Android 4.2.1

Among other things, it showed me useful details of the intent passed in the background. Example:

intent={act=android.intent.action.DELETE dat=package:com.bartat.android.elixir#com.bartat.android.elixir.MainActivity flg=0x10800000 cmp=com.android.packageinstaller/.UninstallerActivity}

Here, you can see the action, data, flag and component - enough for the goal.

Print text in Oracle SQL Developer SQL Worksheet window

enter image description here

for simple comments:

set serveroutput on format wrapped;
begin
    DBMS_OUTPUT.put_line('simple comment');
end;
/

-- do something

begin
    DBMS_OUTPUT.put_line('second simple comment');
end;
/

you should get:

anonymous block completed
simple comment

anonymous block completed
second simple comment

if you want to print out the results of variables, here's another example:

set serveroutput on format wrapped;
declare
a_comment VARCHAR2(200) :='first comment';
begin
    DBMS_OUTPUT.put_line(a_comment);
end;

/

-- do something


declare
a_comment VARCHAR2(200) :='comment';
begin
    DBMS_OUTPUT.put_line(a_comment || 2);
end;

your output should be:

anonymous block completed
first comment

anonymous block completed
comment2

How can I get selector from jQuery object

I added some fixes to @jessegavin's fix.

This will return right away if there is an ID on the element. I also added a name attribute check and a nth-child selector in case a element has no id, class, or name.

The name might need scoping in case there a multiple forms on the page and have similar inputs, but I didn't handle that yet.

function getSelector(el){
    var $el = $(el);

    var id = $el.attr("id");
    if (id) { //"should" only be one of these if theres an ID
        return "#"+ id;
    }

    var selector = $el.parents()
                .map(function() { return this.tagName; })
                .get().reverse().join(" ");

    if (selector) {
        selector += " "+ $el[0].nodeName;
    }

    var classNames = $el.attr("class");
    if (classNames) {
        selector += "." + $.trim(classNames).replace(/\s/gi, ".");
    }

    var name = $el.attr('name');
    if (name) {
        selector += "[name='" + name + "']";
    }
    if (!name){
        var index = $el.index();
        if (index) {
            index = index + 1;
            selector += ":nth-child(" + index + ")";
        }
    }
    return selector;
}

How to refresh or show immediately in datagridview after inserting?

I don't know if you resolved your problem, but a simple way to resolve this is rebuilding the DataSource (it is a property) of your datagridview. For example:

_x000D_
_x000D_
grdPatient.DataSource = MethodThatReturnList();
_x000D_
_x000D_
_x000D_

So, in that MethodThatReturnList() you can build a List (List is a class) with all the items you need. In my case, I have a method that return the values for two columns that I have on my datagridview.

Pasch.

How to pause / sleep thread or process in Android?

I use this:

Thread closeActivity = new Thread(new Runnable() {
  @Override
  public void run() {
    try {
      Thread.sleep(3000);
      // Do some stuff
    } catch (Exception e) {
      e.getLocalizedMessage();
    }
  }
});

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

On Salesforce platform this error is caused by /, the solution is to escape these as //.

UIView bottom border?

You can add a separate UIView with 1 point height and gray background color to self.view and position it right below toScrollView.

EDIT: Unless you have a good reason (want to use some services of UIView which are not offered by CALayer), you should use CALayer as @MattDiPasquale suggests. UIView has a greater overhead, which might not be a problem in most cases, but still, the other solution is more elegant.

Create GUI using Eclipse (Java)

There are lot of GUI designers even like Eclipse plugins, just few of them could use both, Swing and SWT..

WindowBuilder Pro GUI Designer - eclipse marketplace

WindowBuilder Pro GUI Designer - Google code home page

and

Jigloo SWT/Swing GUI Builder - eclipse market place

Jigloo SWT/Swing GUI Builder - home page

The window builder is quite better tool..

But IMHO, GUIs created by those tools have really ugly and unmanageable code..

Find all files in a folder

First off; best practice would be to get the users Desktop folder with

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Then you can find all the files with something like

string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

Then you could copy or move the files by enumerating the above collection like

// For copying...
foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

// ... Or for moving
foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

Check out these for more info:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

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

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

Merge two dataframes by index

Use merge, which is inner join by default:

pd.merge(df1, df2, left_index=True, right_index=True)

Or join, which is left join by default:

df1.join(df2)

Or concat, which is outer join by default:

pd.concat([df1, df2], axis=1)

Samples:

df1 = pd.DataFrame({'a':range(6),
                    'b':[5,3,6,9,2,4]}, index=list('abcdef'))

print (df1)
   a  b
a  0  5
b  1  3
c  2  6
d  3  9
e  4  2
f  5  4

df2 = pd.DataFrame({'c':range(4),
                    'd':[10,20,30, 40]}, index=list('abhi'))

print (df2)
   c   d
a  0  10
b  1  20
h  2  30
i  3  40

#default inner join
df3 = pd.merge(df1, df2, left_index=True, right_index=True)
print (df3)
   a  b  c   d
a  0  5  0  10
b  1  3  1  20

#default left join
df4 = df1.join(df2)
print (df4)
   a  b    c     d
a  0  5  0.0  10.0
b  1  3  1.0  20.0
c  2  6  NaN   NaN
d  3  9  NaN   NaN
e  4  2  NaN   NaN
f  5  4  NaN   NaN

#default outer join
df5 = pd.concat([df1, df2], axis=1)
print (df5)
     a    b    c     d
a  0.0  5.0  0.0  10.0
b  1.0  3.0  1.0  20.0
c  2.0  6.0  NaN   NaN
d  3.0  9.0  NaN   NaN
e  4.0  2.0  NaN   NaN
f  5.0  4.0  NaN   NaN
h  NaN  NaN  2.0  30.0
i  NaN  NaN  3.0  40.0

How to position one element relative to another with jQuery?

This is what worked for me in the end.

var showMenu = function(el, menu) {
    //get the position of the placeholder element  
    var pos = $(el).offset();    
    var eWidth = $(el).outerWidth();
    var mWidth = $(menu).outerWidth();
    var left = (pos.left + eWidth - mWidth) + "px";
    var top = 3+pos.top + "px";
    //show the menu directly over the placeholder  
    $(menu).css( { 
        position: 'absolute',
        zIndex: 5000,
        left: left, 
        top: top
    } );

    $(menu).hide().fadeIn();
};

Where is shared_ptr?

for VS2008 with feature pack update, shared_ptr can be found under namespace std::tr1.

std::tr1::shared_ptr<int> MyIntSmartPtr = new int;

of

if you had boost installation path (for example @ C:\Program Files\Boost\boost_1_40_0) added to your IDE settings:

#include <boost/shared_ptr.hpp>

placeholder for select tag

No need to take any javscript or any method you can just do it with your html css

HTML

<select id="myAwesomeSelect">
    <option selected="selected" class="s">Country Name</option>
    <option value="1">Option #1</option>
    <option value="2">Option #2</option>

</select>

Css

.s
{
    color:white;
        font-size:0px;
    display:none;
}

Redirect all output to file using Bash on Linux?

You can execute a subshell and redirect all output while still putting the process in the background:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

How do I write out a text file in C# with a code page other than UTF-8?

Change the Encoding of the stream writer. It's a property.

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.encoding.aspx

So:

sw.Encoding = Encoding.GetEncoding(28591);

Prior to writing to the stream.

Debian 8 (Live-CD) what is the standard login and password?

I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:

login : Debian Live User
password : live

I hope this helps

Calling a Javascript Function from Console

you can invoke it using window.function_name() or directly function_name()

Standard Android menu icons, for example refresh

Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:

"android_sdk"\platforms\"android_api_level"\data\res\drawable-hdpi\ic_menu_refresh.png

How can I make a clickable link in an NSAttributedString?

In case you're having issues with what @Karl Nosworthy and @esilver had provided above, I've updated the NSMutableAttributedString extension to its Swift 4 version.

extension NSMutableAttributedString {

public func setAsLink(textToFind:String, linkURL:String) -> Bool {

    let foundRange = self.mutableString.range(of: textToFind)
    if foundRange.location != NSNotFound {
         _ = NSMutableAttributedString(string: textToFind)
        // Set Attribuets for Color, HyperLink and Font Size
        let attributes = [NSFontAttributeName: UIFont.bodyFont(.regular, shouldResize: true), NSLinkAttributeName:NSURL(string: linkURL)!, NSForegroundColorAttributeName: UIColor.blue]

        self.setAttributes(attributes, range: foundRange)
        return true
    }
    return false
  }
}

Python decorators in classes

Would something like this do what you need?

class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

test = Test()

test.bar()

This avoids the call to self to access the decorator and leaves it hidden in the class namespace as a regular method.

>>> import stackoverflow
>>> test = stackoverflow.Test()
>>> test.bar()
start magic
normal call
end magic
>>> 

edited to answer question in comments:

How to use the hidden decorator in another class

class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

    _decorator = staticmethod( _decorator )

class TestB( Test ):
    @Test._decorator
    def bar( self ):
        print "override bar in"
        super( TestB, self ).bar()
        print "override bar out"

print "Normal:"
test = Test()
test.bar()
print

print "Inherited:"
b = TestB()
b.bar()
print

Output:

Normal:
start magic
normal call
end magic

Inherited:
start magic
override bar in
start magic
normal call
end magic
override bar out
end magic

Tab space instead of multiple non-breaking spaces ("nbsp")?

This is not a direct answer but I wanted to add a tab in Markdown document. I was drawing an object graph like this:

--Parent
    |
    + Child 1

Of course the easy way it to mark it as code by indenting by 4 spaces and is then treated as code in Markdown.

    --Parent
        |
        + Child 1

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

c# regex matches example

Regex regex = new Regex("%download#(\\d+?)%", RegexOptions.SingleLine);
Matches m = regex.Matches(input);

I think will do the trick (not tested).

Using curl POST with variables defined in bash script functions

Here's what actually worked for me, after guidance from answers here:

export BASH_VARIABLE="[1,2,3]"
curl http://localhost:8080/path -d "$(cat <<EOF
{
  "name": $BASH_VARIABLE,
  "something": [
    "value1",
    "value2",
    "value3"
  ]
}
EOF
)" -H 'Content-Type: application/json'

"Failed to install the following Android SDK packages as some licences have not been accepted" error

Appears to be a bug at the momment: https://issuetracker.google.com/issues/123054726

Solution that worked for me:

Create a .travis.yml file in your project directory and copy these lines:

before_script:
- mkdir "$ANDROID_HOME/licenses" || true
- echo "24333f8a63b6825ea9c5514f83c2829b004d1fee" > "$ANDROID_HOME/licenses/android-sdk-license"

Reference: https://github.com/square/RxIdler/pull/18/files

How to represent a fix number of repeats in regular expression?

The finite repetition syntax uses {m,n} in place of star/plus/question mark.

From java.util.regex.Pattern:

X{n}      X, exactly n times
X{n,}     X, at least n times
X{n,m}    X, at least n but not more than m times

All repetition metacharacter have the same precedence, so just like you may need grouping for *, +, and ?, you may also for {n,m}.

  • ha* matches e.g. "haaaaaaaa"
  • ha{3} matches only "haaa"
  • (ha)* matches e.g. "hahahahaha"
  • (ha){3} matches only "hahaha"

Also, just like *, +, and ?, you can add the ? and + reluctant and possessive repetition modifiers respectively.

    System.out.println(
        "xxxxx".replaceAll("x{2,3}", "[x]")
    ); "[x][x]"

    System.out.println(
        "xxxxx".replaceAll("x{2,3}?", "[x]")
    ); "[x][x]x"

Essentially anywhere a * is a repetition metacharacter for "zero-or-more", you can use {...} repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use * because Java doesn't officially support infinite-length lookbehind.

References

Related questions

When is a C++ destructor called?

To give a detailed answer to question 3: yes, there are (rare) occasions when you might call the destructor explicitly, in particular as the counterpart to a placement new, as dasblinkenlight observes.

To give a concrete example of this:

#include <iostream>
#include <new>

struct Foo
{
    Foo(int i_) : i(i_) {}
    int i;
};

int main()
{
    // Allocate a chunk of memory large enough to hold 5 Foo objects.
    int n = 5;
    char *chunk = static_cast<char*>(::operator new(sizeof(Foo) * n));

    // Use placement new to construct Foo instances at the right places in the chunk.
    for(int i=0; i<n; ++i)
    {
        new (chunk + i*sizeof(Foo)) Foo(i);
    }

    // Output the contents of each Foo instance and use an explicit destructor call to destroy it.
    for(int i=0; i<n; ++i)
    {
        Foo *foo = reinterpret_cast<Foo*>(chunk + i*sizeof(Foo));
        std::cout << foo->i << '\n';
        foo->~Foo();
    }

    // Deallocate the original chunk of memory.
    ::operator delete(chunk);

    return 0;
}

The purpose of this kind of thing is to decouple memory allocation from object construction.

JRE installation directory in Windows

Look the answer to my previous question here

c:\> for %i in (java.exe) do @echo.   %~$PATH:i
C:\WINDOWS\system32\java.exe

JS regex: replace all digits in string

You need to add the "global" flag to your regex:

s.replace(new RegExp("[0-9]", "g"), "X")

or, perhaps prettier, using the built-in literal regexp syntax:

.replace(/[0-9]/g, "X")

KeyListener, keyPressed versus keyTyped

Neither. You should NOT use a KeyLIstener.

Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings.

How can I get the corresponding table header (th) from a table cell (td)?

That's simple, if you reference them by index. If you want to hide the first column, you would:

Copy code

$('#thetable tr').find('td:nth-child(1),th:nth-child(1)').toggle();

The reason I first selected all table rows and then both td's and th's that were the n'th child is so that we wouldn't have to select the table and all table rows twice. This improves script execution speed. Keep in mind, nth-child() is 1 based, not 0.

Django: How can I call a view function from template?

For deleting all data:

HTML FILE

  class="btn btn-primary" href="{% url 'delete_product'%}">Delete

Put the above code in an anchor tag. (the a tag!)

url.py

path('delete_product', views.delete_product, name='delete_product')]

views.py

def delete_product(request):
    if request.method == "GET":
        dest = Racket.objects.all()
        dest.delete()
        return render(request, "admin_page.html")

Converting integer to digit list

Use list on a number converted to string:

In [1]: [int(x) for x in list(str(123))]
Out[2]: [1, 2, 3]

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

angularjs to output plain text instead of html

You can use ng-bind-html, don't forget to inject $sanitize service into your module Hope it helps

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Maven Dependency Scope

provided : This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

Run PostgreSQL queries from the command line

I also noticed that the query

SELECT * FROM tablename;

gives an error on the psql command prompt and

SELECT * FROM "tablename";

runs fine, really strange, so don't forget the double quotes. I always liked databases :-(

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

Very sort cut and effective solution is below:-

Add the below rule in your tsconfig.json file:-

"noImplicitAny": false

Then restart your project.

How to group by month from Date field using sql

DATEPART function doesn't work on MySQL 5.6, instead use MONTH('2018-01-01')

Is there a way to change the spacing between legend items in ggplot2?

A simple fix that I use to add space in horizontal legends, simply add spaces in the labels (see extract below):

  scale_fill_manual(values=c("red","blue","white"),
                    labels=c("Label of category 1          ",
                             "Label of category 2          ",
                             "Label of category 3"))

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

My personal cheatsheet, covering:

DOM element dimensions

  • .offsetWidth/.offsetHeight
  • .clientWidth/.clientHeight
  • .scrollWidth/.scrollHeight
  • .scrollLeft/.scrollTop
  • .getBoundingClientRect()

with small/simple/not-all-in-one diagrams :)


see full-size: https://docs.google.com/drawings/d/1bOOJnkN5G_lBs3Oz9NfQQH1I0aCrX5EZYPY3mu3_ROI/edit?usp=sharing

Showing all errors and warnings

I was able to get all errors via the below code:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

PHP sessions default timeout

It depends on the server configuration or the relevant directives session.gc_maxlifetime in php.ini.

Typically the default is 24 minutes (1440 seconds), but your webhost may have altered the default to something else.

Grep to find item in Perl array

In addition to what eugene and stevenl posted, you might encounter problems with using both <> and <STDIN> in one script: <> iterates through (=concatenating) all files given as command line arguments.

However, should a user ever forget to specify a file on the command line, it will read from STDIN, and your code will wait forever on input

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

Docker has a default entrypoint which is /bin/sh -c but does not have a default command.

When you run docker like this: docker run -i -t ubuntu bash the entrypoint is the default /bin/sh -c, the image is ubuntu and the command is bash.

The command is run via the entrypoint. i.e., the actual thing that gets executed is /bin/sh -c bash. This allowed Docker to implement RUN quickly by relying on the shell's parser.

Later on, people asked to be able to customize this, so ENTRYPOINT and --entrypoint were introduced.

Everything after ubuntu in the example above is the command and is passed to the entrypoint. When using the CMD instruction, it is exactly as if you were doing docker run -i -t ubuntu <cmd>. <cmd> will be the parameter of the entrypoint.

You will also get the same result if you instead type this command docker run -i -t ubuntu. You will still start a bash shell in the container because of the ubuntu Dockerfile specified a default CMD: CMD ["bash"]

As everything is passed to the entrypoint, you can have a very nice behavior from your images. @Jiri example is good, it shows how to use an image as a "binary". When using ["/bin/cat"] as entrypoint and then doing docker run img /etc/passwd, you get it, /etc/passwd is the command and is passed to the entrypoint so the end result execution is simply /bin/cat /etc/passwd.

Another example would be to have any cli as entrypoint. For instance, if you have a redis image, instead of running docker run redisimg redis -H something -u toto get key, you can simply have ENTRYPOINT ["redis", "-H", "something", "-u", "toto"] and then run like this for the same result: docker run redisimg get key.

How can I change the text color with jQuery?

Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.

Download single files from GitHub

Go to the script and click "Raw"

Then copy the link and download it with the aria2c link.

Eg: aria2c https://raw.githubusercontent.com/kodamail/gscript/master/color.gsf

Trick: the file I wanted to download is, https://github.com/kodamail/gscript*/blob*/master/color.gsf

just modify the link into https://raw.githubusercontent.com/kodamail/gscript/master/color.gsf

Remove the italic texts and add bold texts in the same format, it will give you the right link.

which can be used with aria2c,wget or with curl, I used aria2c here.

Using OpenGl with C#?

I think what @korona meant was since it's just a C API, you can consume it from C# directly with a heck of a lot of typing like this:

[DllImport("opengl32")]
public static extern void glVertex3f(float x, float y, float z);

You unfortunately would need to do this for every single OpenGL function you call, and is basically what Tao has done for you.

How do I create a folder in a GitHub repository?

I don't know whenever I use "/" in repository name it is replaced by "-" maybe github changed method of creating folders.

So I'm going to tell you what I did to create a empty folder and to add files.

  1. Click on New
  2. enter your folder name and nothing else
  3. Click on "Add a README file"
  4. Click "Create Repository"
  5. Now clone the folder you created.
  6. Add files or folders in the local repo
  7. Commit changes.
  8. And there you go.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

12 is a compile-time constant which can not be changed unlike the data referenced by int&. What you can do is

const int& z = 12;

How to declare a global variable in php?

$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:

function capital() {
    return my_var() . ' is the capital of Italy';
}

function my_var() {
    return 'Rome';
}

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.

< original link no longer active >

http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"

http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

The VARCHAR datatype is synonymous with the VARCHAR2 datatype. To avoid possible changes in behavior, always use the VARCHAR2 datatype to store variable-length character strings.

If your database runs on a single-byte character set (e.g. US7ASCII, WE8MSWIN1252 or WE8ISO8859P1) it does not make any difference whether you use VARCHAR2(x BYTE) or VARCHAR2(x CHAR).

It makes only a difference when your DB runs on multi-byte character set (e.g. AL32UTF8 or AL16UTF16). You can simply see it in this example:

CREATE TABLE my_table (
    VARCHAR2_byte VARCHAR2(1 BYTE), 
    VARCHAR2_char VARCHAR2(1 CHAR)
);

INSERT INTO my_table (VARCHAR2_char) VALUES ('€');
1 row created.

INSERT INTO my_table (VARCHAR2_char) VALUES ('ü');
1 row created.

INSERT INTO my_table (VARCHAR2_byte) VALUES ('€');
INSERT INTO my_table (VARCHAR2_byte) VALUES ('€')
Error at line 10
ORA-12899: value too large for column "MY_TABLE"."VARCHAR2_BYTE" (actual: 3, maximum: 1)

INSERT INTO my_table (VARCHAR2_byte) VALUES ('ü')
Error at line 11
ORA-12899: value too large for column "MY_TABLE"."VARCHAR2_BYTE" (actual: 2, maximum: 1)

VARCHAR2(1 CHAR) means you can store up to 1 character, no matter how many byte it has. In case of Unicode one character may occupy up to 4 bytes.

VARCHAR2(1 BYTE) means you can store a character which occupies max. 1 byte.

If you don't specify either BYTE or CHAR then the default is taken from NLS_LENGTH_SEMANTICS session parameter.

Unless you have Oracle 12c where you can set MAX_STRING_SIZE=EXTENDED the limit is VARCHAR2(4000 CHAR)

However, VARCHAR2(4000 CHAR) does not mean you are guaranteed to store up to 4000 characters. The limit is still 4000 bytes, so in worst case you may store only up to 1000 characters in such field.

See this example ( in UTF-8 occupies 3 bytes):

CREATE TABLE my_table2(VARCHAR2_char VARCHAR2(4000 CHAR));

BEGIN
    INSERT INTO my_table2 VALUES ('€€€€€€€€€€');
    FOR i IN 1..7 LOOP
        UPDATE my_table2 SET VARCHAR2_char = VARCHAR2_char ||VARCHAR2_char;
    END LOOP;
END;
/

SELECT LENGTHB(VARCHAR2_char) , LENGTHC(VARCHAR2_char) FROM my_table2;

LENGTHB(VARCHAR2_CHAR) LENGTHC(VARCHAR2_CHAR)
---------------------- ----------------------
                  3840                   1280
1 row selected.


UPDATE my_table2 SET VARCHAR2_char = VARCHAR2_char ||VARCHAR2_char;

UPDATE my_table2 SET VARCHAR2_char = VARCHAR2_char ||VARCHAR2_char
Error at line 1
ORA-01489: result of string concatenation is too long

See also Examples and limits of BYTE and CHAR semantics usage (NLS_LENGTH_SEMANTICS) (Doc ID 144808.1)

How to find the index of an element in an array in Java?

In this case, you could create e new String from your array of chars and then do an indeoxOf("e") on that String:

System.out.println(new String(list).indexOf("e")); 

But in other cases of primitive data types, you'll have to iterate over it.