Programs & Examples On #Evaluation

Anything related to evaluation of expressions, i.e. the process used to determine the value of expressions in a running program.

How does a ArrayList's contains() method evaluate objects?

The ArrayList uses the equals method implemented in the class (your case Thing class) to do the equals comparison.

What is the Difference Between read() and recv() , and Between send() and write()?

Per the first hit on Google

read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.

How to set True as default value for BooleanField on Django?

In DJango 3.0 the default value of a BooleanField in model.py is set like this:

class model_name(models.Model):
example_name = models.BooleanField(default=False)

How to make inline plots in Jupyter Notebook larger?

A quick fix to "plot overlap" is to use plt.tight_layout():

Example (in my case)

for i,var in enumerate(categorical_variables):
    plt.title(var)
    plt.xticks(rotation=45)
    df[var].hist()
    plt.subplot(len(categorical_variables)/2, 2, i+1)

plt.tight_layout()

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

This is for Visual Studio 2019, After trying a lot of suggestions that failed to work (including changing the port number etc) I solved my problem by deleting a file that was generated on my project's root folder called "debug". As soon as this file was deleted everything started working.

How to fill Matrix with zeros in OpenCV?

Mat img;

img=Mat::zeros(size of image,CV_8UC3);

if you want it to be of an image img1

img=Mat::zeros(img1.size,CV_8UC3);

How can I dynamically add a directive in AngularJS?

You have a lot of pointless jQuery in there, but the $compile service is actually super simple in this case:

.directive( 'test', function ( $compile ) {
  return {
    restrict: 'E',
    scope: { text: '@' },
    template: '<p ng-click="add()">{{text}}</p>',
    controller: function ( $scope, $element ) {
      $scope.add = function () {
        var el = $compile( "<test text='n'></test>" )( $scope );
        $element.parent().append( el );
      };
    }
  };
});

You'll notice I refactored your directive too in order to follow some best practices. Let me know if you have questions about any of those.

Dialog to pick image from gallery or from camera

The code below can be used for taking a photo and for picking a photo. Just show a dialog with two options and upon selection, use the appropriate code.

To take picture from camera:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code (called requestCode)

To pick photo from gallery:

Intent pickPhoto = new Intent(Intent.ACTION_PICK,
           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code

onActivityResult code:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
    switch(requestCode) {
    case 0:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }

    break; 
    case 1:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }
    break;
    }
}

Finally add this permission in the manifest file:

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

R legend placement in a plot

Building on @P-Lapointe solution, but making it extremely easy, you could use the maximum values from your data using max() and then you re-use those maximum values to set the legend xy coordinates. To make sure you don't get beyond the borders, you set up ylim slightly over the maximum values.

a=c(rnorm(1000))
b=c(rnorm(1000))
par(mfrow=c(1,2))
plot(a,ylim=c(0,max(a)+1))
legend(x=max(a)+0.5,legend="a",pch=1)
plot(a,b,ylim=c(0,max(b)+1),pch=2)
legend(x=max(b)-1.5,y=max(b)+1,legend="b",pch=2)

enter image description here

Difference between app.use and app.get in express.js

app.use() is intended for binding middleware to your application. The path is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:

// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();

app.use('/subapp', require('./subapp'));

// ...

By specifying / as a "mount" path, app.use() will respond to any path that starts with /, which are all of them and regardless of HTTP verb used:

  • GET /
  • PUT /foo
  • POST /foo/bar
  • etc.

app.get(), on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:

  • GET /

And, the equivalent routing for your example of app.use() would actually be:

app.all(/^\/.*/, function (req, res) {
    res.send('Hello');
});

(Update: Attempting to better demonstrate the differences.)

The routing methods, including app.get(), are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route').

Within each app.get() is a call to app.use(), so you can certainly do all of this with app.use() directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.

Examples:

  • For simple, static routes:

    app.get('/', function (req, res) {
      // ...
    });
    

    vs.

    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      // ...
    });
    
  • With multiple handlers for the same route:

    app.get('/', authorize('ADMIN'), function (req, res) {
      // ...
    });
    

    vs.

    const authorizeAdmin = authorize('ADMIN');
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      authorizeAdmin(req, res, function (err) {
        if (err) return next(err);
    
        // ...
      });
    });
    
  • With parameters:

    app.get('/item/:id', function (req, res) {
      let id = req.params.id;
      // ...
    });
    

    vs.

    const pathToRegExp = require('path-to-regexp');
    
    function prepareParams(matches, pathKeys, previousParams) {
      var params = previousParams || {};
    
      // TODO: support repeating keys...
      matches.slice(1).forEach(function (segment, index) {
        let { name } = pathKeys[index];
        params[name] = segment;
      });
    
      return params;
    }
    
    const itemIdKeys = [];
    const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET') return next();
    
      var urlMatch = itemIdPattern.exec(req.url);
      if (!urlMatch) return next();
    
      if (itemIdKeys && itemIdKeys.length)
        req.params = prepareParams(urlMatch, itemIdKeys, req.params);
    
      let id = req.params.id;
      // ...
    });
    

Note: Express' implementation of these features are contained in its Router, Layer, and Route.

How to know installed Oracle Client is 32 bit or 64 bit?

The following, taken from here, was not mentioned here:

If the Oracle Client is 32 bit, it will contain a "lib" folder; but if it is a 64 bit Oracle Client it will have both "lib" and "lib32" folders.

Also, starting in Oracle 11.2.0.1, the client version for 64-bit and the Oracle client for 32-bit are shipped separately, and there is an $ORACLE_HOME/lib64 directory.

$ORACLE_HOME/lib/ ==> 32 bit $ORACLE_HOME/lib64 ==> 64 bit

Or

$ORACLE_HOME/lib/ ==> 64 bit $ORACLE_HOME/lib32 ==> 32 bit

How to un-commit last un-pushed git commit without losing the changes

For the case: "This has not been pushed, only committed." - if you use IntelliJ (or another JetBrains IDE) and you haven't pushed changes yet you can do next.

  1. Go to Version control window (Alt + 9/Command + 9) - "Log" tab.
  2. Right-click on a commit before your last one.
  3. Reset current branch to here
  4. pick Soft (!!!)
  5. push the Reset button in the bottom of the dialog window.

Done.

This will "uncommit" your changes and return your git status to the point before your last local commit. You will not lose any changes you made.

Convert Pandas Series to DateTime in a DataFrame

df=pd.read_csv("filename.csv" , parse_dates=["<column name>"])

type(df.<column name>)

example: if you want to convert day which is initially a string to a Timestamp in Pandas

df=pd.read_csv("weather_data2.csv" , parse_dates=["day"])

type(df.day)

The output will be pandas.tslib.Timestamp

LINQ: Select an object and change some properties without creating a new object

We often run into this where we want to include a the index value and first and last indicators in a list without creating a new object. This allows you to know the position of the item in your list, enumeration, etc. without having to modify the existing class and then knowing whether you're at the first item in the list or the last.

foreach (Item item in this.Items
    .Select((x, i) => {
    x.ListIndex = i;
    x.IsFirst = i == 0;
    x.IsLast = i == this.Items.Count-1;
    return x;
}))

You can simply extend any class by using:

public abstract class IteratorExtender {
    public int ListIndex { get; set; }
    public bool IsFirst { get; set; } 
    public bool IsLast { get; set; } 
}

public class Item : IteratorExtender {}

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

Have you tried to cast it to a date, with <mydatetime>::date ?

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

I was having a similar issue with a property being null or undefined.

This ended up being that IE's document mode was being defaulted to IE7 Standards. This was due to the compatibility mode being automatically set to be used for all intranet sites (Tools > Compatibility View Setting > Display Intranet Sites in Compatibility View).

Bootstrap Modal Backdrop Remaining

try this

$('.modal').on('hide.bs.modal', function () {
    if ($(this).is(':visible')) {
       console.log("show modal")
       $('.modal-backdrop').show();
    }else{
        console.log("hidden modal");
        $('.modal-backdrop').remove();
    }
})

The difference between the Runnable and Callable interfaces in Java

It is a kind of an interface naming convention which matches with functional programming

//Runnable
interface Runnable {
    void run();
}

//Action - throws exception
interface Action {
    void run() throws Exception;
}

//Consumer - consumes a value/values, throws exception
interface Consumer1<T> {
    void accept(T t) throws Exception;
}

//Callable - return result, throws exception
interface Callable<R> {
    R call() throws Exception;
}

//Supplier - returns result, throws exception
interface Supplier<R> {
    R get() throws Exception;
}

//Predicate - consumes a value/values, returns true or false, throws exception
interface Predicate1<T> {
    boolean test(T t) throws Exception;
}

//Function - consumes a value/values, returns result, throws exception
public interface Function1<T, R> {
    R apply(T t) throws Exception;
}

...

php - How do I fix this illegal offset type error

Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.

Example:

$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type

Your $xml array contains an object or array at $xml->entry[$i]->source for some value of $i, and when you try to use that as an index key for $s, you get that warning. You'll have to make sure $xml contains what you want it to and that you're accessing it correctly.

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

Date difference in years using C#

int Age = new DateTime((DateTime.Now - BirthDateTime).Ticks).Year;

To calculate the elapsed years (age), the result will be minus one.

var timeSpan = DateTime.Now - birthDateTime;
int age = new DateTime(timeSpan.Ticks).Year - 1;

How can I add new dimensions to a Numpy array?

Pythonic

X = X[:, :, None]

which is equivalent to

X = X[:, :, numpy.newaxis] and X = numpy.expand_dims(X, axis=-1)

But as you are explicitly asking about stacking images, I would recommend going for stacking the list of images np.stack([X1, X2, X3]) that you may have collected in a loop.

If you do not like the order of the dimensions you can rearrange with np.transpose()

"java.lang.OutOfMemoryError : unable to create new native Thread"

This is not a memory problem even though the exception name highly suggests so, but an operating system resource problem. You are running out of native threads, i.e. how many threads the operating system will allow your JVM to use.

This is an uncommon problem, because you rarely need that many. Do you have a lot of unconditional thread spawning where the threads should but doesn't finish?

You might consider rewriting into using Callable/Runnables under the control of an Executor if at all possible. There are plenty of standard executors with various behavior which your code can easily control.

(There are many reasons why the number of threads is limited, but they vary from operating system to operating system)

PDO's query vs execute

No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:

$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).

Activate tabpage of TabControl

You can use the method SelectTab.

There are 3 versions:

public void SelectTab(int index);
public void SelectTab(string tabPageName);
public void SelectTab(TabPage tabPage);

Alternate table with new not null Column in existing table in SQL

IF NOT EXISTS (SELECT 1
FROM syscolumns sc
JOIN sysobjects so
ON sc.id = so.id
WHERE so.Name = 'Table1'
AND sc.Name = 'Col1')
BEGIN
ALTER TABLE Table1
ADD Col1 INT NOT NULL DEFAULT 0;
END
GO

log4j: Log output of a specific class to a specific appender

An example:

log4j.rootLogger=ERROR, logfile

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false

log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

Open Facebook page from Android app?

Declare constants

  private String FACEBOOK_URL="https://www.facebook.com/approids";
    private String FACEBOOK_PAGE_ID="approids";

Declare Method

public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

            boolean activated =  packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
            if(activated){
                if ((versionCode >= 3002850)) {
                    Log.d("main","fb first url");
                    return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
                } else {
                    return "fb://page/" + FACEBOOK_PAGE_ID;
                }
            }else{
                return FACEBOOK_URL;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL;
        }
    }

Call Function

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
                String facebookUrl = getFacebookPageURL(MainActivity.this);
                facebookIntent.setData(Uri.parse(facebookUrl));
                startActivity(facebookIntent);

Get selected value of a dropdown's item using jQuery

Or if you would try :

$("#foo").find("select[name=bar]").val();

I used It today and It working fine.

Difference between res.send and res.json in Express.js

