Programs & Examples On #Datemodified

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

In my case it was because of the length of the database field is less than the length of the input field.

database table

create table user(
  Username nvarchar(5) not  null
);

My input

User newUser = new User()
{
   Username = "123456"
};

the value for Username length is 5 which is lessthan 6

...this may help someone

What character represents a new line in a text area

It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:

The element's value is defined to be the element's raw value with the following transformation applied:

Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.

Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:

Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.

To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.

SQL select everything in an array

// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');

// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';

// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;

// see what you get
var_dump($sql);

Update: (a short version and update missing comma)

$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';

Checking if a variable exists in javascript

if ( typeof variableName !== 'undefined' && variableName )
//// could throw an error if var doesnt exist at all

if ( window.variableName )
//// could be true if var == 0

////further on it depends on what is stored into that var
// if you expect an object to be stored in that var maybe
if ( !!window.variableName )
//could be the right way

best way => see what works for your case

How to make Sonar ignore some classes for codeCoverage metric?

For me this worked (basically pom.xml level global properties):

<properties>
    <sonar.exclusions>**/Name*.java</sonar.exclusions>
</properties>

According to: http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-Patterns

It appears you can either end it with ".java" or possibly "*"

to get the java classes you're interested in.

What is the recommended way to delete a large number of items from DynamoDB?

What I ideally want to do is call LogTable.DeleteItem(user_id) - Without supplying the range, and have it delete everything for me.

An understandable request indeed; I can imagine advanced operations like these might get added over time by the AWS team (they have a history of starting with a limited feature set first and evaluate extensions based on customer feedback), but here is what you should do to avoid the cost of a full scan at least:

  1. Use Query rather than Scan to retrieve all items for user_id - this works regardless of the combined hash/range primary key in use, because HashKeyValue and RangeKeyCondition are separate parameters in this API and the former only targets the Attribute value of the hash component of the composite primary key..

    • Please note that you''ll have to deal with the query API paging here as usual, see the ExclusiveStartKey parameter:

      Primary key of the item from which to continue an earlier query. An earlier query might provide this value as the LastEvaluatedKey if that query operation was interrupted before completing the query; either because of the result set size or the Limit parameter. The LastEvaluatedKey can be passed back in a new query request to continue the operation from that point.

  2. Loop over all returned items and either facilitate DeleteItem as usual

    • Update: Most likely BatchWriteItem is more appropriate for a use case like this (see below for details).

Update

As highlighted by ivant, the BatchWriteItem operation enables you to put or delete several items across multiple tables in a single API call [emphasis mine]:

To upload one item, you can use the PutItem API and to delete one item, you can use the DeleteItem API. However, when you want to upload or delete large amounts of data, such as uploading large amounts of data from Amazon Elastic MapReduce (EMR) or migrate data from another database in to Amazon DynamoDB, this API offers an efficient alternative.

Please note that this still has some relevant limitations, most notably:

  • Maximum operations in a single request — You can specify a total of up to 25 put or delete operations; however, the total request size cannot exceed 1 MB (the HTTP payload).

  • Not an atomic operation — Individual operations specified in a BatchWriteItem are atomic; however BatchWriteItem as a whole is a "best-effort" operation and not an atomic operation. That is, in a BatchWriteItem request, some operations might succeed and others might fail. [...]

Nevertheless this obviously offers a potentially significant gain for use cases like the one at hand.

Make XAMPP / Apache serve file outside of htdocs folder

You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.

Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.

EDIT:

alias myapp c:\myapp\

I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.

HTML entity for check mark

There is HTML entity &#10003 but it doesn't work in some older browsers.

Why is there no Char.Empty like String.Empty?

Easiest way to blanket remove a character from string is to Trim it

cl = cl.Trim(' ');

Removes all of the spaces in a string

Redirect to an external URL from controller action in Spring MVC

In short "redirect://yahoo.com" will lend you to yahoo.com.

where as "redirect:yahoo.com" will lend you your-context/yahoo.com ie for ex- localhost:8080/yahoo.com

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

Demi Magus answer worked for me until Rails 5.

On Apache2/Passenger/Ruby (2.4)/Rails (5.1.6), I had to put

export SECRET_KEY_BASE=GENERATED_CODE

from Demi Magus answer in /etc/apache2/envvars, cause /etc/profile seems to be ignored.

Source: https://www.phusionpassenger.com/library/indepth/environment_variables.html#apache

Multiple selector chaining in jQuery?

You can combine multiple selectors with a comma:

$('#Create .myClass,#Edit .myClass').plugin({options here});

Or if you're going to have a bunch of them, you could add a class to all your form elements and then search within that class. This doesn't get you the supposed speed savings of restricting the search, but I honestly wouldn't worry too much about that if I were you. Browsers do a lot of fancy things to optimize common operations behind your back -- the simple class selector might be faster.

How to check if NSString begins with a certain character

Use characterAtIndex:. If the first character is an asterisk, use substringFromIndex: to get the string sans '*'.

How to check if object property exists with a variable holding the property name?

You can use hasOwnProperty, but based on the reference you need quotes when using this method:

if (myObj.hasOwnProperty('myProp')) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Another way is to use in operator, but you need quotes here as well:

if ('myProp' in myObj) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

Python extract pattern matches

You want a capture group.

p = re.compile("name (.*) is valid", re.flags) # parentheses for capture groups
print p.match(s).groups() # This gives you a tuple of your matches.

Adding rows to tbody of a table using jQuery

use this

$("#tblEntAttributes tbody").append(newRowContent);

is there any PHP function for open page in new tab

Use the target attribute on your anchor tag with the _blank value.

Example:

<a href="http://google.com" target="_blank">Click Me!</a>

docker-compose up for only certain containers

You usually don't want to do this. With Docker Compose you define services that compose your app. npm and manage.py are just management commands. You don't need a container for them. If you need to, say create your database tables with manage.py, all you have to do is:

docker-compose run client python manage.py create_db

Think of it as the one-off dynos Heroku uses.

If you really need to treat these management commands as separate containers (and also use Docker Compose for these), you could create a separate .yml file and start Docker Compose with the following command:

docker-compose up -f my_custom_docker_compose.yml

Is there a way to return a list of all the image file names from a folder using only Javascript?

This will list all jpg files in the folder you define under url: and append them to a div as a paragraph. Can do it with ul li as well.

$.ajax({
  url: "YOUR FOLDER",
  success: function(data){
     $(data).find("a:contains(.jpg)").each(function(){
        // will loop through 
        var images = $(this).attr("href");

        $('<p></p>').html(images).appendTo('a div of your choice')

     });
  }
});

Convert a video to MP4 (H.264/AAC) with ffmpeg

You need to recompile ffmpeg (from source) so that it supports x264. If you follow the instructions in this page, then you will be able to peform any kind of conversion you want.

How to do a deep comparison between 2 objects with lodash?

This code returns an object with all properties that have a different value and also values of both objects. Useful to logging the difference.

var allkeys = _.union(_.keys(obj1), _.keys(obj2));
var difference = _.reduce(allkeys, function (result, key) {
  if ( !_.isEqual(obj1[key], obj2[key]) ) {
    result[key] = {obj1: obj1[key], obj2: obj2[key]}
  }
  return result;
}, {});

What is the difference between an IntentService and a Service?

service: It runs in the background on your system. For example,

  1. If you went to a hotel and you give your order for a soup to a server
  2. The server gets your order and sends to chef
  3. You don't know how the soup is made in the kitchen and what processes are required for making the soup
  4. Once your order is ready, the server brings you the soup.

background process: chef making soup

IntentService:- it's consecutive service.. (i.e) when you order many food items at a time to server but the server delivers those items one by one and not deliver them all at once.

Android Webview gives net::ERR_CACHE_MISS message

Answers assembled! I wanted to just combine all the answers into one comprehensive one.

1. Check if <uses-permission android:name="android.permission.INTERNET" /> is present in manifest.xml. Make sure that it is nested under <manifest> and not <application>. Thanks to sajid45 and Liyanis Velazquez

2. Ensure that you are using <uses-permission android:name="android.permission.INTERNET"/> instead of the deprecated <uses-permission android:name="android.permission.internet"/>. Much thanks to alan_shi and creos.

3. If minimum version is below KK, check that you have

if (18 < Build.VERSION.SDK_INT ){
    //18 = JellyBean MR2, KITKAT=19
    mWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}

or

if (Build.VERSION.SDK_INT >= 19) {
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}

because proper webview is only added in KK (SDK 19). Thanks to Devavrata, Mike ChanSeong Kim and Liyanis Velazquez

4. Ensure that you don't have webView.getSettings().setBlockNetworkLoads (false);. Thanks to TechNikh for pointing this out.

5. If all else fails, make sure that your Android Studio, Android SDK and the emulator image (if you are using one) is updated. And if you are still meeting the problem, just open a new question and make a comment below to your URL.

Angular2: Cannot read property 'name' of undefined

You just needed to read a little further and you would have been introduced to the *ngIf structural directive.

selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
  <div><label>id: </label>{{selectedHero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="selectedHero.name" placeholder="name"/>
  </div>
</div>

The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.

This document helped me understand structural directives.

ASP.NET Core - Swashbuckle not creating swagger.json file

I'd a similar issue, my Swagger documentation broke after I was adding async version of APIs to existing ones. I played around the Swagger DLL's by installing / Reinstalling, finally commenting newly added APIs, and it worked. Then I added different signature in attributes, and bingo!, It worked.

In your case, you are having two API with matching signatures

[HttpGet]
public IEnumerable<string> Get()
{
  return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{`enter code here`
  return "value";
}

Try providing different names in attributes like
[HttpGet("List")]
public IEnumerable<string> Get()
{
 return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("ListById/{id}")]
public string Get(int id)
{
  return "value";
}

This should solve the issue.

How can I reverse the order of lines in a file?

You may use Perl on the commandline:

perl -e 'my @b=(); while(<>) {push(@b, $_);}; print join("", reverse(@b));' orig > rev

Uncaught TypeError: Cannot assign to read only property

I tried changing year to a different term, and it worked.

public_methods : {
    get: function() {
        return this._year;
    },

    set: function(newValue) {
        if(newValue > this.originYear) {
            this._year = newValue;
            this.edition += newValue - this.originYear;
        }
    }
}

Difference between onStart() and onResume()

Short answer:

We can't live without onStart because that is the state when the activity becomes "visible" to the user, but the user cant "interact" with it yet may be cause it's overlapped with some other small dialog. This ability to interact with the user is the one that differentiates onStart and onResume. Think of it as a person behind a glass door. You can see the person but you can't interact (talk/listen/shake hands) with him. OnResume is like the door opener after which you can begin the interaction.

Additionally onRestart() is the least understood one. We can ask the question as to why not directly go to onStart() or onResume() after onStop() instead of onRestart(). It becomes easier to understand if we note that onRestart() is partially equivalent to onCreate() if the creation part is omitted. Basically both states lead to onStart() (i.e the Activity becomes visible). So both the states have to "prepare" the stuff to be displayed. OnCreate has the additional responsibility to "create" the stuff to be displayed

So their code structures might fit to something like:

onCreate()
{
     createNecessaryObjects();

     prepareObjectsForDisplay();
}


onRestart()
{
     prepareObjectsForDisplay();

}

The entire confusion is caused since Google chose non-intuitive names instead of something as follows:

onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change] 

The Activity Diagram might be interpreted as:

Android Activity Lifecycle

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

Pushing empty commits to remote

pushing commits, whether empty or not, causes eventual git hooks to be triggered. This can do either nothing or have world shattering consequences.

Select row and element in awk

To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:

awk '$2 ~ /abc/'

... and if you want to print only a particular column:

awk '$2 ~ /abc/ { print $3 }'

... and for a particular line number:

awk '$2 ~ /abc/ && FNR == 5 { print $3 }'

How do I use cascade delete with SQL Server?

Use something like

ALTER TABLE T2
ADD CONSTRAINT fk_employee
FOREIGN KEY (employeeID)
REFERENCES T1 (employeeID)
ON DELETE CASCADE;

Fill in the correct column names and you should be set. As mark_s correctly stated, if you have already a foreign key constraint in place, you maybe need to delete the old one first and then create the new one.

How to add a border to a widget in Flutter?

You can add the TextField as a child to a Container that has a BoxDecoration with border property:

enter image description here

new Container(
  margin: const EdgeInsets.all(15.0),
  padding: const EdgeInsets.all(3.0),
  decoration: BoxDecoration(
    border: Border.all(color: Colors.blueAccent)
  ),
  child: Text("My Awesome Border"),
)

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

There is probably another table with a foreign key referencing the primary key you are trying to change.

To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section

Use SHOW CREATE TABLE categories to show the name of constraint.

Most probably it will be categories_ibfk_1

Use the name to drop the foreign key first and the column then:

ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;

Change bootstrap datepicker date format on select

As of 2016 I used datetimepicker like this:

$(function () {
    $('#date_box').datetimepicker({
        format: 'YYYY-MM-DD hh:mm'
    });
});

How to replace a substring of a string

You need to use return value of replaceAll() method. replaceAll() does not replace the characters in the current string, it returns a new string with replacement.

  • String objects are immutable, their values cannot be changed after they are created.
  • You may use replace() instead of replaceAll() if you don't need regex.
    String str = "abcd=0; efgh=1";
    String replacedStr = str.replaceAll("abcd", "dddd");

    System.out.println(str);
    System.out.println(replacedStr);

outputs

abcd=0; efgh=1
dddd=0; efgh=1

Superscript in markdown (Github flavored)?

Use the <sup></sup>tag (<sub></sub> is the equivalent for subscripts). See this gist for an example.

How to test code dependent on environment variables using JUnit?

One slow, dependable, old-school method that always works in every operating system with every language (and even between languages) is to write the "system/environment" data you need to a temporary text file, read it when you need it, and then erase it. Of course, if you're running in parallel, then you need unique names for the file, and if you're putting sensitive information in it, then you need to encrypt it.

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

Use serialize and deserialize methods in SerializationUtils from commons-lang.

How to print float to n decimal places including trailing 0s?

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

>>> print('{0:.16f}'.format(1.6))
1.6000000000000001

>>> print('{0:.15f}'.format(1.6))
1.600000000000000

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

For Python versions prior to 2.6 (at least back to 2.0)

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

How to change DatePicker dialog color for Android 5.0

Create a new style

<!-- Theme.AppCompat.Light.Dialog -->
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">@color/blue_500</item>
</style>

Java code:

The parent theme is the key here. Choose your colorAccent

DatePickerDialog = new DatePickerDialog(context,R.style.DialogTheme,this,now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH);

Result:

enter image description here

Correct way to write loops for promise.

Bergi's suggested function is really nice:

var promiseWhile = Promise.method(function(condition, action) {
      if (!condition()) return;
    return action().then(promiseWhile.bind(null, condition, action));
});

Still I want to make a tiny addition, which makes sense, when using promises:

var promiseWhile = Promise.method(function(condition, action, lastValue) {
  if (!condition()) return lastValue;
  return action().then(promiseWhile.bind(null, condition, action));
});

This way the while loop can be embedded into a promise chain and resolves with lastValue (also if the action() is never run). See example:

var count = 10;
util.promiseWhile(
  function condition() {
    return count > 0;
  },
  function action() {
    return new Promise(function(resolve, reject) {
      count = count - 1;
      resolve(count)
    })
  },
  count)

"Large data" workflows using pandas

I know this is an old thread but I think the Blaze library is worth checking out. It's built for these types of situations.

From the docs:

Blaze extends the usability of NumPy and Pandas to distributed and out-of-core computing. Blaze provides an interface similar to that of the NumPy ND-Array or Pandas DataFrame but maps these familiar interfaces onto a variety of other computational engines like Postgres or Spark.

Edit: By the way, it's supported by ContinuumIO and Travis Oliphant, author of NumPy.

How to make a div center align in HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Center</title>_x000D_
  </head>_x000D_
  <body>_x000D_
_x000D_
    <div style="text-align: center;">_x000D_
      <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Tested and worked in IE, Firefox, Chrome, Safari and Opera. I did not test IE6. The outer text-align is needed for IE. Other browsers (and IE9?) will work when you give the DIV margin (left and right) value of auto. Margin "0 auto" is a shorthand for margin "0 auto 0 auto" (top right bottom left).

Note: the text is also centered inside the inner DIV, if you want it to remain on the left side just specify text-align: left; for the inner DIV.

Edit: IE 6, 7, 8 and 9 running on the Standards Mode will work with margins set to auto.

How to split one string into multiple strings separated by at least one space in bash shell?

$ echo "This is   a sentence." | tr -s " " "\012"
This
is
a
sentence.

For checking for spaces, use grep:

$ echo "This is   a sentence." | grep " " > /dev/null
$ echo $?
0
$ echo "Thisisasentence." | grep " " > /dev/null     
$ echo $?
1

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

How do I run a batch file from my Java Application?

Sometimes the thread execution process time is higher than JVM thread waiting process time, it use to happen when the process you're invoking takes some time to be processed, use the waitFor() command as follows:

try{    
    Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");
    p.waitFor();

}catch( IOException ex ){
    //Validate the case the file can't be accesed (not enought permissions)

}catch( InterruptedException ex ){
    //Validate the case the process is being stopped by some external situation     

}

This way the JVM will stop until the process you're invoking is done before it continue with the thread execution stack.

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you are using CORS middleware and you want to send withCredential boolean true, you can configure CORS like this:

var cors = require('cors');    
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));

Encode URL in JavaScript?

You have three options:

  • escape() will not encode: @*/+

  • encodeURI() will not encode: ~!@#$&*()=:/,;?+'

  • encodeURIComponent() will not encode: ~!*()'

But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.

See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.

Why use #define instead of a variable

C didn't use to have consts, so #defines were the only way of providing constant values. Both C and C++ do have them now, so there is no point in using them, except when they are going to be tested with #ifdef/ifndef.

Parse String to Date with Different Format in Java

Convert a string date to java.sql.Date

String fromDate = "19/05/2009";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dtt = df.parse(fromDate);
java.sql.Date ds = new java.sql.Date(dtt.getTime());
System.out.println(ds);//Mon Jul 05 00:00:00 IST 2010

How to create a directory in Java?

For java 7 and up:

Path path = Paths.get("/your/path/string");
Files.createDirectories(path);

It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:

Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

If this method fails, then it may do so after creating some, but not all, of the parent directories.

Where is android studio building my .apk file?

When Gradle builds your project, it puts all APKs in build/apk directory. You could also just do a simple recursive find command for *.apk in the top level directory of your project.

Here is a better description...

http://i.stack.imgur.com/XwjEZ.png

View full image at http://i.stack.imgur.com/XwjEZ.png

Simple insecure two-way data "obfuscation"?

I cleaned up SimpleAES (above) for my use. Fixed convoluted encrypt/decrypt methods; separated methods for encoding byte buffers, strings, and URL-friendly strings; made use of existing libraries for URL encoding.

The code is small, simpler, faster and the output is more concise. For instance, [email protected] produces:

