Programs & Examples On #Beforeupdate

Case insensitive comparison NSString

On macOS you can simply use -[NSString isCaseInsensitiveLike:], which returns BOOL just like -isEqual:.

if ([@"Test" isCaseInsensitiveLike: @"test"])
    // Success

Pycharm and sys.argv arguments

On PyCharm Community or Professional Edition 2019.1+ :

  1. From the menu bar click Run -> Edit Configurations
  2. Add your arguments in the Parameters textbox (for example file2.txt file3.txt, or --myFlag myArg --anotherFlag mySecondArg)
  3. Click Apply
  4. Click OK

new Runnable() but no new thread?

Best and easy way is just pass argument and create instance and call thread method

Call thread using create a thread object and send a runnable class object with parameter or without parameter and start method of thread object.

In my condition I am sending parameter and I will use in run method.

new Thread(new FCMThreadController("2", null, "3", "1")).start();

OR

new Thread(new FCMThreadController()).start();

public class FCMThreadController implements Runnable {
private String type;
private List<UserDeviceModel> devices;
private String message;
private String id;


    public FCMThreadController(String type, List<UserDeviceModel> devices, String message, String id) {

        this.type = type;
        this.devices = devices;
        this.message = message;
        this.id = id;
    }



    public FCMThreadController( ) {

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

    }



}

Select first occurring element after another element

#many .more.selectors h4 + p { ... }

This is called the adjacent sibling selector.

How to install a previous exact version of a NPM package?

First remove old version, then run literally the following:

npm install [email protected]

and for stable or recent

npm install -g npm@latest    // For the last stable version
npm install -g npm@next      // For the most recent release

Creating and returning Observable from Angular 2 Service

I'm a little late to the party, but I think my approach has the advantage that it lacks the use of EventEmitters and Subjects.

So, here's my approach. We can't get away from subscribe(), and we don't want to. In that vein, our service will return an Observable<T> with an observer that has our precious cargo. From the caller, we'll initialize a variable, Observable<T>, and it will get the service's Observable<T>. Next, we'll subscribe to this object. Finally, you get your "T"! from your service.

First, our people service, but yours doesnt pass parameters, that's more realistic:

people(hairColor: string): Observable<People> {
   this.url = "api/" + hairColor + "/people.json";

   return Observable.create(observer => {
      http.get(this.url)
          .map(res => res.json())
          .subscribe((data) => {
             this._people = data

             observer.next(this._people);
             observer.complete();


          });
   });
}

Ok, as you can see, we're returning an Observable of type "people". The signature of the method, even says so! We tuck-in the _people object into our observer. We'll access this type from our caller in the Component, next!

In the Component:

private _peopleObservable: Observable<people>;

constructor(private peopleService: PeopleService){}

getPeople(hairColor:string) {
   this._peopleObservable = this.peopleService.people(hairColor);

   this._peopleObservable.subscribe((data) => {
      this.people = data;
   });
}

We initialize our _peopleObservable by returning that Observable<people> from our PeopleService. Then, we subscribe to this property. Finally, we set this.people to our data(people) response.

Architecting the service in this fashion has one, major advantage over the typical service: map(...) and component: "subscribe(...)" pattern. In the real world, we need to map the json to our properties in our class and, sometimes, we do some custom stuff there. So this mapping can occur in our service. And, typically, because our service call will be used not once, but, probably, in other places in our code, we don't have to perform that mapping in some component, again. Moreover, what if we add a new field to people?....

How do you use MySQL's source command to import large files in windows

C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql

That worked for me to import 400MB file into my database.

Getting value of HTML text input

If your page is refreshed on submitting - yes, but only through the querystring: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx (You must use method "GET" then). Else, you can return its value from the php script.

Split (explode) pandas dataframe string entry to separate rows

upgraded MaxU's answer with MultiIndex support

def explode(df, lst_cols, fill_value='', preserve_index=False):
    """
    usage:
        In [134]: df
        Out[134]:
           aaa  myid        num          text
        0   10     1  [1, 2, 3]  [aa, bb, cc]
        1   11     2         []            []
        2   12     3     [1, 2]      [cc, dd]
        3   13     4         []            []

        In [135]: explode(df, ['num','text'], fill_value='')
        Out[135]:
           aaa  myid num text
        0   10     1   1   aa
        1   10     1   2   bb
        2   10     1   3   cc
        3   11     2
        4   12     3   1   cc
        5   12     3   2   dd
        6   13     4
    """
    # make sure `lst_cols` is list-alike
    if (lst_cols is not None
        and len(lst_cols) > 0
        and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):
        lst_cols = [lst_cols]
    # all columns except `lst_cols`
    idx_cols = df.columns.difference(lst_cols)
    # calculate lengths of lists
    lens = df[lst_cols[0]].str.len()
    # preserve original index values    
    idx = np.repeat(df.index.values, lens)
    res = (pd.DataFrame({
                col:np.repeat(df[col].values, lens)
                for col in idx_cols},
                index=idx)
             .assign(**{col:np.concatenate(df.loc[lens>0, col].values)
                            for col in lst_cols}))
    # append those rows that have empty lists
    if (lens == 0).any():
        # at least one list in cells is empty
        res = (res.append(df.loc[lens==0, idx_cols], sort=False)
                  .fillna(fill_value))
    # revert the original index order
    res = res.sort_index()
    # reset index if requested
    if not preserve_index:        
        res = res.reset_index(drop=True)

    # if original index is MultiIndex build the dataframe from the multiindex
    # create "exploded" DF
    if isinstance(df.index, pd.MultiIndex):
        res = res.reindex(
            index=pd.MultiIndex.from_tuples(
                res.index,
                names=['number', 'color']
            )
    )
    return res

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

How to add some non-standard font to a website?

You can add some fonts via Google Web Fonts.

Technically, the fonts are hosted at Google and you link them in the HTML header. Then, you can use them freely in CSS with @font-face (read about it).

For example:

In the <head> section:

 <link href=' http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'>

Then in CSS:

h1 { font-family: 'Droid Sans', arial, serif; }

The solution seems quite reliable (even Smashing Magazine uses it for an article title.). There are, however, not so many fonts available so far in Google Font Directory.

In STL maps, is it better to use map::insert than []?

If your application is speed critical i will advice using [] operator because it creates total 3 copies of the original object out of which 2 are temporary objects and sooner or later destroyed as.

But in insert(), 4 copies of the original object are created out of which 3 are temporary objects( not necessarily "temporaries") and are destroyed.

Which means extra time for: 1. One objects memory allocation 2. One extra constructor call 3. One extra destructor call 4. One objects memory deallocation

If your objects are large, constructors are typical, destructors do a lot of resource freeing, above points count even more. Regarding readability, i think both are fair enough.

The same question came into my mind but not over readability but speed. Here is a sample code through which I came to know about the point i mentioned.

class Sample
{
    static int _noOfObjects;

    int _objectNo;
public:
    Sample() :
        _objectNo( _noOfObjects++ )
    {
        std::cout<<"Inside default constructor of object "<<_objectNo<<std::endl;
    }

    Sample( const Sample& sample) :
    _objectNo( _noOfObjects++ )
    {
        std::cout<<"Inside copy constructor of object "<<_objectNo<<std::endl;
    }

    ~Sample()
    {
        std::cout<<"Destroying object "<<_objectNo<<std::endl;
    }
};
int Sample::_noOfObjects = 0;


int main(int argc, char* argv[])
{
    Sample sample;
    std::map<int,Sample> map;

    map.insert( std::make_pair<int,Sample>( 1, sample) );
    //map[1] = sample;
    return 0;
}

Output when insert() is used Output when [] operator is used

How to draw vertical lines on a given plot in matplotlib

The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline

import matplotlib.pyplot as plt

plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)

OR

xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
    plt.axvline(x=xc)

You can use many of the keywords available for other plot commands (e.g. color, linestyle, linewidth ...). You can pass in keyword arguments ymin and ymax if you like in axes corrdinates (e.g. ymin=0.25, ymax=0.75 will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline) and rectangles (axvspan).

Hex colors: Numeric representation for "transparent"?

Very simple: no color, no opacity:

rgba(0, 0, 0, 0);

How to simulate key presses or a click with JavaScript?

Or even shorter, with only standard modern Javascript:

var first_link = document.getElementsByTagName('a')[0];
first_link.dispatchEvent(new MouseEvent('click'));

The new MouseEvent constructor takes a required event type name, then an optional object (at least in Chrome). So you could, for example, set some properties of the event:

first_link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));

Comparing Class Types in Java

As said earlier, your code will work unless you have the same classes loaded on two different class loaders. This might happen in case you need multiple versions of the same class in memory at the same time, or you are doing some weird on the fly compilation stuff (as I am).

In this case, if you want to consider these as the same class (which might be reasonable depending on the case), you can match their names to compare them.

public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
  // TODO handle nulls maybe?
  return c1.getCanonicalName().equals(c2.getCanonicalName());
}

Keep in mind that this comparison will do just what it does: compare class names; I don't think you will be able to cast from one version of a class to the other, and before looking into reflection, you might want to make sure there's a good reason for your classloader mess.

How to redirect all HTTP requests to HTTPS

I'd recommend with 301 redirect:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Can I use DIV class and ID together in CSS?

If you want to target a specific class and ID in CSS, then use a format like div.x#y {}.

Returning anonymous type in C#

With reflection.

public object tst() {
    var a = new {
        prop1 = "test1",
        prop2 = "test2"
    };

    return a;
}


public string tst2(object anonymousObject, string propName) {
    return anonymousObject.GetType().GetProperties()
        .Where(w => w.Name == propName)
        .Select(s => s.GetValue(anonymousObject))
        .FirstOrDefault().ToString();
}

Sample:

object a = tst();
var val = tst2(a, "prop2");

Output:

test2

How to loop through file names returned by find?

I like to use find which is first assigned to variable and IFS switched to new line as follow:

FilesFound=$(find . -name "*.txt")

IFSbkp="$IFS"
IFS=$'\n'
counter=1;
for file in $FilesFound; do
    echo "${counter}: ${file}"
    let counter++;
done
IFS="$IFSbkp"

As commented by @Konrad Rudolph this will not work with "new lines" in file name. I still think it is handy as it covers most of the cases when you need to loop over command output.

disable all form elements inside div

Only text type

$(".form-edit-account :input[type=text]").attr("disabled", "disabled");

Only Password type

$(".form-edit-account :input[type=password]").attr("disabled", "disabled");

Only Email Type

$(".form-edit-account :input[type=email]").attr("disabled", "disabled");

How to create a floating action button (FAB) in android, using AppCompat v21?

There are a bunch of libraries out there add a FAB(Floating Action Button) in your app, Here are few of them i Know.

makovkastar's FAB

futuersimple's Composite FAB

Material Design library which includes FAB too

All these libraries are supported on pre-lollipop devices, minimum to api 8

Extract / Identify Tables from PDF python

After many fruitful hours of exploring OCR libraries, bounding boxes and clustering algorithms - I found a solution so simple it makes you want to cry!

I hope you are using Linux;

pdftotext -layout NAME_OF_PDF.pdf

AMAZING!!

Now you have a nice text file with all the information lined up in nice columns, now it is trivial to format into a csv etc..

It is for times like this that I love Linux, these guys came up with AMAZING solutions to everything, and put it there for FREE!

How can I keep my branch up to date with master with git?

You can use the cherry-pick to get the particular bug fix commit(s)

$ git checkout branch
$ git cherry-pick bugfix

How to find the socket connection state in C?

I had a similar problem. I wanted to know whether the server is connected to client or the client is connected to server. In such circumstances the return value of the recv function can come in handy. If the socket is not connected it will return 0 bytes. Thus using this I broke the loop and did not have to use any extra threads of functions. You might also use this same if experts feel this is the correct method.

What does the 'export' command do?

I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.

In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.

In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile or /etc/.bashrc but otherwise, they're not permanent. They're stored in RAM.

There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.

You can view shell variables with the set command (though note that unlike windows, variables are not set in linux with the set command).

set -o posix; set (doing that set -o posix once first, helps not display too much unnecessary stuff). So set displays shell variables.

You can view environment variables with the env command

shell variables are set with e.g. just a = 5

environment variables are set with export, export also sets the shell variable

Here you see shell variable zzz set with zzz = 5, and see it shows when running set but doesn't show as an environment variable.

Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables

$ zzz=5

$ set | grep zzz
zzz=5

$ env | grep zzz

$ export yyy=5

$ set | grep yyy
yyy=5

$ env | grep yyy
yyy=5

$

other useful threads

https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables

https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference

Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf then it sets $1 to asdf, and if you do echo $1 you see asdf. If you do set a=5 it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose to turn verbose off. Windows has no such usage for its set command.

Split an integer into digits to compute an ISBN checksum

list_of_ints = [int(i) for i in str(ISBN)]

Will give you a ordered list of ints. Of course, given duck typing, you might as well work with str(ISBN).

Edit: As mentioned in the comments, this list isn't sorted in the sense of being ascending or descending, but it does have a defined order (sets, dictionaries, etc in python in theory don't, although in practice the order tends to be fairly reliable). If you want to sort it:

list_of_ints.sort()

is your friend. Note that sort() sorts in place (as in, actually changes the order of the existing list) and doesn't return a new list.

What is the best way to get the minimum or maximum value from an Array of numbers?

There isn't any reliable way to get the minimum/maximum without testing every value. You don't want to try a sort or anything like that, walking through the array is O(n), which is better than any sort algorithm can do in the general case.

Issue pushing new code in Github

I got this error on Azure Git, and this solves the problem:

git fetch
git pull
git push --no-verify

Laravel 5 not finding css files

Stop artisan serve

and try using

php -S localhost:8000 -t public

How to play an android notification sound

It's been a while since your question, but ... Have you tried setting the Audio stream type?

mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

It must be done before prepare.