https://github.com/visionmedia/express/blob/ee228f7aea6448cf85cc052697f8d831dce785d5/lib/response.js#L174

res.json eventually calls res.send, but before that it:

  • respects the json spaces and json replacer app settings
  • ensures the response will have utf8 charset and application/json content-type

How to prevent vim from creating (and leaving) temporary files?

On Windows add following lines to _vimrc

" store backup, undo, and swap files in temp directory
set directory=$HOME/temp//
set backupdir=$HOME/temp//
set undodir=$HOME/temp//

auto refresh for every 5 mins

Page should be refresh auto using meta tag

<meta http-equiv="Refresh" content="60"> 

content value in seconds.after one minute page should be refresh

How do I check if a string is a number (float)?

Which, not only is ugly and slow

I'd dispute both.

A regex or other string parsing method would be uglier and slower.

I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

The issue is that any numeric conversion function has two kinds of results

  • A number, if the number is valid
  • A status code (e.g., via errno) or exception to show that no valid number could be parsed.

C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

I think your code for doing this is perfect.

ngFor with index as value in attribute

Try this

<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>

Sending mail from Python using SMTP

The example code which i did for send mail using SMTP.

import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "sender@email"
receiver_email = "receiver@email"
password = "<your password here>"
message = """ Subject: Hi there

This message is sent from Python."""


# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
server = smtplib.SMTP(smtp_server,port)

try:
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit()

How to remove extension from string (only real extension!)

Landed on this page for looking for the fastest way to remove the extension from a number file names from a glob() result.

So I did some very rudimentary benchmark tests and found this was the quickest method. It was less than half the time of preg_replace():

$result = substr($fileName,0,-4);

Now I know that all of the files in my glob() have a .zip extension, so I could do this.

If the file extension is unknown with an unknown length, the following method will work and is still about 20% faster that preg_replace(). That is, so long as there is an extension.

$result = substr($fileName,0,strrpos($fileName,'.'));

The basic benchmark test code and the results:

$start = microtime(true);

$loop = 10000000;
$fileName = 'a.LONG-filename_forTest.zip';
$result;

// 1.82sec preg_replace() unknown ext
//do {
//    $result = preg_replace('/\\.[^.\\s]{3,4}$/','',$fileName);
//} while(--$loop);

// 1.7sec preg_replace() known ext
//do {
//    $result = preg_replace('/.zip$/','',$fileName);
//} while(--$loop);

// 4.57sec! - pathinfo
//do {
//    $result = pathinfo($fileName,PATHINFO_FILENAME);
//} while(--$loop);

// 2.43sec explode and implode
//do {
//    $result = implode('.',explode('.',$fileName,-1));
//} while(--$loop);

// 3.74sec basename, known ext
//do {
//    $result = basename($fileName,'.zip');
//} while(--$loop);

// 1.45sec strpos unknown ext
//do {
//    $result = substr($fileName,0,strrpos($fileName,'.'));
//} while(--$loop);

// 0.73sec strpos - known ext length
do {
    $result = substr($fileName,0,-4);
} while(--$loop);

var_dump($fileName);
var_dump($result);
echo 'Time:['.(microtime(true) - $start).']';

exit;

How to move (and overwrite) all files from one directory to another?

mv -f source target

From the man page:

-f, --force
          do not prompt before overwriting

How to find cube root using Python?

You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

def is_perfect_cube(x):
    x = abs(x)
    return int(round(x ** (1. / 3))) ** 3 == x

print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
                                   # handles this correctly

This takes the cube root of x, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x.

The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).

how to open *.sdf files?

If you simply need to view the table and run queries on it you can use this third party sdf viewer. It is a lightweight viewer that has all the basic functionalities and is ready to use after install.

and ofcourse, its Free.

Executing a command stored in a variable from PowerShell

Try invoking your command with Invoke-Expression:

Invoke-Expression $cmd1

Here is a working example on my machine:

$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd

iex is an alias for Invoke-Expression so you could do:

iex $cmd1

For a full list : Visit https://ss64.com/ps/ for more Powershell stuff.

Good Luck...

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

Or if you dont know the url, you can use

hadoop fs -rm -r -f /user/the/path/to/your/dir

Does static constexpr variable inside a function make sense?

In addition to given answer, it's worth noting that compiler is not required to initialize constexpr variable at compile time, knowing that the difference between constexpr and static constexpr is that to use static constexpr you ensure the variable is initialized only once.

Following code demonstrates how constexpr variable is initialized multiple times (with same value though), while static constexpr is surely initialized only once.

In addition the code compares the advantage of constexpr against const in combination with static.

#include <iostream>
#include <string>
#include <cassert>
#include <sstream>

const short const_short = 0;
constexpr short constexpr_short = 0;

// print only last 3 address value numbers
const short addr_offset = 3;

// This function will print name, value and address for given parameter
void print_properties(std::string ref_name, const short* param, short offset)
{
    // determine initial size of strings
    std::string title = "value \\ address of ";
    const size_t ref_size = ref_name.size();
    const size_t title_size = title.size();
    assert(title_size > ref_size);

    // create title (resize)
    title.append(ref_name);
    title.append(" is ");
    title.append(title_size - ref_size, ' ');

    // extract last 'offset' values from address
    std::stringstream addr;
    addr << param;
    const std::string addr_str = addr.str();
    const size_t addr_size = addr_str.size();
    assert(addr_size - offset > 0);

    // print title / ref value / address at offset
    std::cout << title << *param << " " << addr_str.substr(addr_size - offset) << std::endl;
}

// here we test initialization of const variable (runtime)
void const_value(const short counter)
{
    static short temp = const_short;
    const short const_var = ++temp;
    print_properties("const", &const_var, addr_offset);

    if (counter)
        const_value(counter - 1);
}

// here we test initialization of static variable (runtime)
void static_value(const short counter)
{
    static short temp = const_short;
    static short static_var = ++temp;
    print_properties("static", &static_var, addr_offset);

    if (counter)
        static_value(counter - 1);
}

// here we test initialization of static const variable (runtime)
void static_const_value(const short counter)
{
    static short temp = const_short;
    static const short static_var = ++temp;
    print_properties("static const", &static_var, addr_offset);

    if (counter)
        static_const_value(counter - 1);
}

// here we test initialization of constexpr variable (compile time)
void constexpr_value(const short counter)
{
    constexpr short constexpr_var = constexpr_short;
    print_properties("constexpr", &constexpr_var, addr_offset);

    if (counter)
        constexpr_value(counter - 1);
}

// here we test initialization of static constexpr variable (compile time)
void static_constexpr_value(const short counter)
{
    static constexpr short static_constexpr_var = constexpr_short;
    print_properties("static constexpr", &static_constexpr_var, addr_offset);

    if (counter)
        static_constexpr_value(counter - 1);
}

// final test call this method from main()
void test_static_const()
{
    constexpr short counter = 2;

    const_value(counter);
    std::cout << std::endl;

    static_value(counter);
    std::cout << std::endl;

    static_const_value(counter);
    std::cout << std::endl;

    constexpr_value(counter);
    std::cout << std::endl;

    static_constexpr_value(counter);
    std::cout << std::endl;
}

Possible program output:

value \ address of const is               1 564
value \ address of const is               2 3D4
value \ address of const is               3 244

value \ address of static is              1 C58
value \ address of static is              1 C58
value \ address of static is              1 C58

value \ address of static const is        1 C64
value \ address of static const is        1 C64
value \ address of static const is        1 C64

value \ address of constexpr is           0 564
value \ address of constexpr is           0 3D4
value \ address of constexpr is           0 244

value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0

As you can see yourself constexpr is initilized multiple times (address is not the same) while static keyword ensures that initialization is performed only once.

How to export JSON from MongoDB using Robomongo

Solution:

mongoexport --db test --collection traffic --out traffic.json<br><br>

enter image description here

Where:
database -> mock-server
collection name -> api_defs
output file name -> childChoreRequest.json

Delete all rows with timestamp older than x days

DELETE FROM on_search WHERE search_date < NOW() - INTERVAL N DAY

Replace N with your day count

Using the slash character in Git branch name

I forgot that I had already an unused labs branch. Deleting it solved my problem:

git branch -d labs
git checkout -b labs/feature

Explanation:

Each name can only be a parent branch or a normal branch, not both. Thats why the branches labs and labs/feature can't exists both at the same time.

The reason: Branches are stored in the file system and there you also can't have a file labs and a directory labs at the same level.

How to change pivot table data source in Excel?

Be a bit wary of any solution that doesn't involve re-creating the PivotTable from scratch. It is possible for your pivot fields' option names to get out of sync with the values they present to the database.

For example, in one workbook I'm dealing with involving demographic data, if you try to select the "20-24" age band option, Excel actually presents you with the figures for ages 25-29. It doesn't tell you it's doing this, of course.

See below for a programmatic (VBA) approach to the problem that solves this issue among others. I think it's fairly complete/robust, but I don't use PivotTables much so would appreciate feedback.

Sub SwapSources()

strOldSource = "2010 Data"
strNewSource = "2009 Data"

Dim tmpArrOut

For Each wsh In ThisWorkbook.Worksheets
    For Each pvt In wsh.PivotTables
        tmpArrIn = pvt.SourceData
        ' row 1 of SourceData is the connection string.
        ' rows 2+ are the SQL code broken down into 255-byte chunks.
        ' we need to concatenate rows 2+, replace, and then split them up again

        strSource1 = tmpArrIn(LBound(tmpArrIn))
        strSource2 = ""
        For ii = LBound(tmpArrIn) + 1 To UBound(tmpArrIn)
            strSource2 = strSource2 & tmpArrIn(ii)
        Next ii

        strSource1 = Replace(strSource1, strOldSource, strNewSource)
        strSource2 = Replace(strSource2, strOldSource, strNewSource)

        ReDim tmpArrOut(1 To Int(Len(strSource2) / 255) + 2)
        tmpArrOut(LBound(tmpArrOut)) = strSource1
        For ii = LBound(tmpArrOut) + 1 To UBound(tmpArrOut)
            tmpArrOut(ii) = Mid(strSource2, 255 * (ii - 2) + 1, 255)
        Next ii

        ' if the replacement SQL is invalid, the PivotTable object will throw an error
        Err.Clear
        On Error Resume Next
            pvt.SourceData = tmpArrOut
        On Error GoTo 0
        If Err.Number <> 0 Then
            MsgBox "Problems changing SQL for table " & wsh.Name & "!" & pvt.Name
            pvt.SourceData = tmpArrIn ' revert
        ElseIf pvt.RefreshTable <> True Then
            MsgBox "Problems refreshing table " & wsh.Name & "!" & pvt.Name
        Else
            ' table is now refreshed
            ' need to ensure that the "display name" for each pivot option matches
            ' the actual value that will be fed to the database.  It is possible for
            ' these to get out of sync.
            For Each pvf In pvt.PivotFields
                'pvf.Name = pvf.SourceName
                If Not IsError(pvf.SourceName) Then ' a broken field may have no SourceName
                    mismatches = 0
                    For Each pvi In pvf.PivotItems
                        If pvi.Name <> pvi.SourceName Then
                            mismatches = mismatches + 1
                            pvi.Name = "_mismatch" & CStr(mismatches)
                        End If
                    Next pvi
                    If mismatches > 0 Then
                        For Each pvi In pvf.PivotItems
                            If pvi.Name <> pvi.SourceName Then
                                pvi.Name = pvi.SourceName
                            End If
                        Next
                    End If
                End If
            Next pvf
        End If
    Next pvt
Next wsh

End Sub

How to create a new text file using Python

Looks like you forgot the mode parameter when calling open, try w:

file = open("copy.txt", "w") 
file.write("Your text goes here") 
file.close() 

The default value is r and will fail if the file does not exist

'r' open for reading (default)
'w' open for writing, truncating the file first

Other interesting options are

'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists

See Doc for Python2.7 or Python3.6