SimpleAES: "096114178117140150104121138042115022037019164188092040214235183167012211175176167001017163166152"
SimplerAES: "YHKydYyWaHmKKnMWJROkvFwo1uu3pwzTr7CnARGjppg%3d"

Code:

public class SimplerAES
{
    private static byte[] key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 });

    // a hardcoded IV should not be used for production AES-CBC code
    // IVs should be unpredictable per ciphertext
    private static byte[] vector = __Replace_Me_({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 });

    private ICryptoTransform encryptor, decryptor;
    private UTF8Encoding encoder;

    public SimplerAES()
    {
        RijndaelManaged rm = new RijndaelManaged();
        encryptor = rm.CreateEncryptor(key, vector);
        decryptor = rm.CreateDecryptor(key, vector);
        encoder = new UTF8Encoding();
    }

    public string Encrypt(string unencrypted)
    {
        return Convert.ToBase64String(Encrypt(encoder.GetBytes(unencrypted)));
    }

    public string Decrypt(string encrypted)
    {
        return encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));
    }

    public byte[] Encrypt(byte[] buffer)
    {
        return Transform(buffer, encryptor);
    }

    public byte[] Decrypt(byte[] buffer)
    {
        return Transform(buffer, decryptor);
    }

    protected byte[] Transform(byte[] buffer, ICryptoTransform transform)
    {
        MemoryStream stream = new MemoryStream();
        using (CryptoStream cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))
        {
            cs.Write(buffer, 0, buffer.Length);
        }
        return stream.ToArray();
    }
}

null terminating a string

'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.

When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.

Is there a method that calculates a factorial in Java?

Try this

public static BigInteger factorial(int value){
    if(value < 0){
        throw new IllegalArgumentException("Value must be positive");
    }

    BigInteger result = BigInteger.ONE;
    for (int i = 2; i <= value; i++) {
        result = result.multiply(BigInteger.valueOf(i));
    }

    return result;
}

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

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

Comparing Java enum members: == or equals()?

In short, both have pros and cons.

On one hand, it has advantages to use ==, as described in the other answers.

On the other hand, if you for any reason replace the enums with a different approach (normal class instances), having used == bites you. (BTDT.)

When is layoutSubviews called?

When migrating an OpenGL app from SDK 3 to 4, layoutSubviews was not called anymore. After a lot of trial and error I finally opened MainWindow.xib, selected the Window object, in the inspector chose Window Attributes tab (leftmost) and checked "Visible at launch". It seems that in SDK 3 it still used to cause a layoutSubViews call, but not in 4.

6 hours of frustration put to an end.

ln (Natural Log) in Python

math.log is the natural logarithm:

From the documentation:

math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).

Your equation is therefore:

n = math.log((1 + (FV * r) / p) / math.log(1 + r)))

Note that in your code you convert n to a str twice which is unnecessary

Interface/enum listing standard mime-type constants

If you're on android you have multiple choices, where only the first is a kind of "enum":

For example

@Override
public String getType(Uri uri) {
    return URLConnection.getFileNameMap().getContentTypeFor(
            uri.getLastPathSegment());
}

Android list view inside a scroll view

Do NEVER put a ListView inside of a ScrollView! You can find more information about that topic on Google. In your case, use a LinearLayout instead of the ListView and add the elements programmatically.

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

simple HTTP server in Java using only Java SE API

Check out NanoHttpd

NanoHTTPD is a light-weight HTTP server designed for embedding in other applications, released under a Modified BSD licence.

It is being developed at Github and uses Apache Maven for builds & unit testing"

How to see top processes sorted by actual memory usage?

ps aux --sort '%mem'

from procps' ps (default on Ubuntu 12.04) generates output like:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
...
tomcat7   3658  0.1  3.3 1782792 124692 ?      Sl   10:12   0:25 /usr/lib/jvm/java-7-oracle/bin/java -Djava.util.logging.config.file=/var/lib/tomcat7/conf/logging.properties -D
root      1284  1.5  3.7 452692 142796 tty7    Ssl+ 10:11   3:19 /usr/bin/X -core :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch
ciro      2286  0.3  3.8 1316000 143312 ?      Sl   10:11   0:49 compiz
ciro      5150  0.0  4.4 660620 168488 pts/0   Sl+  11:01   0:08 unicorn_rails worker[1] -p 3000 -E development -c config/unicorn.rb             
ciro      5147  0.0  4.5 660556 170920 pts/0   Sl+  11:01   0:08 unicorn_rails worker[0] -p 3000 -E development -c config/unicorn.rb             
ciro      5142  0.1  6.3 2581944 239408 pts/0  Sl+  11:01   0:17 sidekiq 2.17.8 gitlab [0 of 25 busy]                                                                          
ciro      2386  3.6 16.0 1752740 605372 ?      Sl   10:11   7:38 /usr/lib/firefox/firefox

So here Firefox is the top consumer with 16% of my memory.

You may also be interested in:

ps aux --sort '%cpu'

What is the right way to POST multipart/form-data using curl?

On Windows 10, curl 7.28.1 within powershell, I found the following to work for me:

$filePath = "c:\temp\dir with spaces\myfile.wav"
$curlPath = ("myfilename=@" + $filePath)
curl -v -F $curlPath URL

How do you get the string length in a batch file?

Yes, of course there's an easy way, using vbscript (or powershell).

WScript.Echo Len( WScript.Arguments(0) )

save this as strlen.vbs and on command line

c:\test> cscript //nologo strlen.vbs "abcd"

Use a for loop to capture the result ( or use vbscript entirely for your scripting task)

Certainly beats having to create cumbersome workarounds using batch and there's no excuse not to use it since vbscript is available with each Windows distribution ( and powershell in later).

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

To increase heap size in IntelliJ IDEA follow the following instructions. It worked for me.

For Windows Users,

Go to the location where IDE is installed and search for following.

idea64.exe.vmoptions

Edit the file and add the following.

-Xms512m
-Xmx2024m
-XX:MaxPermSize=700m
-XX:ReservedCodeCacheSize=480m

That is it !!

What is the meaning of the prefix N in T-SQL statements and when should I use it?

Assuming the value is nvarchar type for that only we are using N''

Java: Simplest way to get last word in a string

String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

Adding HTML entities using CSS content

You have to use the escaped unicode :

Like

.breadcrumbs a:before {
    content: '\0000a0';
}

More info on : http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/

Getting Image from API in Angular 4/5+?

There is no need to use angular http, you can get with js native functions

_x000D_
_x000D_
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
     // on the first then you will return blob from response_x000D_
    return await fetch(url).then(r => r.blob())_x000D_
    .then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
         _x000D_
        return new File([blob], fileName+'.'+   blob.type.split('/')[1]) ;_x000D_
    });_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
    // with file reader you will transform the file in a data url file;_x000D_
    var reader = new FileReader();_x000D_
    reader.readAsDataURL(file);_x000D_
    reader.onloadend = () => {_x000D_
    _x000D_
    // just putting the data url to img element_x000D_
        document.querySelector('#image').src = reader.result ;_x000D_
    }_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
_x000D_
_x000D_

Add resources, config files to your jar using gradle

I came across this post searching how to add an extra directory for resources. I found a solution that may be useful to someone. Here is my final configuration to get that:

sourceSets {
    main {
        resources {
            srcDirs "src/main/resources", "src/main/configs"
        }
    }
}

Basic text editor in command prompt?

There is no command based text editors in windows (at least from Windows 7). But you can try the vi windows clone available here : http://www.vim.org/

You are Wrong! If you are using Windows 7, you can using this command:

copy con [filename.???]

Or if you using Windows XP or lower, use (is have a DOS GUI):

edit

Any comment?

Converting file into Base64String and back again

private String encodeFileToBase64Binary(File file){    
String encodedfile = null;  
try {  
    FileInputStream fileInputStreamReader = new FileInputStream(file);  
    byte[] bytes = new byte[(int)file.length()];
    fileInputStreamReader.read(bytes);  
    encodedfile = Base64.encodeBase64(bytes).toString();  
} catch (FileNotFoundException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
} catch (IOException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
}  
    return encodedfile;  
}

How do I trim whitespace?

For whitespace on both sides use str.strip:

s = "  \t a string example\t  "
s = s.strip()

For whitespace on the right side use rstrip:

s = s.rstrip()

For whitespace on the left side lstrip:

s = s.lstrip()

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

s = s.strip(' \t\n\r')

This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:

import re
print(re.sub('[\s+]', '', s))

That should print out:

astringexample

What method in the String class returns only the first N characters?

I added this in my project just because where I'm using it is a high chance of it being used in loops, in a project hosted online hence I didn't want any crashes if I could manage it. The length fits a column I have. It's C#7

Just a one line:

 public static string SubStringN(this string Message, int Len = 499) => !String.IsNullOrEmpty(Message) ? (Message.Length >= Len ? Message.Substring(0, Len) : Message) : "";

docker error: /var/run/docker.sock: no such file or directory

On my MAC when I start boot2docker-vm on the terminal using


boot2docker start

I see the following


To connect the Docker client to the Docker daemon, please set:
    export DOCKER_CERT_PATH=
    export DOCKER_TLS_VERIFY=1
    export DOCKER_HOST=tcp://:2376

After setting these environment variables I was able to run the build without the problem.

Update [2016-04-28] If you are using a the recent versions of docker you can do

eval $(docker-machine env) will set the environment

(docker-machine env will print the export statements)

"Non-static method cannot be referenced from a static context" error

setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.

You may want to look into some basic object-oriented tutorials to see how static/instance members work.

Good way to encapsulate Integer.parseInt()