Asp.net MVC ModelState.Clear

I had an instance where I wanted to update the model of a sumitted form, and did not want to 'Redirect To Action' for performanace reason. Previous values of hidden fields were being retained on my updated model - causing allsorts of issues!.

A few lines of code soon identified the elements within ModelState that I wanted to remove (after validation), so the new values were used in the form:-

while (ModelState.FirstOrDefault(ms => ms.Key.ToString().StartsWith("SearchResult")).Value != null)
{
    ModelState.Remove(ModelState.FirstOrDefault(ms => ms.Key.ToString().StartsWith("SearchResult")));
}

git pull error :error: remote ref is at but expected

I faced same issue , I just deleted the remote branch and created new branch from the master and merged my changes from old feature branch to new feature branch . Now i tried pull and push requests its worked for me

PHP Echo text Color

This is an old question, but no one responded to the question regarding centering text in a terminal.

/**
 * Centers a string of text in a terminal window
 *
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 *
 * @return string The padded result, ready to echo
 */
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}

echo center('foo');
echo center('bar baz', '=');

Installing PDO driver on MySQL Linux server

That's a good question, but I think you just misunderstand what you read.

Install PDO

The ./config --with-pdo-mysql is something you have to put on only if you compile your own PHP code. If you install it with package managers, you just have to use the command line given by Jany Hartikainen: sudo apt-get install php5-mysql and also sudo apt-get install pdo-mysql

Compatibility with mysql_

Apart from the fact mysql_ is really discouraged, they are both independent. If you use PDO mysql_ is not implicated, and if you use mysql_ PDO is not required.

If you turn off PDO without changing any line in your code, you won't have a problem. But since you started to connect and write queries with PDO, you have to keep it and give up mysql_.

Several years ago the MySQL team published a script to migrate to MySQLi. I don't know if it can be customised, but it's official.

Another git process seems to be running in this repository

I tried deleting .git/indexbut didn't work, I end up uninstalling go and removing all folders that has go name in it, and then installing go again, and it workerd!

How can I do SELECT UNIQUE with LINQ?

var uniqueColors = (from dbo in database.MainTable 
                    where dbo.Property == true
                    select dbo.Color.Name).Distinct();

How to install Ruby 2.1.4 on Ubuntu 14.04

First of all, install the prerequisite libraries:

sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Then install rbenv, which is used to install Ruby:

cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL

rbenv install 2.3.1
rbenv global 2.3.1
ruby -v

Then (optional) tell Rubygems to not install local documentation:

echo "gem: --no-ri --no-rdoc" > ~/.gemrc

Credits: https://gorails.com/setup/ubuntu/14.10

Warning!!! There are issues with Gnome-Shell. See comment below.

How do I get an apk file from an Android device?

Use adb. With adb pull you can copy files from your device to your system, when the device is attached with USB.

Of course you also need the right permissions to access the directory your file is in. If not, you will need to root the device first.


If you find that many of the APKs are named "base.apk" you can also use this one line command to pull all the APKs off a phone you can access while renaming any "base.apk" names to the package name. This also fixes the directory not found issue for APK paths with seemingly random characters after the name:

for i in $(adb shell pm list packages | awk -F':' '{print $2}'); do adb pull "$(adb shell pm path $i | awk -F':' '{print $2}')"; mv base.apk $i.apk 2&> /dev/null ;done

If you get "adb: error: failed to stat remote object" that indicates you don't have the needed permissions. I ran this on a NON-rooted Moto Z2 and was able to download ALL the APKs I did not uninstall (see below) except youtube.

adb shell pm uninstall --user 0 com.android.cellbroadcastreceiver   <--- kills presidential alert app!

(to view users run adb shell pm list users) This is a way to remove/uninstall (not from the phone as it comes back with factory reset) almost ANY app WITHOUT root INCLUDING system apps (hint the annoying update app that updates your phone line it or not can be found by grepping for "ccc")

Getting only 1 decimal place

>>> "{:.1f}".format(45.34531)
'45.3'

Or use the builtin round:

>>> round(45.34531, 1)
45.299999999999997

OR, AND Operator

Use '&&' for AND and use '||' for OR, for example:

bool A;
bool B;

bool resultOfAnd = A && B; // Returns the result of an AND
bool resultOfOr = A || B; // Returns the result of an OR

How to force NSLocalizedString to use a specific language

I like best Mauro Delrio's method. I also have added the following in my Project_Prefix.pch

#import "Language.h"    
#define MyLocalizedString(key, alt) [Language get:key alter:alt]

So if you ever want to use the standard method (that uses NSLocalizedString) you can make a quick syntax substitution in all files.

Chrome desktop notification example

I like: http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examples but it uses old variables, so the demo doesn't work anymore. webkitNotifications is now Notification.

Create Table from View

SQL Server does not support CREATE TABLE AS SELECT.

Use this:

SELECT  *
INTO    A
FROM    myview

or

SELECT  TOP 10
        *
INTO    A
FROM    myview
ORDER BY
        id

How to Bulk Insert from XLSX file extension?

It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

T-SQL query to show table definition?

Simply type the table name and select it and press ATL + F1

Say your table name is Customer then open a new query window, type and select the table name and press ALT + F1

It will show the complete definition of table.

Fixed header, footer with scrollable content

Something like this

<html>
  <body style="height:100%; width:100%">
    <div id="header" style="position:absolute; top:0px; left:0px; height:200px; right:0px;overflow:hidden;"> 
    </div> 
    <div id="content" style="position:absolute; top:200px; bottom:200px; left:0px; right:0px; overflow:auto;"> 
    </div> 
    <div id="footer" style="position:absolute; bottom:0px; height:200px; left:0px; right:0px; overflow:hidden;"> 
    </div>
  </body>
</html> 

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

JavaScript replace/regex

In terms of pattern interpretation, there's no difference between the following forms:

  • /pattern/
  • new RegExp("pattern")

If you want to replace a literal string using the replace method, I think you can just pass a string instead of a regexp to replace.

Otherwise, you'd have to escape any regexp special characters in the pattern first - maybe like so:

function reEscape(s) {
    return s.replace(/([.*+?^$|(){}\[\]])/mg, "\\$1");
}

// ...

var re = new RegExp(reEscape(pattern), "mg");
this.markup = this.markup.replace(re, value);

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

You have to add

<script>jQuery.noConflict();</script>

after

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

How to sort strings in JavaScript

An updated answer (October 2014)

I was really annoyed about this string natural sorting order so I took quite some time to investigate this issue. I hope this helps.

Long story short

localeCompare() character support is badass, just use it. As pointed out by Shog9, the answer to your question is:

return item1.attr.localeCompare(item2.attr);

Bugs found in all the custom javascript "natural string sort order" implementations

There are quite a bunch of custom implementations out there, trying to do string comparison more precisely called "natural string sort order"

When "playing" with these implementations, I always noticed some strange "natural sorting order" choice, or rather mistakes (or omissions in the best cases).

Typically, special characters (space, dash, ampersand, brackets, and so on) are not processed correctly.

You will then find them appearing mixed up in different places, typically that could be:

  • some will be between the uppercase 'Z' and the lowercase 'a'
  • some will be between the '9' and the uppercase 'A'
  • some will be after lowercase 'z'

When one would have expected special characters to all be "grouped" together in one place, except for the space special character maybe (which would always be the first character). That is, either all before numbers, or all between numbers and letters (lowercase & uppercase being "together" one after another), or all after letters.

My conclusion is that they all fail to provide a consistent order when I start adding barely unusual characters (ie. characters with diacritics or charcters such as dash, exclamation mark and so on).

Research on the custom implementations:

Browsers' native "natural string sort order" implementations via localeCompare()

localeCompare() oldest implementation (without the locales and options arguments) is supported by IE6+, see http://msdn.microsoft.com/en-us/library/ie/s4esdbwz(v=vs.94).aspx (scroll down to localeCompare() method). The built-in localeCompare() method does a much better job at sorting, even international & special characters. The only problem using the localeCompare() method is that "the locale and sort order used are entirely implementation dependent". In other words, when using localeCompare such as stringOne.localeCompare(stringTwo): Firefox, Safari, Chrome & IE have a different sort order for Strings.

Research on the browser-native implementations:

Difficulty of "string natural sorting order"

Implementing a solid algorithm (meaning: consistent but also covering a wide range of characters) is a very tough task. UTF8 contains more than 2000 characters & covers more than 120 scripts (languages). Finally, there are some specification for this tasks, it is called the "Unicode Collation Algorithm", which can be found at http://www.unicode.org/reports/tr10/ . You can find more information about this on this question I posted https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order

Final conclusion

So considering the current level of support provided by the javascript custom implementations I came across, we will probably never see anything getting any close to supporting all this characters & scripts (languages). Hence I would rather use the browsers' native localeCompare() method. Yes, it does have the downside of beeing non-consistent across browsers but basic testing shows it covers a much wider range of characters, allowing solid & meaningful sort orders.

So as pointed out by Shog9, the answer to your question is:

return item1.attr.localeCompare(item2.attr);

Further reading:

Thanks to Shog9's nice answer, which put me in the "right" direction I believe

Powershell: count members of a AD group

In Powershell, you'll need to import the active directory module, then use the get-adgroupmember, and then measure-object. For example, to get the number of users belonging to the group "domain users", do the following:

Import-Module activedirecotry
Get-ADGroupMember "domain users" | Measure-Object

When entering the group name after "Get-ADGroupMember", if the name is a single string with no spaces, then no quotes are necessary. If the group name has spaces in it, use the quotes around it.

The output will look something like:

Count    : 12345
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

Note - importing the active directory module may be redundant if you're already using PowerShell for other AD admin tasks.

OrderBy pipe issue

I've created an OrderBy pipe that does just what you need. It supports being able to sort on multiple columns of an enumerable of objects as well.

<li *ngFor="#todo in todos | orderBy : ['completed']">{{todo.name}} {{todo.completed}}</li>

This pipe does allow for adding more items to the array after rendering the page, and will sort the array with the updates dynamically.

I have a write up on the process here.

And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

How can I work with command line on synology?

I use GateOne from the synocommunity.

Go into settings in Package Center and add http://packages.synocommunity.com/ as a package source. Then you should be able to add it easily via Package Center.

SQL query, store result of SELECT in local variable

Isn't this a much simpler solution, if I correctly understand the question, of course.

I want to load email addresses that are in a table called "spam" into a variable.

select email from spam

produces the following list, say:

.accountant
.bid
.buiilldanything.com
.club
.cn
.cricket
.date
.download
.eu

To load into the variable @list:

declare @list as varchar(8000)
set @list += @list (select email from spam)

@list may now be INSERTed into a table, etc.

I hope this helps.

To use it for a .csv file or in VB, spike the code:

declare @list as varchar(8000)
set @list += @list (select '"'+email+',"' from spam)
print @list

and it produces ready-made code to use elsewhere:

".accountant,"
".bid,"
".buiilldanything.com,"
".club,"
".cn,"
".cricket,"
".date,"
".download,"
".eu,"

One can be very creative.

Thanks

Nico

Where is debug.keystore in Android Studio

In the case of Flutter you have to open the android part of the project only File->open->select the android folder of that project wait few minutes to complete the gradle sync after that on the right side click on the gradle->android->Tasks->android->signin Report

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

For Mac users make sure to sudo and when prompted first give your administrator password and that will be followed by keystore password which typically should be "changeit" unless you actually changed it.

how do you filter pandas dataframes by multiple columns

You can create your own filter function using query in pandas. Here you have filtering of df results by all the kwargs parameters. Dont' forgot to add some validators(kwargs filtering) to get filter function for your own df.

def filter(df, **kwargs):
    query_list = []
    for key in kwargs.keys():
        query_list.append(f'{key}=="{kwargs[key]}"')
    query = ' & '.join(query_list)
    return df.query(query)

How to get the file name from a full path using JavaScript?

Another one

var filename = fullPath.split(/[\\\/]/).pop();

Here split have a regular expression with a character class
The two characters have to be escaped with '\'

Or use array to split

var filename = fullPath.split(['/','\\']).pop();

It would be the way to dynamically push more separators into an array, if needed.
If fullPath is explicitly set by a string in your code it need to escape the backslash!
Like "C:\\Documents and Settings\\img\\recycled log.jpg"

Get the client IP address using PHP

In PHP 5.3 or greater, you can get it like this:

$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');

Android: keep Service running when app is killed

The reason for this is that you are trying to use an IntentService. Here is the line from the API Docs

The IntentService does the following:

Stops the service after all start requests have been handled, so you never have to call stopSelf().

Thus if you want your service to run indefinitely i suggest you extend the Service class instead. However this does not guarantee your service will run indefinitely. Your service will still have a chance of being killed by the kernel in a state of low memory if it is low priority.So you have two options:
1)Keep it running in the foreground by calling the startForeground() method.
2)Restart the service if it gets killed. Here is a part of the example from the docs where they talk about restarting the service after it is killed

 public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // For each start request, send a message to start a job and deliver the 
      // start ID so we know which request we're stopping when we finish the job 
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);

      // If we get killed, after returning from here, restart 
      return START_STICKY;
  }  

How to resize an image to a specific size in OpenCV?

You can use cvResize. Or better use c++ interface (eg cv::Mat instead of IplImage and cv::imread instead of cvLoadImage) and then use cv::resize which handles memory allocation and deallocation itself.

Can you do greater than comparison on a date in a Rails 3 search?

Note.
  where(:user_id => current_user.id, :notetype => p[:note_type]).
  where("date > ?", p[:date]).
  order('date ASC, created_at ASC')

or you can also convert everything into the SQL notation

Note.
  where("user_id = ? AND notetype = ? AND date > ?", current_user.id, p[:note_type], p[:date]).
  order('date ASC, created_at ASC')

Indexing vectors and arrays with +:

Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:

logic [31: 0] a_vect;
logic [0 :31] b_vect;
logic [63: 0] dword;
integer sel;
a_vect[ 0 +: 8] // == a_vect[ 7 : 0]
a_vect[15 -: 8] // == a_vect[15 : 8]
b_vect[ 0 +: 8] // == b_vect[0 : 7]
b_vect[15 -: 8] // == b_vect[8 :15]
dword[8*sel +: 8] // variable part-select with fixed width

If sel is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel is 7 then dword[8*(7) +: 8] == dword[63:56]

The value to the left always the starting index. The number to the right is the width and must be a positive constant. the + and - indicates to select the bits of a higher or lower index value then the starting index.

Assuming address is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2]) is the equivalent of if({address[2*pointer+1],address[2*pointer]})

Install msi with msiexec in a Specific Directory

for my msi, I had to set DEFAULTPATHC="D:\myfolder" because later in the installation process, both INSTALLDIR and TARGETDIR were reset to reflect the value in DEFAULTPATHC

What's the purpose of META-INF?

I've noticed that some Java libraries have started using META-INF as a directory in which to include configuration files that should be packaged and included in the CLASSPATH along with JARs. For example, Spring allows you to import XML Files that are on the classpath using:

<import resource="classpath:/META-INF/cxf/cxf.xml" />
<import resource="classpath:/META-INF/cxf/cxf-extensions-*.xml" />

In this example, I'm quoting straight out of the Apache CXF User Guide. On a project I worked on in which we had to allow multiple levels of configuration via Spring, we followed this convention and put our configuration files in META-INF.

When I reflect on this decision, I don't know what exactly would be wrong with simply including the configuration files in a specific Java package, rather than in META-INF. But it seems to be an emerging de facto standard; either that, or an emerging anti-pattern :-)

How do I specify new lines on Python, when writing on files?

The same way with '\n', though you'd probably not need the '\r'. Is there a reason you have it in your Java version? If you do need/want it, you can use it in the same way in Python too.

Accessing the logged-in user in a template

You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

Warning, if the user is not logged, the app.user is null.

If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

So, in every of your pages you can do :

{% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

Markdown and including multiple files

I would just mention that you can use the cat command to concatenate the input files prior to piping them to markdown_py which has the same effect as what pandoc does with multiple input files coming in.

cat *.md | markdown_py > youroutputname.html

works pretty much the same as the pandoc example above for the Python version of Markdown on my Mac.

Two Decimal places using c#

Your question is asking to display two decimal places. Using the following String.format will help:

String.Format("{0:.##}", Debitvalue)

this will display then number with up to two decimal places(e.g. 2.10 would be shown as 2.1 ).

Use "{0:.00}", if you want always show two decimal places(e.g. 2.10 would be shown as 2.10 )

Or if you want the currency symbol displayed use the following:

String.Format("{0:C}", Debitvalue)

Python 3.1.1 string to hex

Yet another method:

s = 'hello'

h = ''.join([hex(ord(i)) for i in s]);

# outputs: '0x680x650x6c0x6c0x6f'

This basically splits the string into chars, does the conversion through hex(ord(char)), and joins the chars back together. In case you want the result without the prefix 0x then do:

h = ''.join([str(hex(ord(i)))[2:4] for i in s]);

# outputs: '68656c6c6f'

Tested with Python 3.5.3.

How to schedule a periodic task in Java?

You should take a look to Quartz it's a java framework wich works with EE and SE editions and allows to define jobs to execute an specific time

Markdown: continue numbered list

If you use tab to indent the code block it will shape the entire block into one line. To avoid this you need to use html ordered list.

  1. item 1
  2. item 2

Code block

<ol start="3">
  <li>item 3</li>
  <li>item 4</li>
</ol>

How to make audio autoplay on chrome

Use iframe instead:

<iframe id="stream" src="YOUTSOURCEAUDIOORVIDEOHERE" frameborder="0"></iframe>

C++ delete vector, objects, free memory

vector::clear() does not free memory allocated by the vector to store objects; it calls destructors for the objects it holds.

For example, if the vector uses an array as a backing store and currently contains 10 elements, then calling clear() will call the destructor of each object in the array, but the backing array will not be deallocated, so there is still sizeof(T) * 10 bytes allocated to the vector (at least). size() will be 0, but size() returns the number of elements in the vector, not necessarily the size of the backing store.

As for your second question, anything you allocate with new you must deallocate with delete. You typically do not maintain a pointer to a vector for this reason. There is rarely (if ever) a good reason to do this and you prevent the vector from being cleaned up when it leaves scope. However, calling clear() will still act the same way regardless of how it was allocated.

SQL Server Error : String or binary data would be truncated

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.

I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

Pad with leading zeros

You can do this with a string datatype. Use the PadLeft method:

var myString = "1";
myString = myString.PadLeft(myString.Length + 5, '0');

000001

Handling InterruptedException in Java

What are you trying to do?

The InterruptedException is thrown when a thread is waiting or sleeping and another thread interrupts it using the interrupt method in class Thread. So if you catch this exception, it means that the thread has been interrupted. Usually there is no point in calling Thread.currentThread().interrupt(); again, unless you want to check the "interrupted" status of the thread from somewhere else.

Regarding your other option of throwing a RuntimeException, it does not seem a very wise thing to do (who will catch this? how will it be handled?) but it is difficult to tell more without additional information.

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

How to access the SMS storage on Android?

You are going to need to call the SmsManager class. You are probably going to need to use the STATUS_ON_ICC_READ constant and maybe put what you get there into your apps local db so that you can keep track of what you have already read vs the new stuff for your app to parse through. BUT bear in mind that you have to declare the use of the class in your manifest, so users will see that you have access to their SMS called out in the permissions dialogue they get when they install. Seeing SMS access is unusual and could put some users off. Good luck.

Here is the link that goes into depth on the Sms Manager

How to retrieve element value of XML using Java?

In case you just need one (first) value to retrieve from xml:

public static String getTagValue(String xml, String tagName){
    return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
}

In case you want to parse whole xml document use JSoup:

Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
for (Element e : doc.select("Request")) {
    System.out.println(e);
}

error, string or binary data would be truncated when trying to insert

When I tried to execute my stored procedure I had the same problem because the size of the column that I need to add some data is shorter than the data I want to add.

You can increase the size of the column data type or reduce the length of your data.

What "wmic bios get serialnumber" actually retrieves?

run cmd

Enter wmic baseboard get product,version,serialnumber

Press the enter key. The result you see under serial number column is your motherboard serial number

Showing which files have changed between two revisions

There are two branches lets say

  • A (Branch on which you are working)
  • B (Another branch with which you want to compare)

Being in branch A you can type

git diff --color B

then this will give you a output of

enter image description here

The important point about this is

  1. Text in green is inside present in Branch A

  2. Text in red is present in Branch B

Using ZXing to create an Android barcode scanning app

The ZXing project provides a standalone barcode reader application which — via Android's intent mechanism — can be called by other applications who wish to integrate barcode scanning.

The easiest way to do this is to call the ZXing SCAN Intent from your application, like this:

public Button.OnClickListener mScan = new Button.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    }
};

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
            // Handle successful scan
        } else if (resultCode == RESULT_CANCELED) {
            // Handle cancel
        }
    }
}

Pressing the button linked to mScan would launch directly into the ZXing barcode scanner screen (or crash if ZXing isn't installed). Once a barcode has been recognised, you'll receive the result in your Activity, here in the contents variable.

To avoid the crashing and simplify things for you, ZXing have provided a utility class which you could integrate into your application to make the installation of ZXing smoother, by redirecting the user to the Android Market if they don't have it installed already.

Finally, if you want to integrate barcode scanning directly into your application without relying on having the separate ZXing application installed, well then it's an open source project and you can do so! :)


Edit: Somebody edited this guide into this answer (it sounds a bit odd, I can't vouch as to its accuracy, and I'm not sure why they're using Eclipse in 2015):

Step by step to setup zxing 3.2.1 in eclipse

  1. Download zxing-master.zip from "https://github.com/zxing/zxing"
  2. Unzip zxing-master.zip, Use eclipse to import "android" project in zxing-master
  3. Download core-3.2.1.jar from "http://repo1.maven.org/maven2/com/google/zxing/core/3.2.1/"
  4. Create "libs" folder in "android" project and paste cor-3.2.1.jar into the libs folder
  5. Click on project: choose "properties" -> "Java Compiler" to change level to 1.7. Then click on "Android" change "Project build target" to android 4.4.2+, because using 1.7 requires compiling with Android 4.4
  6. If "CameraConfigurationUtils.java" don't exist in "zxing-master/android/app/src/main/java/com/google/zxing/client/android/camera/". You can copy it from "zxing-master/android-core/src/main/java/com/google/zxing/client/android/camera/" and paste to your project.
  7. Clean and build project. If your project show error about "switch - case", you should change them to "if - else".
  8. Completed. Clean and build project. You can click on "Proprties" > "Android" > click on "Is Libraries" to use for your project.

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

Please check the following file

%SystemRoot%\system32\drivers\etc\host

The line which bind the host name with ip is probably missing a line which bind them togather

127.0.0.1  localhost

If the given line is missing. Add the line in the file


Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.

Python: finding an element in a list

The best way is probably to use the list method .index.

For the objects in the list, you can do something like:

def __eq__(self, other):
    return self.Value == other.Value

with any special processing you need.

You can also use a for/in statement with enumerate(arr)

Example of finding the index of an item that has value > 100.

for index, item in enumerate(arr):
    if item > 100:
        return index, item

Source

Java: Retrieving an element from a HashSet

You can HashMap<MyHashObject,MyHashObject> instead of HashSet<MyHashObject>.

Calling ContainsKey() on your "reconstructed" MyHashObject will first hashCode()-check the collection, and if a duplicate hashcode is hit, finally equals()-check your "reconstructed" against the original, at which you can retrieve the original using get()

This is O(1) but the downside is you will likely have to override both equals() and hashCode() methods.

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

As per the comment by Cody, this has nothing to do with Linux, but is a hint to the compiler. What happens will depend on the architecture and compiler version.

This particular feature in Linux is somewhat mis-used in drivers. As osgx points out in semantics of hot attribute, any hot or cold function called with in a block can automatically hint that the condition is likely or not. For instance, dump_stack() is marked cold so this is redundant,

 if(unlikely(err)) {
     printk("Driver error found. %d\n", err);
     dump_stack();
 }

Future versions of gcc may selectively inline a function based on these hints. There have also been suggestions that it is not boolean, but a score as in most likely, etc. Generally, it should be preferred to use some alternate mechanism like cold. There is no reason to use it in any place but hot paths. What a compiler will do on one architecture can be completely different on another.

Assigning strings to arrays of characters

Note that you can still do:

s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '\0';

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

As of ES 7, mapping types have been removed. You can read more details here

If you are using Ruby On Rails this means that you may need to remove document_type from your model or concern.

As an alternative to mapping types one solution is to use an index per document type.

Before:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore].join('_')
    document_type self.name.downcase
  end
end

After:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore, self.name.downcase].join('_')
  end
end

How to get a list of column names on Sqlite3 database?

In order to get the column information you can use the following snippet:

String sql = "select * from "+oTablename+" LIMIT 0";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData mrs = rs.getMetaData();
for(int i = 1; i <= mrs.getColumnCount(); i++)
{
    Object row[] = new Object[3];
    row[0] = mrs.getColumnLabel(i);
    row[1] = mrs.getColumnTypeName(i);
    row[2] = mrs.getPrecision(i);
}

Pip freeze vs. pip list

Look at the pip documentation, which describes the functionality of both as:

pip list

List installed packages, including editables.

pip freeze

Output installed packages in requirements format.

So there are two differences:

  1. Output format, freeze gives us the standard requirement format that may be used later with pip install -r to install requirements from.

  2. Output content, pip list include editables which pip freeze does not.

how to rotate a bitmap 90 degrees

Using Java createBitmap() method you can pass the degrees.

Bitmap bInput /*your input bitmap*/, bOutput;
float degrees = 45; //rotation degree
Matrix matrix = new Matrix();
matrix.setRotate(degrees);
bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

You need to install Entity framework by right click on your VS solution and click Manage NuGet Package solution and search there Entity framework. After installation the issue will be solved

go get results in 'terminal prompts disabled' error for github private repo

If you configure your gitconfig with this option, you will later have a problem cloning other repos of GitHub

git config --global --add url. "[email protected]". Instead, "https://github.com/"

Instead, I recommend that you use this option

echo "export GIT_TERMINAL_PROMPT=1" >> ~/.bashrc || ~/.zshrc

and do not forget to generate an access token from your private repository. When prompted to enter your password, just paste the access token. Happy clone :)

How to rebase local branch onto remote master

1.Update Master first...

git checkout [master branch]
git pull [master branch]

2.Now rebase source-branch with master branch

git checkout [source branch]
git rebase [master branch]
git pull [source branch] (remote/source branch)
git push [source branch]

IF source branch does not yet exist on remote then do:

git push -u origin [source branch]

"et voila..."

Loading inline content using FancyBox

Just something I found for Wordpress users,

As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.

So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.

Simple I know ^_^

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

try:

string.decode('utf-8')  # or:
unicode(string, 'utf-8')

edit:

'(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'.decode('utf-8') gives u'(\uff61\uff65\u03c9\uff65\uff61)\uff89', which is correct.

so your problem must be at some oter place, possibly if you try to do something with it were there is an implicit conversion going on (could be printing, writing to a stream...)

to say more we'll need to see some code.

How different is Objective-C from C++?

As others have said, Objective-C is much more dynamic in terms of how it thinks of objects vs. C++'s fairly static realm.

Objective-C, being in the Smalltalk lineage of object-oriented languages, has a concept of objects that is very similar to that of Java, Python, and other "standard", non-C++ object-oriented languages. Lots of dynamic dispatch, no operator overloading, send messages around.