-- EDIT --

As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

For me, it worked as given below:

<div ng-repeat="product in products | filter: { color: 'red'||'blue' }">

<div ng-repeat="product in products | filter: { color: 'red'} | filter: { color:'blue' }">

How to convert a structure to a byte array in C#?

This example here is only applicable to pure blittable types, e.g., types that can be memcpy'd directly in C.

Example - well known 64-bit struct

[StructLayout(LayoutKind.Sequential)]  
public struct Voxel
{
    public ushort m_id;
    public byte m_red, m_green, m_blue, m_alpha, m_matid, m_custom;
}

Defined exactly like this, the struct will be automatically packed as 64-bit.

Now we can create volume of voxels:

Voxel[,,] voxels = new Voxel[16,16,16];

And save them all to a byte array:

int size = voxels.Length * 8; // Well known size: 64 bits
byte[] saved = new byte[size];
GCHandle h = GCHandle.Alloc(voxels, GCHandleType.Pinned);
Marshal.Copy(h.AddrOfPinnedObject(), saved, 0, size);
h.Free();
// now feel free to save 'saved' to a File / memory stream.

However, since the OP wants to know how to convert the struct itself, our Voxel struct can have following method ToBytes:

byte[] bytes = new byte[8]; // Well known size: 64 bits
GCHandle h = GCHandle.Alloc(this, GCHandleType.Pinned);
Marshal.Copy(hh.AddrOfPinnedObject(), bytes, 0, 8);
h.Free();

Javascript: Easier way to format numbers?

Here's the YUI version if anyone's interested:

http://developer.yahoo.com/yui/docs/YAHOO.util.Number.html

var str = YAHOO.util.Number.format(12345, { thousandsSeparator: ',' } );

How can I find out what version of git I'm running?

If you're using the command-line tools, running git --version should give you the version number.

How to convert unsigned long to string

char buffer [50];

unsigned long a = 5;

int n=sprintf (buffer, "%lu", a);

<code> vs <pre> vs <samp> for inline and block code snippets

Something I completely missed: the non-wrapping behaviour of <pre> can be controlled with CSS. So this gives the exact result I was looking for:

_x000D_
_x000D_
code { _x000D_
    background: hsl(220, 80%, 90%); _x000D_
}_x000D_
_x000D_
pre {_x000D_
    white-space: pre-wrap;_x000D_
    background: hsl(30,80%,90%);_x000D_
}
_x000D_
Here's an example demonstrating the <code>&lt;code&gt;</code> tag._x000D_
_x000D_
<pre>_x000D_
Here's a very long pre-formatted formatted using the &lt;pre&gt; tag. Notice how it wraps?  It goes on and on and on and on and on and on and on and on and on and on..._x000D_
</pre>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/9mCN7/

What is "string[] args" in Main class for?

You must have seen some application that run from the commandline and let you to pass them arguments. If you write one such app in C#, the array args serves as the collection of the said arguments.

This how you process them:

static void Main(string[] args) {
    foreach (string arg in args) {
       //Do something with each argument
    }
}

Simple if else onclick then do?

I did it that way and I like it better, but it can be optimized, right?

// Obtengo los botones y la caja de contenido
var home = document.getElementById("home");
var about = document.getElementById("about");
var service = document.getElementById("service");
var contact = document.getElementById("contact");
var content = document.querySelector("section");

function botonPress(e){
  console.log(e.getAttribute("id"));
  var screen = e.getAttribute("id");
  switch(screen){
    case "home":
      // cambiar fondo
      content.style.backgroundColor = 'black';
      break;
    case "about":
      // cambiar fondo
      content.style.backgroundColor = 'blue';
      break;
    case "service":
      // cambiar fondo
      content.style.backgroundColor = 'green';
      break;
    case "contact":
      // cambiar fondo
      content.style.backgroundColor = 'red';
      break;
  }
}

How do I position a div relative to the mouse pointer using jQuery?

var mouseX;
var mouseY;
$(document).mousemove( function(e) {
   mouseX = e.pageX; 
   mouseY = e.pageY;
});  
$(".classForHoverEffect").mouseover(function(){
  $('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});

the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,

$(".classForHoverEffect").mouseout(function(){
  $('#DivToShow').fadeOut('slow');
});

If you DIV is already positioned, you can simply use

$('.classForHoverEffect').hover(function(){
  $('#DivToShow').fadeIn('slow');
});

Also, keep in mind, your DIV style needs to be set to display:none; in order for it to fadeIn or show.

Using Spring RestTemplate in generic method with generic parameter

No, it is not a bug. It is a result of how the ParameterizedTypeReference hack works.

If you look at its implementation, it uses Class#getGenericSuperclass() which states

Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.

If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code.

So, if you use

new ParameterizedTypeReference<ResponseWrapper<MyClass>>() {}

it will accurately return a Type for ResponseWrapper<MyClass>.

If you use

new ParameterizedTypeReference<ResponseWrapper<T>>() {}

it will accurately return a Type for ResponseWrapper<T> because that is how it appears in the source code.

When Spring sees T, which is actually a TypeVariable object, it doesn't know the type to use, so it uses its default.

You cannot use ParameterizedTypeReference the way you are proposing, making it generic in the sense of accepting any type. Consider writing a Map with key Class mapped to a predefined ParameterizedTypeReference for that class.

You can subclass ParameterizedTypeReference and override its getType method to return an appropriately created ParameterizedType, as suggested by IonSpin.

Using DateTime in a SqlParameter for Stored Procedure, format error

How are you setting up the SqlParameter? You should set the SqlDbType property to SqlDbType.DateTime and then pass the DateTime directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).

You should be able to get the value into the DB. If not, here is a very simple example of how to do it:

static void Main(string[] args)
{
    // Create the connection.
    using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
    {
        // Open the connection.
        connection.Open();

        // Create the command.
        using (SqlCommand command = new SqlCommand("xsp_Test", connection))
        {
            // Set the command type.
            command.CommandType = System.Data.CommandType.StoredProcedure;

            // Add the parameter.
            SqlParameter parameter = command.Parameters.Add("@dt",
                System.Data.SqlDbType.DateTime);

            // Set the value.
            parameter.Value = DateTime.Now;

            // Make the call.
            command.ExecuteNonQuery();
        }
    }
}

I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.

If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime struct will easily do).

All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime method, not by converting to a string) to the stored procedure.

And when you get the value back, call the ToLocalTime method to get the time in the local time zone.

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

We got the same issue recently. We found out that the code is looking for the connection string named "LocalSqlServer" in the machine.confg file. We added this line and it is working fine.

Border Height on CSS

For td elements line-height will successfully allow you to resize the border-height as SPrince mentioned.

For other elements such as list items, you can control the border height with line-height and the height of the actual element with margin-top and margin-bottom.

Here is a working example of both: http://jsfiddle.net/byronj/gLcqu6mg/

An example with list items:

li { 
    list-style: none; 
    padding: 0 10px; 
    display: inline-block;
    border-right: 1px solid #000; 
    line-height: 5px; 
    margin: 20px 0; 
}

<ul>
    <li>cats</li>
    <li>dogs</li>
    <li>birds</li>
    <li>swine!</li>
</ul>

How to create an XML document using XmlDocument?

What about:

#region Using Statements
using System;
using System.Xml;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XmlDocument doc = new XmlDocument( );

        //(1) the xml declaration is recommended, but not mandatory
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore( xmlDeclaration, root );

        //(2) string.Empty makes cleaner code
        XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
        doc.AppendChild( element1 );

        XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
        element1.AppendChild( element2 );

        XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text1 = doc.CreateTextNode( "text" );
        element3.AppendChild( text1 );
        element2.AppendChild( element3 );

        XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text2 = doc.CreateTextNode( "other text" );
        element4.AppendChild( text2 );
        element2.AppendChild( element4 );

        doc.Save( "D:\\document.xml" );
    }
}

(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?


The result is:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

But I recommend you to use LINQ to XML which is simpler and more readable like here:

#region Using Statements
using System;
using System.Xml.Linq;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XDocument doc = new XDocument( new XElement( "body", 
                                           new XElement( "level1", 
                                               new XElement( "level2", "text" ), 
                                               new XElement( "level2", "other text" ) ) ) );
        doc.Save( "D:\\document.xml" );
    }
}

How to clamp an integer to some range?

This one seems more pythonic to me:

>>> def clip(val, min_, max_):
...     return min_ if val < min_ else max_ if val > max_ else val

A few tests:

>>> clip(5, 2, 7)
5
>>> clip(1, 2, 7)
2
>>> clip(8, 2, 7)
7

Assign a variable inside a Block to a variable outside a Block

Try __weak if you get any warning regarding retain cycle else use __block

Person *strongPerson = [Person new];
__weak Person *weakPerson = person;

Now you can refer weakPerson object inside block.

How to write multiple line string using Bash with variables?

The syntax (<<<) and the command used (echo) is wrong.

Correct would be:

#!/bin/bash

kernel="2.6.39"
distro="xyz"
cat >/etc/myconfig.conf <<EOL
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 
EOL

cat /etc/myconfig.conf

This construction is referred to as a Here Document and can be found in the Bash man pages under man --pager='less -p "\s*Here Documents"' bash.

How can I do a line break (line continuation) in Python?

It may not be the Pythonic way, but I generally use a list with the join function for writing a long string, like SQL queries:

query = " ".join([
    'SELECT * FROM "TableName"',
    'WHERE "SomeColumn1"=VALUE',
    'ORDER BY "SomeColumn2"',
    'LIMIT 5;'
])

What is SYSNAME data type in SQL Server?

FWIW, you can pass a table name to useful system SP's like this, should you wish to explore a database that way :

DECLARE @Table sysname; SET @Table = 'TableName';
EXEC sp_fkeys @Table;
EXEC sp_help @Table;

What is the best way to connect and use a sqlite database from C#

I've used this with great success:

http://system.data.sqlite.org/

Free with no restrictions.

(Note from review: Original site no longer exists. The above link has a link pointing the the 404 site and has all the info of the original)

--Bruce

How to remove all debug logging calls before building the release version of an Android app?

As zserge's comment suggested,

Timber is very nice, but if you already have an existing project - you may try github.com/zserge/log . It's a drop-in replacement for android.util.Log and has most of the the features that Timber has and even more.

his log library provides simple enable/disable log printing switch as below.

In addition, it only requires to change import lines, and nothing needs to change for Log.d(...); statement.

if (!BuildConfig.DEBUG)
    Log.usePrinter(Log.ANDROID, false); // from now on Log.d etc do nothing and is likely to be optimized with JIT

String field value length in mongoDB

For MongoDB 3.6 and newer:

The $expr operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP operator to check the length of the string as follows:

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] } 
})

For MongoDB 3.4 and newer:

You can also use the aggregation framework with the $redact pipeline operator that allows you to proccess the logical condition with the $cond operator and uses the special operations $$KEEP to "keep" the document where the logical condition is true or $$PRUNE to "remove" the document where the condition was false.

This operation is similar to having a $project pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match, except that $redact uses a single pipeline stage which is more efficient.

As for the logical condition, there are String Aggregation Operators that you can use $strLenCP operator to check the length of the string. If the length is $gt a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.


Consider running the following aggregate operation which demonstrates the above concept:

db.usercollection.aggregate([
    { "$match": { "name": { "$exists": true } } },
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$strLenCP": "$name" }, 40] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    },
    { "$limit": 2 }
])

If using $where, try your query without the enclosing brackets:

db.usercollection.find({$where: "this.name.length > 40"}).limit(2);

A better query would be to to check for the field's existence and then check the length:

db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2); 

or:

db.usercollection.find({name: {$exists: true}, $where: "this.name.length > 
40"}).limit(2); 

MongoDB evaluates non-$where query operations before $where expressions and non-$where query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where will be much slower compared to that. It's recommended to use JavaScript expressions and the $where operator as a last resort when you can't structure the data in any other way, or when you are dealing with a small subset of data.


A different and faster approach that avoids the use of the $where operator is the $regex operator. Consider the following pattern which searches for

db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2); 

Note - From the docs:

If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.

A regular expression is a “prefix expression” if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc.*/ will be optimized by matching only against the values from the index that start with abc.

Additionally, while /^a/, /^a.*/, and /^a.*$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however, /^a.*/, and /^a.*$/ are slower. /^a/ can stop scanning after matching the prefix.

Youtube - downloading a playlist - youtube-dl

Download YouTube playlist videos in separate directory indexed by video order in a playlist

$ youtube-dl -o '%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s'  https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re

Download all playlists of YouTube channel/user keeping each playlist in separate directory:

$ youtube-dl -o '%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' https://www.youtube.com/user/TheLinuxFoundation/playlists

Video Selection:

youtube-dl is a command-line program to download videos from YouTube.com and a few more sites. It requires the Python interpreter, version 2.6, 2.7, or 3.2+, and it is not platform specific. It should work on your Unix box, on Windows or on macOS. It is released to the public domain, which means you can modify it, redistribute it or use it however you like.

$ youtube-dl [OPTIONS] URL [URL...]
--playlist-start NUMBER          Playlist video to start at (default is 1)

--playlist-end NUMBER            Playlist video to end at (default is last)

--playlist-items ITEM_SPEC       Playlist video items to download. Specify
                                 indices of the videos in the playlist
                                 separated by commas like: "--playlist-items
                                 1,2,5,8" if you want to download videos
                                 indexed 1, 2, 5, 8 in the playlist. You can
                                 specify range: "--playlist-items
                                 1-3,7,10-13", it will download the videos
                                 at index 1, 2, 3, 7, 10, 11, 12 and 13.

Are global variables bad?

The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.

To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).

If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.

Full width image with fixed height

If you don't want to lose the ratio of your image, then don't bother with height:300px; and just use width:100%;.

If the image is too large, then you will have to crop it using an image editor.

2D arrays in Python

If you are concerned about memory footprint, the Python standard library contains the array module; these arrays contain elements of the same type.

PHPDoc type hinting for array of objects?

To specify a variable is an array of objects:

$needles = getAllNeedles();
/* @var $needles Needle[] */
$needles[1]->...                        //codehinting works

This works in Netbeans 7.2 (I'm using it)

Works also with:

$needles = getAllNeedles();
/* @var $needles Needle[] */
foreach ($needles as $needle) {
    $needle->...                        //codehinting works
}

Therefore use of declaration inside the foreach is not necessary.

How to automatically close cmd window after batch file execution?

Just try /s as listed below.

As the last line in the batch file type:

exit /s

The above command will close the Windows CMD window.

/s - stands for silent as in (it would wait for an input from the keyboard).

Rewrite all requests to index.php with nginx

Using nginx $is_args instead of ? For GET query Strings

location / { try_files $uri $uri/ /index.php$is_args$args; }

How to post data to specific URL using WebClient in C#

Here is the crisp answer:

public String sendSMS(String phone, String token) {
    WebClient webClient = WebClient.create(smsServiceUrl);

    SMSRequest smsRequest = new SMSRequest();
    smsRequest.setMessage(token);
    smsRequest.setPhoneNo(phone);
    smsRequest.setTokenId(smsServiceTokenId);

    Mono<String> response = webClient.post()
          .uri(smsServiceEndpoint)
          .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
          .body(Mono.just(smsRequest), SMSRequest.class)
          .retrieve().bodyToMono(String.class);

    String deliveryResponse = response.block();
    if (deliveryResponse.equalsIgnoreCase("success")) {
      return deliveryResponse;
    }
    return null;
}

Using an attribute of the current class instance as a default value for method's parameter

There is much more to it than you think. Consider the defaults to be static (=constant reference pointing to one object) and stored somewhere in the definition; evaluated at method definition time; as part of the class, not the instance. As they are constant, they cannot depend on self.

Here is an example. It is counterintuitive, but actually makes perfect sense:

def add(item, s=[]):
    s.append(item)
    print len(s)

add(1)     # 1
add(1)     # 2
add(1, []) # 1
add(1, []) # 1
add(1)     # 3

This will print 1 2 1 1 3.

Because it works the same way as

default_s=[]
def add(item, s=default_s):
    s.append(item)

Obviously, if you modify default_s, it retains these modifications.

There are various workarounds, including

def add(item, s=None):
    if not s: s = []
    s.append(item)

or you could do this:

def add(self, item, s=None):
    if not s: s = self.makeDefaultS()
    s.append(item)

Then the method makeDefaultS will have access to self.

Another variation:

import types
def add(item, s=lambda self:[]):
    if isinstance(s, types.FunctionType): s = s("example")
    s.append(item)

here the default value of s is a factory function.

You can combine all these techniques:

class Foo:
    import types
    def add(self, item, s=Foo.defaultFactory):
        if isinstance(s, types.FunctionType): s = s(self)
        s.append(item)

    def defaultFactory(self):
        """ Can be overridden in a subclass, too!"""
        return []

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

What is a handle in C++?

This appears in the context of the Handle-Body-Idiom, also called Pimpl idiom. It allows one to keep the ABI (binary interface) of a library the same, by keeping actual data into another class object, which is merely referenced by a pointer held in an "handle" object, consisting of functions that delegate to that class "Body".

It's also useful to enable constant time and exception safe swap of two objects. For this, merely the pointer pointing to the body object has to be swapped.

How to name and retrieve a stash by name in git?

use git stash push -m aNameForYourStash to save it. Then use git stash list to learn the index of the stash that you want to apply. Then use git stash pop --index 0 to pop the stash and apply it.

note: I'm using git version 2.21.0.windows.1

How to create timer in angular2

I faced a problem that I had to use a timer, but I had to display them in 2 component same time, same screen. I created the timerObservable in a service. I subscribed to the timer in both component, and what happened? It won't be synched, cause new subscription always creates its own stream.

What I would like to say, is that if you plan to use one timer at several places, always put .publishReplay(1).refCount() at the end of the Observer, cause it will publish the same stream out of it every time.

Example:

this.startDateTimer = Observable.combineLatest(this.timer, this.startDate$, (localTimer, startDate) => {
  return this.calculateTime(startDate);
}).publishReplay(1).refCount();

How to disable a button when an input is empty?

Another way to check is to inline the function, so that the condition will be checked on every render (every props and state change)

const isDisabled = () => 
  // condition check

This works:

<button
  type="button"
  disabled={this.isDisabled()}
>
  Let Me In
</button>

but this will not work:

<button
   type="button"
   disabled={this.isDisabled}
>
  Let Me In
</button>

How do you see recent SVN log entries?

Besides what Bert F said, many commands, including log has the -r (or --revision) option. The following are some practical examples using this option to show ranges of revisions:

To list everything in ascending order:

svn log -r 1:HEAD

To list everything in descending order:

svn log -r HEAD:1

To list everything from the thirteenth to the base of the currently checked-out revision in ascending order:

svn log -r 13:BASE

To get everything between the given dates:

svn log -r {2011-02-02}:{2011-02-03}

You can combine all the above expressions with the --limit option, so that can you have a quite granular control over what is printed. For more info about these -r expressions refer to svn help log or the relevant chapter in the book Version Control with Subversion

How to get all options in a drop-down list by Selenium WebDriver using C#?

Here is code in Java to get all options in dropdown list.

WebElement sel = myD.findElement(By.name("dropdown_name"));
List<WebElement> lists = sel.findElements(By.tagName("option"));
    for(WebElement element: lists)  
    {
        String var2 = tdElement.getText();
        System.out.println(var2);
    }

Hope it may helpful to someone.

How to delete a file or folder?

For deleting files:

os.unlink(path, *, dir_fd=None)

or

os.remove(path, *, dir_fd=None)

Both functions are semantically same. This functions removes (deletes) the file path. If path is not a file and it is directory, then exception is raised.

For deleting folders:

shutil.rmtree(path, ignore_errors=False, onerror=None)

or

os.rmdir(path, *, dir_fd=None)

In order to remove whole directory trees, shutil.rmtree() can be used. os.rmdir only works when the directory is empty and exists.

For deleting folders recursively towards parent:

os.removedirs(name)

It remove every empty parent directory with self until parent which has some content

ex. os.removedirs('abc/xyz/pqr') will remove the directories by order 'abc/xyz/pqr', 'abc/xyz' and 'abc' if they are empty.

For more info check official doc: os.unlink , os.remove, os.rmdir , shutil.rmtree, os.removedirs

Difference between database and schema

A database is the main container, it contains the data and log files, and all the schemas within it. You always back up a database, it is a discrete unit on its own.

Schemas are like folders within a database, and are mainly used to group logical objects together, which leads to ease of setting permissions by schema.

EDIT for additional question

drop schema test1

Msg 3729, Level 16, State 1, Line 1
Cannot drop schema 'test1' because it is being referenced by object 'copyme'.

You cannot drop a schema when it is in use. You have to first remove all objects from the schema.

Related reading:

  1. What good are SQL Server schemas?
  2. MSDN: User-Schema Separation

How to debug ORA-01775: looping chain of synonyms?

The data dictionary table DBA_SYNONYMS has information about all the synonyms in a database. So you can run the query

SELECT table_owner, table_name, db_link
  FROM dba_synonyms 
 WHERE owner        = 'PUBLIC'
   AND synonym_name = <<synonym name>>

to see what the public synonym currently points at.

set serveroutput on in oracle procedure

Procedure successful but any outpout

Error line1: Unexpected identifier

Here is the code:

SET SERVEROUTPUT ON 

DECLARE

    -- Curseurs 
    CURSOR c1 IS        
    SELECT RWID FROM J_EVT
     WHERE DT_SYST < TO_DATE(TO_CHAR(SYSDATE,'DD/MM') || '/' || TO_CHAR(TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY')) - 3));

    -- Collections 

    TYPE tc1 IS TABLE OF c1%RWTYPE;

    -- Variables de type record
    rtc1                        tc1;    

    vCpt                        NUMBER:=0;

BEGIN

    OPEN c1;
    LOOP
        FETCH c1 BULK COLLECT INTO rtc1 LIMIT 5000;

        FORALL i IN 1..rtc1.COUNT 
        DELETE FROM J_EVT
          WHERE RWID = rtc1(i).RWID;
        COMMIT;

        -- Nombres lus : 5025651
        FOR i IN 1..rtc1.COUNT LOOP               
            vCpt := vCpt + SQL%BULK_RWCOUNT(i);
        END LOOP;            

        EXIT WHEN c1%NOTFOUND;   
    END LOOP;
    CLOSE c1;
    COMMIT;

    DBMS_OUTPUT.PUT_LINE ('Nombres supprimes : ' || TO_CHAR(vCpt)); 

END;
/
exit

How to reset AUTO_INCREMENT in MySQL?

I suggest you to go to Query Browser and do the following:

  1. Go to schemata and find the table you want to alter.

  2. Right click and select copy create statement.

  3. Open a result tab and paste the create statement their.

  4. Go to the last line of the create statement and look for the Auto_Increment=N, (Where N is a current number for auto_increment field.)

  5. Replace N with 1.

  6. Press ctrl+enter.

Auto_increment should reset to one once you enter new row int the table.

I don't know what will happen if you try to add a row where an auto_increment field value already exist.

How do I perform an insert and return inserted identity with Dapper?

There is a great library to make your life easier Dapper.Contrib.Extensions. After including this you can just write:

public int Add(Transaction transaction)
{
        using (IDbConnection db = Connection)
        {
                return (int)db.Insert(transaction);
        }
}

Remove HTML tags from string including &nbsp in C#

I've been using this function for a while. Removes pretty much any messy html you can throw at it and leaves the text intact.

        private static readonly Regex _tags_ = new Regex(@"<[^>]+?>", RegexOptions.Multiline | RegexOptions.Compiled);

        //add characters that are should not be removed to this regex
        private static readonly Regex _notOkCharacter_ = new Regex(@"[^\w;&#@.:/\\?=|%!() -]", RegexOptions.Compiled);

        public static String UnHtml(String html)
        {
            html = HttpUtility.UrlDecode(html);
            html = HttpUtility.HtmlDecode(html);

            html = RemoveTag(html, "<!--", "-->");
            html = RemoveTag(html, "<script", "</script>");
            html = RemoveTag(html, "<style", "</style>");

            //replace matches of these regexes with space
            html = _tags_.Replace(html, " ");
            html = _notOkCharacter_.Replace(html, " ");
            html = SingleSpacedTrim(html);

            return html;
        }

        private static String RemoveTag(String html, String startTag, String endTag)
        {
            Boolean bAgain;
            do
            {
                bAgain = false;
                Int32 startTagPos = html.IndexOf(startTag, 0, StringComparison.CurrentCultureIgnoreCase);
                if (startTagPos < 0)
                    continue;
                Int32 endTagPos = html.IndexOf(endTag, startTagPos + 1, StringComparison.CurrentCultureIgnoreCase);
                if (endTagPos <= startTagPos)
                    continue;
                html = html.Remove(startTagPos, endTagPos - startTagPos + endTag.Length);
                bAgain = true;
            } while (bAgain);
            return html;
        }

        private static String SingleSpacedTrim(String inString)
        {
            StringBuilder sb = new StringBuilder();
            Boolean inBlanks = false;
            foreach (Char c in inString)
            {
                switch (c)
                {
                    case '\r':
                    case '\n':
                    case '\t':
                    case ' ':
                        if (!inBlanks)
                        {
                            inBlanks = true;
                            sb.Append(' ');
                        }   
                        continue;
                    default:
                        inBlanks = false;
                        sb.Append(c);
                        break;
                }
            }
            return sb.ToString().Trim();
        }

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Maybe this example listed here can help you out. Statement from the author

about 24 lines of code to encrypt, 23 to decrypt

Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)

  /*
  Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.*/
   
  #region Usings
  using System;
  using System.IO;
  using System.Security.Cryptography;
  using System.Text;
  #endregion
   
  namespace Utilities.Encryption
  {
      /// <summary>
      /// Utility class that handles encryption
      /// </summary>
      public static class AESEncryption
      {
          #region Static Functions
   
          /// <summary>
          /// Encrypts a string
          /// </summary>
          /// <param name="PlainText">Text to be encrypted</param>
          /// <param name="Password">Password to encrypt with</param>
          /// <param name="Salt">Salt to encrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>An encrypted string</returns>
          public static string Encrypt(string PlainText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(PlainText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] CipherTextBytes = null;
              using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream())
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                      {
                          CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                          CryptoStream.FlushFinalBlock();
                          CipherTextBytes = MemStream.ToArray();
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Convert.ToBase64String(CipherTextBytes);
          }
   
          /// <summary>
          /// Decrypts a string
          /// </summary>
          /// <param name="CipherText">Text to be decrypted</param>
          /// <param name="Password">Password to decrypt with</param>
          /// <param name="Salt">Salt to decrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>A decrypted string</returns>
          public static string Decrypt(string CipherText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(CipherText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
              int ByteCount = 0;
              using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                      {
   
                          ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
          }
   
          #endregion
      }
  }

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Very simple:

Just use the below formation###

rules_id = ["9","10"]

sql2 = "SELECT * FROM attendance_rules_staff WHERE id in"+str(tuple(rules_id))

note the str(tuple(rules_id)).

How to store values from foreach loop into an array?

You can try to do my answer,

you wrote this:

<?php
foreach($group_membership as $i => $username) {
    $items = array($username);
}

print_r($items);
?>

And in your case I would do this:

<?php
$items = array();
foreach ($group_membership as $username) { // If you need the pointer (but I don't think) you have to add '$i => ' before $username
    $items[] = $username;
} ?>

As you show in your question it seems that you need an array of usernames that are in a particular group :) In this case I prefer a good sql query with a simple while loop ;)

<?php
$query = "SELECT `username` FROM group_membership AS gm LEFT JOIN users AS u ON gm.`idUser` = u.`idUser`";
$result = mysql_query($query);
while ($record = mysql_fetch_array($result)) { \
    $items[] = $username; 
} 
?>

while is faster, but the last example is only a result of an observation. :)

How to insert a row in an HTML table body in JavaScript

Basic approach:

This should add HTML-formatted content and show the newly added row.

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;

How to zip a whole folder using PHP

I assume this is running on a server where the zip application is in the search path. Should be true for all unix-based and I guess most windows-based servers.

exec('zip -r archive.zip "My folder"');
unlink('My\ folder/index.html');
unlink('My\ folder/picture.jpg');

The archive will reside in archive.zip afterwards. Keep in mind that blanks in file or folder names are a common cause of errors and should be avoided where possible.

Is there an onSelect event or equivalent for HTML <select>?

<select name="test[]" 
onchange="if(this.selectedIndex < 1){this.options[this.selectedIndex].selected = !1}">
<option>1</option>
<option>2</option>
<option>3</option>
</select>

How to get a list of installed android applications and pick one to run

I had a requirement to filter out the system apps which user do not really use(eg. "com.qualcomm.service", "update services", etc). Ultimately I added another condition to filter down the app list. I just checked whether the app has 'launcher intent'.

So, the resultant code looks like...

PackageManager pm = getPackageManager();
        List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_GIDS);

        for (ApplicationInfo app : apps) {
            if(pm.getLaunchIntentForPackage(app.packageName) != null) {
                // apps with launcher intent
                if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                    // updated system apps

                } else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                    // system apps

                } else {
                    // user installed apps

                }
                appsList.add(app);
            }

        }

