Programs & Examples On #Setup project

Programs used to create installers are generically called setup projects. In most cases you are probably using a tool (on Windows examples are Visual Studio, InnoSetup, WiX, Advanced Installer, Wise, InstallShield) to create the setup, so a more accurate and useful tag would be one for that specific tool.

Plot width settings in ipython notebook

If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:

width = 12
height = 12
plt.figure(figsize=(width, height))

Determine the number of NA values in a column

If you are looking to count the number of NAs in the entire dataframe you could also use

sum(is.na(df))

remove table row with specific id

Simply $("#3").remove(); would be enough. But 3 isn't a good id (I think it's even illegal, as it starts with a digit).

This certificate has an invalid issuer Apple Push Services

You need to search the World from the top right search bar and delete the expired certificate. Make sure you selected Login and All items.

Enter image description here

pull out p-values and r-squared from a linear regression

x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
> names(summary(fit))
[1] "call"          "terms"        
 [3] "residuals"     "coefficients" 
 [5] "aliased"       "sigma"        
 [7] "df"            "r.squared"    
 [9] "adj.r.squared" "fstatistic"   
[11] "cov.unscaled" 
    summary(fit)$r.squared

How do I create a local database inside of Microsoft SQL Server 2014?

As per comments, First you need to install an instance of SQL Server if you don't already have one - https://msdn.microsoft.com/en-us/library/ms143219.aspx

Once this is installed you must connect to this instance (server) and then you can create a database here - https://msdn.microsoft.com/en-US/library/ms186312.aspx

True/False vs 0/1 in MySQL

Some "front ends", with the "Use Booleans" option enabled, will treat all TINYINT(1) columns as Boolean, and vice versa.

This allows you to, in the application, use TRUE and FALSE rather than 1 and 0.

This doesn't affect the database at all, since it's implemented in the application.

There is not really a BOOLEAN type in MySQL. BOOLEAN is just a synonym for TINYINT(1), and TRUE and FALSE are synonyms for 1 and 0.

If the conversion is done in the compiler, there will be no difference in performance in the application. Otherwise, the difference still won't be noticeable.

You should use whichever method allows you to code more efficiently, though not using the feature may reduce dependency on that particular "front end" vendor.

IntelliJ Organize Imports

Under "Settings -> Editor -> General -> Auto Import" there are several options regarding automatic imports. Only unambiguous imports may be added automatically; this is one of the options.

AngularJS - Passing data between pages

You need to create a service to be able to share data between controllers.

app.factory('myService', function() {
 var savedData = {}
 function set(data) {
   savedData = data;
 }
 function get() {
  return savedData;
 }

 return {
  set: set,
  get: get
 }

});

In your controller A:

myService.set(yourSharedData);

In your controller B:

$scope.desiredLocation = myService.get();

Remember to inject myService in the controllers by passing it as a parameter.

How to make clang compile to llvm IR

If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.

Instead, you want to compile with link-time-optimization

clang -flto -c program1.c -o program1.o
clang -flto -c program2.c -o program2.o

and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm

clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program

This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing

clang program.bc -o program

although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.

Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option

-B/home/jeremy/fakebin

to any linking steps above.

How to set max width of an image in CSS

The problem is that img tag is inline element and you can't restrict width of inline element.

So to restrict img tag width first you need to convert it into a inline-block element

img.Image{
    display: inline-block;
}

Immutable array in Java

Not with primitive arrays. You'll need to use a List or some other data structure:

List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));

How to completely remove Python from a Windows machine?

Almost all of the python files should live in their respective folders (C:\Python26 and C:\Python27). Some installers (ActiveState) will also associate .py* files and add the python path to %PATH% with an install if you tick the "use this as the default installation" box.

Passing parameter to controller action from a Html.ActionLink

Addition to the accepted answer:

if you are going to use

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)

this will create actionlink where you can't create new custom attribute or style for the link.

However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })

Check if passed argument is file or directory in Bash

Using -f and -d switches on /bin/test:

F_NAME="${1}"

if test -f "${F_NAME}"
then                                   
   echo "${F_NAME} is a file"
elif test -d "${F_NAME}"
then
   echo "${F_NAME} is a directory"
else                                   
   echo "${F_NAME} is not valid"
fi

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

There are literal arrowheads in the Spacing Modifier Letters block:

U+02C2  ?   &#706;  Modifier Letter Left  Arrowhead
U+02C3  ?   &#707;  Modifier Letter Right Arrowhead
U+02C4  ^   &#708;  Modifier Letter Up    Arrowhead
U+02C5  ?   &#709;  Modifier Letter Down  Arrowhead

Turning a string into a Uri in Android

Uri.parse(STRING);

See doc:

String: an RFC 2396-compliant, encoded URI

Url must be canonicalized before using, like this:

Uri.parse(Uri.decode(STRING));

How to make a JSON call to a url?

DickFeynman's answer is a workable solution for any circumstance in which JQuery is not a good fit, or isn't otherwise necessary. As ComFreek notes, this requires setting the CORS headers on the server-side. If it's your service, and you have a handle on the bigger question of security, then that's entirely feasible.

Here's a listing of a Flask service, setting the CORS headers, grabbing data from a database, responding with JSON, and working happily with DickFeynman's approach on the client-side:

#!/usr/bin/env python 
from __future__ import unicode_literals
from flask      import Flask, Response, jsonify, redirect, request, url_for
from your_model import *
import os
try:
    import simplejson as json;
except ImportError:
    import json
try:
    from flask.ext.cors import *
except:
    from flask_cors import *

app = Flask(__name__)

@app.before_request
def before_request():
try:
    # Provided by an object in your_model
    app.session = SessionManager.connect()
except:
    print "Database connection failed."

@app.teardown_request
def shutdown_session(exception=None):
    app.session.close()

# A route with a CORS header, to enable your javascript client to access 
# JSON created from a database query.
@app.route('/whatever-data/', methods=['GET', 'OPTIONS'])
@cross_origin(headers=['Content-Type'])
def json_data():
    whatever_list = []
    results_json  = None
    try:
        # Use SQL Alchemy to select all Whatevers, WHERE size > 0.
        whatevers = app.session.query(Whatever).filter(Whatever.size > 0).all()
        if whatevers and len(whatevers) > 0:
            for whatever in whatevers:
                # Each whatever is able to return a serialized version of itself. 
                # Refer to your_model.
                whatever_list.append(whatever.serialize())
             # Convert a list to JSON. 
             results_json = json.dumps(whatever_list)
    except SQLAlchemyError as e:
        print 'Error {0}'.format(e)
        exit(0)

    if len(whatevers) < 1 or not results_json:
        exit(0)
    else:
        # Because we used json.dumps(), rather than jsonify(), 
        # we need to create a Flask Response object, here.
        return Response(response=str(results_json), mimetype='application/json')

if __name__ == '__main__':
    #@NOTE Not suitable for production. As configured, 
    #      your Flask service is in debug mode and publicly accessible.  
    app.run(debug=True, host='0.0.0.0', port=5001) # http://localhost:5001/

your_model contains the serialization method for your whatever, as well as the database connection manager (which could stand a little refactoring, but suffices to centralize the creation of database sessions, in bigger systems or Model/View/Control architectures). This happens to use postgreSQL, but could just as easily use any server side data store:

#!/usr/bin/env python 
# Filename: your_model.py
import time
import psycopg2
import psycopg2.pool
import psycopg2.extras
from   psycopg2.extensions        import adapt, register_adapter, AsIs
from   sqlalchemy                 import update
from   sqlalchemy.orm             import *
from   sqlalchemy.exc             import *
from   sqlalchemy.dialects        import postgresql
from   sqlalchemy                 import Table, Column, Integer, ForeignKey
from   sqlalchemy.ext.declarative import declarative_base

class SessionManager(object):
    @staticmethod
    def connect():
        engine = create_engine('postgresql://id:passwd@localhost/mydatabase', 
                                echo = True)
        Session = sessionmaker(bind = engine, 
                               autoflush = True, 
                               expire_on_commit = False, 
                               autocommit = False)
    session = Session()
    return session

  @staticmethod
  def declareBase():
      engine = create_engine('postgresql://id:passwd@localhost/mydatabase', echo=True)
      whatever_metadata = MetaData(engine, schema ='public')
      Base = declarative_base(metadata=whatever_metadata)
      return Base

Base = SessionManager.declareBase()

class Whatever(Base):
    """Create, supply information about, and manage the state of one or more whatever.
    """
    __tablename__         = 'whatever'
    id                    = Column(Integer, primary_key=True)
    whatever_digest       = Column(VARCHAR, unique=True)
    best_name             = Column(VARCHAR, nullable = True)
    whatever_timestamp    = Column(BigInteger, default = time.time())
    whatever_raw          = Column(Numeric(precision = 1000, scale = 0), default = 0.0)
    whatever_label        = Column(postgresql.VARCHAR, nullable = True)
    size                  = Column(BigInteger, default = 0)

    def __init__(self, 
                 whatever_digest = '', 
                 best_name = '', 
                 whatever_timestamp = 0, 
                 whatever_raw = 0, 
                 whatever_label = '', 
                 size = 0):
        self.whatever_digest         = whatever_digest
        self.best_name               = best_name
        self.whatever_timestamp      = whatever_timestamp
        self.whatever_raw            = whatever_raw
        self.whatever_label          = whatever_label

    # Serialize one way or another, just handle appropriately in the client.  
    def serialize(self):
        return {
            'best_name'     :self.best_name,
            'whatever_label':self.whatever_label,
            'size'          :self.size,
        }