C++ is its own weird animal; it mostly skipped the Smalltalk portion of the family tree. In some ways, it has a good module system with support for inheritance that happens to be able to be used for object-oriented programming. Things are much more static (overridable methods are not the default, for example).

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

Add the all tiles jars like(tiles-jsp,tiles-servlet,tiles-template,tiles-extras.tiles-core ) to your server lib folder and your application build path then it work if you using apache tailes with spring mvc application

VBA Excel - Insert row below with same format including borders and frames

When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.

I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).

I've found three workarounds that don't require copying the formatting from the source row:

  1. Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)

  2. Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:

    • Conditional formatting borders are limited to the thin-weight lines.
    • Works best for sheets where borders are relatively consistent so you don't have to create a bunch of conditional formatting rules.
  3. Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).

concatenate two database columns into one resultset column

If you were using SQL 2012 or above you could use the CONCAT function:

SELECT CONCAT(field1, field2, field3) FROM table1

NULL fields won't break your concatenation.

@bummi - Thanks for the comment - edited my answer to correspond to it.

What is the difference between persist() and merge() in JPA and Hibernate?

This is coming from JPA. In a very simple way:

  • persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).

  • merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.

How do you find the row count for all your tables in Postgres

Here is a solution that does not require functions to get an accurate count for each table:

select table_schema, 
       table_name, 
       (xpath('/row/cnt/text()', xml_count))[1]::text::int as row_count
from (
  select table_name, table_schema, 
         query_to_xml(format('select count(*) as cnt from %I.%I', table_schema, table_name), false, true, '') as xml_count
  from information_schema.tables
  where table_schema = 'public' --<< change here for the schema you want
) t

query_to_xml will run the passed SQL query and return an XML with the result (the row count for that table). The outer xpath() will then extract the count information from that xml and convert it to a number

The derived table is not really necessary, but makes the xpath() a bit easier to understand - otherwise the whole query_to_xml() would need to be passed to the xpath() function.

Sublime Text 2: How do I change the color that the row number is highlighted?

tmtheme-editor.herokuapp.com seems pretty nice.

On the mac, the default theme files are in ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/Color\ Scheme\ -\ Default

On Win7, the default theme files are in %appdata%\Sublime Text 2\Packages\Color Scheme - Default

Build a basic Python iterator

Include the following code in your class code.

 def __iter__(self):
        for x in self.iterable:
            yield x

Make sure that you replace self.iterablewith the iterable which you iterate through.

Here's an example code

class someClass:
    def __init__(self,list):
        self.list = list
    def __iter__(self):
        for x in self.list:
            yield x


var = someClass([1,2,3,4,5])
for num in var: 
    print(num) 

Output

1
2
3
4
5

Note: Since strings are also iterable, they can also be used as an argument for the class

foo = someClass("Python")
for x in foo:
    print(x)

Output

P
y
t
h
o
n

Counting repeated elements in an integer array

You have to use or read about associative arrays, or maps,..etc. Storing the the number of occurrences of the repeated elements in array, and holding another array for the repeated elements themselves, don't make much sense.

Your problem in your code is in the inner loop

 for (int j = i + 1; j < x.length; j++) {

        if (x[i] == x[j]) {
            y[i] = x[i];
            times[i]++;
        }

    }

Catch an exception thrown by an async void method

The exception can be caught in the async function.

public async void Foo()
{
    try
    {
        var x = await DoSomethingAsync();
        /* Handle the result, but sometimes an exception might be thrown
           For example, DoSomethingAsync get's data from the network
           and the data is invalid... a ProtocolException might be thrown */
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught here */
    }
}

public void DoFoo()
{
    Foo();
}

Cloning an Object in Node.js

npm install node-v8-clone

Fastest cloner, it open native clone method from node.js

var clone = require('node-v8-clone').clone;
var newObj = clone(obj, true); //true - deep recursive clone

background:none vs background:transparent what is the difference?

As aditional information on @Quentin answer, and as he rightly says, background CSS property itself, is a shorthand for:

background-color
background-image
background-repeat
background-attachment
background-position

That's mean, you can group all styles in one, like:

background: red url(../img.jpg) 0 0 no-repeat fixed;

This would be (in this example):

background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;

So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none; and all the others to the initial state (as they are not being declared).
So, background:none; is:

background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

Now, when you define only the color (in your case transparent) then you are basically saying:

background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

I repeat, as @Quentin rightly says the default transparent and none values in this case are the same, so in your example and for your original question, No, there's no difference between them.

But!.. if you say background:none Vs background:red then yes... there's a big diference, as I say, the first would set all properties to none/default and the second one, will only change the color and remains the rest in his default state.

So in brief:

Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.


Upd1: Initial value (aka default)

Initial value the concatenation of the initial values of its longhand properties:

background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent

See more background descriptions here


Upd2: Clarify better the background:none; specification.

In C#, why is String a reference type that behaves like a value type?

In a very simple words any value which has a definite size can be treated as a value type.

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

I solved my problem in AngularJS as follows:

var configPopOver = {
        animation: 500,
        container: 'body',
        placement: function (context, source) {
                    var elBounding = source.getBoundingClientRect();
                    var pageWidth = angular.element('body')[0].clientWidth
                    var pageHeith = angular.element('body')[0].clientHeith

                    if (elBounding.left > (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
                        return "left";
                    }

                    if (elBounding.left < (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
                        return "right";
                    }

                    if (elBounding.top < 110){
                        return "bottom";
                    }

                    return "top";
                },
        html: true
    };

This function do the position of Bootstrap popover float to the best position, based on element position.

Toggle show/hide on click with jQuery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js</script>        <script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").toggle();
  });
});
</script>
</head>
<body>
<p>Welcome !!!</p>
<button>Toggle between hide() and show()</button>
</body>
</html>

NameError: name 'reduce' is not defined in Python

you need to install and import reduce from functools python package

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

@Blorgbeard:

New Features in C99

  • inline functions
  • variable declaration no longer restricted to file scope or the start of a compound statement
  • several new data types, including long long int, optional extended integer types, an explicit boolean data type, and a complex type to represent complex numbers
  • variable-length arrays
  • support for one-line comments beginning with //, as in BCPL or C++
  • new library functions, such as snprintf
  • new header files, such as stdbool.h and inttypes.h
  • type-generic math functions (tgmath.h)
  • improved support for IEEE floating point
  • designated initializers
  • compound literals
  • support for variadic macros (macros of variable arity)
  • restrict qualification to allow more aggressive code optimization

http://en.wikipedia.org/wiki/C99

A Tour of C99

CSS @font-face not working in ie

1) Try putting an absolute link not relative link to your eot font - somehow old IE just don't know in which folder the css file is 2) make 2 extra @font-face declarations so it should look like this:

@font-face { /* for modern browsers and modern IE */
    font-family: "Futura";
    src: url("../fonts/Futura_Medium_BT.eot"); 
    src: url("../fonts/Futura_Medium_BT.eot?#iefix") format("embedded-opentype"), 
    url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); 
}
@font-face{ /* for old IE */
  font-family: "Futura_IE"; 
  src: url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot);
}

@font-face{ /* for old IE */
  font-family: "Futura_IE2"; 
  src:url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot?#iefix) 
  format("embedded-opentype");
}