Java Error: "Your security settings have blocked a local application from running"

If you are using Linux, these settings are available using /usr/bin/jcontrol (or your path setting to get the current Java tools). You can also edit the files in ~/.java/deployment/deployment.properties to set "deployment.security.level=MEDIUM".

Surprisingly, this information is not readily available from the Oracle web site. I miss java.sun.com...

Angular 2 declaring an array of objects

Another approach that is especially useful if you want to store data coming from an external API or a DB would be this:

  1. Create a class that represent your data model

    export class Data{
        private id:number;
        private text: string;
    
        constructor(id,text) {
            this.id = id;
            this.text = text;
        }
    
  2. In your component class you create an empty array of type Data and populate this array whenever you get a response from API or whatever data source you are using

    export class AppComponent {
        private search_key: string;
        private dataList: Data[] = [];
    
        getWikiData() {
           this.httpService.getDataFromAPI()
            .subscribe(data => {
              this.parseData(data);
            });
         }
    
        parseData(jsonData: string) {
        //considering you get your data in json arrays
        for (let i = 0; i < jsonData[1].length; i++) {
             const data = new WikiData(jsonData[1][i], jsonData[2][i]);
             this.wikiData.push(data);
        }
      }
    }
    

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

Just convert the text explicitly to string using str(). Worked for me.

Delete all items from a c++ std::vector

vector.clear() should work for you. In case you want to shrink the capacity of the vector along with clear then

std::vector<T>(v).swap(v);

Java Multithreading concept and join() method

You must understand , threads scheduling is controlled by thread scheduler.So, you cannot guarantee the order of execution of threads under normal circumstances.

However, you can use join() to wait for a thread to complete its work.

For example, in your case

ob1.t.join();

This statement will not return until thread t has finished running.

Try this,

class Demo {
   Thread t = new Thread(
                 new Runnable() {
                     public void run () {
                         //do something
                     }
                  }
    );
    Thread t1 = new Thread(
                 new Runnable() {
                     public void run () {
                         //do something
                     }
                  }
    );
    t.start(); // Line 15
    t.join();  // Line 16
    t1.start();
}

In the above example, your main thread is executing. When it encounters line 15, thread t is available at thread scheduler. As soon as main thread comes to line 16, it will wait for thread t to finish.

NOTE that t.join did not do anything to thread t or to thread t1. It only affected the thread that called it (i.e., the main() thread).

Edited:

t.join(); needs to be inside the try block because it throws the InterruptedException exception, otherwise you will get an error at compile time. So, it should be:

try{
    t.join();
}catch(InterruptedException e){
    // ...
}

Check string length in PHP

An XPath solution is to use:

string-length((//div[@class='contest'])[$k])

where $k should be substituted by a number.

This evaluates to the string length of the $k-th (in document order) div in the XML document that has a class attribute with value 'contest'.

Create an array or List of all dates between two dates

I know this is an old post but try using an extension method:

    public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
    {
        return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
    }

and use it like this

    var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));

Feel free to choose your own dates, you don't have to restrict yourself to January 2000.

How to create a generic array?

checked :

public Constructor(Class<E> c, int length) {

    elements = (E[]) Array.newInstance(c, length);
}

or unchecked :

public Constructor(int s) {
    elements = new Object[s];
}

Difference between Python's Generators and Iterators

Generator Function, Generator Object, Generator:

A Generator function is just like a regular function in Python but it contains one or more yield statements. Generator functions is a great tool to create Iterator objects as easy as possible. The Iterator object returend by generator function is also called Generator object or Generator.

In this example I have created a Generator function which returns a Generator object <generator object fib at 0x01342480>. Just like other iterators, Generator objects can be used in a for loop or with the built-in function next() which returns the next value from generator.

def fib(max):
    a, b = 0, 1
    for i in range(max):
        yield a
        a, b = b, a + b
print(fib(10))             #<generator object fib at 0x01342480>

for i in fib(10):
    print(i)               # 0 1 1 2 3 5 8 13 21 34


print(next(myfib))         #0
print(next(myfib))         #1
print(next(myfib))         #1
print(next(myfib))         #2

So a generator function is the easiest way to create an Iterator object.

Iterator:

Every generator object is an iterator but not vice versa. A custom iterator object can be created if its class implements __iter__ and __next__ method (also called iterator protocol).

However, it is much easier to use generators function to create iterators because they simplify their creation, but a custom Iterator gives you more freedom and you can also implement other methods according to your requirements as shown in the below example.

class Fib:
    def __init__(self,max):
        self.current=0
        self.next=1
        self.max=max
        self.count=0

    def __iter__(self):
        return self

    def __next__(self):
        if self.count>self.max:
            raise StopIteration
        else:
            self.current,self.next=self.next,(self.current+self.next)
            self.count+=1
            return self.next-self.current

    def __str__(self):
        return "Generator object"

itobj=Fib(4)
print(itobj)               #Generator object

for i in Fib(4):  
    print(i)               #0 1 1 2

print(next(itobj))         #0
print(next(itobj))         #1
print(next(itobj))         #1

Wait for shell command to complete

Use the WScript.Shell instead, because it has a waitOnReturn option:

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

(Idea copied from Wait for Shell to finish, then format cells - synchronously execute a command)

How do I declare an array with a custom class?

You need a parameterless constructor to be able to create an instance of your class. Your current constructor requires two input string parameters.

Normally C++ implies having such a constructor (=default parameterless constructor) if there is no other constructor declared. By declaring your first constructor with two parameters you overwrite this default behaviour and now you have to declare this constructor explicitly.

Here is the working code:

#include <iostream> 
#include <string>  // <-- you need this if you want to use string type

using namespace std; 

class name { 
  public: 
    string first; 
    string last; 

  name(string a, string b){ 
    first = a; 
    last = b; 

  }

  name ()  // <-- this is your explicit parameterless constructor
  {}

}; 

int main (int argc, const char * argv[]) 
{ 

  const int howManyNames = 3; 

  name someName[howManyNames]; 

  return 0; 
}

(BTW, you need to include to make the code compilable.)

An alternative way is to initialize your instances explicitly on declaration

  name someName[howManyNames] = { {"Ivan", "The Terrible"}, {"Catherine", "The Great"} };

How do you generate dynamic (parameterized) unit tests in Python?

The metaclass-based answers still work in Python 3, but instead of the __metaclass__ attribute, one has to use the metaclass parameter, as in:

class ExampleTestCase(TestCase,metaclass=DocTestMeta):
    pass

milliseconds to time in javascript

Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:

function msToTime(s) {
  var ms = s % 1000;
  s = (s - ms) / 1000;
  var secs = s % 60;
  s = (s - secs) / 60;
  var mins = s % 60;
  var hrs = (s - mins) / 60;

  return hrs + ':' + mins + ':' + secs + '.' + ms;
}

If you want it formatted as hh:mm:ss.sss then use:

_x000D_
_x000D_
function msToTime(s) {_x000D_
_x000D_
  // Pad to 2 or 3 digits, default is 2_x000D_
  function pad(n, z) {_x000D_
    z = z || 2;_x000D_
    return ('00' + n).slice(-z);_x000D_
  }_x000D_
_x000D_
  var ms = s % 1000;_x000D_
  s = (s - ms) / 1000;_x000D_
  var secs = s % 60;_x000D_
  s = (s - secs) / 60;_x000D_
  var mins = s % 60;_x000D_
  var hrs = (s - mins) / 60;_x000D_
_x000D_
  return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);_x000D_
}_x000D_
_x000D_
console.log(msToTime(55018))
_x000D_
_x000D_
_x000D_