In retrospect, I might have serialized the whatever objects as lists, rather than a Python dict, which might have simplified their processing in the Flask service, and I might have separated concerns better in the Flask implementation (The database call probably shouldn't be built-in the the route handler), but you can improve on this, once you have a working solution in your own development environment.

Also, I'm not suggesting people avoid JQuery. But, if JQuery's not in the picture, for one reason or another, this approach seems like a reasonable alternative.

It works, in any case.

Here's my implementation of DickFeynman's approach, in the the client:

<script type="text/javascript">
    var addr = "dev.yourserver.yourorg.tld"
    var port = "5001"

    function Get(whateverUrl){
        var Httpreq = new XMLHttpRequest(); // a new request
        Httpreq.open("GET",whateverUrl,false);
        Httpreq.send(null);
        return Httpreq.responseText;          
    }

    var whatever_list_obj = JSON.parse(Get("http://" + addr + ":" + port + "/whatever-data/"));
    whatever_qty = whatever_list_obj.length;
    for (var i = 0; i < whatever_qty; i++) {
        console.log(whatever_list_obj[i].best_name);
    }
</script>

I'm not going to list my console output, but I'm looking at a long list of whatever.best_name strings.

More to the point: The whatever_list_obj is available for use in my javascript namespace, for whatever I care to do with it, ...which might include generating graphics with D3.js, mapping with OpenLayers or CesiumJS, or calculating some intermediate values which have no particular need to live in my DOM.

Preferred way to create a Scala list

Using List.tabulate, like this,

List.tabulate(3)( x => 2*x )
res: List(0, 2, 4)

List.tabulate(3)( _ => Math.random )
res: List(0.935455779102479, 0.6004888906328091, 0.3425278797788426)

List.tabulate(3)( _ => (Math.random*10).toInt )
res: List(8, 0, 7)

How do I tell what type of value is in a Perl variable?

$x is always a scalar. The hint is the sigil $: any variable (or dereferencing of some other type) starting with $ is a scalar. (See perldoc perldata for more about data types.)

A reference is just a particular type of scalar. The built-in function ref will tell you what kind of reference it is. On the other hand, if you have a blessed reference, ref will only tell you the package name the reference was blessed into, not the actual core type of the data (blessed references can be hashrefs, arrayrefs or other things). You can use Scalar::Util 's reftype will tell you what type of reference it is:

use Scalar::Util qw(reftype);

my $x = bless {}, 'My::Foo';
my $y = { };

print "type of x: " . ref($x) . "\n";
print "type of y: " . ref($y) . "\n";
print "base type of x: " . reftype($x) . "\n";
print "base type of y: " . reftype($y) . "\n";

...produces the output:

type of x: My::Foo
type of y: HASH
base type of x: HASH
base type of y: HASH

For more information about the other types of references (e.g. coderef, arrayref etc), see this question: How can I get Perl's ref() function to return REF, IO, and LVALUE? and perldoc perlref.

Note: You should not use ref to implement code branches with a blessed object (e.g. $ref($a) eq "My::Foo" ? say "is a Foo object" : say "foo not defined";) -- if you need to make any decisions based on the type of a variable, use isa (i.e if ($a->isa("My::Foo") { ... or if ($a->can("foo") { ...). Also see polymorphism.

How to convert SecureString to System.String?

In my opinion, extension methods are the most comfortable way to solve this.

I took Steve in CO's excellent answer and put it into an extension class as follows, together with a second method I added to support the other direction (string -> secure string) as well, so you can create a secure string and convert it into a normal string afterwards:

public static class Extensions
{
    // convert a secure string into a normal plain text string
    public static String ToPlainString(this System.Security.SecureString secureStr)
    {
        String plainStr=new System.Net.NetworkCredential(string.Empty, secureStr).Password;
        return plainStr;
    }

    // convert a plain text string into a secure string
    public static System.Security.SecureString ToSecureString(this String plainStr)
    {
        var secStr = new System.Security.SecureString(); secStr.Clear();
        foreach (char c in plainStr.ToCharArray())
        {
            secStr.AppendChar(c);
        }
        return secStr;
    }
}

With this, you can now simply convert your strings back and forth like so:

// create a secure string
System.Security.SecureString securePassword = "MyCleverPwd123".ToSecureString(); 
// convert it back to plain text
String plainPassword = securePassword.ToPlainString();  // convert back to normal string

But keep in mind the decoding method should only be used for testing.

Saving numpy array to txt file row wise

Very very easy: [1,2,3]

A list is like a column.

1
2
3

If you want a list like a row, double corchete:

[[1, 2, 3]]  --->    1, 2, 3

and

[[1, 2, 3], [4, 5, 6]]  ---> 1, 2, 3
                             4, 5, 6

Finally:

np.savetxt("file", [['r1c1', 'r1c2'], ['r2c1', 'r2c2']], delimiter=';', fmt='%s')

Note, the comma between square brackets, inner list are elements of the outer list

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Just to add another solution to the list, what I've found is that Visual Studio (2012 in my case) occasionally locks files under different processes.

So, on a crash, devenv.exe might still be running and holding onto the file(s). Alternatively (as I just discovered), vstestrunner or vstestdiscovery might be holding onto the file as well.

Kill all those processes and it might fix up the issue.

Undefined symbols for architecture x86_64 on Xcode 6.1

Make sure the WOExerciseListViewController is a Target Member; that worked for me!

enter image description here

How to set all elements of an array to zero or any same value?

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 };    // Will initialize all elements to 0
int myArray[10] = { 5 };    // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i;  // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
    myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works only in GCC

FileNotFoundError: [Errno 2] No such file or directory

For people who are still getting error despite of passing absolute path, should check that if file has a valid name. For me I was trying to create a file with '/' in the file name. As soon as I removed '/', I was able to create the file.

Best way to access a control on another form in Windows Forms?

You should only ever access one view's contents from another if you're creating more complex controls/modules/components. Otherwise, you should do this through the standard Model-View-Controller architecture: You should connect the enabled state of the controls you care about to some model-level predicate that supplies the right information.

For example, if I wanted to enable a Save button only when all required information was entered, I'd have a predicate method that tells when the model objects representing that form are in a state that can be saved. Then in the context where I'm choosing whether to enable the button, I'd just use the result of that method.

This results in a much cleaner separation of business logic from presentation logic, allowing both of them to evolve more independently — letting you create one front-end with multiple back-ends, or multiple front-ends with a single back-end with ease.

It will also be much, much easier to write unit and acceptance tests for, because you can follow a "Trust But Verify" pattern in doing so:

  1. You can write one set of tests that set up your model objects in various ways and check that the "is savable" predicate returns an appropriate result.

  2. You can write a separate set of that check whether your Save button is connected in an appropriate fashion to the "is savable" predicate (whatever that is for your framework, in Cocoa on Mac OS X this would often be through a binding).

As long as both sets of tests are passing, you can be confident that your user interface will work the way you want it to.

Trigger a keypress/keydown/keyup event in JS/jQuery?

To trigger an enter keypress, I had to modify @ebynum response, specifically, using the keyCode property.

e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

Another addition: be careful when replacing multiples and converting the type of the column back from object to float. If you want to be certain that your None's won't flip back to np.NaN's apply @andy-hayden's suggestion with using pd.where. Illustration of how replace can still go 'wrong':

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: df = pd.DataFrame({"a": [1, np.NAN, np.inf]})

In [4]: df
Out[4]:
     a
0  1.0
1  NaN
2  inf

In [5]: df.replace({np.NAN: None})
Out[5]:
      a
0     1
1  None
2   inf

In [6]: df.replace({np.NAN: None, np.inf: None})
Out[6]:
     a
0  1.0
1  NaN
2  NaN

In [7]: df.where((pd.notnull(df)), None).replace({np.inf: None})
Out[7]:
     a
0  1.0
1  NaN
2  NaN

Can't install nuget package because of "Failed to initialize the PowerShell host"

Had the same problem and this solved it for me (Powershell as admin):

Set-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell -Name ExecutionPolicy -Value ByPass 

Swift addsubview and remove it

Assuming you have access to it via outlets or programmatic code, you can remove it by referencing your view foo and the removeFromSuperview method

foo.removeFromSuperview()

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

Boolean vs boolean in Java

Boolean wraps the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this

boolean result = Boolean.TRUE;

or

Boolean result = true; 

Which essentially the compiler does,

Boolean result = Boolean.valueOf(true);

So, for your answer, it's YES.

Troubleshooting misplaced .git directory (nothing to commit)

Don't try commiting / adding files. Just run the following 2 commands (:

    git remote add origin http://xyzremotedir/xyzgitproject.git
    git push origin master

Iterating through populated rows

I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.

This code will:

  1. Find the last row in column A that has data
  2. Loop through each row
  3. Find the last column in current row with data
  4. Loop through each cell in current row up to last column found.

This is not a fast method but will iterate through each one individually as you suggested is your intention.


Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        'Find Last column in current row
        LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
        Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))

        'Loop through all cells in row up to last col
        For Each cell In colRange
            'Do something to each cell
            Debug.Print (cell.Value)
        Next cell
    Next rrow
    ScreenUpdating = True
End Sub

Regular expression to find URLs within a string

Using the regex provided by @JustinLevene did not have the proper escape sequences on the back-slashes. Updated to now be correct, and added in condition to match the FTP protocol as well: Will match to all urls with or without protocols, and with out without "www."

Code: ^((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?

Example: https://regex101.com/r/uQ9aL4/65

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

How to test that a registered variable is not empty?

- name: set pkg copy dir name
  set_fact:
    PKG_DIR: >-
      {% if ansible_os_family == "RedHat" %}centos/*.rpm
      {%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
      {%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
      {%- else %}{%- endif %}

Python assigning multiple variables to same value? list behavior

In python, everything is an object, also "simple" variables types (int, float, etc..).

When you changes a variable value, you actually changes it's pointer, and if you compares between two variables it's compares their pointers. (To be clear, pointer is the address in physical computer memory where a variable is stored).

As a result, when you changes an inner variable value, you changes it's value in the memory and it's affects all the variables that point to this address.

For your example, when you do:

a = b =  5 

This means that a and b points to the same address in memory that contains the value 5, but when you do:

a = 6

It's not affect b because a is now points to another memory location that contains 6 and b still points to the memory address that contains 5.

But, when you do:

a = b = [1,2,3]

a and b, again, points to the same location but the difference is that if you change the one of the list values:

a[0] = 2

It's changes the value of the memory that a is points on, but a is still points to the same address as b, and as a result, b changes as well.

PHP PDO returning single row

how about using limit 0,1 for mysql optimisation

and about your code:

$DBH = new PDO( "connection string goes here" );

$STH - $DBH -> prepare( "select figure from table1" );

$STH -> execute();

$result = $STH ->fetch(PDO::FETCH_ASSOC)

echo $result["figure"];

$DBH = null;

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

Java - Including variables within strings?

This is called string interpolation; it doesn't exist as such in Java.

One approach is to use String.format:

String string = String.format("A string %s", aVariable);

Another approach is to use a templating library such as Velocity or FreeMarker.

Tips for debugging .htaccess rewrite rules

(Similar to Doin idea) To show what is being matched, I use this code

$keys = array_keys($_GET);
foreach($keys as $i=>$key){
    echo "$i => $key <br>";
}

Save it to r.php on the server root and then do some tests in .htaccess
For example, i want to match urls that do not start with a language prefix

RewriteRule ^(?!(en|de)/)(.*)$ /r.php?$1&$2 [L] #$1&$2&...
RewriteRule ^(.*)$ /r.php?nomatch [L] #report nomatch and exit

Git says local branch is behind remote branch, but it's not

The solution is very simple and worked for me.

Try this :

git pull --rebase <url>

then

git push -u origin master

How to get all elements inside "div" that starts with a known text

Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :

var elements = document.getElementById('parentContainer').children;

Option 2: Likely slowest :

var elements = document.getElementById('parentContainer').getElementsByTagName('*');

Option 3: Requires change to code (wrap a form instead of a div around it) :

// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;

var matches = [];

for (var i = 0; i < elements.length; i++)
    if (elements[i].value.indexOf('q17_') == 0)
        matches.push(elements[i]);

pandas DataFrame: replace nan values with average of columns

You can simply use DataFrame.fillna to fill the nan's directly:

In [27]: df 
Out[27]: 
          A         B         C
0 -0.166919  0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3       NaN -2.027325  1.533582
4       NaN       NaN  0.461821
5 -0.788073       NaN       NaN
6 -0.916080 -0.612343       NaN
7 -0.887858  1.033826       NaN
8  1.948430  1.025011 -2.982224
9  0.019698 -0.795876 -0.046431

In [28]: df.mean()
Out[28]: 
A   -0.151121
B   -0.231291
C   -0.530307
dtype: float64

In [29]: df.fillna(df.mean())
Out[29]: 
          A         B         C
0 -0.166919  0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3 -0.151121 -2.027325  1.533582
4 -0.151121 -0.231291  0.461821
5 -0.788073 -0.231291 -0.530307
6 -0.916080 -0.612343 -0.530307
7 -0.887858  1.033826 -0.530307
8  1.948430  1.025011 -2.982224
9  0.019698 -0.795876 -0.046431

The docstring of fillna says that value should be a scalar or a dict, however, it seems to work with a Series as well. If you want to pass a dict, you could use df.mean().to_dict().

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Works in 2020

$response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization'=> 'key='. $token,
        ])->post($url, [
            'notification' => [
                'body' => $request->summary,
                'title' => $request->title,
                'image' => 'http://'.request()->getHttpHost().$path,
                
            ],
            'priority'=> 'high',
            'data' => [
                'click_action'=> 'FLUTTER_NOTIFICATION_CLICK',
                
                'status'=> 'done',
                
            ],
            'to' => '/topics/all'
        ]);

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

When connecting to SQL Server with Windows Authentication (as opposed to a local SQL Server account), attempting to use a linked server may result in the error message:

Cannot create an instance of OLE DB provider "(OLEDB provider name)"...

The most direct answer to this problem is provided by Microsoft KB 2647989, because "Security settings for the MSDAINITIALIZE DCOM class are incorrect."

The solution is to fix the security settings for MSDAINITIALIZE. In Windows Vista and later, the class is owned by TrustedInstaller, so the ownership of MSDAINITIALIZE must be changed before the security can be adjusted. The KB above has detailed instructions for doing so.

This MSDN blog post describes the reason:

MSDAINITIALIZE is a COM class that is provided by OLE DB. This class can parse OLE DB connection strings and load/initialize the provider based on property values in the connection string. MSDAINITILIAZE is initiated by users connected to SQL Server. If Windows Authentication is used to connect to SQL Server, then the provider is initialized under the logged in user account. If the logged in user is a SQL login, then provider is initialized under SQL Server service account. Based on the type of login used, permissions on MSDAINITIALIZE have to be provided accordingly.

The issue dates back at least to SQL Server 2000; KB 280106 from Microsoft describes the error (see "Message 3") and has the suggested fix of setting the In Process flag for the OLEDB provider.

While setting In Process can solve the immediate problem, it may not be what you want. According to Microsoft,

Instantiating the provider outside the SQL Server process protects the SQL Server process from errors in the provider. When the provider is instantiated outside the SQL Server process, updates or inserts referencing long columns (text, ntext, or image) are not allowed. -- Linked Server Properties doc for SQL Server 2008 R2.

The better answer is to go with the Microsoft guidance and adjust the MSDAINITIALIZE security.

How to convert HH:mm:ss.SSS to milliseconds?

If you want to parse the format yourself you could do it easily with a regex such as

private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");

public static long dateParseRegExp(String period) {
    Matcher matcher = pattern.matcher(period);
    if (matcher.matches()) {
        return Long.parseLong(matcher.group(1)) * 3600000L 
            + Long.parseLong(matcher.group(2)) * 60000 
            + Long.parseLong(matcher.group(3)) * 1000 
            + Long.parseLong(matcher.group(4)); 
    } else {
        throw new IllegalArgumentException("Invalid format " + period);
    }
}

However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.

How to query GROUP BY Month in a Year

For MS SQL you can do this.

    select  CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+ 
CAST(DATEPART(YEAR, DateTyme) as VARCHAR) as 'Date' from #temp
    group by Name, CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
 CAST(DATEPART(YEAR, DateTyme) as VARCHAR) 

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

Converting NSData to NSString in Objective c

-[NSString initWithData:encoding] will return nil if the specified encoding doesn't match the data's encoding.

Make sure your data is encoded in UTF-8 (or change NSUTF8StringEncoding to whatever encoding that's appropriate for the data).

Foreign key referencing a 2 columns primary key in SQL Server

The Content table likely to have multiple duplicate Application values that can't be mapped to Libraries. Is it possible to drop the Application column from the Libraries Primary Key Index and add it as a Unique Key Index instead?

How to set the env variable for PHP?

For windows: Go to your "system properties" please.then follow as bellow.

Advanced system settings(from left sidebar)->Environment variables(very last option)->path(from lower box/system variables called as I know)->edit

then concatenate the "php" location you have in your pc (usually it is where your xampp is installed say c:/xampp/php)

N.B : Please never forget to set semicolon (;) between your recent concatenated path and the existed path in your "Path"

Something like C:\Program Files\Git\usr\bin;C:\xampp\php

Hope this will help.Happy coding. :) :)

"Cannot instantiate the type..."

You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();.

std::string to char*

  • If you just want a C-style string representing the same content:

    char const* ca = str.c_str();
    
  • If you want a C-style string with new contents, one way (given that you don't know the string size at compile-time) is dynamic allocation:

    char* ca = new char[str.size()+1];
    std::copy(str.begin(), str.end(), ca);
    ca[str.size()] = '\0';
    

    Don't forget to delete[] it later.

  • If you want a statically-allocated, limited-length array instead:

    size_t const MAX = 80; // maximum number of chars
    char ca[MAX] = {};
    std::copy(str.begin(), (str.size() >= MAX ? str.begin() + MAX : str.end()), ca);
    

std::string doesn't implicitly convert to these types for the simple reason that needing to do this is usually a design smell. Make sure that you really need it.

If you definitely need a char*, the best way is probably:

vector<char> v(str.begin(), str.end());
char* ca = &v[0]; // pointer to start of vector

What is App.config in C#.NET? How to use it?

You can access keys in the App.Config using:

ConfigurationSettings.AppSettings["KeyName"]

Take alook at this Thread

What are enums and why are they useful?

In my opinion, all the answers you got up to now are valid, but in my experience, I would express it in a few words:

Use enums if you want the compiler to check the validity of the value of an identifier.

Otherwise, you can use strings as you always did (probably you defined some "conventions" for your application) and you will be very flexible... but you will not get 100% security against typos on your strings and you will realize them only in runtime.

How do I run two commands in one line in Windows CMD?

If you want to create a cmd shortcut (for example on your desktop) add /k parameter (/k means keep, /c will close window):

cmd /k echo hello && cd c:\ && cd Windows

Getting the class name of an instance?

Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'

If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:

x.__class__.__name__

Is it possible to have empty RequestParam values use the defaultValue?

You can keep primitive type by setting default value, in the your case just add "required = false" property:

@RequestParam(value = "i", required = false, defaultValue = "10") int i

P.S. This page from Spring documentation might be useful: Annotation Type RequestParam

Why doesn't Java support unsigned ints?

The reason IMHO is because they are/were too lazy to implement/correct that mistake. Suggesting that C/C++ programmers does not understand unsigned, structure, union, bit flag... Is just preposterous.

Ether you were talking with a basic/bash/java programmer on the verge of beginning programming a la C, without any real knowledge this language or you are just talking out of your own mind. ;)

when you deal every day on format either from file or hardware you begin to question, what in the hell they were thinking.

A good example here would be trying to use an unsigned byte as a self rotating loop. For those of you who do not understand the last sentence, how on earth you call yourself a programmer.

DC

How to fix Git error: object file is empty?

I'm having this problem every once in a while, It is happening due to computer or VM operation problems during a git operation.

The best solution for me is to remove the git objects and all related ref git files:

sudo rm -r .git/objects/* .git/refs/heads/* .git/refs/remotes/* .git/refs/stash .git/refs/tags/*

and then pull the repo:

git pull

That solves everything for me in the easiest way without risking my source code or cloning the repo again.

How to find integer array size in java

Integer Array doesn't contain size() or length() method. Try the below code, it'll work. ArrayList contains size() method. String contains length(). Since you have used int array[], so it will be array.length

public class Example {

    int array[] = {1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554, 22, 22, 211};

    public void Printrange() {

        for (int i = 0; i < array.length; i++) {
            if (array[i] > 100 && array[i] < 500) {
                System.out.println("numbers with in range" + i);
            }
        }
    }
}

docker error - 'name is already in use by container'

Here what i did, it works fine.

step 1:(it lists docker container with its name)

docker ps -a

step 2:

docker rm name_of_the_docker_container

How to echo with different colors in the Windows command line

This isn't a great answer, but if you know the target workstation has Powershell you can do something like this (assuming BAT / CMD script):

CALL:ECHORED "Print me in red!"

:ECHORED
%Windir%\System32\WindowsPowerShell\v1.0\Powershell.exe write-host -foregroundcolor Red %1
goto:eof

Edit: (now simpler!)

It's an old answer but I figured I'd clarify & simplify a bit

img

PowerShell is now included in all versions of Windows since 7. Therefore the syntax for this answer can be shortened to a simpler form:

  • the path doesn't need to be specified since it should be in the environment variable already.
  • unambiguous commands can be abbreviated. For example you can:
    • use -fore instead of -foregroundcolor
    • use -back instead of -backgroundcolor
  • the command can also basically be used 'inline' in place of echo
    (rather than creating a separate batch file as above).

Example:

powershell write-host -fore Cyan This is Cyan text
powershell write-host -back Red This is Red background

More Information:

The complete list of colors and more information is available in the
- PowerShell Documentation for Write-Host

sql like operator to get the numbers only

what might get you where you want in plain SQL92:

select * from tbl where lower(answer) = upper(answer)

or, if you also want to be robust for leading/trailing spaces:

select * from tbl where lower(answer) = trim(upper(answer))

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

You may need to write code that handles a range with multiple areas, which this does:

Public Function GetAddressWithSheetname(Range As Range, Optional blnBuildAddressForNamedRangeValue As Boolean = False) As String

    Const Seperator As String = ","

    Dim WorksheetName As String
    Dim TheAddress As String
    Dim Areas As Areas
    Dim Area As Range

    WorksheetName = "'" & Range.Worksheet.Name & "'"

    For Each Area In Range.Areas
'           ='Sheet 1'!$H$8:$H$15,'Sheet 1'!$C$12:$J$12
        TheAddress = TheAddress & WorksheetName & "!" & Area.Address(External:=False) & Seperator

    Next Area

    GetAddressWithSheetname = Left(TheAddress, Len(TheAddress) - Len(Seperator))

    If blnBuildAddressForNamedRangeValue Then
        GetAddressWithSheetname = "=" & GetAddressWithSheetname
    End If

End Function

Using two values for one switch case statement

You can use:

case text1: case text4: 
     do stuff;
     break;

What does 'public static void' mean in Java?

static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class. Because of use of a static keyword main() is your first method to be invoked.. static doesn't need to any object to instance... so,main( ) is called by the Java interpreter before any objects are made.

How to install plugins to Sublime Text 2 editor?

  1. Install the Package Manager as directed on https://packagecontrol.io/installation

  2. Open the Package Manager using Ctrl+Shift+P

  3. Type Package Control to show related commands (Install Package, Remove Package etc.) with packages

Enjoy it!

enter image description here

What is difference between Axios and Fetch?

  1. Fetch API, need to deal with two promises to get the response data in JSON Object property. While axios result into JSON object.

  2. Also error handling is different in fetch, as it does not handle server side error in the catch block, the Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. While in axios you can catch all error in catch block.

I will say better to use axios, straightforward to handle interceptors, headers config, set cookies and error handling.

Refer this

javac: invalid target release: 1.8

Installing a newer release of IDEA Community (2018.3 instead of 2017.x) was solved my issue with same error but java version:11. Reimport hadn't worked for me. But it worth a try.

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

Here is a solution similar to jayson.centeno's and other answers, but using the built-in extension from System.Net.Http.Formatting.

public static void Register(HttpConfiguration config)
{
    // add support for the 'format' query param
    // cref: http://blogs.msdn.com/b/hongyes/archive/2012/09/02/support-format-in-asp-net-web-api.aspx
    config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
    config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");

    // ... additional configuration
 }

The solution was primarily geared toward supporting $format for OData in the early releases of WebApi, but it also applies to the non-OData implementation, and returns the Content-Type: application/json; charset=utf-8 header in the response.

It allows you to tack &$format=json or &$format=xml to the end of your uri when testing with a browser. It does not interfere with other expected behavior when using a non-browser client where you can set your own headers.

pdftk compression option

Trying to compress a PDF I made with 400ppi tiffs, mostly 8-bit, a few 24-bit, with PackBits compression, using tiff2pdf compressed with Zip/Deflate. One problem I had with every one of these methods: none of the above methods preserved the bookmarks TOC that I painstakingly manually created in Acrobat Pro X. Not even the recommended ebook setting for gs. Sure, I could just open a copy of the original with the TOC intact and do a Replace pages but unfortunately, none of these methods did a satisfactory job to begin with. Either they reduced the size so much that the quality was unacceptably pixellated, or they didn't reduce the size at all and in one case actually increased it despite quality loss.

pdftk compress:

no change in size
bookmarks TOC are gone

gs screen:

takes a ridiculously long time and 100% CPU
errors:
    sfopen: gs_parse_file_name failed.                                 ? 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->10.2MB hideously pixellated
bookmarks TOC are gone

gs printer:

takes a ridiculously long time and 100% CPU
no errors
74.8MB-->66.1MB
light blue background on pages 1-4
bookmarks TOC are gone

gs ebook:

errors:
    sfopen: gs_parse_file_name failed.
      ./base/gsicc_manage.c:1050: gsicc_open_search(): Could not find default_rgb.ic 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->32.2MB
badly pixellated
bookmarks TOC are gone

qpdf --linearize:

very fast, a few seconds
no size change
bookmarks TOC are gone

pdf2ps:

took very long time
output_pdf2ps.ps 74.8MB-->331.6MB

ps2pdf:

pretty fast
74.8MB-->79MB
very slightly degraded with sl. bluish background
bookmarks TOC are gone

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 would I extract a single file (or changes to a file) from a git stash?

If the stashed files need to merge with the current version so use the previous ways using diff. Otherwise you might use git pop for unstashing them, git add fileWantToKeep for staging your file, and do a git stash save --keep-index, for stashing everything except what is on stage. Remember that the difference of this way with the previous ones is that it "pops" the file from stash. The previous answers keep it git checkout stash@{0} -- <filename> so it goes according to your needs.

Why is "using namespace std;" considered bad practice?

I agree with others – it is asking for name clashes, ambiguities and then the fact is it is less explicit. While I can see the use of using, my personal preference is to limit it. I would also strongly consider what some others pointed out:

If you want to find a function name that might be a fairly common name, but you only want to find it in the std namespace (or the reverse – you want to change all calls that are not in namespace std, namespace X, ...), then how do you propose to do this?

You could write a program to do it, but wouldn't it be better to spend time working on your project itself rather than writing a program to maintain your project?

Personally, I actually don't mind the std:: prefix. I like the look more than not having it. I don't know if that is because it is explicit and says to me "this isn't my code... I am using the standard library" or if it is something else, but I think it looks nicer. This might be odd given that I only recently got into C++ (used and still do C and other languages for much longer and C is my favourite language of all time, right above assembly).

There is one other thing although it is somewhat related to the above and what others point out. While this might be bad practise, I sometimes reserve std::name for the standard library version and name for program-specific implementation. Yes, indeed this could bite you and bite you hard, but it all comes down to that I started this project from scratch, and I'm the only programmer for it. Example: I overload std::string and call it string. I have helpful additions. I did it in part because of my C and Unix (+ Linux) tendency towards lower-case names.

Besides that, you can have namespace aliases. Here is an example of where it is useful that might not have been referred to. I use the C++11 standard and specifically with libstdc++. Well, it doesn't have complete std::regex support. Sure, it compiles, but it throws an exception along the lines of it being an error on the programmer's end. But it is lack of implementation.

So here's how I solved it. Install Boost's regex, and link it in. Then, I do the following so that when libstdc++ has it implemented entirely, I need only remove this block and the code remains the same:

namespace std
{
    using boost::regex;
    using boost::regex_error;
    using boost::regex_replace;
    using boost::regex_search;
    using boost::regex_match;
    using boost::smatch;
    namespace regex_constants = boost::regex_constants;
}

I won't argue on whether that is a bad idea or not. I will however argue that it keeps it clean for my project and at the same time makes it specific: True, I have to use Boost, but I'm using it like the libstdc++ will eventually have it. Yes, starting your own project and starting with a standard (...) at the very beginning goes a very long way with helping maintenance, development and everything involved with the project!

Just to clarify something: I don't actually think it is a good idea to use a name of a class/whatever in the STL deliberately and more specifically in place of. The string is the exception (ignore the first, above, or second here, pun if you must) for me as I didn't like the idea of 'String'.

As it is, I am still very biased towards C and biased against C++. Sparing details, much of what I work on fits C more (but it was a good exercise and a good way to make myself a. learn another language and b. try not be less biased against object/classes/etc which is maybe better stated as less closed-minded, less arrogant, and more accepting.). But what is useful is what some already suggested: I do indeed use list (it is fairly generic, is it not ?), and sort (same thing) to name two that would cause a name clash if I were to do using namespace std;, and so to that end I prefer being specific, in control and knowing that if I intend it to be the standard use then I will have to specify it. Put simply: no assuming allowed.

And as for making Boost's regex part of std. I do that for future integration and – again, I admit fully this is bias - I don't think it is as ugly as boost::regex:: .... Indeed, that is another thing for me. There are many things in C++ that I still have yet to come to fully accept in looks and methods (another example: variadic templates versus var arguments [though I admit variadic templates are very very useful!]). Even those that I do accept it was difficult, and I still have issues with them.

How to change Format of a Cell to Text using VBA

Well this should change your format to text.

Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"

How to activate "Share" button in android app?

Create a button with an id share and add the following code snippet.

share.setOnClickListener(new View.OnClickListener() {             
    @Override
    public void onClick(View v) {

        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = "Your body here";
        String shareSub = "Your subject here";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share using"));
    }
});

The above code snippet will open the share chooser on share button click action. However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.

Android ADB doesn't see device

I had same issue, none of the solutions worked for me.

Open Settings Menu -> Developer Options -> USB Debugging should be on

Changing background color of selected cell?

Works for me

UIView *customColorView = [[UIView alloc] init];
    customColorView.backgroundColor = [UIColor colorWithRed:180/255.0 
                                                      green:138/255.0 
                                                       blue:171/255.0 
                                                      alpha:0.5];
    cell.selectedBackgroundView =  customColorView;

REST API Best practice: How to accept list of parameter values as input

First:

I think you can do it 2 ways

http://our.api.com/Product/<id> : if you just want one record

http://our.api.com/Product : if you want all records

http://our.api.com/Product/<id1>,<id2> :as James suggested can be an option since what comes after the Product tag is a parameter

Or the one I like most is:

You can use the the Hypermedia as the engine of application state (HATEOAS) property of a RestFul WS and do a call http://our.api.com/Product that should return the equivalent urls of http://our.api.com/Product/<id> and call them after this.

Second

When you have to do queries on the url calls. I would suggest using HATEOAS again.

1) Do a get call to http://our.api.com/term/pumas/productType/clothing/color/black

2) Do a get call to http://our.api.com/term/pumas/productType/clothing,bags/color/black,red

3) (Using HATEOAS) Do a get call to `http://our.api.com/term/pumas/productType/ -> receive the urls all clothing possible urls -> call the ones you want (clothing and bags) -> receive the possible color urls -> call the ones you want

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

For me the error was:

Error: unexpected input in "?"

and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.

EDIT: OP requested an example. Here it goes.

?  ~ cat a.R
cat('hello world\n')
?  ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f  ...cat('hello wo
00000010: 726c 645c 6e27 290a                      rld\n').
?  ~ R -f a.R        

R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> cat('hello world\n')
Error: unexpected input in "?"
Execution halted

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

Unzip files programmatically in .net

Use the DotNetZip library at http://www.codeplex.com/DotNetZip

class library and toolset for manipulating zip files. Use VB, C# or any .NET language to easily create, extract, or update zip files...

DotNetZip works on PCs with the full .NET Framework, and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language, or any scripting environment...

If all you want is a better DeflateStream or GZipStream class to replace the one that is built-into the .NET BCL, DotNetZip has that, too. DotNetZip's DeflateStream and GZipStream are available in a standalone assembly, based on a .NET port of Zlib. These streams support compression levels and deliver much better performance than the built-in classes. There is also a ZlibStream to complete the set (RFC 1950, 1951, 1952)...

New line in Sql Query

You could do Char(13) and Char(10). Cr and Lf.

Char() works in SQL Server, I don't know about other databases.

'Missing contentDescription attribute on image' in XML

Add

tools:ignore="ContentDescription"

to your image. Make sure you have xmlns:tools="http://schemas.android.com/tools" . in your root layout.

Angular 2 / 4 / 5 - Set base href dynamically

This work fine for me in prod environment

<base href="/" id="baseHref">
<script>
  (function() {
    document.getElementById('baseHref').href = '/' + window.location.pathname.split('/')[1] + "/";
  })();
</script>

Parse HTML table to Python list?

If the HTML is not XML you can't do it with etree. But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with HTMLParser from html.parser. I've the code of the simple derived HTMLParser class here in a github repo.

You can use that class (here named HTMLTableParser) the following way:

import urllib.request
from html_table_parser import HTMLTableParser

target = 'http://www.twitter.com'

# get website content
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml = f.read().decode('utf-8')

# instantiate the parser and feed it
p = HTMLTableParser()
p.feed(xhtml)
print(p.tables)

The output of this is a list of 2D-lists representing tables. It looks maybe like this:

[[['   ', ' Anmelden ']],
 [['Land', 'Code', 'Für Kunden von'],
  ['Vereinigte Staaten', '40404', '(beliebig)'],
  ['Kanada', '21212', '(beliebig)'],
  ...
  ['3424486444', 'Vodafone'],
  ['  Zeige SMS-Kurzwahlen für andere Länder ']]]

Head and tail in one line

Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.

t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]

If you need it to be exception-proof (i.e. supporting empty list), then add:

t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]

If you want to do it without the semicolon, use:

h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]

iOS - UIImageView - how to handle UIImage image orientation

If you need to rotate and fix the image orientation below extension would be useful.

extension UIImage {

    public func imageRotatedByDegrees(degrees: CGFloat) -> UIImage {
        //Calculate the size of the rotated view's containing box for our drawing space
        let rotatedViewBox: UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        let t: CGAffineTransform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi / 180)
        rotatedViewBox.transform = t
        let rotatedSize: CGSize = rotatedViewBox.frame.size
        //Create the bitmap context
        UIGraphicsBeginImageContext(rotatedSize)
        let bitmap: CGContext = UIGraphicsGetCurrentContext()!
        //Move the origin to the middle of the image so we will rotate and scale around the center.
        bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
        //Rotate the image context
        bitmap.rotate(by: (degrees * CGFloat.pi / 180))
        //Now, draw the rotated/scaled image into the context
        bitmap.scaleBy(x: 1.0, y: -1.0)
        bitmap.draw(self.cgImage!, in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }


    public func fixedOrientation() -> UIImage {
        if imageOrientation == UIImageOrientation.up {
            return self
        }

        var transform: CGAffineTransform = CGAffineTransform.identity

        switch imageOrientation {
        case UIImageOrientation.down, UIImageOrientation.downMirrored:
            transform = transform.translatedBy(x: size.width, y: size.height)
            transform = transform.rotated(by: CGFloat.pi)
            break
        case UIImageOrientation.left, UIImageOrientation.leftMirrored:
            transform = transform.translatedBy(x: size.width, y: 0)
            transform = transform.rotated(by: CGFloat.pi/2)
            break
        case UIImageOrientation.right, UIImageOrientation.rightMirrored:
            transform = transform.translatedBy(x: 0, y: size.height)
            transform = transform.rotated(by: -CGFloat.pi/2)
            break
        case UIImageOrientation.up, UIImageOrientation.upMirrored:
            break
        }

        switch imageOrientation {
        case UIImageOrientation.upMirrored, UIImageOrientation.downMirrored:
            transform.translatedBy(x: size.width, y: 0)
            transform.scaledBy(x: -1, y: 1)
            break
        case UIImageOrientation.leftMirrored, UIImageOrientation.rightMirrored:
            transform.translatedBy(x: size.height, y: 0)
            transform.scaledBy(x: -1, y: 1)
        case UIImageOrientation.up, UIImageOrientation.down, UIImageOrientation.left, UIImageOrientation.right:
            break
        }

        let ctx: CGContext = CGContext(data: nil,
                                       width: Int(size.width),
                                       height: Int(size.height),
                                       bitsPerComponent: self.cgImage!.bitsPerComponent,
                                       bytesPerRow: 0,
                                       space: self.cgImage!.colorSpace!,
                                       bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!

        ctx.concatenate(transform)

        switch imageOrientation {
        case UIImageOrientation.left, UIImageOrientation.leftMirrored, UIImageOrientation.right, UIImageOrientation.rightMirrored:
            ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
        default:
            ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            break
        }

        let cgImage: CGImage = ctx.makeImage()!

        return UIImage(cgImage: cgImage)
    }
}

Proxy Error 502 : The proxy server received an invalid response from an upstream server

Add this into your httpd.conf file

Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore 

localhost refused to connect Error in visual studio

Right Click on Project >> Properties >> Select Web Tab >> Under server Select "Use Visual development server" so indirectly it will uncheck "Local IIS Server"

Hope so it may resolve this issue.

@Html.DropDownListFor how to set default value

try this

 @Html.DropDownListFor(model => model.UserName, new List<SelectListItem> 
   { new SelectListItem{Text="Active", Value="True",Selected =true },
     new SelectListItem{Text="Deactive", Value="False"}})

Immutable vs Mutable types

A mutable object has to have at least a method able to mutate the object. For example, the list object has the append method, which will actually mutate the object:

>>> a = [1,2,3]
>>> a.append('hello') # `a` has mutated but is still the same object
>>> a
[1, 2, 3, 'hello']

but the class float has no method to mutate a float object. You can do:

>>> b = 5.0 
>>> b = b + 0.1
>>> b
5.1

but the = operand is not a method. It just make a bind between the variable and whatever is to the right of it, nothing else. It never changes or creates objects. It is a declaration of what the variable will point to, since now on.

When you do b = b + 0.1 the = operand binds the variable to a new float, wich is created with te result of 5 + 0.1.

When you assign a variable to an existent object, mutable or not, the = operand binds the variable to that object. And nothing more happens

In either case, the = just make the bind. It doesn't change or create objects.

When you do a = 1.0, the = operand is not wich create the float, but the 1.0 part of the line. Actually when you write 1.0 it is a shorthand for float(1.0) a constructor call returning a float object. (That is the reason why if you type 1.0 and press enter you get the "echo" 1.0 printed below; that is the return value of the constructor function you called)

Now, if b is a float and you assign a = b, both variables are pointing to the same object, but actually the variables can't comunicate betweem themselves, because the object is inmutable, and if you do b += 1, now b point to a new object, and a is still pointing to the oldone and cannot know what b is pointing to.

but if c is, let's say, a list, and you assign a = c, now a and c can "comunicate", because list is mutable, and if you do c.append('msg'), then just checking a you get the message.

(By the way, every object has an unique id number asociated to, wich you can get with id(x). So you can check if an object is the same or not checking if its unique id has changed.)

Change the color of a bullet in a html list?

<ul style="color: red;">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
  • One
  • Two
  • Three
  • How to add an element to the beginning of an OrderedDict?

    EDIT (2019-02-03) Note that the following answer only works on older versions of Python. More recently, OrderedDict has been rewritten in C. In addition this does touch double-underscore attributes which is frowned upon.

    I just wrote a subclass of OrderedDict in a project of mine for a similar purpose. Here's the gist.

    Insertion operations are also constant time O(1) (they don't require you to rebuild the data structure), unlike most of these solutions.

    >>> d1 = ListDict([('a', '1'), ('b', '2')])
    >>> d1.insert_before('a', ('c', 3))
    >>> d1
    ListDict([('c', 3), ('a', '1'), ('b', '2')])
    

    browser sessionStorage. share between tabs?

    You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.

    This code would need to exist on ALL tabs. It should execute before your other scripts.

    // transfers sessionStorage from one tab to another
    var sessionStorage_transfer = function(event) {
      if(!event) { event = window.event; } // ie suq
      if(!event.newValue) return;          // do nothing if no value to work with
      if (event.key == 'getSessionStorage') {
        // another tab asked for the sessionStorage -> send it
        localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
        // the other tab should now have it, so we're done with it.
        localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
      } else if (event.key == 'sessionStorage' && !sessionStorage.length) {
        // another tab sent data <- get it
        var data = JSON.parse(event.newValue);
        for (var key in data) {
          sessionStorage.setItem(key, data[key]);
        }
      }
    };
    
    // listen for changes to localStorage
    if(window.addEventListener) {
      window.addEventListener("storage", sessionStorage_transfer, false);
    } else {
      window.attachEvent("onstorage", sessionStorage_transfer);
    };
    
    
    // Ask other tabs for session storage (this is ONLY to trigger event)
    if (!sessionStorage.length) {
      localStorage.setItem('getSessionStorage', 'foobar');
      localStorage.removeItem('getSessionStorage', 'foobar');
    };
    

    I tested this in chrome, ff, safari, ie 11, ie 10, ie9

    This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)

    Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/

    How do I pass a list as a parameter in a stored procedure?

    You can use this simple 'inline' method to construct a string_list_type parameter (works in SQL Server 2014):

    declare @p1 dbo.string_list_type
    insert into @p1 values(N'myFirstString')
    insert into @p1 values(N'mySecondString')
    

    Example use when executing a stored proc:

    exec MyStoredProc @MyParam=@p1
    

    Typedef function pointer?

    For general case of syntax you can look at annex A of the ANSI C standard.

    In the Backus-Naur form from there, you can see that typedef has the type storage-class-specifier.

    In the type declaration-specifiers you can see that you can mix many specifier types, the order of which does not matter.

    For example, it is correct to say,

    long typedef long a;
    

    to define the type a as an alias for long long. So , to understand the typedef on the exhaustive use you need to consult some backus-naur form that defines the syntax (there are many correct grammars for ANSI C, not only that of ISO).

    When you use typedef to define an alias for a function type you need to put the alias in the same place where you put the identifier of the function. In your case you define the type FunctionFunc as an alias for a pointer to function whose type checking is disabled at call and returning nothing.

    How do I return the response from an asynchronous call?

    You are using Ajax incorrectly. The idea is not to have it return anything, but instead hand off the data to something called a callback function, which handles the data.

    That is:

    function handleData( responseData ) {
    
        // Do what you want with the data
        console.log(responseData);
    }
    
    $.ajax({
        url: "hi.php",
        ...
        success: function ( data, status, XHR ) {
            handleData(data);
        }
    });
    

    Returning anything in the submit handler will not do anything. You must instead either hand off the data, or do what you want with it directly inside the success function.

    String Padding in C

    You must make sure that the input string has enough space to hold all the padding characters. Try this:

    char hello[11] = "Hello";
    StringPadRight(hello, 10, "0");
    

    Note that I allocated 11 bytes for the hello string to account for the null terminator at the end.

    Best way to copy a database (SQL Server 2008)

    Its hard to detach your production dB or other running dB's and deal with that downtime, so I almost always use a Backup / restore method.

    If you also want to make sure to keep your login's in sync check out the MS KB article on using the stored proc sp_help_revlogin to do this.

    Getting Gradle dependencies in IntelliJ IDEA using Gradle build

    After adding dependencies open "Gradle" ('View'->Tool Windows->Gradle) tab and hit "refresh"

    example of adding (compile 'io.reactivex:rxjava:1.1.0'):

    hit refresh

    If Idea still can not resolve dependency, hence it is possibly the dependency is not in mavenCentral() repository and you need add repository where this dependency located into repositories{}

    Round integers to the nearest 10

    About the round(..) function returning a float

    That float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)

    See the discussion here for details.

    Get data from file input in JQuery

    input file element:

    <input type="file" id="fileinput" />
    

    get file :

    var myFile = $('#fileinput').prop('files');
    

    How do I change the select box arrow

    CSS

    select.inpSelect {
      //Remove original arrows
      -webkit-appearance: none; 
      //Use png at assets/selectArrow.png for the arrow on the right
      //Set the background color to a BadAss Green color 
      background: url(assets/selectArrow.png) no-repeat right #BADA55;
    }
    

    Using CSS in Laravel views?

    To my opinion the best option to route to css & js use the following code:

    <link rel="stylesheet" type="text/css" href="{{ URL::to('route/to/css') }}">
    

    So if you have css file called main.css inside of css folder in public folder it should be the following:

    <link rel="stylesheet" type="text/css" href="{{ URL::to('css/main.css') }}">
    

    What exactly is the meaning of an API?

    1) What is an API?

    API is a contract. A promise to perform described services when asked in specific ways.

    2) How is it used?

    According to the rules specified in the contract. The whole point of an API is to define how it's used.

    3) When and where is it used?

    It's used when 2 or more separate systems need to work together to achieve something they can't do alone.

    How to set the maxAllowedContentLength to 500MB while running on IIS7?

    The limit of requests in .Net can be configured from two properties together:

    First

    • Web.Config/system.web/httpRuntime/maxRequestLength
    • Unit of measurement: kilobytes
    • Default value 4096 KB (4 MB)
    • Max. value 2147483647 KB (2 TB)

    Second

    • Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength (in bytes)
    • Unit of measurement: bytes
    • Default value 30000000 bytes (28.6 MB)
    • Max. value 4294967295 bytes (4 GB)

    References:

    Example:

    <location path="upl">
       <system.web>
         <!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
         <!-- 100 MB in kilobytes -->
         <httpRuntime maxRequestLength="102400" />
       </system.web>
       <system.webServer>
         <security>
           <requestFiltering>          
             <!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
             <!-- 100 MB in bytes -->
             <requestLimits maxAllowedContentLength="104857600" />
           </requestFiltering>
         </security>
       </system.webServer>
     </location>
    

    Call Activity method from adapter

    Original:

    I understand the current answer but needed a more clear example. Here is an example of what I used with an Adapter(RecyclerView.Adapter) and an Activity.

    In your Activity:

    This will implement the interface that we have in our Adapter. In this example, it will be called when the user clicks on an item in the RecyclerView.

    public class MyActivity extends Activity implements AdapterCallback {
    
        private MyAdapter myAdapter;
    
        @Override
        public void onMethodCallback() {
           // do something
        }
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            myAdapter = new MyAdapter(this);
        }
    }
    

    In your Adapter:

    In the Activity, we initiated our Adapter and passed this as an argument to the constructer. This will initiate our interface for our callback method. You can see that we use our callback method for user clicks.

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    
        private AdapterCallback adapterCallback;
    
        public MyAdapter(Context context) {
            try {
                adapterCallback = ((AdapterCallback) context);
            } catch (ClassCastException e) {
                throw new ClassCastException("Activity must implement AdapterCallback.", e);
            }
        }
    
        @Override
        public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
            // simple example, call interface here
            // not complete
            viewHolder.itemView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        adapterCallback.onMethodCallback();
                    } catch (ClassCastException e) {
                       // do something
                    }
                }
            });
        }
    
        public static interface AdapterCallback {
            void onMethodCallback();
        }
    }
    

    What does it mean to "call" a function in Python?

    When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:

    def add(a,b):
        return a + b
    

    you would call the function like this:

    add(3,5)
    

    which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:

    answer = add(4,7)
    

    Which would set the variable answer equal to 11 in this case.

    How do I check if a number is positive or negative in C#?

    bool isNegative(int n) {
      int i;
      for (i = 0; i <= Int32.MaxValue; i++) {
        if (n == i) 
          return false;
      }
      return true;
    }
    

    How can I disable the default console handler, while using the java logging API?

    Do a reset of the configuration and set the root level to OFF

    LogManager.getLogManager().reset();
    Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
    globalLogger.setLevel(java.util.logging.Level.OFF);
    

    Spring Boot and multiple external configuration files

    this is one simple approach using spring boot

    TestClass.java

    @Configuration
    @Profile("one")
    @PropertySource("file:/{selected location}/app.properties")
    public class TestClass {
    
        @Autowired
        Environment env;
    
        @Bean
        public boolean test() {
            System.out.println(env.getProperty("test.one"));
            return true;
        }
    }
    

    the app.properties context, in your selected location

    test.one = 1234
    

    your spring boot application

    @SpringBootApplication
    
    public class TestApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(testApplication.class, args);
        }
    }
    

    and the predefined application.properties context

    spring.profiles.active = one
    

    you can write as many configuration class as you like and enable/disable them just by setting spring.profiles.active = the profile name/names {separated by commas}

    as you can see spring boot is great it just needs sometime to get familiar with, it's worth mentioning that you may use @Value on your fields as well

    @Value("${test.one}")
    String str;
    

    Showing data values on stacked bar chart in ggplot2

    From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

    ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
      geom_bar(stat = "identity") +
      geom_text(size = 3, position = position_stack(vjust = 0.5))
    

    enter image description here

    Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


    Answer valid for older versions of ggplot:

    Here is one approach, which calculates the midpoints of the bars.

    library(ggplot2)
    library(plyr)
    
    # calculate midpoints of bars (simplified using comment by @DWin)
    Data <- ddply(Data, .(Year), 
       transform, pos = cumsum(Frequency) - (0.5 * Frequency)
    )
    
    # library(dplyr) ## If using dplyr... 
    # Data <- group_by(Data,Year) %>%
    #    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))
    
    # plot bars and add text
    p <- ggplot(Data, aes(x = Year, y = Frequency)) +
         geom_bar(aes(fill = Category), stat="identity") +
         geom_text(aes(label = Frequency, y = pos), size = 3)
    

    Resultant chart

    How to sort a list of lists by a specific index of the inner list?

    Make sure that you do not have any null or NaN values in the list you want to sort. If there are NaN values, then your sort will be off, impacting the sorting of the non-null values.

    Check out Python: sort function breaks in the presence of nan

    Compiled vs. Interpreted Languages

    Start thinking in terms of a: blast from the past

    Once upon a time, long long ago, there lived in the land of computing interpreters and compilers. All kinds of fuss ensued over the merits of one over the other. The general opinion at that time was something along the lines of:

    • Interpreter: Fast to develop (edit and run). Slow to execute because each statement had to be interpreted into machine code every time it was executed (think of what this meant for a loop executed thousands of times).
    • Compiler: Slow to develop (edit, compile, link and run. The compile/link steps could take serious time). Fast to execute. The whole program was already in native machine code.

    A one or two order of magnitude difference in the runtime performance existed between an interpreted program and a compiled program. Other distinguishing points, run-time mutability of the code for example, were also of some interest but the major distinction revolved around the run-time performance issues.

    Today the landscape has evolved to such an extent that the compiled/interpreted distinction is pretty much irrelevant. Many compiled languages call upon run-time services that are not completely machine code based. Also, most interpreted languages are "compiled" into byte-code before execution. Byte-code interpreters can be very efficient and rival some compiler generated code from an execution speed point of view.

    The classic difference is that compilers generated native machine code, interpreters read source code and generated machine code on the fly using some sort of run-time system. Today there are very few classic interpreters left - almost all of them compile into byte-code (or some other semi-compiled state) which then runs on a virtual "machine".

    Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

    Important note: You should only apply plugin at bottom of build.gradle (App level)

    apply plugin: 'com.google.gms.google-services'

    I mistakenly apply this plugin at top of the build.gradle. So I get error.

    One more tips : You no need to remove even you use the 3.1.0 or above. Because google not officially announced

       classpath 'com.google.gms:google-services:3.1.0' 
    

    How do I create a file at a specific path?

    The file is created wherever the root of the python interpreter was started.

    Eg, you start python in /home/user/program, then the file "test.py" would be located at /home/user/program/test.py

    Cut Java String at a number of character

    Something like this may be:

    String str = "abcdefghijklmnopqrtuvwxyz";
    if (str.length() > 8)
        str = str.substring(0, 8) + "...";
    

    SQL- Ignore case while searching for a string

    You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI as your collation. The one you specify in your question is explictly case sensitive.

    You can see a list of collations here.

    How does Facebook disable the browser's integrated Developer Tools?

    This is not a security measure for weak code to be left unattended. Always get a permanent solution to weak code and secure your websites properly before implementing this strategy

    The best tool by far according to my knowledge would be to add multiple javascript files that simply changes the integrity of the page back to normal by refreshing or replacing content. Disabling this developer tool would not be the greatest idea since bypassing is always in question since the code is part of the browser and not a server rendering, thus it could be cracked.

    Should you have js file one checking for <element> changes on important elements and js file two and js file three checking that this file exists per period you will have full integrity restore on the page within the period.

    Lets take an example of the 4 files and show you what I mean.

    index.html

       <!DOCTYPE html>
       <html>
       <head id="mainhead">
       <script src="ks.js" id="ksjs"></script>
       <script src="mainfile.js" id="mainjs"></script>
       <link rel="stylesheet" href="style.css" id="style">
       <meta id="meta1" name="description" content="Proper mitigation against script kiddies via Javascript" >
       </head>
       <body>
       <h1 id="heading" name="dontdel" value="2">Delete this from console and it will refresh. If you change the name attribute in this it will also refresh. This is mitigating an attack on attribute change via console to exploit vulnerabilities. You can even try and change the value attribute from 2 to anything you like. If This script says it is 2 it should be 2 or it will refresh. </h1>
       <h3>Deleting this wont refresh the page due to it having no integrity check on it</h3>
    
       <p>You can also add this type of error checking on meta tags and add one script out of the head tag to check for changes in the head tag. You can add many js files to ensure an attacker cannot delete all in the second it takes to refresh. Be creative and make this your own as your website needs it. 
       </p>
    
       <p>This is not the end of it since we can still enter any tag to load anything from everywhere (Dependent on headers etc) but we want to prevent the important ones like an override in meta tags that load headers. The console is designed to edit html but that could add potential html that is dangerous. You should not be able to enter any meta tags into this document unless it is as specified by the ks.js file as permissable. <br>This is not only possible with meta tags but you can do this for important tags like input and script. This is not a replacement for headers!!! Add your headers aswell and protect them with this method.</p>
       </body>
       <script src="ps.js" id="psjs"></script>
       </html>
    

    mainfile.js

       setInterval(function() {
       // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
       var ksExists = document.getElementById("ksjs"); 
       if(ksExists) {
       }else{ location.reload();};
    
       var psExists = document.getElementById("psjs");
       if(psExists) {
       }else{ location.reload();};
    
       var styleExists = document.getElementById("style");
       if(styleExists) {
       }else{ location.reload();};
    
    
       }, 1 * 1000); // 1 * 1000 milsec
    

    ps.js

       /*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload!You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.
    
       */
    
       setInterval(function() {
       // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
       var mainExists = document.getElementById("mainjs"); 
       if(mainExists) {
       }else{ location.reload();};
    
       //check that heading with id exists and name tag is dontdel.
       var headingExists = document.getElementById("heading"); 
       if(headingExists) {
       }else{ location.reload();};
       var integrityHeading = headingExists.getAttribute('name');
       if(integrityHeading == 'dontdel') {
       }else{ location.reload();};
       var integrity2Heading = headingExists.getAttribute('value');
       if(integrity2Heading == '2') {
       }else{ location.reload();};
       //check that all meta tags stay there
       var meta1Exists = document.getElementById("meta1"); 
       if(meta1Exists) {
       }else{ location.reload();};
    
       var headExists = document.getElementById("mainhead"); 
       if(headExists) {
       }else{ location.reload();};
    
       }, 1 * 1000); // 1 * 1000 milsec
    

    ks.js

       /*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload! You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.
    
       */
    
       setInterval(function() {
       // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
       var mainExists = document.getElementById("mainjs"); 
       if(mainExists) {
       }else{ location.reload();};
       //Check meta tag 1 for content changes. meta1 will always be 0. This you do for each meta on the page to ensure content credibility. No one will change a meta and get away with it. Addition of a meta in spot 10, say a meta after the id="meta10" should also be covered as below.
       var x = document.getElementsByTagName("meta")[0];
       var p = x.getAttribute("name");
       var s = x.getAttribute("content");
       if (p != 'description') {
       location.reload();
       }
       if ( s != 'Proper mitigation against script kiddies via Javascript') {
       location.reload();
       }
       // This will prevent a meta tag after this meta tag @ id="meta1". This prevents new meta tags from being added to your pages. This can be used for scripts or any tag you feel is needed to do integrity check on like inputs and scripts. (Yet again. It is not a replacement for headers to be added. Add your headers aswell!)
       var lastMeta = document.getElementsByTagName("meta")[1];
       if (lastMeta) {
       location.reload();
       }
       }, 1 * 1000); // 1 * 1000 milsec
    

    style.css

    Now this is just to show it works on all files and tags aswell

       #heading {
       background-color:red;
       }
    

    If you put all these files together and build the example you will see the function of this measure. This will prevent some unforseen injections should you implement it correctly on all important elements in your index file especially when working with PHP.

    Why I chose reload instead of change back to normal value per attribute is the fact that some attackers could have another part of the website already configured and ready and it lessens code amount. The reload will remove all the attacker's hard work and he will probably go play somewhere easier.

    Another note: This could become a lot of code so keep it clean and make sure to add definitions to where they belong to make edits easy in future. Also set the seconds to your preferred amount as 1 second intervals on large pages could have drastic effects on older computers your visitors might be using

    What is the opposite of evt.preventDefault();

    Here's something useful...

    First of all we'll click on the link , run some code, and than we'll perform default action. This will be possible using event.currentTarget Take a look. Here we'll gonna try to access Google on a new tab, but before we need to run some code.

    <a href="https://www.google.com.br" target="_blank" id="link">Google</a>
    
    <script type="text/javascript">
        $(document).ready(function() {
            $("#link").click(function(e) {
    
                // Prevent default action
                e.preventDefault();
    
                // Here you'll put your code, what you want to execute before default action
                alert(123); 
    
                // Prevent infinite loop
                $(this).unbind('click');
    
                // Execute default action
                e.currentTarget.click();
            });
        });
    </script>
    

    Android: how to refresh ListView contents?

    Another easy way:

    //In your ListViewActivity:
    public void refreshListView() {
        listAdapter = new ListAdapter(this);
        setListAdapter(listAdapter);
    }
    

    MVC Redirect to View from jQuery with parameters

    redirect with query string

     $('#results').on('click', '.item', function () {
                        var NestId = $(this).data('id');
                       // var url = '@Url.Action("Details", "Artists",new { NestId = '+NestId+'  })'; 
                        var url = '@ Url.Content("~/Artists/Details?NestId =' + NestId + '")'
                        window.location.href = url; 
                    })
    

    Create web service proxy in Visual Studio from a WSDL file

    Since the true Binding URL for the web service is located in the file, you could do these simple steps from your local machine:

    1) Save the file to your local computer for example:

    C:\Documents and Settings\[user]\Desktop\Webservice1.asmx
    

    2) In Visual Studio Right Click on your project > Choose Add Web Reference, A dialog will open.

    3) In the URL Box Copy the local file location above C:\Documents and Settings[user]\Desktop\Webservice1.asmx, Click Next

    4) Now you will see the functions appear, choose your name for the reference, Click add reference

    5) You are done! you can start using it as a namespace in your application don't worry that you used a local file, because anyway the true URL for the service is located in the file at the Binding section

    Difference between Encapsulation and Abstraction

    Encapsulation is wrapping up of data and methods in a single unit and making the data accessible only through methods(getter/setter) to ensure safety of data.

    Abstraction is hiding internal implementation details of how work is done.

    Take and example of following stack class:

    Class Stack
    {
    private top;
    void push();
    int pop();
    }
    

    Now encapsulation helps to safeguard internal data as top cannot be accessed directly outside.

    And abstraction helps to do push or pop on stack without worrying about what are steps to push or pop

    When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

    Use dynamic_cast for converting pointers/references within an inheritance hierarchy.

    Use static_cast for ordinary type conversions.

    Use reinterpret_cast for low-level reinterpreting of bit patterns. Use with extreme caution.

    Use const_cast for casting away const/volatile. Avoid this unless you are stuck using a const-incorrect API.

    Can I get image from canvas element and use it in img src tag?

    canvas.toDataURL() will provide you a data url which can be used as source:

    var image = new Image();
    image.id = "pic";
    image.src = canvas.toDataURL();
    document.getElementById('image_for_crop').appendChild(image);
    

    Complete example

    Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a <img>, filled with the <canvas>'s data url.

    _x000D_
    _x000D_
    // This is just image generation, skip to DATAURL: below
    var canvas = document.getElementById("canvas")
    var ctx = canvas.getContext("2d");
    
    // Just some example drawings
    var gradient = ctx.createLinearGradient(0, 0, 200, 100);
    gradient.addColorStop("0", "#ff0000");
    gradient.addColorStop("0.5" ,"#00a0ff");
    gradient.addColorStop("1.0", "#f0bf00");
    
    ctx.beginPath();
    ctx.moveTo(0, 0);
    for (let i = 0; i < 30; ++i) {
      ctx.lineTo(Math.random() * 200, Math.random() * 100);
    }
    ctx.strokeStyle = gradient;
    ctx.stroke();
    
    // DATAURL: Actual image generation via data url
    var target = new Image();
    target.src = canvas.toDataURL();
    
    document.getElementById('result').appendChild(target);
    _x000D_
    canvas { border: 1px solid black; }
    img    { border: 1px solid blue;  }
    body   { display: flex; }
    div + div {margin-left: 1ex; }
    _x000D_
    <div>
      <p>Original:</p>
      <canvas id="canvas" width=200 height=100></canvas>
    </div>
    <div id="result">
      <p>Result via &lt;img&gt;:</p>
    </div>
    _x000D_
    _x000D_
    _x000D_

    See also:

    How to convert Map keys to array?

    Array.from(myMap.keys()) does not work in google application scripts.

    Trying to use it results in the error TypeError: Cannot find function from in object function Array() { [native code for Array.Array, arity=1] }.

    To get a list of keys in GAS do this:

    var keysList = Object.keys(myMap);
    

    Javascript code for showing yesterday's date and todays date

    Yesterday's date can be calculated as,

    var prev_date = new Date();
    prev_date.setDate(prev_date.getDate() - 1);
    

    How to get value of a div using javascript

    DIVs do not have a value property.

    Technically, according to the DTDs, they shouldn't have a value attribute either, but generally you'll want to use .getAttribute() in this case:

    function overlay()
    {
        var cookieValue = document.getElementById('demo').getAttribute('value');
        alert(cookieValue);
    }
    

    Where is Xcode's build folder?

    I wondered the same myself. I found that under File(menu) there is an item "Project Settings". It opens a dialog box with 3 choices: "Default Location", "Project-relative Location", and "Custom location" "Project-relative" puts the build products in the project folder, like before. This is not in the Preferences menu and must be set every time a project is created. Hope this helps.

    How to set standard encoding in Visual Studio

    The Problem is Windows and Microsoft applications put byte order marks at the beginning of all your files so other applications often break or don't read these UTF-8 encoding marks. I perfect example of this problem was triggering quirsksmode in old IE web browsers when encoding in UTF-8 as browsers often display web pages based on what encoding falls at the start of the page. It makes a mess when other applications view those UTF-8 Visual Studio pages.

    I usually do not recommend Visual Studio Extensions, but I do this one to fix that issue:

    Fix File Encoding: https://vlasovstudio.com/fix-file-encoding/

    The FixFileEncoding above install REMOVES the byte order mark and forces VS to save ALL FILES without signature in UTF-8. After installing go to Tools > Option then choose "FixFileEncoding". It should allow you to set all saves as UTF-8 . Add "cshtml to the list of files to always save in UTF-8 without the byte order mark as so: ".(htm|html|cshtml)$)".

    Now open one of your files in Visual Studio. To verify its saving as UTF-8 go to File > Save As, then under the Save button choose "Save With Encoding". It should choose "UNICODE (Save without Signature)" by default from the list of encodings. Now when you save that page it should always save as UTF-8 without byte order mark at the beginning of the file when saving in Visual Studio.

    Django {% with %} tags within {% if %} {% else %} tags?

    Like this:

    {% if age > 18 %}
        {% with patient as p %}
        <my html here>
        {% endwith %}
    {% else %}
        {% with patient.parent as p %}
        <my html here>
        {% endwith %}
    {% endif %}
    

    If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:

    p = (age > 18 && patient) or patient.parent
    

    and then just use {{ p }} in the template.

    How do I add one month to current date in Java?

    public Date  addMonths(String dateAsString, int nbMonths) throws ParseException {
            String format = "MM/dd/yyyy" ;
            SimpleDateFormat sdf = new SimpleDateFormat(format) ;
            Date dateAsObj = sdf.parse(dateAsString) ;
            Calendar cal = Calendar.getInstance();
            cal.setTime(dateAsObj);
            cal.add(Calendar.MONTH, nbMonths);
            Date dateAsObjAfterAMonth = cal.getTime() ;
        System.out.println(sdf.format(dateAsObjAfterAMonth));
        return dateAsObjAfterAMonth ;
    }`
    

    C# Macro definitions in Preprocessor

    Since C# 7.0 supports using static directive and Local functions you don't need preprocessor macros for most cases.

    How to set the environmental variable LD_LIBRARY_PATH in linux

    1. Go to the home folder and edit .profile
    2. Place the following line at the end

      export LD_LIBRARY_PATH=<your path>

    3. Save and Exit.

    4. Execute this command

      sudo ldconfig

    Java - Create a new String instance with specified length and filled with specific character. Best solution?

    Try this jobber

    String stringy =null;
     byte[] buffer =  new byte[100000];
                for (int i = 0; i < buffer.length; i++) {
                buffer[i] =0;
    
            }
                stringy =StringUtils.toAsciiString(buffer);
    

    Closing Excel Application using VBA

    Application.Quit 
    

    Should do the trick.

    adding noise to a signal in python

    AWGN Similar to Matlab Function

    def awgn(sinal):
        regsnr=54
        sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
        sigpower=sigpower/len(sinal)
        noisepower=sigpower/(math.pow(10,regsnr/10))
        noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
        return noise
    

    When using a Settings.settings file in .NET, where is the config actually stored?

    Here is the snippet you can use to programmatically get user.config file location:

    public static string GetDefaultExeConfigPath(ConfigurationUserLevel userLevel)
    {
      try
      {
        var UserConfig = ConfigurationManager.OpenExeConfiguration(userLevel);
        return UserConfig.FilePath;
      }
      catch (ConfigurationException e)
      {
        return e.Filename;
      }
    }
    

    ApplicationSettings (i.e. settings.settings) use PerUserRoamingAndLocal for user settings by default (as I remembered).

    Update: Strange but there are too many incorrect answers here. If you are looking for you user scoped settings file (user.config) it will be located in the following folder (for Windows XP):

    C:\Documents and Settings\(username)\Local Settings\Application Data\(company-name-if-exists)\(app-name).exe_(Url|StrongName)_(hash)\(app-version)\

    Url or StrongName depends on have you application assembly strong name or not.

    Serializing/deserializing with memory stream

    BinaryFormatter may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.

    If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer or XmlSerializer.

    Drop all tables command

    Once you've dropped all the tables (and the indexes will disappear when the table goes) then there's nothing left in a SQLite database as far as I know, although the file doesn't seem to shrink (from a quick test I just did).

    So deleting the file would seem to be fastest - it should just be recreated when your app tries to access the db file.

    Looping through dictionary object

    It depends on what you are after in the Dictionary

    Models.TestModels obj = new Models.TestModels();
    
    foreach (var keyValuPair in obj.sp)
    {
        // KeyValuePair<int, dynamic>
    }
    
    foreach (var key in obj.sp.Keys)
    {
         // Int 
    }
    
    foreach (var value in obj.sp.Values)
    {
        // dynamic
    }
    

    ffmpeg usage to encode a video to H264 codec format

    I used these options to convert to the H.264/AAC .mp4 format for HTML5 playback (I think it may help other guys with this problem in some way):

    ffmpeg -i input.flv -vcodec mpeg4 -acodec aac output.mp4
    

    UPDATE

    As @LordNeckbeard mentioned, the previous line will produce MPEG-4 Part 2 (back in 2012 that worked somehow, I don't remember/understand why). Use the libx264 encoder to produce the proper video with H.264/AAC. To test the output file you can just drag it to a browser window and it should playback just fine.

    ffmpeg -i input.flv -vcodec libx264 -acodec aac output.mp4

    How to append something to an array?

    If you know the highest index (such as stored in a variable "i") then you can do

    myArray[i + 1] = someValue;
    

    However if you don't know then you can either use

    myArray.push(someValue);
    

    as other answers suggested, or you can use

    myArray[myArray.length] = someValue; 
    

    Note that the array is zero based so .length return the highest index plus one.

    Also note that you don't have to add in order and you can actually skip values, as in

    myArray[myArray.length + 1000] = someValue;
    

    In which case the values in between will have a value of undefined.

    It is therefore a good practice when looping through a JavaScript to verify that a value actually exists at that point.

    This can be done by something like the following:

    if(myArray[i] === "undefined"){ continue; }
    

    if you are certain that you don't have any zeros in the array then you can just do:

    if(!myArray[i]){ continue; }
    

    Of course make sure in this case that you don't use as the condition myArray[i] (as some people over the internet suggest based on the end that as soon as i is greater then the highest index it will return undefined which evaluates to false)

    addEventListener in Internet Explorer

    addEventListener is the proper DOM method to use for attaching event handlers.

    Internet Explorer (up to version 8) used an alternate attachEvent method.

    Internet Explorer 9 supports the proper addEventListener method.

    The following should be an attempt to write a cross-browser addEvent function.

    function addEvent(evnt, elem, func) {
       if (elem.addEventListener)  // W3C DOM
          elem.addEventListener(evnt,func,false);
       else if (elem.attachEvent) { // IE DOM
          elem.attachEvent("on"+evnt, func);
       }
       else { // No much to do
          elem["on"+evnt] = func;
       }
    }
    

    Append key/value pair to hash with << in Ruby

    Perhaps you want Hash#merge ?

    1.9.3p194 :015 > h={}
     => {} 
    1.9.3p194 :016 > h.merge(:key => 'bar')
     => {:key=>"bar"} 
    1.9.3p194 :017 > 
    

    If you want to change the array in place use merge!

    1.9.3p194 :016 > h.merge!(:key => 'bar')
     => {:key=>"bar"} 
    

    fcntl substitute on Windows

    The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

    In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

    There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

    If you provide more details about the fcntl calls people can find windows equivalents.

    Escaping double quotes in JavaScript onClick event handler

    While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:

    <script type="text/javascript">
    function parse(a, b, c) {
        alert(c);
      }
    
    </script>
    
    <a href="#x" onclick="parse('#', false, 'xyc&quot;foo');return false;">Test</a>
    

    The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..

    Basic http file downloading and saving to disk in python?

    A clean way to download a file is:

    import urllib
    
    testfile = urllib.URLopener()
    testfile.retrieve("http://randomsite.com/file.gz", "file.gz")
    

    This downloads a file from a website and names it file.gz. This is one of my favorite solutions, from Downloading a picture via urllib and python.

    This example uses the urllib library, and it will directly retrieve the file form a source.

    div inside php echo

    You can do the following:

    echo '<div class="my_class">';
    echo ($cart->count_product > 0) ? $cart->count_product : '';
    echo '</div>';
    

    If you want to have it inside your statement, do this:

    if($cart->count_product > 0) 
    {
        echo '<div class="my_class">'.$cart->count_product.'</div>';
    }
    

    You don't need the else statement, since you're only going to output the above when it's truthy anyway.

    Mongoose and multiple database in single node.js project

    One thing you can do is, you might have subfolders for each projects. So, install mongoose in that subfolders and require() mongoose from own folders in each sub applications. Not from the project root or from global. So one sub project, one mongoose installation and one mongoose instance.

    -app_root/
    --foo_app/
    ---db_access.js
    ---foo_db_connect.js
    ---node_modules/
    ----mongoose/
    --bar_app/
    ---db_access.js
    ---bar_db_connect.js
    ---node_modules/
    ----mongoose/
    

    In foo_db_connect.js

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/foo_db');
    module.exports = exports = mongoose;
    

    In bar_db_connect.js

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/bar_db');
    module.exports = exports = mongoose;
    

    In db_access.js files

    var mongoose = require("./foo_db_connect.js"); // bar_db_connect.js for bar app
    

    Now, you can access multiple databases with mongoose.

    Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

    Just had a very similar problem and solved it by adding

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    

    Apparently the site I'm fetching redirects to another location and php-curl doesn't follow redirects by default.

    Checking if a folder exists using a .bat file

    I think the answer is here (possibly duplicate):

    How to test if a file is a directory in a batch script?

    IF EXIST %VAR%\NUL ECHO It's a directory
    

    Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

    As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

    if exist "c:\folder\" echo folder exists 
    

    should be enough for modern windows.

    How do I make a JAR from a .java file?

    Often you will want to specify a manifest, like so:

    jar -cvfm myJar.jar myManifest.txt myApp.class
    

    Which reads: "create verbose jarFilename manifestFilename", followed by the files you want to include. Verbose means print messages about what it's doing.

    Note that the name of the manifest file you supply can be anything, as jar will automatically rename it and put it into the right directory within the jar file.

    Copying an array of objects into another array in javascript

    If you want to keep reference:

    Array.prototype.push.apply(destinationArray, sourceArray);

    Java getting the Enum name given the Enum Value

    Here is the below code, it will return the Enum name from Enum value.

    public enum Test {
    
        PLUS("Plus One"), MINUS("MinusTwo"), TIMES("MultiplyByFour"), DIVIDE(
                "DivideByZero");
        private String operationName;
    
        private Test(final String operationName) {
            setOperationName(operationName);
        }
    
        public String getOperationName() {
            return operationName;
        }
    
        public void setOperationName(final String operationName) {
            this.operationName = operationName;
        }
    
        public static Test getOperationName(final String operationName) {
    
            for (Test oprname : Test.values()) {
                if (operationName.equals(oprname.toString())) {
                    return oprname;
                }
            }
            return null;
        }
    
        @Override
        public String toString() {
            return operationName;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Test test = Test.getOperationName("Plus One");
            switch (test) {
            case PLUS:
                System.out.println("Plus.....");
                break;
            case MINUS:
                System.out.println("Minus.....");
                break;
    
            default:
                System.out.println("Nothing..");
                break;
            }
        }
    }
    

    How to force uninstallation of windows service

    Just in case this answer helps someone: as found here, you might save yourself a lot of trouble running Sysinternals Autoruns as administrator. Just go to the "Services" tab and delete your service.

    It did the trick for me on a machine where I didn't have any permission to edit the registry.

    How to get form input array into PHP array

    E.g. by naming the fields like

    <input type="text" name="item[0][name]" />
    <input type="text" name="item[0][email]" />
    
    <input type="text" name="item[1][name]" />
    <input type="text" name="item[1][email]" />
    
    <input type="text" name="item[2][name]" />
    <input type="text" name="item[2][email]" />
    

    (which is also possible when adding elements via javascript)

    The corresponding php script might look like

    function show_Names($e)
    {
      return "The name is $e[name] and email is $e[email], thank you";
    }
    
    $c = array_map("show_Names", $_POST['item']);
    print_r($c);
    

    Mysql command not found in OS X 10.7

    If you installed MySQL Server and you still get

    mysql -u root -p command not found
    

    You're most likely experiencing this because you have an older mac version.

    Try this:

    in the home directory in terminal open -t .bash_profile

    paste export PATH=${PATH}:/usr/local/mysql/bin/ inside and save it

    instead of writing mysql -u root -p paste the following in your terminal:

    /usr/local/mysql/bin/mysql -u root -p 
    

    Enter your password. Now you're in.

    How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

    double doubleVal = 1.745;
    double doubleVal1 = 0.745;
    System.out.println(new BigDecimal(doubleVal));
    System.out.println(new BigDecimal(doubleVal1));
    

    outputs:

    1.74500000000000010658141036401502788066864013671875
    0.74499999999999999555910790149937383830547332763671875
    

    Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).

    More about double precision:

    How can I dynamically add a directive in AngularJS?

    The accepted answer by Josh David Miller works great if you are trying to dynamically add a directive that uses an inline template. However if your directive takes advantage of templateUrl his answer will not work. Here is what worked for me:

    .directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
        return {
            restrict: 'E',
            replace: true,
            scope: {}, 
            templateUrl: "app/views/modal.html",
            link: function (scope, element, attrs) {
                scope.modalTitle = attrs.modaltitle;
                scope.modalContentDirective = attrs.modalcontentdirective;
            },
            controller: function ($scope, $element, $attrs) {
                if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
                    var el = $compile($attrs.modalcontentdirective)($scope);
                    $timeout(function () {
                        $scope.$digest();
                        $element.find('.modal-body').append(el);
                    }, 0);
                }
            }
        }
    }]);
    

    Call function with setInterval in jQuery?

    setInterval(function() {
        updatechat();
    }, 2000);
    
    function updatechat() {
        alert('hello world');
    }
    

    Is there a timeout for idle PostgreSQL connections?

    It sounds like you have a connection leak in your application because it fails to close pooled connections. You aren't having issues just with <idle> in transaction sessions, but with too many connections overall.

    Killing connections is not the right answer for that, but it's an OK-ish temporary workaround.

    Rather than re-starting PostgreSQL to boot all other connections off a PostgreSQL database, see: How do I detach all other users from a postgres database? and How to drop a PostgreSQL database if there are active connections to it? . The latter shows a better query.

    For setting timeouts, as @Doon suggested see How to close idle connections in PostgreSQL automatically?, which advises you to use PgBouncer to proxy for PostgreSQL and manage idle connections. This is a very good idea if you have a buggy application that leaks connections anyway; I very strongly recommend configuring PgBouncer.

    A TCP keepalive won't do the job here, because the app is still connected and alive, it just shouldn't be.

    In PostgreSQL 9.2 and above, you can use the new state_change timestamp column and the state field of pg_stat_activity to implement an idle connection reaper. Have a cron job run something like this:

    SELECT pg_terminate_backend(pid)
        FROM pg_stat_activity
        WHERE datname = 'regress'
          AND pid <> pg_backend_pid()
          AND state = 'idle'
          AND state_change < current_timestamp - INTERVAL '5' MINUTE;
    

    In older versions you need to implement complicated schemes that keep track of when the connection went idle. Do not bother; just use pgbouncer.

    maven command line how to point to a specific settings.xml for a single command?

    You can simply use:

    mvn --settings YourOwnSettings.xml clean install
    

    or

    mvn -s YourOwnSettings.xml clean install
    

    MySQL maximum memory usage

    in /etc/my.cnf:

    [mysqld]
    ...
    
    performance_schema = 0
    
    table_cache = 0
    table_definition_cache = 0
    max-connect-errors = 10000
    
    query_cache_size = 0
    query_cache_limit = 0
    
    ...
    

    Good work on server with 256MB Memory.

    How to force R to use a specified factor level as reference in a regression?

    For those looking for a dplyr/tidyverse version. Building on Gavin Simpson solution:

    # Create DF
    set.seed(123)
    x <- rnorm(100)
    DF <- data.frame(x = x,
                     y = 4 + (1.5*x) + rnorm(100, sd = 2),
                     b = gl(5, 20))
    
    # Change reference level
    DF = DF %>% mutate(b = relevel(b, 3))
    
    m2 <- lm(y ~ x + b, data = DF)
    summary(m2)
    

    C: What is the difference between ++i and i++?

    Pre-crement means increment on the same line. Post-increment means increment after the line executes.

    int j=0;
    System.out.println(j); //0
    System.out.println(j++); //0. post-increment. It means after this line executes j increments.
    
    int k=0;
    System.out.println(k); //0
    System.out.println(++k); //1. pre increment. It means it increments first and then the line executes
    

    When it comes with OR, AND operators, it becomes more interesting.

    int m=0;
    if((m == 0 || m++ == 0) && (m++ == 1)) { //false
    /* in OR condition if first line is already true then compiler doesn't check the rest. It is technique of compiler optimization */
    System.out.println("post-increment "+m);
    }
    
    int n=0;
    if((n == 0 || n++ == 0) && (++n == 1)) { //true
    System.out.println("pre-increment "+n); //1
    }
    

    In Array

    System.out.println("In Array");
    int[] a = { 55, 11, 15, 20, 25 } ;
    int ii, jj, kk = 1, mm;
    ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
    System.out.println(a[1]); //12
    
    jj = a[1]++; //12
    System.out.println(a[1]); //a[1] = 13
    
    mm = a[1];//13
    System.out.printf ( "\n%d %d %d\n", ii, jj, mm ) ; //12, 12, 13
    
    for (int val: a) {
         System.out.print(" " +val); //55, 13, 15, 20, 25
    }
    

    In C++ post/pre-increment of pointer variable

    #include <iostream>
    using namespace std;
    
    int main() {
    
        int x=10;
        int* p = &x;
    
        std::cout<<"address = "<<p<<"\n"; //prints address of x
        std::cout<<"address = "<<p<<"\n"; //prints (address of x) + sizeof(int)
        std::cout<<"address = "<<&x<<"\n"; //prints address of x
    
        std::cout<<"address = "<<++&x<<"\n"; //error. reference can't re-assign because it is fixed (immutable)
    }
    

    Pandas - 'Series' object has no attribute 'colNames' when using apply()

    When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

    So this should work:

    df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 
    

    How to shut down the computer from C#

    There is no .net native method for shutting off the computer. You need to P/Invoke the ExitWindows or ExitWindowsEx API call.

    DateTime.TryParseExact() rejecting valid formats

    Here you can check for couple of things.

    1. Date formats you are using correctly. You can provide more than one format for DateTime.TryParseExact. Check the complete list of formats, available here.
    2. CultureInfo.InvariantCulture which is more likely add problem. So instead of passing a NULL value or setting it to CultureInfo provider = new CultureInfo("en-US"), you may write it like. .

      if (!DateTime.TryParseExact(txtStartDate.Text, formats, 
                      System.Globalization.CultureInfo.InvariantCulture,
                      System.Globalization.DateTimeStyles.None, out startDate))
      {
          //your condition fail code goes here
          return false;
      }
      else
      {
          //success code
      }
      

    How do I purge a linux mail box with huge number of emails?

    On UNIX / Linux / Mac OS X you can copy and override files, can't you? So how about this solution:

    cp /dev/null /var/mail/root
    

    Uninstall Django completely

    I used the same method mentioned by @S-T after the pip uninstall command. And even after that the I got the message that Django was already installed. So i deleted the 'Django-1.7.6.egg-info' folder from '/usr/lib/python2.7/dist-packages' and then it worked for me.

    How to draw rounded rectangle in Android UI?

    Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.

    Assign static IP to Docker container

    I stumbled upon this problem during attempt to dockerise Avahi which needs to be aware of its public IP to function properly. Assigning static IP to the container is tricky due to lack of support for static IP assignment in Docker.

    This article describes technique how to assign static IP to the container on Debian:

    1. Docker service should be started with DOCKER_OPTS="--bridge=br0 --ip-masq=false --iptables=false". I assume that br0 bridge is already configured.

    2. Container should be started with --cap-add=NET_ADMIN --net=bridge

    3. Inside container pre-up ip addr flush dev eth0 in /etc/network/interfaces can be used to dismiss IP address assigned by Docker as in following example:


    auto lo
    iface lo inet loopback
    
    auto eth0
    iface eth0 inet static
        pre-up ip addr flush dev eth0
        address 192.168.0.249
        netmask 255.255.255.0
        gateway 192.168.0.1
    
    1. Container's entry script should begin with /etc/init.d/networking start. Also entry script needs to edit or populate /etc/hosts file in order to remove references to Docker-assigned IP.

    Convert java.util.Date to String

    Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String s = formatter.format(date);
    

    fatal: Not a git repository (or any of the parent directories): .git

    The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

    1. Are you in the right directory? Does typing ls show the right files?
    2. Have you initialized the repository yet? Typed git init? (git-init documentation)

    Either of those would cause your error.

    HTTP 404 when accessing .svc file in IIS

    There are 2 .net framework version are given under the features in add role/ features in server 2012

    a. 3.5

    b. 4.5

    Depending up on used framework you can enable HTTP-Activation under WCF services. :)

    Why is Android Studio reporting "URI is not registered"?

    Try to Install the android tracker plugin. you will find it on the studio.

    Restart the studio

    What is the string concatenation operator in Oracle?

    It is ||, for example:

    select 'Mr ' || ename from emp;
    

    The only "interesting" feature I can think of is that 'x' || null returns 'x', not null as you might perhaps expect.

    Can we have multiple "WITH AS" in single sql - Oracle SQL

    the correct syntax is -

    with t1
    as
    (select * from tab1
    where conditions...
    ),
    t2
    as
    (select * from tab2
    where conditions...
    (you can access columns of t1 here as well)
    )
    select * from t1, t2
    where t1.col1=t2.col2;
    

    How to create/read/write JSON files in Qt5

    Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.

    So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:

    value x(ctx);
    x["appDesc"]["description"] = "SomeDescription";
    x["appDesc"]["message"] = "SomeMessage";
    x["appName"]["description"] = "Home";
    x["appName"]["message"] = "Welcome";
    x["appName"]["imp"][0] = "awesome";
    x["appName"]["imp"][1] = "best";
    x["appName"]["imp"][2] = "good";
    std::cout << x << std::endl;
    

    and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL as needed):

    value x(ctx);
    std::cin >> x;
    if (x.soap->error)
      exit(EXIT_FAILURE); // error parsing JSON
    #define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
    if (x.has("appDesc"))
    {
      if (x["appDesc"].has("description"))
        USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
      if (x["appDesc"].has("message"))
        USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
    }
    if (x.has("appName"))
    {
      if (x["appName"].has("description"))
        USE_VAL("$.appName.description", x["appName"]["description"]);
      if (x["appName"].has("message"))
        USE_VAL("$.appName.message", x["appName"]["message"]);
      if (x["appName"].has("imp"))
      {
        for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
          USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
      }
    }
    

    This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.

    Regex for empty string or white space

    http://jsfiddle.net/DqGB8/1/

    This is my solution

    var error=0;
    var test = [" ", "   "];
     if(test[0].match(/^\s*$/g)) {
         $("#output").html("MATCH!");
         error+=1;
     } else {
         $("#output").html("no_match");
     }
    

    SQL Server Configuration Manager not found

    For SQL Server 2017 it is : C:\Windows\SysWOW64\SQLServerManager14.msc

    For SQL Server 2016 it is : C:\Windows\SysWOW64\SQLServerManager13.msc

    For SQL Server 2016 it is :C:\Windows\SysWOW64\SQLServerManager12.msc

    and to add it back to the start menu, copy it from the original location provided above and paste it to

    C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft SQL Server 2017\Configuration Tools\
    

    This would put back the configuration manager under start menu.

    Source: How to open sql server configuration manager in windows 10?

    Digital Certificate: How to import .cer file in to .truststore file using?

    Instead of using sed to filter out the certificate, you can also pipe the openssl s_client output through openssl x509 -out certfile.txt, for example:

    echo "" | openssl s_client -connect my.server.com:443 -showcerts 2>/dev/null | openssl x509 -out certfile.txt
    

    How to empty a Heroku database

    This is what worked for me.

    1.clear db.

    heroku pg:reset --app YOUR_APP
    

    After running that you will have to type in your app name again to confirm.

    2.migrate db to recreate.

    heroku run rake db:migrate  --app YOUR_APP
    

    3.add seed data to db.

    heroku run rake db:seed --app YOUR_APP
    

    How to install python developer package?

    For me none of the packages mentioned above did help.

    I finally managed to install lxml after running:

    sudo apt-get install python3.5-dev
    

    Subtract days, months, years from a date in JavaScript

    You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.

    You need to individually add/remove unit of time in date object

    var date = new Date();
    date.setDate( date.getDate() - 6 );
    date.setFullYear( date.getFullYear() - 1 );
    $("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));
    

    Algorithm to generate all possible permutations of a list?

    Here's an implementation for ColdFusion (requires CF10 because of the merge argument to ArrayAppend() ):

    public array function permutateArray(arr){
    
        if (not isArray(arguments.arr) ) {
            return ['The ARR argument passed to the permutateArray function is not of type array.'];    
        }
    
        var len = arrayLen(arguments.arr);
        var perms = [];
        var rest = [];
        var restPerms = [];
        var rpLen = 0;
        var next = [];
    
        //for one or less item there is only one permutation 
        if (len <= 1) {
            return arguments.arr;
        }
    
        for (var i=1; i <= len; i++) {
            // copy the original array so as not to change it and then remove the picked (current) element
            rest = arraySlice(arguments.arr, 1);
            arrayDeleteAt(rest, i);
    
             // recursively get the permutation of the rest of the elements
             restPerms = permutateArray(rest);
             rpLen = arrayLen(restPerms);
    
            // Now concat each permutation to the current (picked) array, and append the concatenated array to the end result
            for (var j=1; j <= rpLen; j++) {
                // for each array returned, we need to make a fresh copy of the picked(current) element array so as to not change the original array
                next = arraySlice(arguments.arr, i, 1);
                arrayAppend(next, restPerms[j], true);
                arrayAppend(perms, next);
            }
         }
    
        return perms;
    }
    

    Based on KhanSharp's js solution above.

    "The specified Android SDK Build Tools version (26.0.0) is ignored..."

    Update to Android Studio 3.0.1 which treats these as warnings. Android 3.0 was treating such warnings as errors and hence causing the gradle sync operation to fail.

    Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

    You can set environment variables in the notebook using os.environ. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.

    import os
    os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"   # see issue #152
    os.environ["CUDA_VISIBLE_DEVICES"]="0"
    

    You can double check that you have the correct devices visible to TF

    from tensorflow.python.client import device_lib
    print device_lib.list_local_devices()
    

    I tend to use it from utility module like notebook_util

    import notebook_util
    notebook_util.pick_gpu_lowest_memory()
    import tensorflow as tf
    

    Escape Character in SQL Server

    WHERE username LIKE '%[_]d';            -- @Lasse solution
    WHERE username LIKE '%$_d' ESCAPE '$';
    WHERE username LIKE '%^_d' ESCAPE '^';
    

    FROM: SQL Server Escape an Underscore

    ImportError: No module named 'encodings'

    I was facing the same problem under Windows7. The error message looks like that:

    Fatal Python error: Py_Initialize: unable to load the file system codec
    ModuleNotFoundError: No module named 'encodings'
    
    Current thread 0x000011f4 (most recent call first):
    

    I have installed python 2.7(uninstalled now), and I checked "Add Python to environment variables in Advanced Options" while installing python 3.6. It comes out that the Environment Variable "PYTHONHOME" and "PYTHONPATH" is still python2.7.

    Finally I solved it by modify "PYTHONHOME" to python3.6 install path and remove variable "PYTHONPATH".