.p{ font-family: "Futura", "Futura_IE", "Futura_IE2", Arial, sans-serif;

This is an example for wordpress template - absolute link should point from where your start index file is.

Logger slf4j advantages of formatting with {} instead of string concatenation

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.

jQuery: Load Modal Dialog Contents via Ajax

var dialogName = '#dialog_XYZ';
$.ajax({
        url: "/ajax_pages/my_page.ext",
        data: {....},
        success: function(data) {
          $(dialogName ).remove();

          $('BODY').append(data);

          $(dialogName )
            .dialog(options.dialogOptions);
        }
});

The Ajax-Request load the Dialog, add them to the Body of the current page and open the Dialog.

If you only whant to load the content you can do:

var dialogName = '#dialog_XYZ';
$.ajax({
            url: "/ajax_pages/my_page.ext",
            data: {....},
            success: function(data) {
              $(dialogName).append(data);

              $(dialogName )
                .dialog(options.dialogOptions);
            }
});

Removing duplicate rows in Notepad++

Notepad++ with the TextFX plugin can do this, provided you wanted to sort by line, and remove the duplicate lines at the same time.

To install the TextFX in the latest release of Notepad++ you need to download it from here: https://sourceforge.net/projects/npp-plugins/files/TextFX

The TextFX plugin used to be included in older versions of Notepad++, or be possible to add from the menu by going to Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX -> Install. In some cases it may also be called TextFX Characters, but this is the same thing.

The check boxes and buttons required will now appear in the menu under: TextFX -> TextFX Tools.

Make sure "sort outputs only unique..." is checked. Next, select a block of text (Ctrl+A to select the entire document). Finally, click "sort lines case sensitive" or "sort lines case insensitive"

menu layout in n++

How to find the operating system version using JavaScript?

Hey for a quick solution you can consider the following library : UAPARSER - https://www.npmjs.com/package/ua-parser-js

example :

<script type="text/javascript" src="ua-parser.min.js"></script>
<script type="text/javascript">

var parser = new UAParser();
console.log(parser.getOS()) // will log  {name: "", version:""}

you can also install the library via npm, and import it like this:

import { UAParser } from 'ua-parser-js';
let parser = new UAParser();
parser.getOS();

the library is a JS based user agent string parser (window.navigator.userAgent is the user agent on browser) , so you can get with it other details aswell such as Browser,device,engines etc..and it can work with node js as well.

if you need typing for the library : https://www.npmjs.com/package/@types/ua-parser-js

Generating random whole numbers in JavaScript in a specific range?

    <!DOCTYPE html>
<html>
    <head>
            <meta charset="utf-8" />
    </head>
    <body>
        <script>
            /*

                assuming that window.crypto.getRandomValues is available
                the real range would be fron 0 to 1,998 instead of 0 to 2,000
                See javascript documentation for explanation
                https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
            */
            var array = new Uint8Array(2);
            window.crypto.getRandomValues(array);
            console.log(array[0] + array[1]);

        </script>
    </body>
</html>

Uint8Array create a array filled with a number up to 3 digits which would be a maximum of 999. This code is very short.

Total size of the contents of all the files in a directory

Just an alternative:

ls -lAR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'

grep -v '^d' will exclude the directories.

Difference between pre-increment and post-increment in a loop?

a++ is known as postfix.

add 1 to a, returns the old value.

++a is known as prefix.

add 1 to a, returns the new value.

C#:

string[] items = {"a","b","c","d"};
int i = 0;
foreach (string item in items)
{
    Console.WriteLine(++i);
}
Console.WriteLine("");

i = 0;
foreach (string item in items)
{
    Console.WriteLine(i++);
}

Output:

1
2
3
4

0
1
2
3

foreach and while loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:

for (int i = 0; i < 5; i++) { Console.Write(i);}
Console.WriteLine("");
for (int i = 0; i < 5; ++i) { Console.Write(i); }

0 1 2 3 4
0 1 2 3 4

If the value as evaluated is used then the type of increment becomes significant:

int n = 0;
for (int i = 0; n < 5; n = i++) { }

How do you determine what SQL Tables have an identity column programmatically

sys.columns.is_identity = 1

e.g.,

select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1

Which is the fastest algorithm to find prime numbers?

I know it's somewhat later, but this could be useful to people arriving here from searches. Anyway, here's some JavaScript that relies on the fact that only prime factors need to be tested, so the earlier primes generated by the code are re-used as test factors for later ones. Of course, all even and mod 5 values are filtered out first. The result will be in the array P, and this code can crunch 10 million primes in under 1.5 seconds on an i7 PC (or 100 million in about 20). Rewritten in C it should be very fast.

var P = [1, 2], j, k, l = 3

for (k = 3 ; k < 10000000 ; k += 2)
{
  loop: if (++l < 5)
  {
    for (j = 2 ; P[j] <= Math.sqrt(k) ; ++j)
      if (k % P[j] == 0) break loop

    P[P.length] = k
  }
  else l = 0
}

Stop node.js program from command line

I ran into an issue where I have multiple node servers running, and I want to just kill one of them and redeploy it from a script.

Note: This example is in a bash shell on Mac.

To do so I make sure to make my node call as specific as possible. For example rather than calling node server.js from the apps directory, I call node app_name_1/app/server.js

Then I can kill it using:

kill -9 $(ps aux | grep 'node\ app_name_1/app/server.js' | awk '{print $2}')

This will only kill the node process running app_name_1/app/server.js.

If you ran node app_name_2/app/server.js this node process will continue to run.

If you decide you want to kill them all you can use killall node as others have mentioned.

How do you use https / SSL on localhost?

If you have IIS Express (with Visual Studio):

To enable the SSL within IIS Express, you have to just set “SSL Enabled = true” in the project properties window.

See the steps and pictures at this code project.

IIS Express will generate a certificate for you (you'll be prompted for it, etc.). Note that depending on configuration the site may still automatically start with the URL rather than the SSL URL. You can see the SSL URL - note the port number and replace it in your browser address bar, you should be able to get in and test.

From there you can right click on your project, click property pages, then start options and assign the start URL - put the new https with the new port (usually 44301 - notice the similarity to port 443) and your project will start correctly from then on.

enter image description here

Convert List<Object> to String[] in Java

If we are very sure that List<Object> will contain collection of String, then probably try this.

List<Object> lst = new ArrayList<Object>();
lst.add("sample");
lst.add("simple");
String[] arr = lst.toArray(new String[] {});
System.out.println(Arrays.deepToString(arr));

Enabling SSL with XAMPP

I finally got this to work on my own hosted xampp windows 10 server web site. I.e. padlocks came up as ssl. I am using xampp version from November 2020.

  1. Went to certbot.eff.org. Selected from their home page software [apache] and system [windows]. Then downloaded and installed certbot software found at the next page into my C drive.

  2. Then from command line [cmd in Windows Start and then before you open cmd right click to run cmd as admin] I enhtered the command from Certbot page above. I.e. navigated to system32-- C:\WINDOWS\system32> certbot certonly --standalone

  3. Then followed the prompts and enteredmy domain name. This created certs as cert1.pem and key1.pem in C:\Certbot yourwebsitedomain folder. the cmd windows tells you where these are.

  4. Then took these and changed their names from cert1.pem to my domainname or shorter+cert.pem and same for domainname or shorter+key.key. Copied these into C:\xampp\apache\ssl.crt and ssl.key folders respectively.

  5. Then for G:\xampp\apache\conf\extra\httpd-vhosts entered the following:

<VirtualHost *:443>
    DocumentRoot "G:/xampp/htdocs/yourwebsitedomainname.hopto.org/public/" ###NB My document root is public.  Yours may not be.  Or could have an index.php page before /public###
    ServerName yourwebsitedomainnamee.hopto.org 
    <Directory G:/xampp/htdocs/yourwebsitedomainname.hopto.org>
        Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog "G:/xampp/apache/logs/error.log"
    CustomLog "G:/xampp/apache/logs/access.log" common
    SSLEngine on
SSLCertificateFile "G:\xampp\apache\conf\ssl.crt\abscert.pem"
SSLCertificateKeyFile "G:\xampp\apache\conf\ssl.key\abskey.pem"
</VirtualHost>  
     
  1. Then navigated to G:\xampp\apache\conf\extra\httpd-ssl.conf and did as was advised above. I missed this important step for days until I read this post. Thank you! I.e. entered
<VirtualHost _default_:443>
DocumentRoot "G:/xampp/htdocs/yourwebsitedomainnamee.hopto.org/public/"
###NB My document root is public.  Yours may not be.  Or could have an index.php page before /public###
SSLEngine on
SSLCertificateFile "conf/ssl.crt/abscert.pem"
SSLCertificateKeyFile "conf/ssl.key/abskey.pem"
CustomLog "G:/xampp/apache/logs/ssl_request.log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>  

Note1. I used www.noip.com to register the domain name. Note2. Rather then try to get them to give me a ssl certificate, as I could not get it to work, the above worked instead. Note3 I use the noip DUC software to keep my personally hosted web site in sync with noip. Note4. Very important to stop and start xampp server after each change you make in xampp. If xampp fails for some reason instead of starting the xampp consol try the start xampp as this will give you problems you can bug fix. Copy these quickly and paste into note.txt.

List comprehension vs map

So since Python 3, map() is an iterator, you need to keep in mind what do you need: an iterator or list object.

As @AlexMartelli already mentioned, map() is faster than list comprehension only if you don't use lambda function.

I will present you some time comparisons.

Python 3.5.2 and CPython
I've used Jupiter notebook and especially %timeit built-in magic command
Measurements: s == 1000 ms == 1000 * 1000 µs = 1000 * 1000 * 1000 ns

Setup:

x_list = [(i, i+1, i+2, i*2, i-9) for i in range(1000)]
i_list = list(range(1000))

Built-in function:

%timeit map(sum, x_list)  # creating iterator object
# Output: The slowest run took 9.91 times longer than the fastest. 
# This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 277 ns per loop

%timeit list(map(sum, x_list))  # creating list with map
# Output: 1000 loops, best of 3: 214 µs per loop

%timeit [sum(x) for x in x_list]  # creating list with list comprehension
# Output: 1000 loops, best of 3: 290 µs per loop

lambda function:

%timeit map(lambda i: i+1, i_list)
# Output: The slowest run took 8.64 times longer than the fastest. 
# This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 325 ns per loop

%timeit list(map(lambda i: i+1, i_list))
# Output: 1000 loops, best of 3: 183 µs per loop

%timeit [i+1 for i in i_list]
# Output: 10000 loops, best of 3: 84.2 µs per loop

There is also such thing as generator expression, see PEP-0289. So i thought it would be useful to add it to comparison

%timeit (sum(i) for i in x_list)
# Output: The slowest run took 6.66 times longer than the fastest. 
# This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 495 ns per loop

%timeit list((sum(x) for x in x_list))
# Output: 1000 loops, best of 3: 319 µs per loop

%timeit (i+1 for i in i_list)
# Output: The slowest run took 6.83 times longer than the fastest. 
# This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 506 ns per loop

%timeit list((i+1 for i in i_list))
# Output: 10000 loops, best of 3: 125 µs per loop

You need list object:

Use list comprehension if it's custom function, use list(map()) if there is builtin function

You don't need list object, you just need iterable one:

Always use map()!

create a white rgba / CSS3

For completely transparent color, use:

rbga(255,255,255,0)

A little more visible:

rbga(255,255,255,.3)

How to Publish Web with msbuild?

I came up with such solution, works great for me:

msbuild /t:ResolveReferences;_WPPCopyWebApplication /p:BuildingProject=true;OutDir=C:\Temp\build\ Test.csproj

The secret sauce is _WPPCopyWebApplication target.

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How to remove single character from a String

If you need some logical control over character removal, use this

String string = "sdsdsd";
char[] arr = string.toCharArray();
// Run loop or whatever you need
String ss = new String(arr);

If you don't need any such control, you can use what Oscar orBhesh mentioned. They are spot on.

How to debug Google Apps Script (aka where does Logger.log log to?)

I've gone through these posts and somehow ended up finding a simple answer, which I'm posting here for those how want short and sweet solutions:

  1. Use console.log("Hello World") in your script.
  2. Go to https://script.google.com/home/my and select your add-on.
  3. Click on the ellipsis menu on Project Details, select Executions.

enter image description here

  1. Click on the header of the latest execution and read the log.

enter image description here

Get google map link with latitude/longitude

  <iframe src="https://maps.google.com/maps?q='+YOUR_LAT+','+YOUR_LON+'&hl=en&z=14&amp;output=embed" width="100%" height="400" frameborder="0" style="border:0" allowfullscreen></iframe>

put your replace lattitude,longitude values on YOUR_LAT,YOUR_LON respectively. hl parameter for setting language on map, z for zoomlevel;

how do you view macro code in access?

EDIT: Per Michael Dillon's answer, SaveAsText does save the commands in a macro without having to go through converting to VBA. I don't know what happened when I tested that, but it didn't produce useful text in the resulting file.

So, I learned something new today!

ORIGINAL POST: To expand the question, I wondered if there was a way to retrieve the contents of a macro from code, and it doesn't appear that there is (at least not in A2003, which is what I'm running).

There are two collections through which you can access stored Macros:

  CurrentDB.Containers("Scripts").Documents
  CurrentProject.AllMacros

The properties that Intellisense identifies for the two collections are rather different, because the collections are of different types. The first (i.e., traditional, pre-A2000 way) is via a documents collection, and the methods/properties/members of all documents are the same, i.e., not specific to Macros.

Likewise, the All... collections of CurrentProject return collections where the individual items are of type Access Object. The result is that Intellisense gives you methods/properties/members that may not exist for the particular document/object.

So far as I can tell, there is no way to programatically retrieve the contents of a macro.

This would stand to reason, as macros aren't of much use to anyone who would have the capability of writing code to examine them programatically.

But if you just want to evaluate what the macros do, one alternative would be to convert them to VBA, which can be done programmatically thus:

  Dim varItem As Variant
  Dim strMacroName As String

  For Each varItem In CurrentProject.AllMacros
    strMacroName = varItem.Name
    'Debug.Print strMacroName
    DoCmd.SelectObject acMacro, strMacroName, True
    DoCmd.RunCommand acCmdConvertMacrosToVisualBasic
    Application.SaveAsText acModule, "Converted Macro- " & strMacroName, _
      CurrentProject.Path & "\" & "Converted Macro- " & strMacroName & ".txt"
  Next varItem

Then you could use the resulting text files for whatever you needed to do.

Note that this has to be run interactively in Access because it uses DoCmd.RunCommand, and you have to click OK for each macro -- tedious for databases with lots of macros, but not too onerous for a normal app, which shouldn't have more than a handful of macros.

Is arr.__len__() the preferred way to get the length of an array in Python?

my_list = [1,2,3,4,5]
len(my_list)
# 5

The same works for tuples:

my_tuple = (1,2,3,4,5)
len(my_tuple)
# 5

And strings, which are really just arrays of characters:

my_string = 'hello world'
len(my_string)
# 11

It was intentionally done this way so that lists, tuples and other container types or iterables didn't all need to explicitly implement a public .length() method, instead you can just check the len() of anything that implements the 'magic' __len__() method.

Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a .length() method while another type uses a .length property, while yet another uses .count(). Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.

The functional nature of len() also lends itself well to functional styles of programming.

lengths = map(len, list_of_containers)

Laravel blade check empty foreach

I think you are trying to check whether the array is empty or not.You can do like this :

@if(!$result->isEmpty())
     // $result is not empty
@else
    // $result is empty
@endif

Reference isEmpty()

Extracting text from HTML file using Python

There is Pattern library for data mining.

http://www.clips.ua.ac.be/pages/pattern-web

You can even decide what tags to keep:

s = URL('http://www.clips.ua.ac.be').download()
s = plaintext(s, keep={'h1':[], 'h2':[], 'strong':[], 'a':['href']})
print s

Saving and Reading Bitmaps/Images from Internal memory in Android

    public static String saveImage(String folderName, String imageName, RelativeLayout layoutCollage) {
        String selectedOutputPath = "";
        if (isSDCARDMounted()) {
            File mediaStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
            // Create a storage directory if it does not exist
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("PhotoEditorSDK", "Failed to create directory");
                }
            }
            // Create a media file name
            selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
            Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
            File file = new File(selectedOutputPath);
            try {
                FileOutputStream out = new FileOutputStream(file);
                if (layoutCollage != null) {
                    layoutCollage.setDrawingCacheEnabled(true);
                    layoutCollage.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
                }
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return selectedOutputPath;
    }



private static boolean isSDCARDMounted() {
        String status = Environment.getExternalStorageState();
        return status.equals(Environment.MEDIA_MOUNTED);
    }

How do I move to end of line in Vim?

I was used to Home/End getting me to the start and end of lines in Insert mode (from use in Windows and I think Linux), which Mac doesn't support. This is particularly annoying because when I'm using vim on a remote system, I also can't easily do it. After some painful trial and error, I came up with these .vimrc lines which do the same thing, but bound to Ctrl-A for the start of the line and Ctrl-D for the end of the line. (For some reason, Ctrl-E I guess is reserved or at least I couldn't figure a way to bind it.) Enjoy.

:imap <Char-1> <Char-15>:normal 0<Char-13>
:imap <Char-4> <Char-15>:normal $<Char-13>

There's a good chart here for the ASCII control character codes here for others as well:

http://www.physics.udel.edu/~watson/scen103/ascii.html

You can also do Ctrl-V + Ctrl- as well, but that doesn't paste as well to places like this.

Will using 'var' affect performance?

The C# compiler infers the true type of the var variable at compile time. There's no difference in the generated IL.

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

Here are shortcuts for the IPython Notebook.

Ctrl-m i interrupts the kernel. (that is, the sole letter i after Ctrl-m)

According to this answer, I twice works as well.

How do I replace all line breaks in a string with <br /> elements?

This worked for me when value came from a TextBox:

string.replace(/\n|\r\n|\r/g, '<br/>');

How to convert int[] to Integer[] in Java?

This worked like a charm!

int[] mInt = new int[10];
Integer[] mInteger = new Integer[mInt.length];

List<Integer> wrapper = new AbstractList<Integer>() {
    @Override
    public int size() {
        return mInt.length;
    }

    @Override
    public Integer get(int i) {
        return mInt[i];
    }
};

wrapper.toArray(mInteger);

How do you do a ‘Pause’ with PowerShell 2.0?

I assume that you want to read input from the console. If so, use Read-Host.

'nuget' is not recognized but other nuget commands working

In [Package Manager Console] try the below

Install-Package NuGet.CommandLine

ModuleNotFoundError: What does it mean __main__ is not a package?

If you have created directory and sub-directory, follow the steps below and please keep in mind all directory must have __init__.py to get it recognized as a directory.

  1. In your script, include import sys and sys.path, you will be able to see all the paths available to Python. You must be able to see your current working directory.

  2. Now import sub-directory and respective module that you want to use using: import subdir.subdir.modulename as abc and now you can use the methods in that module.

enter image description here

As an example, you can see in this screenshot I have one parent directory and two sub-directories and under second sub-directories I have the module CommonFunction. On the right my console shows that after execution of sys.path, I can see my working directory.

Auto increment primary key in SQL Server Management Studio 2012

CREATE TABLE Persons (
    Personid int IDENTITY(1,1) PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.

In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.

Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).

To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid" column (a unique value will be added automatically):

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

T-SQL - function with default parameters

With user defined functions, you have to declare every parameter, even if they have a default value.

The following would execute successfully:

IF dbo.CheckIfSFExists( 23, default ) = 0
    SET @retValue = 'bla bla bla;

How to install npm peer dependencies automatically?

The automatic install of peer dependencies was explicitly removed with npm 3, as it cause more problems than it tried to solve. You can read about it here for example:

So no, for the reasons given, you cannot install them automatically with npm 3 upwards.

NPM V7

NPM v7 has reintroduced the automatic peerDependencies installation. They had made some changes to fix old problems as version compatibility across multiple dependants. You can see the discussion here and the announcement here

Now in V7, as in versions before V3, you only need to do an npm i and all peerDependences should be automatically installed.

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

How to add property to a class dynamically?

A lot of the supplied answers require so many lines per property, ie / and / or - what I'd consider an ugly or tedious implementation because of repetitiveness required for multiple properties, etc. I prefer keeping boiling things down / simplifying them until they can't be simplified anymore or until it doesn't serve much purpose to do so.