Using some recently added language features, the pad function can be more concise:

_x000D_
_x000D_
function msToTime(s) {_x000D_
    // Pad to 2 or 3 digits, default is 2_x000D_
  var pad = (n, z = 2) => ('00' + n).slice(-z);_x000D_
  return pad(s/3.6e6|0) + ':' + pad((s%3.6e6)/6e4 | 0) + ':' + pad((s%6e4)/1000|0) + '.' + pad(s%1000, 3);_x000D_
}_x000D_
_x000D_
// Current hh:mm:ss.sss UTC_x000D_
console.log(msToTime(new Date() % 8.64e7))
_x000D_
_x000D_
_x000D_

Enable the display of line numbers in Visual Studio

For me, line numbers wouldn't appear in the editor until I added the option under both the "all languages" pane, and the language I was working under (C# etc)... screen capture showing editor options

How to fix '.' is not an internal or external command error

Replacing forward(/) slash with backward(\) slash will do the job. The folder separator in Windows is \ not /

Error TF30063: You are not authorized to access ... \DefaultCollection

I was also facing the same issue as you did. Here is what I did to solve:

METHOD 1

  1. Click the 'Connect' icon just next to Home icon in Solution Explorer.
  2. Choose your project > Right Click > Connect.
  3. Try Check-in the project and this time it will happily proceed.

This is what I tried, and I did not need to logout from any sessions from TFS or VS Account.

METHOD 2

  1. Just press refresh on the top of Team Explorer.
  2. Try to Check-in.

This is also easy method.

Hope this helps.

$(...).datepicker is not a function - JQuery - Bootstrap

Not the right function name I think

$(document).ready(function() {

    $('.datepicker').datetimepicker({
        format: 'dd/mm/yyyy'
    });
});

Getting Java version at runtime

Here's the implementation in JOSM:

/**
 * Returns the Java version as an int value.
 * @return the Java version as an int value (8, 9, etc.)
 * @since 12130
 */
public static int getJavaVersion() {
    String version = System.getProperty("java.version");
    if (version.startsWith("1.")) {
        version = version.substring(2);
    }
    // Allow these formats:
    // 1.8.0_72-ea
    // 9-ea
    // 9
    // 9.0.1
    int dotPos = version.indexOf('.');
    int dashPos = version.indexOf('-');
    return Integer.parseInt(version.substring(0,
            dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : 1));
}

How to link to a named anchor in Multimarkdown?

Here is my solution (derived from SaraubhM's answer)

**Jump To**: [Hotkeys & Markers](#hotkeys-markers) / [Radii](#radii) / [Route Wizard 2.0](#route-wizard-2-0)

Which gives you:

Jump To: Hotkeys & Markers / Radii / Route Wizard 2.0

Note the changes from and . to - and also the loss of the & in the links.

How to center form in bootstrap 3

Many people advise using col- and col-offset- classes, but it doesn't work right for me, it centers the form only for a certain screen size, but if you change it, the markup slides out.

I found two ways to align form:

Use a custom CSS:

<div class=".center">
  <form>

  </form>
</div>

.center {
  margin: 0 auto;
  width: 100%;
}
form {
  margin: 0 auto;
  width: 500px; /*find your value*/
  text-align: center;
}

Original code

OR just copy a CSS class "justify-content-center" from bootstrap 4, it's very short:

.justify-content-center {
    -ms-flex-pack: center !important;
    justify-content: center !important;
}

And then use it:

<div class="container">
    <div class="row">
        <div class="form-inline justify-content-center">
        </div>
    </div>
</div>

Calculate the center point of multiple latitude/longitude coordinate pairs

Here is the Android version based on @Yodacheese's C# answer using Google Maps api:

public static LatLng GetCentralGeoCoordinate(List<LatLng> geoCoordinates) {        
    if (geoCoordinates.size() == 1)
    {
        return geoCoordinates.get(0);
    }

    double x = 0;
    double y = 0;
    double z = 0;

    for(LatLng geoCoordinate : geoCoordinates)
    {
        double  latitude = geoCoordinate.latitude * Math.PI / 180;
        double longitude = geoCoordinate.longitude * Math.PI / 180;

        x += Math.cos(latitude) * Math.cos(longitude);
        y += Math.cos(latitude) * Math.sin(longitude);
        z += Math.sin(latitude);
    }

    int total = geoCoordinates.size();

    x = x / total;
    y = y / total;
    z = z / total;

    double centralLongitude = Math.atan2(y, x);
    double centralSquareRoot = Math.sqrt(x * x + y * y);
    double centralLatitude = Math.atan2(z, centralSquareRoot);

    return new LatLng(centralLatitude * 180 / Math.PI, centralLongitude * 180 / Math.PI);

}

in app build.gradle add:

implementation 'com.google.android.gms:play-services-maps:17.0.0'

Generic Property in C#

Okay, I'll bite. You want something like this: If you declare a "property" like this:

Update: I'm now pretty sure that Fredrik Mörk answered your question and gave a solution. I'm not really happy with the idea, but it seems to answer exactly what I understood from your question.

public class PropertyFoo {
  public MyProp<String> Name;
}

this ends up as

public class PropertyFoo {
  public string Name {
    get { /* do predefined stuff here */ }
    set { /*other predefined stuff here */ }
  }
}

No. Not possible and not a property, really. Look for template/snippet support in your IDE.

How do I display the value of a Django form field in a template?

On Django 1.2, {{ form.data.field }} and {{ form.field.data }} are all OK, but not {{ form.field.value }}.
As others said, {{ form.field.value }} is Django 1.3+ only, but there's no specification in https://docs.djangoproject.com/en/1.3/topics/forms/. It can be found in https://docs.djangoproject.com/en/1.4/topics/forms/.

How to read a file in other directory in python

i found this way useful also.

import tkinter.filedialog
from_filename = tkinter.filedialog.askopenfilename()  

here a window will appear so you can browse till you find the file , you click on it then you can continue using open , and read .

from_file = open(from_filename, 'r')
contents = from_file.read()
contents

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

Apple Link

Below is the information about screen sizes. These details are taken from the apple website

Below is the information

Responsive timeline UI with Bootstrap3

BootFlat

You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:

enter image description here

HTTP headers in Websockets client API

Updated 2x

Short answer: No, only the path and protocol field can be specified.

Longer answer:

There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. The HTTP path ("GET /xyz") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.

The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor:

var ws = new WebSocket("ws://example.com/path", "protocol");
var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]);

The above results in the following headers:

Sec-WebSocket-Protocol: protocol

and

Sec-WebSocket-Protocol: protocol1, protocol2

A common pattern for achieving WebSocket authentication/authorization is to implement a ticketing system where the page hosting the WebSocket client requests a ticket from the server and then passes this ticket during WebSocket connection setup either in the URL/query string, in the protocol field, or required as the first message after the connection is established. The server then only allows the connection to continue if the ticket is valid (exists, has not been already used, client IP encoded in ticket matches, timestamp in ticket is recent, etc). Here is a summary of WebSocket security information: https://devcenter.heroku.com/articles/websocket-security

Basic authentication was formerly an option but this has been deprecated and modern browsers don't send the header even if it is specified.

Basic Auth Info (Deprecated - No longer functional):

NOTE: the following information is no longer accurate in any modern browsers.

The Authorization header is generated from the username and password (or just username) field of the WebSocket URI:

var ws = new WebSocket("ws://username:[email protected]")

The above results in the following header with the string "username:password" base64 encoded:

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

I have tested basic auth in Chrome 55 and Firefox 50 and verified that the basic auth info is indeed negotiated with the server (this may not work in Safari).

Thanks to Dmitry Frank's for the basic auth answer

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Something like this should work:

<%=Html.TextBox("test", new { style="width:50px" })%>

Or better:

<%=Html.TextBox("test")%>

<style type="text/css">
    input[type="text"] { width:50px; }     
</style>

Android: Create a toggle button with image and no text

I know this is a little late, however for anyone interested, I've created a custom component that is basically a toggle image button, the drawable can have states as well as the background

https://gist.github.com/akshaydashrath/9662072

how to get javaScript event source element?

You can pass this when you call the function

<button onclick="doSomething('param',this)" id="id_button">action</button>

<script>
    function doSomething(param,me){

    var source = me
    console.log(source);
}
</script>

In Unix, how do you remove everything in the current directory and below it?

Use

rm -rf *

Update: The . stands for current directory, but we cannot use this. The command seems to have explicit checks for . and ... Use the wildcard globbing instead. But this can be risky.

A safer version IMO is to use:

rm -ri * 

(this prompts you for confirmation before deleting every file/directory.)

Launch Failed. Binary not found. CDT on Eclipse Helios

I faced the same problem while installing Eclipse for c/c++ applications .I downloaded Mingw GCC ,put its bin folder in your path ,used it in toolchains while making new C++ project in Eclipse and build which solved my problem. Referred to this video

Initializing a dictionary in python with a key value and no corresponding values

Comprehension could be also convenient in this case:

# from a list
keys = ["k1", "k2"]
d = {k:None for k in keys}

# or from another dict
d1 = {"k1" : 1, "k2" : 2}
d2 = {k:None for k in d1.keys()}

d2
# {'k1': None, 'k2': None}

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

I solved the same error, by adding "zizaco/entrust": "*" instead of the "zizaco/entrust": "~1.2".

Error in eval(expr, envir, enclos) : object not found

I think I got what I was looking for..

data.train <- read.table("Assign2.WineComplete.csv",sep=",",header=T)
fit <- rpart(quality ~ ., method="class",data=data.train)
plot(fit)
text(fit, use.n=TRUE)
summary(fit)

Create a dictionary with list comprehension

Yes, it's possible. In python, Comprehension can be used in List, Set, Dictionary, etc. You can write it this way

mydict = {k:v for (k,v) in blah}

Another detailed example of Dictionary Comprehension with the Conditional Statement and Loop:

parents = [father, mother]
            
parents = {parent:1 - P["mutation"] if parent in two_genes else 0.5 if parent in one_gene else P["mutation"] for parent in parents}

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";

Hope this helps someone else.

CSS Border Not Working

Use this line of code in your css

border: 1px solid #000 !important;

or if you want border only in left and right side of container then use:

border-right: 1px solid #000 !important;
border-left: 1px solid #000 !important;

jQuery - trapping tab select event

Simply use the on click event for tab shown.

$(document).on('shown.bs.tab', 'a[href="#tab"]', function (){
});

How can I see what has changed in a file before committing to git?

Well, my case when you don't want to care about files list. Just show them all.