To avoid an exception, you can use Java's Format.parseObject method. The code below is basically a simplified version of Apache Common's IntegerValidator class.

public static boolean tryParse(String s, int[] result)
{
    NumberFormat format = NumberFormat.getIntegerInstance();
    ParsePosition position = new ParsePosition(0);
    Object parsedValue = format.parseObject(s, position);

    if (position.getErrorIndex() > -1)
    {
        return false;
    }

    if (position.getIndex() < s.length())
    {
        return false;
    }

    result[0] = ((Long) parsedValue).intValue();
    return true;
}

You can either use AtomicInteger or the int[] array trick depending upon your preference.

Here is my test that uses it -

int[] i = new int[1];
Assert.assertTrue(IntUtils.tryParse("123", i));
Assert.assertEquals(123, i[0]);

Query error with ambiguous column name in SQL

Because you are joining two tables Invoices and InvoiceLineItems that both contain InvoiceID. change to Invoices.InvoiceID to make it correct.

error: This is probably not a problem with npm. There is likely additional logging output above

Delete your package-lock.json file and node_modules folder. Then do npm cache clean

npm cache clean --force

do npm install

again and run

java howto ArrayList push, pop, shift, and unshift

maybe you want to take a look java.util.Stack class. it has push, pop methods. and implemented List interface.

for shift/unshift, you can reference @Jon's answer.

however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.

Ajax passing data to php script

Try sending the data like this:

var data = {};
data.album = this.title;

Then you can access it like

$_POST['album']

Notice not a 'GET'

Python urllib2: Receive JSON response from url

If the URL is returning valid JSON-encoded data, use the json library to decode that:

import urllib2
import json

response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
data = json.load(response)   
print data

ERROR in Cannot find module 'node-sass'

I have also been facing this error. None of the above methods work for me. Please follow this as it worked for me.

For Installing node-sass in Ubuntu 16 via npm :-

You can install with npm 5.2.0 Version

If you are using nvm :-

nvm install 8.2.1
nvm use 8.2.1
npm install node-sass

If you are using npm separately then upgrade or downgrade npm version to 5.2.0

npm install node-sass

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Seems your resource POSTmethod won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).

Since in you already add Access-Control-Allow-Origin headers to your Response, you can add new OPTIONS method to your resource class.

    @OPTIONS
@Path("{path : .*}")
public Response options() {
    return Response.ok("")
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "2000")
            .build();
}

invalid conversion from 'const char*' to 'char*'

First of all this code snippet

char *addr=NULL;
strcpy(addr,retstring().c_str());

is invalid because you did not allocate memory where you are going to copy retstring().c_str().

As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.

Trying Gradle build - "Task 'build' not found in root project"

You didn't do what you're being asked to do.

What is asked:

I have to execute ../gradlew build

What you do

cd ..
gradlew build

That's not the same thing.

The first one will use the gradlew command found in the .. directory (mdeinum...), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore.

The second one will execute the gradlew command found in the current directory (mdeinum...), and look for the build file to execute in the current directory, which is mdeinum....

So the build file executed is not the same.

Using Pipes within ngModel on INPUT Elements in Angular

You can't use Template expression operators(pipe, save navigator) within template statement:

(ngModelChange)="Template statements"

(ngModelChange)="item.value | useMyPipeToFormatThatValue=$event"

https://angular.io/guide/template-syntax#template-statements

Like template expressions, template statements use a language that looks like JavaScript. The template statement parser differs from the template expression parser and specifically supports both basic assignment (=) and chaining expressions (with ; or ,).

However, certain JavaScript syntax is not allowed:

  • new
  • increment and decrement operators, ++ and --
  • operator assignment, such as += and -=
  • the bitwise operators | and &
  • the template expression operators

So you should write it as follows:

<input [ngModel]="item.value | useMyPipeToFormatThatValue" 
      (ngModelChange)="item.value=$event" name="inputField" type="text" />

Plunker Example

What is the maximum number of characters that nvarchar(MAX) will hold?

From char and varchar (Transact-SQL)

varchar [ ( n | max ) ]

Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

python pandas extract year from datetime: df['year'] = df['date'].year is not working

If you're running a recent-ish version of pandas then you can use the datetime attribute dt to access the datetime components:

In [6]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
df
Out[6]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

EDIT

It looks like you're running an older version of pandas in which case the following would work:

In [18]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month)
df
Out[18]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

Regarding why it didn't parse this into a datetime in read_csv you need to pass the ordinal position of your column ([0]) because when True it tries to parse columns [1,2,3] see the docs

In [20]:

t="""date   Count
6/30/2010   525
7/30/2010   136
8/31/2010   125
9/30/2010   84
10/29/2010  4469"""
df = pd.read_csv(io.StringIO(t), sep='\s+', parse_dates=[0])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 2 columns):
date     5 non-null datetime64[ns]
Count    5 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 120.0 bytes

So if you pass param parse_dates=[0] to read_csv there shouldn't be any need to call to_datetime on the 'date' column after loading.

Python Progress Bar

use the os_sys lib:

i use it for many types of bars, example:

from os_sys.progress import bar as Bar
bar = Bar('progresing: ', max=20)
for i in range(20):
    #do somthing
    bar.next()
bar.finish()

your output will be:

procesing:  |######                          | 2/10

read more in the discription of os_sys

How do you tell if a string contains another string in POSIX sh?

See the manpage for the 'test' program. If you're just testing for the existence of a directory you would normally do something like so:

if test -d "String1"; then
  echo "String1 present"
end

If you're actually trying to match a string you can use bash expansion rules & wildcards as well:

if test -d "String*"; then
  echo "A directory starting with 'String' is present"
end

If you need to do something more complex you'll need to use another program like expr.

Safari 3rd party cookie iframe trick no longer working?

Some context that I haven't seen clearly stated in the existing answers (and also a lot has changed since 2012!):

If you can control both the 3rd party iframe and the parent page (i.e. you are able to insert JavaScript on the parent page), then several workarounds are available. I would suggest the most elegant of these is making use of the postMessage API as described by @Frank's answer, as a) this does not require any redirects and b) does not require any user interactions.

If you do NOT control both the 3rd party iframe and the parent page, e.g. you have a widget hosted on a site you do not control, then most of the answers posted here will not work in Safari as of May 2020, and will stop working in Chrome around 2022. That is, unless a user has already visited your domain or interacts with the iframe, you are not able to set cookies. However, there are some commercial services offering solutions to solve this problem, such as CloudCookie.io

How to increase the Java stack size?

Add this option

--driver-java-options -Xss512m

to your spark-submit command will fix this issue.

How to "pretty" format JSON output in Ruby on Rails

Check out Awesome Print. Parse the JSON string into a Ruby Hash, then display it with ap like so:

require "awesome_print"
require "json"

json = '{"holy": ["nested", "json"], "batman!": {"a": 1, "b": 2}}'

ap(JSON.parse(json))

With the above, you'll see:

{
  "holy" => [
    [0] "nested",
    [1] "json"
  ],
  "batman!" => {
    "a" => 1,
    "b" => 2
  }
}

Awesome Print will also add some color that Stack Overflow won't show you.

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

String to HashMap JAVA

You can do that with Guava's Splitter.MapSplitter:

Map<String, String> properties = Splitter.on(",").withKeyValueSeparator(":").split(inputString);

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Casting a number to a string in TypeScript

Use the "+" symbol to cast a string to a number.

window.location.hash = +page_number;

I forgot the password I entered during postgres installation

Just a note, on Linux You can simply run sudo su - postgres to become the postgres user and from there change what required using psql.

How to bundle an Angular app for production

Angular 2 with Webpack (without CLI setup)

1- The tutorial by the Angular2 team

The Angular2 team published a tutorial for using Webpack

I created and placed the files from the tutorial in a small GitHub seed project. So you can quickly try the workflow.

Instructions:

  • npm install

  • npm start. For development. This will create a virtual "dist" folder that will be livereloaded at your localhost address.

  • npm run build. For production. "This will create a physical "dist" folder version than can be sent to a webserver. The dist folder is 7.8MB but only 234KB is actually required to load the page in a web browser.

2 - A Webkit starter kit

This Webpack Starter Kit offers some more testing features than the above tutorial and seem quite popular.

What does "restore purchases" in In-App purchases mean?

You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.

for other type of products it will automatically restore it.

Please read following text which will clear your concept about this :

Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.

Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.

If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices

MySQL timestamp select date range

Usually it would be this:

SELECT * 
  FROM yourtable
 WHERE yourtimetimefield>='2010-10-01'
   AND yourtimetimefield< '2010-11-01'

But because you have a unix timestamps, you'll need something like this:

SELECT * 
  FROM yourtable
 WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
   AND yourtimetimefield< unix_timestamp('2010-11-01')

Group By Multiple Columns

You can also use a Tuple<> for a strongly-typed grouping.

from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
{
    LastName = grouping.Key.Item1,
    FirstName = grouping.Key.Item2,
    MiddleName = grouping.Key.Item3,
    DayCount = grouping.Count(), 
    AmountBilled = grouping.Sum(x => x.Rate),
}

Select query with date condition

The semicolon character is used to terminate the SQL statement.

You can either use # signs around a date value or use Access's (ACE, Jet, whatever) cast to DATETIME function CDATE(). As its name suggests, DATETIME always includes a time element so your literal values should reflect this fact. The ISO date format is understood perfectly by the SQL engine.

Best not to use BETWEEN for DATETIME in Access: it's modelled using a floating point type and anyhow time is a continuum ;)

DATE and TABLE are reserved words in the SQL Standards, ODBC and Jet 4.0 (and probably beyond) so are best avoided for a data element names:

Your predicates suggest open-open representation of periods (where neither its start date or the end date is included in the period), which is arguably the least popular choice. It makes me wonder if you meant to use closed-open representation (where neither its start date is included but the period ends immediately prior to the end date):

SELECT my_date
  FROM MyTable
 WHERE my_date >= #2008-09-01 00:00:00#
       AND my_date < #2010-09-01 00:00:00#;

Alternatively:

SELECT my_date
  FROM MyTable
 WHERE my_date >= CDate('2008-09-01 00:00:00')
       AND my_date < CDate('2010-09-01 00:00:00'); 

Android ListView Divider

Folks, here's why you should use 1px instead of 1dp or 1dip: if you specify 1dp or 1dip, Android will scale that down. On a 120dpi device, that becomes something like 0.75px translated, which rounds to 0. On some devices, that translates to 2-3 pixels, and it usually looks ugly or sloppy

For dividers, 1px is the correct height if you want a 1 pixel divider and is one of the exceptions for the "everything should be dip" rule. It'll be 1 pixel on all screens. Plus, 1px usually looks better on hdpi and above screens

"It's not 2012 anymore" edit: you may have to switch over to dp/dip starting at a certain screen density

How do I disable orientation change on Android?

Add

android:configChanges="keyboardHidden|orientation|screenSize" 

to your manifest.

How to indent HTML tags in Notepad++

In Notepad++ v7.8.9 you can use the Tab key to increase the indention level, and use Shift + Tab to decrease the indentation level.

How to save a plot into a PDF file without a large margin around

The script in How to get rid of the white margin in MATLAB's saveas or print outputs does what you want.

Make your figure boundaries tight:

ti = get(gca,'TightInset')
set(gca,'Position',[ti(1) ti(2) 1-ti(3)-ti(1) 1-ti(4)-ti(2)]);

... if you directly do saveas (or print), MATLAB will still add the annoying white space. To get rid of them, we need to adjust the ``paper size":

set(gca,'units','centimeters')
pos = get(gca,'Position');
ti = get(gca,'TightInset');