In short: in completed works, if I repeat 2 lines of code, I typically convert it into a single line helper function, and so on... I simplify math or odd arguments such as ( start_x, start_y, end_x, end_y ) to ( x, y, w, h ) ie x, y, x + w, y + h ( sometimes requiring min / max or if w / h are negative and the implementation doesn't like it, I'll subtract from x / y and abs w / h. etc.. ).

Overriding the internal getters / setters is an ok way to go, but the problem is you need to do that for every class, or parent the class to that base... This doesn't work for me as I'd prefer to be free to choose the children / parents for inheritance, child nodes, etc.

I have created a solution which answers the question without using a Dict data-type to supply the data as I find that to be tedious to enter the data, etc...

My solution requires you to add 2 extra lines above your class to create a base class for the class you want to add the properties to, then 1 line per and you have the option to add callbacks to control the data, inform you when data changes, restrict the data which can be set based on value and / or data-type, and much more.

You also have the option to use _object.x, _object.x = value, _object.GetX( ), _object.SetX( value ) and they are handled equivalently.

Additionally, the values are the only non-static data which are assigned to the class instance, but the actual property is assigned to the class meaning the things you don't want to repeat, don't need to be repeated... You can assign a default value so the getter doesn't need it each time, although there is an option to override the default default value, and there is another option so the getter returns the raw stored value by overriding default returns ( note: this method means the raw value is only assigned when a value is assigned, otherwise it is None - when the value is Reset, then it assigns None, etc.. )

There are many helper functions too - the first property which gets added adds 2 or so helpers to the class for referencing the instance values... They are ResetAccessors( _key, .. ) varargs repeated ( all can be repeated using the first named args ) and SetAccessors( _key, _value ) with the option of more being added to the main class to aide in efficiency - the ones planned are: a way to group accessors together, so if you tend to reset a few at a time, every time, you can assign them to a group and reset the group instead of repeating the named keys each time, and more.

The instance / raw stored value is stored at class., the __class. references the Accessor Class which holds static vars / values / functions for the property. _class. is the property itself which is called when accessed via the instance class during setting / getting, etc.

The Accessor _class.__ points to the class, but because it is internal it needs to be assigned in the class which is why I opted to use __Name = AccessorFunc( ... ) to assign it, a single line per property with many optional arguments to use ( using keyed varargs because they're easier and more efficient to identify and maintain )...

I also create a lot of functions, as mentioned, some of which use accessor function information so it doesn't need to be called ( as it is a bit inconvenient at the moment - right now you need to use _class..FunctionName( _class_instance, args ) - I got around using the stack / trace to grab the instance reference to grab the value by adding the functions which either run this bit marathon, or by adding the accessors to the object and using self ( named this to point out they're for the instance and to retain access to self, the AccessorFunc class reference, and other information from within the function definitions ).

It isn't quite done, but it is a fantastic foot-hold. Note: If you do not use __Name = AccessorFunc( ... ) to create the properties, you won't have access to the __ key even though I define it within the init function. If you do, then there are no issues.

Also: Note that Name and Key are different... Name is 'formal', used in Function Name Creation, and the key is for data storage and access. ie _class.x where lowercase x is key, the name would be uppercase X so that GetX( ) is the function instead of Getx( ) which looks a little odd. this allows self.x to work and look appropriate, but also allow GetX( ) and look appropriate.

I have an example class set up with key / name identical, and different to show. a lot of helper functions created in order to output the data ( Note: Not all of this is complete ) so you can see what is going on.

The current list of functions using key: x, name: X outputs as:

This is by no means a comprehensive list - there are a few which haven't made it on this at the time of posting...

_instance.SetAccessors( _key, _value [ , _key, _value ] .. )                   Instance Class Helper Function: Allows assigning many keys / values on a single line - useful for initial setup, or to minimize lines.    In short: Calls this.Set<Name>( _value ) for each _key / _value pairing.
_instance.ResetAccessors( _key [ , _key ] .. )                                 Instance Class Helper Function: Allows resetting many key stored values to None on a single line.                                           In short: Calls this.Reset<Name>() for each name provided.


Note: Functions below may list self.Get / Set / Name( _args ) - self is meant as the class instance reference in the cases below - coded as this in AccessorFuncBase Class.

this.GetX( _default_override = None, _ignore_defaults = False )                 GET:            Returns    IF ISSET: STORED_VALUE .. IF IGNORE_DEFAULTS: None  .. IF PROVIDED: DEFAULT_OVERRIDE ELSE: DEFAULT_VALUE       100
this.GetXRaw( )                                                                 RAW:            Returns    STORED_VALUE                                                                                                     100
this.IsXSet( )                                                                  ISSET:          Returns    ( STORED_VALUE != None )                                                                                         True

this.GetXToString( )                                                            GETSTR:         Returns    str( GET )                                                                                                       100
this.GetXLen( _default_override = None, _ignore_defaults = False )              LEN:            Returns    len( GET )                                                                                                       3
this.GetXLenToString( _default_override = None, _ignore_defaults = False )      LENSTR:         Returns    str( len( GET ) )                                                                                                3
this.GetXDefaultValue( )                                                        DEFAULT:        Returns    DEFAULT_VALUE                                                                                                    1111

this.GetXAccessor( )                                                            ACCESSOR:       Returns    ACCESSOR_REF ( self.__<key> )                                                                                    [ AccessorFuncBase ] Key: x : Class ID: 2231452344344 : self ID: 2231448283848        Default: 1111       Allowed Types: {"<class 'int'>": "<class 'type'>", "<class 'float'>": "<class 'type'>"}     Allowed Values: None
this.GetXAllowedTypes( )                                                        ALLOWED_TYPES:  Returns    Allowed Data-Types                                                                                               {"<class 'int'>": "<class 'type'>", "<class 'float'>": "<class 'type'>"}
this.GetXAllowedValues( )                                                       ALLOWED_VALUES: Returns    Allowed Values                                                                                                   None

this.GetXHelpers( )                                                             HELPERS:        Returns    Helper Functions String List - ie what you're reading now...                                                     THESE ROWS OF TEXT
this.GetXKeyOutput( )                                                           Returns information about this Name / Key                                                                                                   ROWS OF TEXT
this.GetXGetterOutput( )                                                        Returns information about this Name / Key                                                                                                   ROWS OF TEXT

this.SetX( _value )                                                             SET:            STORED_VALUE Setter - ie Redirect to __<Key>.Set                                                                            N / A
this.ResetX( )                                                                  RESET:          Resets STORED_VALUE to None                                                                                                 N / A

this.HasXGetterPrefix( )                                                        Returns Whether or Not this key has a Getter Prefix...                                                                                      True
this.GetXGetterPrefix( )                                                        Returns Getter Prefix...                                                                                                                    Get

this.GetXName( )                                                                Returns Accessor Name - Typically Formal / Title-Case                                                                                       X
this.GetXKey( )                                                                 Returns Accessor Property Key - Typically Lower-Case                                                                                        x
this.GetXAccessorKey( )                                                         Returns Accessor Key - This is to access internal functions, and static data...                                                             __x
this.GetXDataKey( )                                                             Returns Accessor Data-Storage Key - This is the location where the class instance value is stored..                                         _x

Some of the data being output is:

This is for a brand new class created using the Demo class without any data assigned other than the name ( so it can be output ) which is _foo, the variable name I used...

_foo         --- MyClass: ---- id( this.__class__ ): 2231452349064 :::: id( this ): 2231448475016

    Key       Getter Value        | Raw Key   Raw / Stored Value       | Get Default Value             Default Value            | Get Allowed Types             Allowed Types                                                              | Get Allowed Values            Allowed Values                                                                                                                                                                                                                   |

    Name:     _foo                | _Name:    _foo                     | __Name.DefaultValue( ):       AccessorFuncDemoClass    | __Name.GetAllowedTypes( )     <class 'str'>                                                              | __Name.GetAllowedValues( )    Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    x:        1111                | _x:       None                     | __x.DefaultValue( ):          1111                     | __x.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __x.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    y:        2222                | _y:       None                     | __y.DefaultValue( ):          2222                     | __y.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __y.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    z:        3333                | _z:       None                     | __z.DefaultValue( ):          3333                     | __z.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __z.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Blah:     <class 'int'>       | _Blah:    None                     | __Blah.DefaultValue( ):       <class 'int'>            | __Blah.GetAllowedTypes( )     <class 'str'>                                                              | __Blah.GetAllowedValues( )    Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Width:    1                   | _Width:   None                     | __Width.DefaultValue( ):      1                        | __Width.GetAllowedTypes( )    (<class 'int'>, <class 'bool'>)                                            | __Width.GetAllowedValues( )   Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Height:   0                   | _Height:  None                     | __Height.DefaultValue( ):     0                        | __Height.GetAllowedTypes( )   <class 'int'>                                                              | __Height.GetAllowedValues( )  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)                                                                                                                                                                                                   |
    Depth:    2                   | _Depth:   None                     | __Depth.DefaultValue( ):      2                        | __Depth.GetAllowedTypes( )    Saved Value Restricted to Authorized Values ONLY                           | __Depth.GetAllowedValues( )   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)                                                                                                                                                                                                   |


this.IsNameSet( ):    True      this.GetName( ):     _foo                     this.GetNameRaw( ):    _foo                     this.GetNameDefaultValue( ):    AccessorFuncDemoClass    this.GetNameLen( ):    4    this.HasNameGetterPrefix( ):    <class 'str'>                                this.GetNameGetterPrefix( ):    None
this.IsXSet( ):       False     this.GetX( ):        1111                     this.GetXRaw( ):       None                     this.GetXDefaultValue( ):       1111                     this.GetXLen( ):       4    this.HasXGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetXGetterPrefix( ):       None
this.IsYSet( ):       False     this.GetY( ):        2222                     this.GetYRaw( ):       None                     this.GetYDefaultValue( ):       2222                     this.GetYLen( ):       4    this.HasYGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetYGetterPrefix( ):       None
this.IsZSet( ):       False     this.GetZ( ):        3333                     this.GetZRaw( ):       None                     this.GetZDefaultValue( ):       3333                     this.GetZLen( ):       4    this.HasZGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetZGetterPrefix( ):       None
this.IsBlahSet( ):    False     this.GetBlah( ):     <class 'int'>            this.GetBlahRaw( ):    None                     this.GetBlahDefaultValue( ):    <class 'int'>            this.GetBlahLen( ):    13   this.HasBlahGetterPrefix( ):    <class 'str'>                                this.GetBlahGetterPrefix( ):    None
this.IsWidthSet( ):   False     this.GetWidth( ):    1                        this.GetWidthRaw( ):   None                     this.GetWidthDefaultValue( ):   1                        this.GetWidthLen( ):   1    this.HasWidthGetterPrefix( ):   (<class 'int'>, <class 'bool'>)              this.GetWidthGetterPrefix( ):   None
this.IsDepthSet( ):   False     this.GetDepth( ):    2                        this.GetDepthRaw( ):   None                     this.GetDepthDefaultValue( ):   2                        this.GetDepthLen( ):   1    this.HasDepthGetterPrefix( ):   None                                         this.GetDepthGetterPrefix( ):   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
this.IsHeightSet( ):  False     this.GetHeight( ):   0                        this.GetHeightRaw( ):  None                     this.GetHeightDefaultValue( ):  0                        this.GetHeightLen( ):  1    this.HasHeightGetterPrefix( ):  <class 'int'>                                this.GetHeightGetterPrefix( ):  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

And this is after assigning all of _foo properties ( except the name ) the following values in the same order: 'string ', 1.0, True, 9, 10, False

this.IsNameSet( ):    True      this.GetName( ):     _foo                     this.GetNameRaw( ):    _foo                     this.GetNameDefaultValue( ):    AccessorFuncDemoClass    this.GetNameLen( ):    4    this.HasNameGetterPrefix( ):    <class 'str'>                                this.GetNameGetterPrefix( ):    None
this.IsXSet( ):       True      this.GetX( ):        10                       this.GetXRaw( ):       10                       this.GetXDefaultValue( ):       1111                     this.GetXLen( ):       2    this.HasXGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetXGetterPrefix( ):       None
this.IsYSet( ):       True      this.GetY( ):        10                       this.GetYRaw( ):       10                       this.GetYDefaultValue( ):       2222                     this.GetYLen( ):       2    this.HasYGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetYGetterPrefix( ):       None
this.IsZSet( ):       True      this.GetZ( ):        10                       this.GetZRaw( ):       10                       this.GetZDefaultValue( ):       3333                     this.GetZLen( ):       2    this.HasZGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetZGetterPrefix( ):       None
this.IsBlahSet( ):    True      this.GetBlah( ):     string Blah              this.GetBlahRaw( ):    string Blah              this.GetBlahDefaultValue( ):    <class 'int'>            this.GetBlahLen( ):    11   this.HasBlahGetterPrefix( ):    <class 'str'>                                this.GetBlahGetterPrefix( ):    None
this.IsWidthSet( ):   True      this.GetWidth( ):    False                    this.GetWidthRaw( ):   False                    this.GetWidthDefaultValue( ):   1                        this.GetWidthLen( ):   5    this.HasWidthGetterPrefix( ):   (<class 'int'>, <class 'bool'>)              this.GetWidthGetterPrefix( ):   None
this.IsDepthSet( ):   True      this.GetDepth( ):    9                        this.GetDepthRaw( ):   9                        this.GetDepthDefaultValue( ):   2                        this.GetDepthLen( ):   1    this.HasDepthGetterPrefix( ):   None                                         this.GetDepthGetterPrefix( ):   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
this.IsHeightSet( ):  True      this.GetHeight( ):   9                        this.GetHeightRaw( ):  9                        this.GetHeightDefaultValue( ):  0                        this.GetHeightLen( ):  1    this.HasHeightGetterPrefix( ):  <class 'int'>                                this.GetHeightGetterPrefix( ):  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