When you already ran git add with your files list:

$ git diff --cached $(git diff --cached --name-only)

In more recent versions of git, you can use --staged also, which is a synonym of --cached.

The same can be used for haven't added files but without --cached option.

$ git diff $(git diff --name-only)

Git command alias for "cached" option:

$ git config --global alias.diff-cached '!git diff --cached $(git diff --cached --name-only)'

How to make certain text not selectable with CSS

The CSS below stops users from being able to select text.

-webkit-user-select: none; /* Safari */        
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */

To target IE9 downwards the html attribute unselectable must be used instead:

<p unselectable="on">Test Text</p>

Effective swapping of elements of an array in Java

If you want to swap string. it's already the efficient way to do that.

However, if you want to swap integer, you can use XOR to swap two integers more efficiently like this:

int a = 1; int b = 2; a ^= b; b ^= a; a ^= b;

Is it possible only to declare a variable without assigning any value in Python?

In Python 3.6+ you could use Variable Annotations for this:

https://www.python.org/dev/peps/pep-0526/#abstract

PEP 484 introduced type hints, a.k.a. type annotations. While its main focus was function annotations, it also introduced the notion of type comments to annotate variables:

# 'captain' is a string (Note: initial value is a problem)
captain = ...  # type: str

PEP 526 aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments:

captain: str  # Note: no initial value!

It seems to be more directly in line with what you were asking "Is it possible only to declare a variable without assigning any value in Python?"

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

What's the difference between Instant and LocalDateTime?

Instant corresponds to time on the prime meridian (Greenwich).

Whereas LocalDateTime relative to OS time zone settings, and

cannot represent an instant without additional information such as an offset or time-zone.

Is it possible to delete an object's property in PHP?

unset($a->new_property);

This works for array elements, variables, and object attributes.

Example:

$a = new stdClass();

$a->new_property = 'foo';
var_export($a);  // -> stdClass::__set_state(array('new_property' => 'foo'))

unset($a->new_property);
var_export($a);  // -> stdClass::__set_state(array())

Join two sql queries

Here's what worked for me:

select visits, activations, simulations, simulations/activations
   as sims_per_visit, activations/visits*100
   as adoption_rate, simulations/activations*100
   as completion_rate, duration/60
   as minutes, m1 as month, Wk1 as week, Yr1 as year 

from
(
    (select count(*) as visits, year(stamp) as Yr1, week(stamp) as Wk1, month(stamp)
    as m1 from sessions group by week(stamp), year(stamp)) as t3

    join

    (select count(*) as activations, year(stamp) as Yr2, week(stamp) as Wk2,
    month(stamp) as m2 from sessions where activated='1' group by week(stamp),
    year(stamp)) as t4

    join

    (select count(*) as simulations, year(stamp) as Yr3 , week(stamp) as Wk3,
    month(stamp) as m3 from sessions where simulations>'0' group by week(stamp),
    year(stamp)) as t5

    join

    (select avg(duration) as duration, year(stamp) as Yr4 , week(stamp) as Wk4,
    month(stamp) as m4 from sessions where activated='1' group by week(stamp),
    year(stamp)) as t6
)
where Yr1=Yr2 and Wk1=Wk2 and Wk1=Wk3 and Yr1=Yr3 and Yr1=Yr4 and Wk1=Wk4

I used joins, not unions (I needed different columns for each query, a join puts it all in the same column) and I dropped the quotation marks (compared to what Liam was doing) because they were giving me errors.

Thanks! I couldn't have pulled that off without this page! PS: Sorry I don't know how you're getting your statements formatted with colors. etc.

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

Interesting to note, all sources emphasize that @Column(nullable=false) is used only for DDL generation.

However, even if there is no @NotNull annotation, and hibernate.check_nullability option is set to true, Hibernate will perform validation of entities to be persisted.

It will throw PropertyValueException saying that "not-null property references a null or transient value", if nullable=false attributes do not have values, even if such restrictions are not implemented in the database layer.

More information about hibernate.check_nullability option is available here: http://docs.jboss.org/hibernate/orm/5.0/userguide/html_single/Hibernate_User_Guide.html#configurations-mapping.

How to automatically insert a blank row after a group of data

  1. Insert a column at the left of the table 'Control'
  2. Number the data as 1 to 1000 (assuming there are 1000 rows)
  3. Copy the key field to another sheet and remove duplicates
  4. Copy the unique row items to the main sheet, after 1000th record
  5. In the 'Control' column, add number 1001 to all unique records
  6. Sort the data (including the added records), first on key field and then on 'Control'
  7. A blank line (with data in key field and 'Control') is added

Declaring & Setting Variables in a Select Statement

The SET command is TSQL specific - here's the PLSQL equivalent to what you posted:

v_date1 DATE := TO_DATE('03-AUG-2010', 'DD-MON-YYYY');

SELECT u.visualid
  FROM USAGE u 
 WHERE u.usetime > v_date1;

There's also no need for prefixing variables with "@"; I tend to prefix variables with "v_" to distinguish between variables & columns/etc.

See this thread about the Oracle equivalent of NOLOCK...

What is the definition of "interface" in object oriented programming

In my opinion, interface has a broader meaning than the one commonly associated with it in Java. I would define "interface" as a set of available operations with some common functionality, that allow controlling/monitoring a module.

In this definition I try to cover both programatic interfaces, where the client is some module, and human interfaces (GUI for example).

As others already said, an interface always has some contract behind it, in terms of inputs and outputs. The interface does not promise anything about the "how" of the operations; it only guarantees some properties of the outcome, given the current state, the selected operation and its parameters.

Cannot find Microsoft.Office.Interop Visual Studio

Look for them under COM when trying to add the references. You should find the reference below, and possibly Microsoft Outlook 15.0 Object Library, if you need that. There are similar libraries for Word, Excel, etc.:

enter image description here

Update: The Object Library should contain the Interop stuff. Try to add this to a source file, and see if it does not find what you need:

using Microsoft.Office.Interop.Outlook;

enter image description here

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

You need to do two additional things after following the link that you have mentioned in your post:

One have to map the changed login cridentials in phpmyadmin's config.inc.php

and second, you need to restart your web and mysql servers..

php version is not the issue here..you need to go to phpmyadmin installation directory and find file config.inc.php and in that file put your current mysql password at line

$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here

How To Upload Files on GitHub

If you want to upload a folder or a file to Github

1- Create a repository on the Github

2- make: git remote add origin "Your Link" as it is described on the Github

3- Then use git push -u origin master.

4- You have to enter your username and Password.

5- After the authentication, the transfer will start

CGContextDrawImage draws image upside down when passed UIImage.CGImage

Instead of

CGContextDrawImage(context, CGRectMake(0, 0, 145, 15), image.CGImage);

Use

[image drawInRect:CGRectMake(0, 0, 145, 15)];

In the middle of your begin/end CGcontext methods.

This will draw the image with the correct orientation into your current image context - I'm pretty sure this has something to do with the UIImage holding onto knowledge of the orientation while the CGContextDrawImage method gets the underlying raw image data with no understanding of orientation.

git diff between cloned and original remote repository

This example might help someone:

Note "origin" is my alias for remote "What is on Github"
Note "mybranch" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch to show where the branch name parameter is used.


What exactly are my remote repos on github?

$ git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)

Add the "other github repository of the same code" - we call this a fork:

$ git remote add someOtherRepo https://github.com/otherUser/Playground.git

$git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)

make sure our local repo is up to date:

$ git fetch

Change some stuff locally. let's say file ./foo/bar.py

$ git status
# On branch mybranch
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   foo/bar.py

Review my uncommitted changes

$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

Commit locally.

$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)

Now, I'm different than my remote (on github)

$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)

Diff this with remote - your fork: (this is frequently done with git diff master origin)

$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

(git push to apply these to remote)

How does my remote branch differ from the remote master branch?

$ git diff origin/mybranch origin/master

How does my local stuff differ from the remote master branch?

$ git diff origin/master

How does my stuff differ from someone else's fork, master branch of the same repo?

$git diff mybranch someOtherRepo/master

Flutter position stack widget in center

Probably the most elegant way.

You can simply use the alignment option present in Stack

child: Stack(
  alignment: Alignment.center
)

Get name of currently executing test in JUnit 4

JUnit 5 via ExtensionContext

Advantage:

You get to have the added functionalities of ExtensionContext by overriding afterEach(ExtensionContext context).

public abstract class BaseTest {

    protected WebDriver driver;

    @RegisterExtension
    AfterEachExtension afterEachExtension = new AfterEachExtension();

    @BeforeEach
    public void beforeEach() {
        // Initialise driver
    }

    @AfterEach
    public void afterEach() {
        afterEachExtension.setDriver(driver);
    }

}
public class AfterEachExtension implements AfterEachCallback {

    private WebDriver driver;

    public void setDriver(WebDriver driver) {
        this.driver = driver;
    }

    @Override
    public void afterEach(ExtensionContext context) {
        String testMethodName = context.getTestMethod().orElseThrow().getName();
        // Attach test steps, attach scsreenshots on failure only, etc.
        driver.quit();
    }

}

How can one tell the version of React running at runtime in the browser?

For an app created with create-react-app I managed to see the version:

  1. Open Chrome Dev Tools / Firefox Dev Tools,
  2. Search and open main.XXXXXXXX.js file where XXXXXXXX is a builds hash /could be different,
  3. Optional: format source by clicking on the {} to show the formatted source,
  4. Search as text inside the source for react-dom,
  5. in Chrome was found: "react-dom": "^16.4.0",
  6. in Firefox was found: 'react-dom': '^16.4.0'

The app was deployed without source map.

How to Set the Background Color of a JButton on the Mac OS

Have you tried setting JButton.setOpaque(true)?

JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);

The requested URL /about was not found on this server

I deleted the previous .htaccess file and created new one by clicking on save button in Settings->Permalinks

and now that pages started working fine...

Reading images in python

import matplotlib.pyplot as plt
image = plt.imread('images/my_image4.jpg')
plt.imshow(image)

Using 'matplotlib.pyplot.imread' is recommended by warning messages in jupyter.

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

How to delete all data from solr and hbase

fire this in the browser

http://localhost:8983/solr/update?stream.body=<delete><query>*:*</query></delete>&commit=true this commmand will delete all the documents in index in solr

How to picture "for" loop in block representation of algorithm

Here's a flow chart that illustrates a for loop:

Flow Chart For Loop

The equivalent C code would be

for(i = 2; i <= 6; i = i + 2) {
    printf("%d\t", i + 1);
}

I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

ld.exe: cannot open output file ... : Permission denied

i experienced a similar issue. Bitdefender automatically quarantined each exe-file i created by MinGW g++. Instead of the full exe-file i found a file with a weird extension 'qzquar' testAutoPtr1.exe.48352.gzquar

When i opened quarantined items in Bitdefender i found my exe-file quarantined there.

finding and replacing elements in a list

My usecase was replacing None with some default value.

I've timed approaches to this problem that were presented here, including the one by @kxr - using str.count.

Test code in ipython with Python 3.8.1:

def rep1(lst, replacer = 0):
    ''' List comprehension, new list '''

    return [item if item is not None else replacer for item in lst]


def rep2(lst, replacer = 0):
    ''' List comprehension, in-place '''    
    lst[:] =  [item if item is not None else replacer for item in lst]

    return lst


def rep3(lst, replacer = 0):
    ''' enumerate() with comparison - in-place '''
    for idx, item in enumerate(lst):
        if item is None:
            lst[idx] = replacer

    return lst


def rep4(lst, replacer = 0):
    ''' Using str.index + Exception, in-place '''

    idx = -1
    # none_amount = lst.count(None)
    while True:
        try:
            idx = lst.index(None, idx+1)
        except ValueError:
            break
        else:
            lst[idx] = replacer

    return lst