set(gcf, 'PaperUnits','centimeters');
set(gcf, 'PaperSize', [pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);
set(gcf, 'PaperPositionMode', 'manual');
set(gcf, 'PaperPosition',[0 0 pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);

Finding an item in a List<> using C#

item = objects.Find(obj => obj.property==myValue);

Usage of @see in JavaDoc?

The @see tag is a bit different than the @link tag,
limited in some ways and more flexible in others:

different JavaDoc link types Different JavaDoc link types

  1. Displays the member name for better learning, and is refactorable; the name will update when renaming by refactor
  2. Refactorable and customizable; your text is displayed instead of the member name
  3. Displays name, refactorable
  4. Refactorable, customizable
  5. A rather mediocre combination that is:
  • Refactorable, customizable, and stays in the See Also section
  • Displays nicely in the Eclipse hover
  • Displays the link tag and its formatting when generated
  • When using multiple @see items, commas in the description make the output confusing
  1. Completely illegal; causes unexpected content and illegal character errors in the generator

See the results below:

JavaDoc generation results with different link types JavaDoc generation results with different link types

Best regards.

How to format DateTime in Flutter , How to get current time in flutter?

You can also use this syntax. For YYYY-MM-JJ HH-MM:

var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';

How to count instances of character in SQL Column

Here's what I used in Oracle SQL to see if someone was passing a correctly formatted phone number:

WHERE REPLACE(TRANSLATE('555-555-1212','0123456789-','00000000000'),'0','') IS NULL AND
LENGTH(REPLACE(TRANSLATE('555-555-1212','0123456789','0000000000'),'0','')) = 2

The first part checks to see if the phone number has only numbers and the hyphen and the second part checks to see that the phone number has only two hyphens.

Preferred way to create a Scala list

ListBuffer is a mutable list which has constant-time append, and constant-time conversion into a List.

List is immutable and has constant-time prepend and linear-time append.

How you construct your list depends on the algorithm you'll use the list for and the order in which you get the elements to create it.

For instance, if you get the elements in the opposite order of when they are going to be used, then you can just use a List and do prepends. Whether you'll do so with a tail-recursive function, foldLeft, or something else is not really relevant.

If you get the elements in the same order you use them, then a ListBuffer is most likely a preferable choice, if performance is critical.

But, if you are not on a critical path and the input is low enough, you can always reverse the list later, or just foldRight, or reverse the input, which is linear-time.

What you DON'T do is use a List and append to it. This will give you much worse performance than just prepending and reversing at the end.

Convert boolean to int in Java

If you want to obfuscate, use this:

System.out.println( 1 & Boolean.hashCode( true ) >> 1 );  // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0

Python class returning value

Use __new__ to return value from a class.

As others suggest __repr__,__str__ or even __init__ (somehow) CAN give you what you want, But __new__ will be a semantically better solution for your purpose since you want the actual object to be returned and not just the string representation of it.

Read this answer for more insights into __str__ and __repr__ https://stackoverflow.com/a/19331543/4985585

class MyClass():
    def __new__(cls):
        return list() #or anything you want

>>> MyClass()
[]   #Returns a true list not a repr or string

Must declare the scalar variable

Declare @v1 varchar(max), @v2 varchar(200);

Declare @sql nvarchar(max);

Set @sql = N'SELECT @v1 = value1, @v2 = value2
FROM dbo.TblTest -- always use schema
WHERE ID = 61;';

EXEC sp_executesql @sql,
  N'@v1 varchar(max) output, @v2 varchar(200) output',
  @v1 output, @v2 output;

You should also pass your input, like wherever 61 comes from, as proper parameters (but you won't be able to pass table and column names that way).

Omitting the first line from any Linux command output

Pipe it to awk:

awk '{if(NR>1)print}'

or sed

sed -n '1!p'

Unknown version of Tomcat was specified in Eclipse

Go to "Window -> preferences -> Server -> Runtime Environments"

Remove the existing servers they might not have downloaded completely.

Add new Server

Temporary tables in stored procedures

For all those recommending using table variables, be cautious in doing so. Table variable cannot be indexed whereas a temp table can be. A table variable is best when working with small amounts of data but if you are working on larger sets of data (e.g. 50k records) a temp table will be much faster than a table variable.

Also keep in mind that you can't rely on a try/catch to force a cleanup within the stored procedure. certain types of failures cannot be caught within a try/catch (e.g. compile failures due to delayed name resolution) if you want to be really certain you may need to create a wrapper stored procedure that can do a try/catch of the worker stored procedure and do the cleanup there.

e.g. create proc worker AS BEGIN -- do something here END

create proc wrapper AS
BEGIN
    Create table #...
    BEGIN TRY
       exec worker
       exec worker2 -- using same temp table
       -- etc
    END TRY
    END CATCH
       -- handle transaction cleanup here
       drop table #...
    END CATCH 
END

One place where table variables are always useful is they do not get rolled back when a transaction is rolled back. This can be useful for capturing debug data that you want to commit outside the primary transaction.

Missing styles. Is the correct theme chosen for this layout?

I got this error after overriding action bar style like this. Also i lost action bar in preview.

<style name="general_app_theme" parent="@style/Theme.AppCompat">
    <!-- for API level 11 -->
    <item name="android:actionBarStyle">@style/action_bar_style</item>

    <!-- Support library compatibility -->
    <item name="actionBarStyle">@style/action_bar_style</item>

</style>

<style name="action_bar_style" parent="@style/Widget.AppCompat.ActionBar">
    <!-- for API level 11 -->
    <item name="android:height">@dimen/action_bar_height</item>
    <item name="android:background">@color/action_bar_color</item>
    <item name="android:displayOptions">showTitle</item>

    <!-- Support library compatibility -->
    <item name="displayOptions">showTitle</item>
</style>

So, problem is overriding theme by my custom. this is the reason, why I've changed AppCompat (from "Project Themes") to general_app_theme (from "Manifest Themes"). Now I have no this error and action bar in preview come back.

Unordered List (<ul>) default indent

It has a default indent/padding so that the bullets will not end up outside the list itself.

A CSS reset might or might not contain rules to reset the list, that would depend on which one you use.

Copy entire contents of a directory to another using php

// using exec

function rCopy($directory, $destination)
{

    $command = sprintf('cp -r %s/* %s', $directory, $destination);

    exec($command);

}

Round number to nearest integer

For this purpose I would suggest just do the following thing -

int(round(x))

This will give you nearest integer.

Hope this helps!!

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

Change key pair for ec2 instance

if you are unable to login in VM and deleted your ssh key's and you can also change the key pair of your ec2 using below steps. Go step by step 1) stop your ec2 instance. 2)take a snapshot of VM and storage. 3)create a new VM while creating it select your snapshot and create VM from your Snapshot. 4) while the creation of VM downloads your keypair. 5) once your VM UP you can ssh with a new key pair and your data will also back.

How to make an app's background image repeat

There is a property in the drawable xml to do it. android:tileMode="repeat"

See this site: http://androidforbeginners.blogspot.com/2010/06/how-to-tile-background-image-in-android.html

Set the value of a variable with the result of a command in a Windows batch file

To do what Jesse describes, from a Windows batch file you will need to write:

for /f "delims=" %%a in ('ver') do @set foobar=%%a 

But, I instead suggest using Cygwin on your Windows system if you are used to Unix-type scripting.

Why does the C preprocessor interpret the word "linux" as the constant "1"?

This appears to be an (undocumented) "GNU extension": [correction: I finally found a mention in the docs. See below.]

The following command uses the -dM option to print all preprocessor defines; since the input "file" is empty, it shows exactly the predefined macros. It was run with gcc-4.7.3 on a standard ubuntu install. You can see that the preprocessor is standard-aware. In total, there 243 macros with -std=gnu99 and 240 with -std=c99; I filtered the output for relevance.

$ cpp --std=c89 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1

$ cpp --std=gnu89 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1

$ cpp --std=c99 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1

$ cpp --std=gnu99 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1

The "gnu standard" versions also #define unix. (Using c11 and gnu11 produces the same results.)

I suppose they had their reasons, but it seems to me to make the default installation of gcc (which compiles C code with -std=gnu89 unless otherwise specified) non-conformant, and -- as in this question -- surprising. Polluting the global namespace with macros whose names don't begin with an underscore is not permitted in a conformant implementation. (6.8.10p2: "Any other predefined macro names shall begin with a leading underscore followed by an uppercase letter or a second underscore," but, as mentioned in Appendix J.5 (portability issues), such names are often predefined.)

When I originally wrote this answer, I wasn't able to find any documentation in gcc about this issue, but I did finally discover it, not in C implementation-defined behaviour nor in C extensions but in the cpp manual section 3.7.3, where it notes that:

We are slowly phasing out all predefined macros which are outside the reserved namespace. You should never use them in new programs…

rails 3 validation on uniqueness on multiple attributes

Multiple Scope Parameters:

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

This should answer Greg's question.

laravel compact() and ->with()

the best way for me :

    $data=[
'var1'=>'something',
'var2'=>'something',
'var3'=>'something',
      ];
return View::make('view',$data);

How can I pipe stderr, and not stdout?

Or to swap the output from standard error and standard output over, use:

command 3>&1 1>&2 2>&3

This creates a new file descriptor (3) and assigns it to the same place as 1 (standard output), then assigns fd 1 (standard output) to the same place as fd 2 (standard error) and finally assigns fd 2 (standard error) to the same place as fd 3 (standard output).

Standard error is now available as standard output and the old standard output is preserved in standard error. This may be overkill, but it hopefully gives more details on Bash file descriptors (there are nine available to each process).

How do I generate random number for each row in a TSQL Select?

Try this:

SELECT RAND(convert(varbinary, newid()))*(b-a)+a magic_number 

Where a is the lower number and b is the upper number

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

PHP: How to check if image file exists?

if (file_exists('http://www.mydomain.com/images/'.$filename)) {}

This didn't work for me. The way I did it was using getimagesize.

$src = 'http://www.mydomain.com/images/'.$filename;

if (@getimagesize($src)) {

Note that the '@' will mean that if the image does not exist (in which case the function would usually throw an error: getimagesize(http://www.mydomain.com/images/filename.png) [function.getimagesize]: failed) it will return false.

How to view file diff in git before commit

Another technique to consider if you want to compare a file to the last commit which is more pedantic:

git diff master myfile.txt

The advantage with this technique is you can also compare to the penultimate commit with:

git diff master^ myfile.txt

and the one before that:

git diff master^^ myfile.txt

Also you can substitute '~' for the caret '^' character and 'you branch name' for 'master' if you are not on the master branch.

Python: Open file in zip without temporarily extracting it

import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')

# read bytes from archive
img_data = archive.read('img_01.png')

# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)

img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.

How to create correct JSONArray in Java using JSONObject

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }

check if variable empty

empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:

if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

_x000D_
_x000D_
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
_x000D_
_x000D_

CSS "color" vs. "font-color"

I would think that one reason could be that the color is applied to things other than font. For example:

div {
    border: 1px solid;
    color: red;
}

Yields both a red font color and a red border.

Alternatively, it could just be that the W3C's CSS standards are completely backwards and nonsensical as evidenced elsewhere.

Git merge develop into feature branch outputs "Already up-to-date" while it's not

Initially my repo said "Already up to date."

MINGW64 (feature/Issue_123) 
$ git merge develop

Output:

Already up to date.

But the code is not up to date & it is showing some differences in some files.

MINGW64 (feature/Issue_123)
$ git diff develop

Output:

diff --git 
a/src/main/database/sql/additional/pkg_etl.sql 
b/src/main/database/sql/additional/pkg_etl.sql
index ba2a257..1c219bb 100644
--- a/src/main/database/sql/additional/pkg_etl.sql
+++ b/src/main/database/sql/additional/pkg_etl.sql

However, merging fixes it.

MINGW64 (feature/Issue_123)
$ git merge origin/develop

Output:

Updating c7c0ac9..09959e3
Fast-forward
3 files changed, 157 insertions(+), 92 deletions(-)

Again I have confirmed this by using diff command.

MINGW64 (feature/Issue_123)
$ git diff develop

No differences in the code now!

IE Enable/Disable Proxy Settings via Registry

I know this is an old question, however here is a simple one-liner to switch it on or off depending on its current state:

set-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable -value (-not ([bool](get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable).proxyenable))

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

AngularJS: How to run additional code after AngularJS has rendered a template?

First, the right place to mess with rendering are directives. My advice would be to wrap DOM manipulating jQuery plugins by directives like this one.

I had the same problem and came up with this snippet. It uses $watch and $evalAsync to ensure your code runs after directives like ng-repeat have been resolved and templates like {{ value }} got rendered.

app.directive('name', function() {
    return {
        link: function($scope, element, attrs) {
            // Trigger when number of children changes,
            // including by directives like ng-repeat
            var watch = $scope.$watch(function() {
                return element.children().length;
            }, function() {
                // Wait for templates to render
                $scope.$evalAsync(function() {
                    // Finally, directives are evaluated
                    // and templates are renderer here
                    var children = element.children();
                    console.log(children);
                });
            });
        },
    };
});

Hope this can help you prevent some struggle.

csv.Error: iterator should return strings, not bytes

I had this error when running an old python script developped with Python 2.6.4

When updating to 3.6.2, I had to remove all 'rb' parameters from open calls in order to fix this csv reading error.

What is the (function() { } )() construct in JavaScript?

The reason self-evoking anonymous functions are used is they should never be called by other code since they "set up" the code which IS meant to be called (along with giving scope to functions and variables).

In other words, they are like programs that "make classes', at the beginning of program. After they are instantiated (automatically), the only functions that are available are the ones returned in by the anonymous function. However, all the other 'hidden' functions are still there, along with any state (variables set during scope creation).

Very cool.

Check if a specific tab page is selected (active)

I think that using the event tabPage1.Enter is more convenient.

tabPage1.Enter += new System.EventHandler(tabPage1_Enter);

private void tabPage1_Enter(object sender, EventArgs e)
{
    MessageBox.Show("you entered tabPage1");
}

This is better than having nested if-else statement when you have different logic for different tabs. And more suitable in case new tabs may be added in the future.

Note that this event fires if the form loads and tabPage1 is opened by default.

Determine if a String is an Integer in Java

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if(!sc.hasNextInt(radix)) return false;
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    } catch(NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}

How to change options of <select> with jQuery?

$('#comboBx').append($("<option></option>").attr("value",key).text(value));

where comboBx is your combo box id.

or you can append options as string to the already existing innerHTML and then assign to the select innerHTML.

Edit

If you need to keep the first option and remove all other then you can use

var firstOption = $("#cmb1 option:first-child");
$("#cmb1").empty().append(firstOption);

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

Java function for arrays like PHP's join()?

In case you're using Functional Java library and for some reason can't use Streams from Java 8 (which might be the case when using Android + Retrolambda plugin), here is a functional solution for you:

String joinWithSeparator(List<String> items, String separator) {
    return items
            .bind(id -> list(separator, id))
            .drop(1)
            .foldLeft(
                    (result, item) -> result + item,
                    ""
            );
}

Note that it's not the most efficient approach, but it does work good for small lists.

Http Post With Body

You could use this snippet -

HttpURLConnection urlConn;
URL mUrl = new URL(url);
urlConn = (HttpURLConnection) mUrl.openConnection();
...
//query is your body
urlConn.addRequestProperty("Content-Type", "application/" + "POST");
if (query != null) {
urlConn.setRequestProperty("Content-Length", Integer.toString(query.length()));
urlConn.getOutputStream().write(query.getBytes("UTF8"));
}

How to get today's Date?

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

found here

History or log of commands executed in Git

If you use Windows PowerShell, you could type "git" and the press F8. Continue to press F8 to cycle through all your git commands.

Or, if you use cygwin, you could do the same thing with ^R.

urlencoded Forward slash is breaking URL

I solved this by using 2 custom functions like so:

function slash_replace($query){

    return str_replace('/','_', $query);
}

function slash_unreplace($query){

    return str_replace('_','/', $query);
}

So to encode I could call:

rawurlencode(slash_replace($param))

and to decode I could call

slash_unreplace(rawurldecode($param);

Cheers!

How do I calculate a trendline for a graph?

Thank You so much for the solution, I was scratching my head.
Here's how I applied the solution in Excel.
I successfully used the two functions given by MUHD in Excel:
a = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)
b = sum(y)/n - b(sum(x)/n)
(careful my a and b are the b and a in MUHD's solution).

- Made 4 columns, for example:
NB: my values y values are in B3:B17, so I have n=15;
my x values are 1,2,3,4...15.
1. Column B: Known x's
2. Column C: Known y's
3. Column D: The computed trend line
4. Column E: B values * C values (E3=B3*C3, E4=B4*C4, ..., E17=B17*C17)
5. Column F: x squared values
I then sum the columns B,C and E, the sums go in line 18 for me, so I have B18 as sum of Xs, C18 as sum of Ys, E18 as sum of X*Y, and F18 as sum of squares.
To compute a, enter the followin formula in any cell (F35 for me):
F35=(E18-(B18*C18)/15)/(F18-(B18*B18)/15)
To compute b (in F36 for me):
F36=C18/15-F35*(B18/15)
Column D values, computing the trend line according to the y = ax + b:
D3=$F$35*B3+$F$36, D4=$F$35*B4+$F$36 and so on (until D17 for me).

Select the column datas (C2:D17) to make the graph.
HTH.

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

Two ways that can be works

1: Uninstall app from mobile device manually

2: Open command prompt , trace path of adband execute following command

adb uninstall your_package_name

Call a Class From another class

If your class2 looks like this having static members

public class2
{
    static int var = 1;

    public static void myMethod()
    {
      // some code

    }
}

Then you can simply call them like

class2.myMethod();
class2.var = 1;

If you want to access non-static members then you would have to instantiate an object.

class2 object = new class2();
object.myMethod();  // non static method
object.var = 1;     // non static variable

How can I post an array of string to ASP.NET MVC Controller without a form?

Don't post the data as an array. To bind to a list, the key/value pairs should be submitted with the same value for each key.

You should not need a form to do this. You just need a list of key/value pairs, which you can include in the call to $.post.

How to get the mysql table columns data type?

ResultSet rs = Sstatement.executeQuery("SELECT * FROM Table Name");

ResultSetMetaData rsMetaData = rs.getMetaData();

int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);

for (int i = 1; i <= numberOfColumns; i++) {
 System.out.println("column number " + i);

  System.out.println(rsMetaData.getColumnTypeName(i));
}

Express.js: how to get remote client address

With could-flare, nginx and x-real-ip support

var user_ip;

    if(req.headers['cf-connecting-ip'] && req.headers['cf-connecting-ip'].split(', ').length) {
      let first = req.headers['cf-connecting-ip'].split(', ');
      user_ip = first[0];
    } else {
      let user_ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
    }

Generate pdf from HTML in div using Javascript

This example works great.

<button onclick="genPDF()">Generate PDF</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script>
    function genPDF() {
        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
        doc.addPage();
        doc.text(20, 20, 'Do you like that?');
    
        doc.save('Test.pdf');
    }
</script>

How do I delete multiple rows with different IDs?

If you have to select the id:

 DELETE FROM table WHERE id IN (SELECT id FROM somewhere_else)

If you already know them (and they are not in the thousands):

 DELETE FROM table WHERE id IN (?,?,?,?,?,?,?,?)

jQuery: how to find first visible input/select/textarea excluding buttons?

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):

$('form').find(':text,textarea,select').filter(':visible:first')

I'm getting Key error in python

For dict, just use

if key in dict

and don't use searching in key list

if key in dict.keys()

The latter will be more time-consuming.

How to know when a web page was last updated?

Take a look at archive.org

You can find almost everything about the past of a website there.

Call to undefined function mysql_query() with Login

You are mixing the deprecated mysql extension with mysqli.

Try something like:

$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);

What is the difference between an abstract function and a virtual function?

If a class derives from this abstract class, it is then forced to override the abstract member. This is different from the virtual modifier, which specifies that the member may optionally be overridden.

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

It depends on your IDE or compiler.

Here is a list for Eclipse Galileo:

  • all to suppress all warnings
  • boxing to suppress warnings relative to boxing/unboxing operations
  • cast to suppress warnings relative to cast operations
  • dep-ann to suppress warnings relative to deprecated annotation
  • deprecation to suppress warnings relative to deprecation
  • fallthrough to suppress warnings relative to missing breaks in switch statements
  • finally to suppress warnings relative to finally block that don’t return
  • hiding to suppress warnings relative to locals that hide variable
  • incomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)
  • nls to suppress warnings relative to non-nls string literals
  • null to suppress warnings relative to null analysis
  • restriction to suppress warnings relative to usage of discouraged or forbidden references
  • serial to suppress warnings relative to missing serialVersionUID field for a serializable class
  • static-access to suppress warnings relative to incorrect static access
  • synthetic-access to suppress warnings relative to unoptimized access from inner classes
  • unchecked to suppress warnings relative to unchecked operations
  • unqualified-field-access to suppress warnings relative to field access unqualified
  • unused to suppress warnings relative to unused code

List for Indigo adds:

  • javadoc to suppress warnings relative to javadoc warnings
  • rawtypes to suppress warnings relative to usage of raw types
  • static-method to suppress warnings relative to methods that could be declared as static
  • super to suppress warnings relative to overriding a method without super invocations

List for Juno adds:

  • resource to suppress warnings relative to usage of resources of type Closeable
  • sync-override to suppress warnings because of missing synchronize when overriding a synchronized method

Kepler and Luna use the same token list as Juno (list).

Others will be similar but vary.

A variable modified inside a while loop is not remembered

echo -e $lines | while read line 
    ...
done

The while loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.

Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines will run in a subshell:

while read line
do
    if [[ "$line" == "second line" ]]
    then
        foo=2
        echo "Variable \$foo updated to $foo inside if inside while loop"
    fi
    echo "Value of \$foo in while loop body: $foo"
done <<< "$(echo -e "$lines")"

You can get rid of the rather ugly echo in the here-string above by expanding the backslash sequences immediately when assigning lines. The $'...' form of quoting can be used there:

lines=$'first line\nsecond line\nthird line'
while read line; do
    ...
done <<< "$lines"

Remove the last chars of the Java String variable

I am surprised to see that all the other answers (as of Sep 8, 2013) either involve counting the number of characters in the substring ".null" or throw a StringIndexOutOfBoundsException if the substring is not found. Or both :(

I suggest the following:

public class Main {

    public static void main(String[] args) {

        String path = "file.txt";
        String extension = ".doc";

        int position = path.lastIndexOf(extension);

        if (position!=-1)
            path = path.substring(0, position);
        else
            System.out.println("Extension: "+extension+" not found");

        System.out.println("Result: "+path);
    }

}

If the substring is not found, nothing happens, as there is nothing to cut off. You won't get the StringIndexOutOfBoundsException. Also, you don't have to count the characters yourself in the substring.

Remove .php extension with .htaccess

If your url in PHP like http://yourdomain.com/demo.php than comes like http://yourdomain.com/demo

This is all you need:

create file .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Storing Images in PostgreSQL

If your images are small, consider storing them as base64 in a plain text field.

The reason is that while base64 has an overhead of 33%, with compression that mostly goes away. (See What is the space overhead of Base64 encoding?) Your database will be bigger, but the packets your webserver sends to the client won't be. In html, you can inline base64 in an <img src=""> tag, which can possibly simplify your app because you won't have to serve up the images as binary in a separate browser fetch. Handling images as text also simplifies things when you have to send/receive json, which doesn't handle binary very well.

Yes, I understand you could store the binary in the database and convert it to/from text on the way in and out of the database, but sometimes ORMs make that a hassle. It can be simpler just to treat it as straight text just like all your other fields.

This is definitely the right way to handle thumbnails.

(OP's images are not small, so this is not really an answer to his question.)

Change bootstrap navbar collapse breakpoint without using LESS

Finally worked out how to change the collapse width by fiddling with '@grid-float-breakpoint' at http://getbootstrap.com/customize/.

Go to line 2923 in bootstrap.css(also min version) and change @media screen and (min-width: 768px) { to @media screen and (min-width: 1000px) {

So the code will end up being:

@media screen and (min-width: 1000px) {
  .navbar-brand {
    float: left;
    margin-right: 5px;
    margin-left: -15px;
  }
  .navbar-nav {
    float: left;
    margin-top: 0;
    margin-bottom: 0;
  }
  .navbar-nav > li {
    float: left;
  }
  .navbar-nav > li > a {
    border-radius: 0;
  }
  .navbar-nav.pull-right {
    float: right;
    width: auto;
  }
  .navbar-toggle {
    position: relative;
    top: auto;
    left: auto;
    display: none;
  }
  .nav-collapse.collapse {
    display: block !important;
    height: auto !important;
    overflow: visible !important;
  }
}

Using global variables between files?

Hai Vu answer works great, just one comment:

In case you are using the global in other module and you want to set the global dynamically, pay attention to import the other modules after you set the global variables, for example:

# settings.py
def init(arg):
    global myList
    myList = []
    mylist.append(arg)


# subfile.py
import settings

def print():
    settings.myList[0]


# main.py
import settings
settings.init("1st")     # global init before used in other imported modules
                         # Or else they will be undefined

import subfile    
subfile.print()          # global usage

Switching between GCC and Clang/LLVM using CMake

You can use the syntax: $ENV{environment-variable} in your CMakeLists.txt to access environment variables. You could create scripts which initialize a set of environment variables appropriately and just have references to those variables in your CMakeLists.txt files.

How to update primary key

You could use this recursive function for generate necessary T-SQL script.

CREATE FUNCTION dbo.Update_Delete_PrimaryKey
(
    @TableName      NVARCHAR(255),
    @ColumnName     NVARCHAR(255),
    @OldValue       NVARCHAR(MAX),
    @NewValue       NVARCHAR(MAX),
    @Del            BIT
)
RETURNS NVARCHAR 
(
    MAX
)
AS
BEGIN
    DECLARE @fks TABLE 
            (
                constraint_name NVARCHAR(255),
                table_name NVARCHAR(255),
                col NVARCHAR(255)
            );
    DECLARE @Sql                  NVARCHAR(MAX),
            @EnableConstraints     NVARCHAR(MAX);

    SET @Sql = '';
    SET @EnableConstraints = '';

    INSERT INTO @fks
      (
        constraint_name,
        table_name,
        col
      )
    SELECT oConstraint.name     constraint_name,
           oParent.name         table_name,
           oParentCol.name      col
    FROM   sys.foreign_key_columns sfkc
           --INNER JOIN sys.foreign_keys sfk
           --     ON  sfk.[object_id] = sfkc.constraint_object_id

           INNER JOIN sys.sysobjects oConstraint
                ON  sfkc.constraint_object_id = oConstraint.id
           INNER JOIN sys.sysobjects oParent
                ON  sfkc.parent_object_id = oParent.id
           INNER JOIN sys.all_columns oParentCol
                ON  sfkc.parent_object_id = oParentCol.object_id
                AND sfkc.parent_column_id = oParentCol.column_id
           INNER JOIN sys.sysobjects oReference
                ON  sfkc.referenced_object_id = oReference.id
           INNER JOIN sys.all_columns oReferenceCol
                ON  sfkc.referenced_object_id = oReferenceCol.object_id
                AND sfkc.referenced_column_id = oReferenceCol.column_id
    WHERE  oReference.name = @TableName
           AND oReferenceCol.name = @ColumnName
    --AND (@Del <> 1 OR sfk.delete_referential_action = 0)
    --AND (@Del = 1 OR sfk.update_referential_action = 0)

    IF EXISTS(
           SELECT 1
           FROM   @fks
       )
    BEGIN
        DECLARE @Constraint     NVARCHAR(255),
                @Table          NVARCHAR(255),
                @Col            NVARCHAR(255)  

        DECLARE Table_Cursor CURSOR LOCAL 
        FOR
            SELECT f.constraint_name,
                   f.table_name,
                   f.col
            FROM   @fks AS f

        OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col  
        WHILE (@@FETCH_STATUS = 0)
        BEGIN
            IF @Del <> 1
            BEGIN
                SET @Sql = @Sql + 'ALTER TABLE ' + @Table + ' NOCHECK CONSTRAINT ' + @Constraint + CHAR(13) + CHAR(10);
                SET @EnableConstraints = @EnableConstraints + 'ALTER TABLE ' + @Table + ' CHECK CONSTRAINT ' + @Constraint 
                    + CHAR(13) + CHAR(10);
            END

            SET @Sql = @Sql + dbo.Update_Delete_PrimaryKey(@Table, @Col, @OldValue, @NewValue, @Del);
            FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col
        END

        CLOSE Table_Cursor DEALLOCATE Table_Cursor
    END

    DECLARE @DataType NVARCHAR(30);
    SELECT @DataType = t.name +
           CASE 
                WHEN t.name IN ('char', 'varchar', 'nchar', 'nvarchar') THEN '(' +
                     CASE 
                          WHEN c.max_length = -1 THEN 'MAX'
                          ELSE CONVERT(
                                   VARCHAR(4),
                                   CASE 
                                        WHEN t.name IN ('nchar', 'nvarchar') THEN c.max_length / 2
                                        ELSE c.max_length
                                   END
                               )
                     END + ')'
                WHEN t.name IN ('decimal', 'numeric') THEN '(' + CONVERT(VARCHAR(4), c.precision) + ',' 
                     + CONVERT(VARCHAR(4), c.Scale) + ')'
                ELSE ''
           END
    FROM   sys.columns c
           INNER JOIN sys.types t
                ON  c.user_type_id = t.user_type_id
    WHERE  c.object_id = OBJECT_ID(@TableName)
           AND c.name = @ColumnName

    IF @Del <> 1
    BEGIN
        SET @Sql = @Sql + 'UPDATE [' + @TableName + '] SET [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @NewValue + '''', 'NULL') 
            + ') WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @OldValue + '''', 'NULL') +
            ');' + CHAR(13) + CHAR(10);
        SET @Sql = @Sql + @EnableConstraints;
    END
    ELSE
        SET @Sql = @Sql + 'DELETE [' + @TableName + '] WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', N''' + @OldValue 
            + ''');' + CHAR(13) + CHAR(10);
    RETURN @Sql;
END
GO

DECLARE @Result NVARCHAR(MAX);
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', '@NewValue', 0);/*Update*/
EXEC (@Result)
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', NULL, 1);/*Delete*/
EXEC (@Result)
GO

DROP FUNCTION Update_Delete_PrimaryKey;

How can I get a first element from a sorted list?

You have to access lists a little differently than arrays in Java. See the javadocs for the List interface for more information.

playersList.get(0)

However if you want to find the smallest element in playersList, you shouldn't sort it and then get the first element. This runs very slowly compared to just searching once through the list to find the smallest element.

For example:

int smallestIndex = 0;
for (int i = 1; i < playersList.size(); i++) {
    if (playersList.get(i) < playersList.get(smallestIndex))
        smallestIndex = i;
}

playersList.get(smallestIndex);

The above code will find the smallest element in O(n) instead of O(n log n) time.

Convert hex to binary

bin(int("abc123efff", 16))[2:]

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

  1. Set cell mode to Markdown
  2. Drag and drop your image into the cell. The following command will be created:

![image.png](attachment:image.png)

  1. Execute/Run the cell and the image shows up.

The image is actually embedded in the ipynb Notebook and you don't need to mess around with separate files. This is unfortunately not working with Jupyter-Lab (v 1.1.4) yet.

Edit: Works in JupyterLab Version 1.2.6

Can I assume (bool)true == (int)1 for any C++ compiler?

I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.

Bloomberg BDH function with ISIN

The problem is that an isin does not identify the exchange, only an issuer.

Let's say your isin is US4592001014 (IBM), one way to do it would be:

  • get the ticker (in A1):

    =BDP("US4592001014 ISIN", "TICKER") => IBM
    
  • get a proper symbol (in A2)

    =BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
    

    where XX depends on your terminal settings, which you can check on CNDF <Go>.

  • get the main exchange composite ticker, or whatever suits your need (in A3):

    =BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
    
  • and finally:

    =BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
    

How should I store GUID in MySQL tables?

char(36) would be a good choice. Also MySQL's UUID() function can be used which returns a 36-character text format (hex with hyphens) which can be used for retrievals of such IDs from the db.

Properties private set;

Perhaps, you can have them marked as internal, and in this case only classes in your DAL or BL (assuming they are separate dlls) would be able to set it.

You could also supply a constructor that takes the fields and then only exposes them as properties.

How do I use Spring Boot to serve static content located in Dropbox folder?

You can place your folder in the root of the ServletContext.

Then specify a relative or absolute path to this directory in application.yml:

spring:
  resources:
    static-locations: file:some_temp_files/

The resources in this folder will be available (for downloading, for example) at:

http://<host>:<port>/<context>/your_file.csv

Global variables in R

I found a solution for how to set a global variable in a mailinglist posting via assign:

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value

$_POST not working. "Notice: Undefined index: username..."

You should check if the POST['username'] is defined. Use this above:

$username = "";

if(isset($_POST['username'])){
    $username = $_POST['username'];
}

"SELECT password FROM users WHERE username='".$username."'"

Mount current directory as a volume in Docker on Windows 10

This works for me in PowerShell:

docker run --rm -v ${PWD}:/data alpine ls /data

What is the lifetime of a static variable in a C++ function?

The lifetime of function static variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.

Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.

Example

struct emitter {
    string str;
    emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
    ~emitter() { cout << "Destroyed " << str << endl; }
};

void foo(bool skip_first) 
{
    if (!skip_first)
        static emitter a("in if");
    static emitter b("in foo");
}

int main(int argc, char*[])
{
    foo(argc != 2);
    if (argc == 3)
        foo(false);
}

Output:

C:>sample.exe
Created in foo
Destroyed in foo

C:>sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in if

C:>sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo

[0] Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.

[1] C++98 section 3.6.3.1 [basic.start.term]

[2] In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.

Change a Rails application to production

If you're running on Passenger, then the default is to run in production, in your apache conf:

<VirtualHost *:80>
  ServerName application_name.rails.local
  DocumentRoot "/Users/rails/application_name/public"
  RailsEnv production ## This is the default
</VirtualHost>

If you're just running a local server with mongrel or webrick, you can do:

./script/server -e production

or in bash:

RAILS_ENV=production ./script/server

actually overriding the RAILS_ENV constant in the enviornment.rb should probably be your last resort, as it's probably not going to stay set (see another answer I gave on that)

align text center with android

use this way

txt.setGravity(Gravity.CENTER);

Reloading .env variables without restarting server (Laravel 5, shared hosting)

In case anybody stumbles upon this question who cannot reload their webserver (long running console command like a queue runner) or needs to reload their .env file mid-request, i found a way to properly reload .env variables in laravel 5.

use Dotenv;
use InvalidArgumentException;

try {
    Dotenv::makeMutable();
    Dotenv::load(app()->environmentPath(), app()->environmentFile());
    Dotenv::makeImmutable();
} catch (InvalidArgumentException $e) {
    //
}

How to exit when back button is pressed?

To exit from an Android app, just simply use. in your Main Activity, or you can use Android manifest file to set

android:noHistory="true"

How to get form input array into PHP array

They are already in arrays: $name is an array, as is $email

So all you need to do is add a bit of processing to attack both arrays:

$name = $_POST['name'];
$email = $_POST['account'];

foreach( $name as $key => $n ) {
  print "The name is ".$n." and email is ".$email[$key].", thank you\n";
}

To handle more inputs, just extend the pattern:

$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];

foreach( $name as $key => $n ) {
  print "The name is ".$n.", email is ".$email[$key].
        ", and location is ".$location[$key].". Thank you\n";
}

How to call webmethod in Asp.net C#

you need to JSON.stringify the data parameter before sending it.