_foo         --- MyClass: ---- id( this.__class__ ): 2231452349064 :::: id( this ): 2231448475016

    Key       Getter Value        | Raw Key   Raw / Stored Value       | Get Default Value             Default Value            | Get Allowed Types             Allowed Types                                                              | Get Allowed Values            Allowed Values                                                                                                                                                                                                                   |

    Name:     _foo                | _Name:    _foo                     | __Name.DefaultValue( ):       AccessorFuncDemoClass    | __Name.GetAllowedTypes( )     <class 'str'>                                                              | __Name.GetAllowedValues( )    Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    x:        10                  | _x:       10                       | __x.DefaultValue( ):          1111                     | __x.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __x.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    y:        10                  | _y:       10                       | __y.DefaultValue( ):          2222                     | __y.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __y.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    z:        10                  | _z:       10                       | __z.DefaultValue( ):          3333                     | __z.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __z.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Blah:     string Blah         | _Blah:    string Blah              | __Blah.DefaultValue( ):       <class 'int'>            | __Blah.GetAllowedTypes( )     <class 'str'>                                                              | __Blah.GetAllowedValues( )    Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Width:    False               | _Width:   False                    | __Width.DefaultValue( ):      1                        | __Width.GetAllowedTypes( )    (<class 'int'>, <class 'bool'>)                                            | __Width.GetAllowedValues( )   Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Height:   9                   | _Height:  9                        | __Height.DefaultValue( ):     0                        | __Height.GetAllowedTypes( )   <class 'int'>                                                              | __Height.GetAllowedValues( )  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)                                                                                                                                                                                                   |
    Depth:    9                   | _Depth:   9                        | __Depth.DefaultValue( ):      2                        | __Depth.GetAllowedTypes( )    Saved Value Restricted to Authorized Values ONLY                           | __Depth.GetAllowedValues( )   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)                                                                                                                                                                                                   |

Note that because of restricted data-types or value restrictions, some data wasn't assigned - this is by design. The setter prohibits bad data-types or values from being assigned, even from being assigned as a default value ( unless you override the default value protection behavior )

The code hasn't been posted here because I didn't have room after the examples and explanations... Also because it will change.

Please Note: at the time of this posting, the file is messy - this will change. But, if you run it in Sublime Text and compile it, or run it from Python, it will compile and spit out a ton of information - the AccessorDB portion isn't done ( which will be used to update the Print Getters and GetKeyOutput helper functions along with being changed to an Instance function, probably put into a single function and renamed - look for it.. )

Next: Not everything is required for it to run - a lot of the commented stuff at the bottom is for more information used for debugging - it may not be there when you download it. If it is, you should be able to uncomment and recompile to get more information.

I am looking for a work-around to needing MyClassBase: pass, MyClass( MyClassBase ): ... - if you know of a solution - post it.

The only thing necessary in the class are the __ lines - the str is for debugging as is the init - they can be removed from the Demo Class but you will need to comment out or remove some of the lines below ( _foo / 2 / 3 )..

The String, Dict, and Util classes at the top are a part of my Python library - they are not complete. I copied over a few things I needed from the library, and I created a few new ones. The full code will link to the complete library and will include it along with providing updated calls and removing the code ( actually, the only code left will be the Demo Class and the print statements - the AccessorFunc system will be moved to the library )...

Part of file:

##
## MyClass Test AccessorFunc Implementation for Dynamic 1-line Parameters
##
class AccessorFuncDemoClassBase( ):
    pass
class AccessorFuncDemoClass( AccessorFuncDemoClassBase ):
    __Name      = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'Name',      default = 'AccessorFuncDemoClass',  allowed_types = ( TYPE_STRING ),                    allowed_values = VALUE_ANY,                 documentation = 'Name Docs',        getter_prefix = 'Get',  key = 'Name',       allow_erroneous_default = False,    options = { } )
    __x         = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'X',         default = 1111,                     allowed_types = ( TYPE_INTEGER, TYPE_FLOAT ),       allowed_values = VALUE_ANY,                 documentation = 'X Docs',           getter_prefix = 'Get',  key = 'x',          allow_erroneous_default = False,    options = { } )
    __Height    = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'Height',    default = 0,                        allowed_types = TYPE_INTEGER,                       allowed_values = VALUE_SINGLE_DIGITS,       documentation = 'Height Docs',      getter_prefix = 'Get',  key = 'Height',     allow_erroneous_default = False,    options = { } )

This beauty makes it incredibly easy to create new classes with dynamically added properties with AccessorFuncs / callbacks / data-type / value enforcement, etc.

For now, the link is at ( This link should reflect changes to the document. ): https://www.dropbox.com/s/6gzi44i7dh58v61/dynamic_properties_accessorfuncs_and_more.py?dl=0

Also: If you don't use Sublime Text, I recommend it over Notepad++, Atom, Visual Code, and others because of proper threading implementations making it much, much faster to use... I am also working on an IDE-like code mapping system for it - take a look at: https://bitbucket.org/Acecool/acecoolcodemappingsystem/src/master/ ( Add Repo in Package Manager first, then Install Plugin - when version 1.0.0 is ready, I'll add it to the main plugin list... )

I hope this solution helps... and, as always:

Just because it works, doesn't make it right - Josh 'Acecool' Moser

codeigniter, result() vs. result_array()

result_array() is faster, result() is easier

Storing Form Data as a Session Variable

You can solve this problem using this code:

if(!empty($_GET['variable from which you get'])) 
{
$_SESSION['something']= $_GET['variable from which you get'];
}

So you get the variable from a GET form, you will store in the $_SESSION['whatever'] variable just once when $_GET['variable from which you get']is set and if it is empty $_SESSION['something'] will store the old parameter

Regex to remove all special characters from string?

tmp = Regex.Replace(n, @"\W+", "");

\w matches letters, digits, and underscores, \W is the negated version.

Function to convert timestamp to human date in javascript

Moment.js can convert unix timestamps into any custom format

In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");

will print 18-10-2013 11:53:14;

Here's a plunker that demonstrates this.

Detecting a long press with Android

The idea is creating a Runnable for execute long click in a future, but this execution can be canceled because of a click, or move.

You also need to know, when long click was consumed, and when it is canceled because finger moved too much. We use initialTouchX & initialTouchY for checking if the user exit a square area of 10 pixels, 5 each side.

Here is my complete code for delegating Click & LongClick from Cell in ListView to Activity with OnTouchListener:

    ClickDelegate delegate; 
    boolean goneFlag = false;
    float initialTouchX;
    float initialTouchY;
    final Handler handler = new Handler();
    Runnable mLongPressed = new Runnable() {
        public void run() {
            Log.i("TOUCH_EVENT", "Long press!");
            if (delegate != null) {
                goneFlag = delegate.onItemLongClick(index);
            } else {
                goneFlag = true;
            }
        }
    };

    @OnTouch({R.id.layout})
    public boolean onTouch (View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                handler.postDelayed(mLongPressed, ViewConfiguration.getLongPressTimeout());
                initialTouchX = motionEvent.getRawX();
                initialTouchY = motionEvent.getRawY();
                return true;
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_CANCEL:
                if (Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
                    handler.removeCallbacks(mLongPressed);
                    return true;
                }
                return false;
            case MotionEvent.ACTION_UP:
                handler.removeCallbacks(mLongPressed);
                if (goneFlag || Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
                    goneFlag = false;
                    return true;
                }
                break;
        }
        Log.i("TOUCH_EVENT", "Short press!");
        if (delegate != null) {
            if (delegate.onItemClick(index)) {
                return false;
            }
        }
        return false;
    }

ClickDelegateis an interface for sending click events to the handler class like an Activity

    public interface ClickDelegate {
        boolean onItemClick(int position);
        boolean onItemLongClick(int position);
    }

And all what you need is to implement it in your Activity or parent Viewif you need to delegate the behavior:

public class MyActivity extends Activity implements ClickDelegate {

    //code...
    //in some place of you code like onCreate, 
    //you need to set the delegate like this:
    SomeArrayAdapter.delegate = this;
    //or:
    SomeViewHolder.delegate = this;
    //or:
    SomeCustomView.delegate = this;

    @Override
    public boolean onItemClick(int position) {
        Object obj = list.get(position);
        if (obj) {
            return true; //if you handle click
        } else {
            return false; //if not, it could be another event
        }
    }

    @Override
    public boolean onItemLongClick(int position) {
        Object obj = list.get(position);
        if (obj) {
            return true; //if you handle long click
        } else {
            return false; //if not, it's a click
        }
    }
}

Node.js ES6 classes with require

Yes, your example would work fine.

As for exposing your classes, you can export a class just like anything else:

class Animal {...}
module.exports = Animal;

Or the shorter:

module.exports = class Animal {

};

Once imported into another module, then you can treat it as if it were defined in that file:

var Animal = require('./Animal');

class Cat extends Animal {
    ...
}

What is the SQL command to return the field names of a table?

SQL-92 standard defines INFORMATION_SCHEMA which conforming rdbms's like MS SQL Server support. The following works for MS SQL Server 2000/2005/2008 and MySql 5 and above

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'myTable'

MS SQl Server Specific:

exec sp_help 'myTable'

This solution returns several result sets within which is the information you desire, where as the former gives you exactly what you want.

Also just for completeness you can query the sys tables directly. This is not recommended as the schema can change between versions of SQL Server and INFORMATION_SCHEMA is a layer of abstraction above these tables. But here it is anyway for SQL Server 2000

select [name] from dbo.syscolumns where id = object_id(N'[dbo].[myTable]')

Run bash command on jenkins pipeline

For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash), and simply run it with sh from Jenkinsfile:

sh 'chmod +x ./script.sh'
sh './script.sh'

Should methods in a Java interface be declared with or without a public access modifier?

The reason for methods in interfaces being by default public and abstract seems quite logical and obvious to me.

A method in an interface it is by default abstract to force the implementing class to provide an implementation and is public by default so the implementing class has access to do so.

Adding those modifiers in your code is redundant and useless and can only lead to the conclusion that you lack knowledge and/or understanding of Java fundamentals.

Hot deploy on JBoss - how do I make JBoss "see" the change?

I have had the same problem, but think I've got it under control now.

Are you using eclipse or command line or ??

When I use the command line, I think I did "seam clean" or "seam undeploy" or maybe even "seam restart" followed by "seam explode". I probably tried all of these at one time or another never bothering to look up what each one does.

The idea is to remove the deployed war file from TWO places

1. $JBOSS_HOME/server/default/deploy
2. $PROJECT_HOME/exploded_archives

I'm pretty sure "seam undeploy" removes the 1st and "seam clean" removes the 2nd.

When I use eclipse (I use the free one), I first turn off "Project/Build Automatically" Then when I am ready to deploy I do either Project/Build Project or Project/Build All depending on what I've changed. When I change xhtml, Build Project is sufficient. When I change java source Build All works. It's possible these do the same things and the difference is in my imagination, but some combination of this stuff will work for you.

You have to watch the output though. Occasionally the app does not get cleaned or undeployed. This would result in not seeing your change. Sometimes I shut down the server first and then rebuild/clean/deploy the project.

Hope this helps.

TDR

Iterating over dictionaries using 'for' loops

This will print the output in sorted order by values in ascending order.

d = {'x': 3, 'y': 1, 'z': 2}

def by_value(item):
    return item[1]

for key, value in sorted(d.items(), key=by_value):
    print(key, '->', value)

Output:

y -> 1
z -> 2
x -> 3

http://localhost:50070 does not work HADOOP

After installing and configuring Hadoop, you can quickly run the command netstat -tulpn

to find the ports open. In the new version of Hadoop 3.1.3 the ports are as follows:-

localhost:8042 Hadoop, localhost:9870 HDFS, localhost:8088 YARN

How do I sort a two-dimensional (rectangular) array in C#?

I like the DataTable approach proposed by MusiGenesis above. The nice thing about it is that you can sort by any valid SQL 'order by' string that uses column names, e.g. "x, y desc, z" for 'order by x, y desc, z'. (FWIW, I could not get it to work using column ordinals, e.g. "3,2,1 " for 'order by 3,2,1') I used only integers, but clearly you could add mixed type data into the DataTable and sort it any which way.

In the example below, I first loaded some unsorted integer data into a tblToBeSorted in Sandbox (not shown). With the table and its data already existing, I load it (unsorted) into a 2D integer array, then to a DataTable. The array of DataRows is the sorted version of DataTable. The example is a little odd in that I load my array from the DB and could have sorted it then, but I just wanted to get an unsorted array into C# to use with the DataTable object.

static void Main(string[] args)
{
    SqlConnection cnnX = new SqlConnection("Data Source=r90jroughgarden\\;Initial Catalog=Sandbox;Integrated Security=True");
    SqlCommand cmdX = new SqlCommand("select * from tblToBeSorted", cnnX);
    cmdX.CommandType = CommandType.Text;
    SqlDataReader rdrX = null;
    if (cnnX.State == ConnectionState.Closed) cnnX.Open();

    int[,] aintSortingArray = new int[100, 4];     //i, elementid, planid, timeid

    try
    {
        //Load unsorted table data from DB to array
        rdrX = cmdX.ExecuteReader();
        if (!rdrX.HasRows) return;

        int i = -1;
        while (rdrX.Read() && i < 100)
        {
            i++;
            aintSortingArray[i, 0] = rdrX.GetInt32(0);
            aintSortingArray[i, 1] = rdrX.GetInt32(1);
            aintSortingArray[i, 2] = rdrX.GetInt32(2);
            aintSortingArray[i, 3] = rdrX.GetInt32(3);
        }
        rdrX.Close();

        DataTable dtblX = new DataTable();
        dtblX.Columns.Add("ChangeID");
        dtblX.Columns.Add("ElementID");
        dtblX.Columns.Add("PlanID");
        dtblX.Columns.Add("TimeID");
        for (int j = 0; j < i; j++)
        {
            DataRow drowX = dtblX.NewRow();
            for (int k = 0; k < 4; k++)
            {
                drowX[k] = aintSortingArray[j, k];
            }
            dtblX.Rows.Add(drowX);
        }

        DataRow[] adrowX = dtblX.Select("", "ElementID, PlanID, TimeID");
        adrowX = dtblX.Select("", "ElementID desc, PlanID asc, TimeID desc");

    }
    catch (Exception ex)
    {
        string strErrMsg = ex.Message;
    }
    finally
    {
        if (cnnX.State == ConnectionState.Open) cnnX.Close();
    }
}