def rep5(lst, replacer = 0):
    ''' Using str.index + str.count, in-place '''

    idx = -1
    for _ in range(lst.count(None)):
        idx = lst.index(None, idx+1)
        lst[idx] = replacer

    return lst


def rep6(lst, replacer = 0):
    ''' Using map, return map iterator '''

    return map(lambda item: item if item is not None else replacer, lst)


def rep7(lst, replacer = 0):
    ''' Using map, return new list '''

    return list(map(lambda item: item if item is not None else replacer, lst))


lst = [5]*10**6
# lst = [None]*10**6

%timeit rep1(lst)    
%timeit rep2(lst)    
%timeit rep3(lst)    
%timeit rep4(lst)    
%timeit rep5(lst)    
%timeit rep6(lst)    
%timeit rep7(lst)    

I get:

26.3 ms ± 163 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
29.3 ms ± 206 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
33.8 ms ± 191 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
11.9 ms ± 37.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
11.9 ms ± 60.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
260 ns ± 1.84 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
56.5 ms ± 204 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Using the internal str.index is in fact faster than any manual comparison.

I didn't know if the exception in test 4 would be more laborious than using str.count, the difference seems negligible.

Note that map() (test 6) returns an iterator and not an actual list, thus test 7.

Converting an object to a string

If you wont aplay join() to Object.

const obj = {one:1, two:2, three:3};
let arr = [];
for(let p in obj)
    arr.push(obj[p]);
const str = arr.join(',');

jQuery select change show/hide div event

I used the following jQuery-based snippet to have a select-element show a div-element that has an id that matches the value of the option-element while hiding the divs that do not match. Not sure that it's the best way, but it is a way.

_x000D_
_x000D_
$('#sectionChooser').change(function(){_x000D_
    var myID = $(this).val();_x000D_
    $('.panel').each(function(){_x000D_
        myID === $(this).attr('id') ? $(this).show() : $(this).hide();_x000D_
    });_x000D_
});
_x000D_
.panel {display: none;}_x000D_
#one {display: block;}
_x000D_
<select id="sectionChooser">_x000D_
    <option value="one" selected>Thing One</option>_x000D_
    <option value="two">Thing Two</option>_x000D_
    <option value="three">Thing Three</option>_x000D_
</select>_x000D_
_x000D_
<div class="panel" id="one">_x000D_
    <p>Thing One</p>_x000D_
</div>_x000D_
<div class="panel" id="two">_x000D_
    <p>Thing Two</p>_x000D_
</div>_x000D_
<div class="panel" id="three">_x000D_
    <p>Thing Three</p>_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to get maximum value from the Collection (for example ArrayList)?

Java 8

As integers are comparable we can use the following one liner in:

List<Integer> ints = Stream.of(22,44,11,66,33,55).collect(Collectors.toList());
Integer max = ints.stream().mapToInt(i->i).max().orElseThrow(NoSuchElementException::new); //66
Integer min = ints.stream().mapToInt(i->i).min().orElseThrow(NoSuchElementException::new); //11

Another point to note is we cannot use Funtion.identity() in place of i->i as mapToInt expects ToIntFunction which is a completely different interface and is not related to Function. Moreover this interface has only one method applyAsInt and no identity() method.

Moving items around in an ArrayList

Applying recursion to reorder items in an arraylist

public class ArrayListUtils {
            public static <T> void reArrange(List<T> list,int from, int to){
                if(from != to){
                     if(from > to)
                        reArrange(list,from -1, to);
                      else
                        reArrange(list,from +1, to);

                     Collections.swap(list, from, to);
                }
            }
    }

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

pip install access denied on Windows

Try to delete the folder c:\\users\\bruno\\appdata\\local\\temp\\easy_install-0fme6u manually and then retry the pip command.

How to get file path from OpenFileDialog and FolderBrowserDialog?

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);

Import MySQL database into a MS SQL Server

Also you can use 'ODBC' + 'SQL Server Import and Export Wizard'. Below link describes it: https://www.mssqltips.com/sqlservertutorial/2205/mysql-to-sql-server-data-migration/

enter image description here

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

jQuery rotate/transform

I came up with some kind of solution to the problem. It involves jquery and css. This works like toggle but instead of toggling the display of elements it just changes its properties upon alternate clicks. Upon clicking the div it rotates the element with tag 180 degrees and when you click it again the element with tag returns to its original position. If you want to change the animation duration just change transition-duration property.

CSS

#example1{
transition-duration:1s;
}

jQuery

$(document).ready( function ()  {  var toggle = 1;
  $('div').click( function () {
      toggle++;
      if ( (toggle%2)==0){
          $('#example1').css( {'transform': 'rotate(180deg)'});
      }
      else{
          $('#example1').css({'transform': 'rotate(0deg)'});
      }
  });

});

Remove local git tags that are no longer on the remote repository

I add the command to SourceTree as a Custom Action on my MacOS.


Setting Custom Actions by Sourcetree -> Preferences... -> Custom Actions


Script to run have to be the git path.

I use git fetch --prune --prune-tags origin to sync tags from remote to local.

enter image description here enter image description here

Importing packages in Java

Take out the method name from in your import statement. e.g.

import Dan.Vik.disp;

becomes:

import Dan.Vik;

How do I mock a service that returns promise in AngularJS Jasmine unit test?

describe('testing a method() on a service', function () {    

    var mock, service

    function init(){
         return angular.mock.inject(function ($injector,, _serviceUnderTest_) {
                mock = $injector.get('service_that_is_being_mocked');;                    
                service = __serviceUnderTest_;
            });
    }

    beforeEach(module('yourApp'));
    beforeEach(init());

    it('that has a then', function () {
       //arrange                   
        var spy= spyOn(mock, 'actionBeingCalled').and.callFake(function () {
            return {
                then: function (callback) {
                    return callback({'foo' : "bar"});
                }
            };
        });

        //act                
        var result = service.actionUnderTest(); // does cleverness

        //assert 
        expect(spy).toHaveBeenCalled();  
    });
});

Combine GET and POST request methods in Spring

Below is one of the way by which you can achieve that, may not be an ideal way to do.

Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.

@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
     //handle both get and post request here
     // first check request type and do respective actions needed for get and post.

    if(GET REQUEST){

     //WORK RELATED TO GET

    }else if(POST REQUEST){

      //WORK RELATED TO POST

    }

    commonMethod(param1, param2....);
}

Background color on input type=button :hover state sticks in IE

Try using the type attribute selector to find buttons (maybe this'll fix it too):

input[type=button]
{
  background-color: #E3E1B8; 
}

input[type=button]:hover
{
  background-color: #46000D
}

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I had to do it slightly different to work for me:

  1. rightclick project, remove maven nature (or in newer eclipse, "Maven->Disable Maven Nature")
  2. mvn eclipse:clean (with project open in eclipse/STS)
  3. delete the project in eclipse (but do not delete the sources)
  4. Import existing Maven project

How to use android emulator for testing bluetooth application?

Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

Typing the Enter/Return key using Python and Selenium

For those folks who are using WebDriverJS Keys.RETURN would be referenced as

webdriver.Key.RETURN

A more complete example as a reference might be helpful too:

var pressEnterToSend = function () {
    var deferred = webdriver.promise.defer();
    webdriver.findElement(webdriver.By.id('id-of-input-element')).then(function (element) {
        element.sendKeys(webdriver.Key.RETURN);
        deferred.resolve();
    });

    return deferred.promise;
};

Vba macro to copy row from table if value in table meets condition

you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.

You should always consider a non-vba solution first.

Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):

http://www.youtube.com/watch?v=RCLUM0UMLXo

http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx


If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.

If it has to be the latter, then there is need for more details on your specification, regarding performance questions.

You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.

This would look something like that:

Public Sub CopyFilter()

  Dim wks As Worksheet
  Dim avarTemp() As Variant
  'go through each worksheet
  For Each wks In ThisWorkbook.Worksheets
        avarTemp = wks.UsedRange
        For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
          'check in the first column in each row
          If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
            'copy cell
             targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
          End If
        Next i
  Next wks
End Sub

Ok, now i have something nice which could come in handy for myself:

Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
  Dim avarTemp() As Variant
  Dim avarResult() As Variant
  Dim i As Long
  avarTemp = rng

  ReDim avarResult(0)

  For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
      If avarTemp(i, 1) = "active" Then
        avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
        'expand our result array
        ReDim Preserve avarResult(UBound(avarResult) + 1)
      End If
  Next i

  FILTER = avarResult
End Function

You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)

How to check if all of the following items are in a list?

What if your lists contain duplicates like this:

v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']

Sets do not contain duplicates. So, the following line returns True.

set(v2).issubset(v1)

To count for duplicates, you can use the code:

v1 = sorted(v1)
v2 = sorted(v2)


def is_subseq(v2, v1):
    """Check whether v2 is a subsequence of v1."""
    it = iter(v1)
    return all(c in it for c in v2) 

So, the following line returns False.

is_subseq(v2, v1)

C# LINQ select from list

The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.

Let's say you have a list of integers, and want to find the items that match those integers.

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var items = from p in context.Items
                 where numbers.Contains(p.ItemId)
                select p;

Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0

Simulate a specific CURL in PostMan

A simpler approach would be:

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!
  5. Click Send to post the command

Hope this helps!

How to set ssh timeout?

Well, you could use nohup to run whatever you are running on 'non-blocking mode'. So you can just keep checking if whatever it was supposed to run, ran, otherwise exit.

nohup ./my-script-that-may-take-long-to-finish.sh &
./check-if-previous-script-ran-or-exit.sh

echo "Script ended on Feb 15, 2011, 9:20AM" > /tmp/done.txt

So in the second one you just check if the file exists.

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

Lua string to int

All numbers in Lua are floats (edit: Lua 5.2 or less). If you truly want to convert to an "int" (or at least replicate this behavior), you can do this:

local function ToInteger(number)
    return math.floor(tonumber(number) or error("Could not cast '" .. tostring(number) .. "' to number.'"))
end

In which case you explicitly convert the string (or really, whatever it is) into a number, and then truncate the number like an (int) cast would do in Java.

Edit: This still works in Lua 5.3, even thought Lua 5.3 has real integers, as math.floor() returns an integer, whereas an operator such as number // 1 will still return a float if number is a float.

Error in spring application context schema

use this:

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"

Codeigniter $this->input->post() empty while $_POST is working correctly

Solved as follows:

Does the following exclude the redirection that is .htacess that will run the $ this-> input- > post ('name' ) on the controller, in my case it worked perfectly .

abs, José Camargo]

Failed binder transaction when putting an bitmap dynamically in a widget

I have solved this issue by storing images on internal storage and then using .setImageURI() rather than .setBitmap().

How do I get an apk file from an Android device?

The procedures outlined here do not work for Android 7 (Nougat) [and possibly Android 6, but I'm unable to verify]. You can't pull the .apk files directly under Nougat (unless in root mode, but that requires a rooted phone). But, you can copy the .apk to an alternate path (say /sdcard/Download) on the phone using adb shell, then you can do an adb pull from the alternate path.

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Months after this question, I've levelup my Docker skills. I should use Docker container name instead.

That use dokerized-nginx as bridge to expose ip+port of the container.

Within WEB configuration, I now use mysql://USERNAME:PASSWORD@docker_container_name/DB_NAME to access to Mysql socket through docker (also works with docker-compose, use compose-name instead of container one)

How can I save an image with PIL?

Try removing the . before the .bmp (it isn't matching BMP as expected). As you can see from the error, the save_handler is upper-casing the format you provided and then looking for a match in SAVE. However the corresponding key in that object is BMP (instead of .BMP).

I don't know a great deal about PIL, but from some quick searching around it seems that it is a problem with the mode of the image. Changing the definition of j to:

j = Image.fromarray(b, mode='RGB')

Seemed to work for me (however note that I have very little knowledge of PIL, so I would suggest using @mmgp's solution as s/he clearly knows what they are doing :) ). For the types of mode, I used this page - hopefully one of the choices there will work for you.