How do I toggle an ng-show in AngularJS based on a boolean?

If based on click here it is:

ng-click="orderReverse = orderReverse ? false : true"

Is there a constraint that restricts my generic method to numeric types?

Unfortunately you are only able to specify struct in the where clause in this instance. It does seem strange you can't specify Int16, Int32, etc. specifically but I'm sure there's some deep implementation reason underlying the decision to not permit value types in a where clause.

I guess the only solution is to do a runtime check which unfortunately prevents the problem being picked up at compile time. That'd go something like:-

static bool IntegerFunction<T>(T value) where T : struct {
  if (typeof(T) != typeof(Int16)  &&
      typeof(T) != typeof(Int32)  &&
      typeof(T) != typeof(Int64)  &&
      typeof(T) != typeof(UInt16) &&
      typeof(T) != typeof(UInt32) &&
      typeof(T) != typeof(UInt64)) {
    throw new ArgumentException(
      string.Format("Type '{0}' is not valid.", typeof(T).ToString()));
  }

  // Rest of code...
}

Which is a little bit ugly I know, but at least provides the required constraints.

I'd also look into possible performance implications for this implementation, perhaps there's a faster way out there.

Connect to Amazon EC2 file directory using Filezilla and SFTP

the most simple and straight forward is to create a FTP login. Here is a little and easy to understand tutorial site on stackoverflow itself, how to set things up in 2min... Setting up FTP on Amazon Cloud Server

Disable/Enable button in Excel/VBA

... I don't know if you're using an activex button or not, but when I insert an activex button into sheet1 in Excel called CommandButton1, the following code works fine:

Sub test()

   Sheets(1).CommandButton1.Enabled = False

End Sub

Hope this helps...

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

As a slight improvement to this suggestion, you can use the Validation plugin with its number(), digits, and range methods. For example, the following ensures you get a positive integer between 0 and 50:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true,
      digits: true,
      range : [0, 50]
    }
  }
});

Read url to string in few lines of java code

Here's Jeanne's lovely answer, but wrapped in a tidy function for muppets like me:

private static String getUrl(String aUrl) throws MalformedURLException, IOException
{
    String urlData = "";
    URL urlObj = new URL(aUrl);
    URLConnection conn = urlObj.openConnection();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) 
    {
        urlData = reader.lines().collect(Collectors.joining("\n"));
    }
    return urlData;
}

What is REST call and how to send a REST call?

REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET or POST, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)

With REST, you might instead PUT /profiles/cHao and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.

http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.

jQuery UI accordion that keeps multiple sections open?

Just call each section of the accordion as its own accordion. active: n will be 0 for the first one( so it will display) and 1, 2, 3, 4, etc for the rest. Since each one is it's own accordion, they will all have only 1 section, and the rest will be collapsed to start.

$('.accordian').each(function(n, el) {
  $(el).accordion({
    heightStyle: 'content',
    collapsible: true,
    active: n
  });
});

Uncaught SyntaxError: Unexpected token < On Chrome

I faced similar issue when I moved some of the js files into folders then deployed into production, after some struggle I found out that the js files were not actually got deployed to production. So

  1. make sure that the file for which the error is shown does exist in the server
  2. the path given is correct

So, In the absence of js file, the server then server responds with as below

<!doctype html>
    <html>
        <someTag />
        <AnotherTag />
    </html>

Thats why we get Uncaught SyntaxError: Unexpected token <

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

How do I check my gcc C++ compiler version for my Eclipse?

Just type

gcc --version

in any terminal near you.. ;-)

Change div width live with jQuery

You can't just use a percentage width for the div? Setting the width to 50% will make it 50% as wide as the window (assuming there is no parent element with a width assigned to it).

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

Dynamically Add C# Properties at Runtime

Have you taken a look at ExpandoObject?

see: http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx

From MSDN:

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

Allowing you to do cool things like:

dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
    {
        Console.WriteLine(msg);
    };

dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);

Based on your actual code you may be more interested in:

public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
    return new MyDynObject(properties);
}

public sealed class MyDynObject : DynamicObject
{
    private readonly Dictionary<string, object> _properties;

    public MyDynObject(Dictionary<string, object> properties)
    {
        _properties = properties;
    }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            result = _properties[binder.Name];
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            _properties[binder.Name] = value;
            return true;
        }
        else
        {
            return false;
        }
    }
}

That way you just need:

var dyn = GetDynamicObject(new Dictionary<string, object>()
    {
        {"prop1", 12},
    });

Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;

Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

Move branch pointer to different commit without checkout

You can also pass git reset --hard a commit reference.

For example:

git checkout branch-name
git reset --hard new-tip-commit

I find I do something like this semi-frequently:

Assuming this history

$ git log --decorate --oneline --graph
* 3daed46 (HEAD, master) New thing I shouldn't have committed to master
* a0d9687 This is the commit that I actually want to be master

# Backup my latest commit to a wip branch
$ git branch wip_doing_stuff

# Ditch that commit on this branch
$ git reset --hard HEAD^

# Now my changes are in a new branch
$ git log --decorate --oneline --graph
* 3daed46 (wip_doing_stuff) New thing I shouldn't have committed to master
* a0d9687 (HEAD, master) This is the commit that I actually want to be master

How to send a "multipart/form-data" with requests in python?

Since the previous answers were written, requests have changed. Have a look at the bug thread at Github for more detail and this comment for an example.

In short, the files parameter takes a dict with the key being the name of the form field and the value being either a string or a 2, 3 or 4-length tuple, as described in the section POST a Multipart-Encoded File in the requests quickstart:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

In the above, the tuple is composed as follows:

(filename, data, content_type, headers)

If the value is just a string, the filename will be the same as the key, as in the following:

>>> files = {'obvius_session_id': '72c2b6f406cdabd578c5fd7598557c52'}

Content-Disposition: form-data; name="obvius_session_id"; filename="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

If the value is a tuple and the first entry is None the filename property will not be included:

>>> files = {'obvius_session_id': (None, '72c2b6f406cdabd578c5fd7598557c52')}

Content-Disposition: form-data; name="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

relative path in require_once doesn't work

In my case it doesn't work, even with __DIR__ or getcwd() it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:

if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/

I have MAMP with php 5.4.10 and my folder hierarchy is basilar:

q.php 
w.php 
e.php 
r.php 
cache/a.php 
cache/b.php 
setting/a.php 
setting/b.php

....

axios post request to send form data

Check out querystring.

You can use it as follows:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

How to query for Xml values and attributes from table in SQL Server?

I don't understand why some people are suggesting using cross apply or outer apply to convert the xml into a table of values. For me, that just brought back way too much data.

Here's my example of how you'd create an xml object, then turn it into a table.

(I've added spaces in my xml string, just to make it easier to read.)

DECLARE @str nvarchar(2000)

SET @str = ''
SET @str = @str + '<users>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mike</firstName>'
SET @str = @str + '     <lastName>Gledhill</lastName>'
SET @str = @str + '     <age>31</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mark</firstName>'
SET @str = @str + '     <lastName>Stevens</lastName>'
SET @str = @str + '     <age>42</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Sarah</firstName>'
SET @str = @str + '     <lastName>Brown</lastName>'
SET @str = @str + '     <age>23</age>'
SET @str = @str + '  </user>'
SET @str = @str + '</users>'

DECLARE @xml xml
SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML) 

--  Iterate through each of the "users\user" records in our XML
SELECT 
    x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
    x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
    x.Rec.query('./age').value('.', 'int') AS 'Age'
FROM @xml.nodes('/users/user') as x(Rec)

And here's the output:

enter image description here

How to make asynchronous HTTP requests in PHP

let me show you my way :)

needs nodejs installed on the server

(my server sends 1000 https get request takes only 2 seconds)

url.php :

<?
$urls = array_fill(0, 100, 'http://google.com/blank.html');

function execinbackground($cmd) { 
    if (substr(php_uname(), 0, 7) == "Windows"){ 
        pclose(popen("start /B ". $cmd, "r"));  
    } 
    else { 
        exec($cmd . " > /dev/null &");   
    } 
} 
fwite(fopen("urls.txt","w"),implode("\n",$urls);
execinbackground("nodejs urlscript.js urls.txt");
// { do your work while get requests being executed.. }
?>

urlscript.js >

var https = require('https');
var url = require('url');
var http = require('http');
var fs = require('fs');
var dosya = process.argv[2];
var logdosya = 'log.txt';
var count=0;
http.globalAgent.maxSockets = 300;
https.globalAgent.maxSockets = 300;

setTimeout(timeout,100000); // maximum execution time (in ms)

function trim(string) {
    return string.replace(/^\s*|\s*$/g, '')
}

fs.readFile(process.argv[2], 'utf8', function (err, data) {
    if (err) {
        throw err;
    }
    parcala(data);
});

function parcala(data) {
    var data = data.split("\n");
    count=''+data.length+'-'+data[1];
    data.forEach(function (d) {
        req(trim(d));
    });
    /*
    fs.unlink(dosya, function d() {
        console.log('<%s> file deleted', dosya);
    });
    */
}


function req(link) {
    var linkinfo = url.parse(link);
    if (linkinfo.protocol == 'https:') {
        var options = {
        host: linkinfo.host,
        port: 443,
        path: linkinfo.path,
        method: 'GET'
    };
https.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});
    } else {
    var options = {
        host: linkinfo.host,
        port: 80,
        path: linkinfo.path,
        method: 'GET'
    };        
http.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});
    }
}


process.on('exit', onExit);

function onExit() {
    log();
}

function timeout()
{
console.log("i am too far gone");process.exit();
}

function log() 
{
    var fd = fs.openSync(logdosya, 'a+');
    fs.writeSync(fd, dosya + '-'+count+'\n');
    fs.closeSync(fd);
}

bool to int conversion

You tagged your question [C] and [C++] at the same time. The results will be consistent between the languages, but the structure of the the answer is different for each of these languages.

In C language your examples has no relation to bool whatsoever (that applies to C99 as well). In C language relational operators do not produce bool results. Both 4 > 5 and 4 < 5 are expressions that produce results of type int with values 0 or 1. So, there's no "bool to int conversion" of any kind taking place in your examples in C.

In C++ relational operators do indeed produce bool results. bool values are convertible to int type, with true converting to 1 and false converting to 0. This is guaranteed by the language.

P.S. C language also has a dedicated boolean type _Bool (macro-aliased as bool), and its integral conversion rules are essentially the same as in C++. But nevertheless this is not relevant to your specific examples in C. Once again, relational operators in C always produce int (not bool) results regardless of the version of the language specification.

How to get evaluated attributes inside a custom directive

For the same solution I was looking for Angularjs directive with ng-Model.
Here is the code that resolve the problem.

    myApp.directive('zipcodeformatter', function () {
    return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        link: function (scope, element, attrs, ngModel) {

            scope.$watch(attrs.ngModel, function (v) {
                if (v) {
                    console.log('value changed, new value is: ' + v + ' ' + v.length);
                    if (v.length > 5) {
                        var newzip = v.replace("-", '');
                        var str = newzip.substring(0, 5) + '-' + newzip.substring(5, newzip.length);
                        element.val(str);

                    } else {
                        element.val(v);
                    }

                }

            });

        }
    };
});


HTML DOM

<input maxlength="10" zipcodeformatter onkeypress="return isNumberKey(event)" placeholder="Zipcode" type="text" ng-readonly="!checked" name="zipcode" id="postal_code" class="form-control input-sm" ng-model="patient.shippingZipcode" required ng-required="true">


My Result is:

92108-2223

Modulo operator in Python

you should use fmod(a,b)

While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff.

For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 % 1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100.

Function fmod() in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application.

where x = a%b is used for integer modulo

How do implement a breadth first traversal?

Breadth first is a queue, depth first is a stack.

For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.

For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.

How to split a String by space

Here is a method to trim a String that has a "," or white space

private String shorterName(String s){
        String[] sArr = s.split("\\,|\\s+");
        String output = sArr[0];

        return output;
    }

How to pass boolean values to a PowerShell script from a command prompt

It appears that powershell.exe does not fully evaluate script arguments when the -File parameter is used. In particular, the $false argument is being treated as a string value, in a similar way to the example below:

PS> function f( [bool]$b ) { $b }; f -b '$false'
f : Cannot process argument transformation on parameter 'b'. Cannot convert value 
"System.String" to type "System.Boolean", parameters of this type only accept 
booleans or numbers, use $true, $false, 1 or 0 instead.
At line:1 char:36
+ function f( [bool]$b ) { $b }; f -b <<<<  '$false'
    + CategoryInfo          : InvalidData: (:) [f], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,f

Instead of using -File you could try -Command, which will evaluate the call as script:

CMD> powershell.exe -NoProfile -Command .\RunScript.ps1 -Turn 1 -Unify $false
Turn: 1
Unify: False

As David suggests, using a switch argument would also be more idiomatic, simplifying the call by removing the need to pass a boolean value explicitly:

CMD> powershell.exe -NoProfile -File .\RunScript.ps1 -Turn 1 -Unify
Turn: 1
Unify: True

Cannot connect to the Docker daemon on macOS

I was facing similar issue on my mac, and I found that docker wasn't running in my machine, I just went to applications and invoked whale and then it worked .