Programs & Examples On #Field description

Where to put default parameter value in C++?

If the functions are exposed - non-member, public or protected - then the caller should know about them, and the default values must be in the header.

If the functions are private and out-of-line, then it does make sense to put the defaults in the implementation file because that allows changes that don't trigger client recompilation (a sometimes serious issue for low-level libraries shared in enterprise scale development). That said, it is definitely potentially confusing, and there is documentation value in presenting the API in a more intuitive way in the header, so pick your compromise - though consistency's the main thing when there's no compelling reason either way.

How to save final model using keras?

You can save the best model using keras.callbacks.ModelCheckpoint()

Example:

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model_checkpoint_callback = keras.callbacks.ModelCheckpoint("best_Model.h5",save_best_only=True)
history = model.fit(x_train,y_train,
          epochs=10,
          validation_data=(x_valid,y_valid),
          callbacks=[model_checkpoint_callback])

This will save the best model in your working directory.

Memory address of an object in C#

This works for me...

#region AddressOf

    /// <summary>
    /// Provides the current address of the given object.
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    public static System.IntPtr AddressOf(object obj)
    {
        if (obj == null) return System.IntPtr.Zero;

        System.TypedReference reference = __makeref(obj);

        System.TypedReference* pRef = &reference;

        return (System.IntPtr)pRef; //(&pRef)
    }

    /// <summary>
    /// Provides the current address of the given element
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="t"></param>
    /// <returns></returns>
    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    public static System.IntPtr AddressOf<T>(T t)
        //refember ReferenceTypes are references to the CLRHeader
        //where TOriginal : struct
    {
        System.TypedReference reference = __makeref(t);

        return *(System.IntPtr*)(&reference);
    }

    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    static System.IntPtr AddressOfRef<T>(ref T t)
    //refember ReferenceTypes are references to the CLRHeader
    //where TOriginal : struct
    {
        System.TypedReference reference = __makeref(t);

        System.TypedReference* pRef = &reference;

        return (System.IntPtr)pRef; //(&pRef)
    }

    /// <summary>
    /// Returns the unmanaged address of the given array.
    /// </summary>
    /// <param name="array"></param>
    /// <returns><see cref="IntPtr.Zero"/> if null, otherwise the address of the array</returns>
    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    public static System.IntPtr AddressOfByteArray(byte[] array)
    {
        if (array == null) return System.IntPtr.Zero;

        fixed (byte* ptr = array)
            return (System.IntPtr)(ptr - 2 * sizeof(void*)); //Todo staticaly determine size of void?
    }

    #endregion

Read and Write CSV files including unicode with Python 2.7

Because str in python2 is bytes actually. So if want to write unicode to csv, you must encode unicode to str using utf-8 encoding.

def py2_unicode_to_str(u):
    # unicode is only exist in python2
    assert isinstance(u, unicode)
    return u.encode('utf-8')

Use class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds):

  • py2
    • The csvfile: open(fp, 'w')
    • pass key and value in bytes which are encoded with utf-8
      • writer.writerow({py2_unicode_to_str(k): py2_unicode_to_str(v) for k,v in row.items()})
  • py3
    • The csvfile: open(fp, 'w')
    • pass normal dict contains str as row to writer.writerow(row)

Finally code

import sys

is_py2 = sys.version_info[0] == 2

def py2_unicode_to_str(u):
    # unicode is only exist in python2
    assert isinstance(u, unicode)
    return u.encode('utf-8')

with open('file.csv', 'w') as f:
    if is_py2:
        data = {u'Python??': u'Python??', u'Python??2': u'Python??2'}

        # just one more line to handle this
        data = {py2_unicode_to_str(k): py2_unicode_to_str(v) for k, v in data.items()}

        fields = list(data[0])
        writer = csv.DictWriter(f, fieldnames=fields)

        for row in data:
            writer.writerow(row)
    else:
        data = {'Python??': 'Python??', 'Python??2': 'Python??2'}

        fields = list(data[0])
        writer = csv.DictWriter(f, fieldnames=fields)

        for row in data:
            writer.writerow(row)

Conclusion

In python3, just use the unicode str.

In python2, use unicode handle text, use str when I/O occurs.

Failed to locate the winutils binary in the hadoop binary path

I was getting the same issue in windows. I fixed it by

  • Downloading hadoop-common-2.2.0-bin-master from link.
  • Create a user variable HADOOP_HOME in Environment variable and assign the path of hadoop-common bin directory as a value.
  • You can verify it by running hadoop in cmd.
  • Restart the IDE and Run it.

Android Layout Right Align

To support older version Space can be replaced with View as below. Add this view between after left most component and before right most component. This view with weight=1 will stretch and fill the space

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

Complete sample code is given here. It has has 4 components. Two arrows will be on the right and left side. The Text and Spinner will be in the middle.

    <ImageButton
        android:id="@+id/btnGenesis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|center_vertical"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="2dp"
        android:background="@null"
        android:gravity="left"
        android:src="@drawable/prev" />

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/lblVerseHeading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:textSize="25sp" />

    <Spinner
        android:id="@+id/spinnerVerses"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:gravity="center"
        android:textSize="25sp" />

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

    <ImageButton
        android:id="@+id/btnExodus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|center_vertical"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="2dp"
        android:background="@null"
        android:gravity="right"
        android:src="@drawable/next" />
</LinearLayout>

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

You should have name column as a unique constraint. here is a 3 lines of code to change your issues

  1. First find out the primary key constraints by typing this code

    \d table_name
    

    you are shown like this at bottom "some_constraint" PRIMARY KEY, btree (column)

  2. Drop the constraint:

    ALTER TABLE table_name DROP CONSTRAINT some_constraint
    
  3. Add a new primary key column with existing one:

    ALTER TABLE table_name ADD CONSTRAINT some_constraint PRIMARY KEY(COLUMN_NAME1,COLUMN_NAME2);
    

That's All.

How can you sort an array without mutating the original array?

You can use slice with no arguments to copy an array:

var foo,
    bar;
foo = [3,1,2];
bar = foo.slice().sort();

How to indent HTML tags in Notepad++

I have a solution for you.

Just you need to install a plugin named Indent By Fold.

You can install this by going through Plugins -> Plugin Manager -> Show Plugin Manager. OR Plugins -> Plugins Admin -> chekmark Indent By Fold from list than install

Then just select the list item and all you need is to type the first word then you got it.

you can use this plugin from a plugin in the menu bar.


What is a handle in C++?

A handle is whatever you want it to be.

A handle can be a unsigned integer used in some lookup table.

A handle can be a pointer to, or into, a larger set of data.

It depends on how the code that uses the handle behaves. That determines the handle type.

The reason the term 'handle' is used is what is important. That indicates them as an identification or access type of object. Meaning, to the programmer, they represent a 'key' or access to something.

Sleep Command in T-SQL?

You can also "WAITFOR" a "TIME":

    RAISERROR('Im about to wait for a certain time...', 0, 1) WITH NOWAIT
    WAITFOR TIME '16:43:30.000'
    RAISERROR('I waited!', 0, 1) WITH NOWAIT

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

Sorry, it is a reponse to an old thread, but might still be usefull.

In addition to above reponses, This genrally happens when two columns with same name, even from different tables are included in the same query. for example if we joining two tables city and state where tables have column name e.g. city.name and state.name. when such a query is added to the dataset, ssrs removes the table name or the table alias and only keeps the name, whih eventually appears twice in the query and errors as duplicate key. The best way to avoid it is to use alias such as calling the column names city.name as c_name state.name as s_name. This will resolve the issue.

How do you change the value inside of a textfield flutter?

First Thing

  TextEditingController MyController= new TextEditingController();

Then add it to init State or in any SetState

    MyController.value = TextEditingValue(text: "ANY TEXT");

How to write both h1 and h2 in the same line?

<h1 style="text-align: left; float: left;">Text 1</h1>
<h2 style="text-align: right; float: right; display: inline;">Text 2</h2>
<hr style="clear: both;" />

Hope this helps!

Laravel PHP Command Not Found

If you are coming here 2021 this has worked for me also using Ubuntu 16.04

nano ~/.bash_profile 
export PATH=$HOME/.config/composer/vendor/bin:$PATH
ctrl+x and save 
source ~/.bash_profile

Check with jquery if div has overflowing elements

So I used the overflowing jquery library: https://github.com/kevinmarx/overflowing

After installing the library, if you want to assign the class overflowing to all overflowing elements, you simply run:

$('.targetElement').overflowing('.parentElement')

This will then give the class overflowing, as in <div class="targetElement overflowing"> to all elements that are overflowing. You could then add this to some event handler(click, mouseover) or other function that will run the above code so that it updates dynamically.

Override standard close (X) button in a Windows Form

Override the OnFormClosing method.

CAUTION: You need to check the CloseReason and only alter the behaviour if it is UserClosing. You should not put anything in here that would stall the Windows shutdown routine.

Application Shutdown Changes in Windows Vista

This is from the Windows 7 logo program requirements.

JavaScript Extending Class

If you don't like the prototype approach, because it doesn't really behave in a nice OOP-way, you could try this:

var BaseClass = function() 
{
    this.some_var = "foobar";

    /**
     * @return string
     */
    this.someMethod = function() {
        return this.some_var;
    }
};

var MyClass = new Class({ extends: BaseClass }, function()
{
    /**
     * @param string value
     */
    this.__construct = function(value)
    {
        this.some_var = value;
    }
})

Using lightweight library (2k minified): https://github.com/haroldiedema/joii

SQL Server format decimal places with commas

From a related SO question: Format a number with commas but without decimals in SQL Server 2008 R2?

SELECT CONVERT(varchar, CAST(1112 AS money), 1)

This was tested in SQL Server 2008 R2.

How do I download a file from the internet to my linux server with Bash

You can use the command wget to download from command line. Specifically, you could use

wget http://download.oracle.com/otn-pub/java/jdk/7u10-b18/jdk-7u10-linux-x64.tar.gz

However because Oracle requires you to accept a license agreement this may not work (and I am currently unable to test it).

How to convert date in to yyyy-MM-dd Format?

Modern answer: Use LocalDate from java.time, the modern Java date and time API, and its toString method:

    LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
    String formattedDate = date.toString();
    System.out.println(formattedDate);

This prints

2012-12-01

A date (whether we’re talking java.util.Date or java.time.LocalDate) doesn’t have a format in it. All it’s got is a toString method that produces some format, and you cannot change the toString method. Fortunately, LocalDate.toString produces exactly the format you asked for.

The Date class is long outdated, and the SimpleDateFormat class that you tried to use, is notoriously troublesome. I recommend you forget about those classes and use java.time instead. The modern API is so much nicer to work with.

Except: it happens that you get a Date from a legacy API that you cannot change or don’t want to change just now. The best thing you can do with it is convert it to java.time.Instant and do any further operations from there:

    Date oldfashoinedDate = // get from somewhere
    LocalDate date = oldfashoinedDate.toInstant()
            .atZone(ZoneId.of("Asia/Beirut"))
            .toLocalDate();

Please substitute your desired time zone if it didn’t happen to be Asia/Beirut. Then proceed as above.

Link: Oracle tutorial: Date Time, explaining how to use java.time.

SDK Manager.exe doesn't work

Step #1: Open up a command prompt.

Step #2: Use the cd command to move to wherever you installed your Android SDK.

Step #3: Run tools\android.

If that does not work, you should have information dumped to the command prompt that will help you diagnose your setup problem.

C#: Printing all properties of an object

Following snippet will do the desired function:

Type t = obj.GetType(); // Where obj is object whose properties you need.
PropertyInfo [] pi = t.GetProperties();
foreach (PropertyInfo p in pi)
{
    System.Console.WriteLine(p.Name + " : " + p.GetValue(obj));
}

I think if you write this as extension method you could use it on all type of objects.

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Open Cygwin at a specific folder

Create a bash file say move.sh which has the following code C:\cygwin64\bin\run.exe -p /bin bash runFile.sh This starts the Cygwin and executes the runFile.sh present in the bin directory of Cygwin Suppose you want to navigate to a specific directory say E:\code then runFile.sh has the following code cd E: cd code

HTML Tags in Javascript Alert() method

alert() is a method of the window object that cannot interpret HTML tags

Locate the nginx.conf file my nginx is actually using

All other answers are useful but they may not help you in case nginx is not on PATH so you're getting command not found when trying to run nginx:

I have nginx 1.2.1 on Debian 7 Wheezy, the nginx executable is not on PATH, so I needed to locate it first. It was already running, so using ps aux | grep nginx I have found out that it's located on /usr/sbin/nginx, therefore I needed to run /usr/sbin/nginx -t.

If you want to use a non-default configuration file (i.e. not /etc/nginx/nginx.conf), run it with the -c parameter: /usr/sbin/nginx -c <path-to-configuration> -t.

You may also need to run it as root, otherwise nginx may not have permissions to open for example logs, so the command would fail.

Find and kill a process in one line using bash and regex

Find and kill all the processes in one line in bash.

kill -9 $(ps -ef | grep '<exe_name>' | grep -v 'grep' | awk {'print $2'})
  • ps -ef | grep '<exe_name>' - Gives the list of running process details (uname, pid, etc ) which matches the pattern. Output list includes this grep command also which searches it. Now for killing we need to ignore this grep command process.
  • ps -ef | grep '<exec_name>' | grep -v 'grep' - Adding another grep with -v 'grep' removes the current grep process.
  • Then using awk get the process id alone.
  • Then keep this command inside $(...) and pass it to kill command, to kill all process.

How to make a button redirect to another page using jQuery or just Javascript

And in Rails 3 with CoffeeScript using unobtrusive JavaScript (UJS):

Add to assets/javascripts/my_controller.js.coffee:

$ ->
  $('#field_name').click ->
    window.location.href = 'new_url'

which reads: when the document.ready event has fired, add an onclick event to a DOM object whose ID is field_name which executes the javascript window.location.href='new_url';

How to get all properties values of a JavaScript Object (without knowing the keys)?

Use: Object.values(), we pass in an object as an argument and receive an array of the values as a return value.

This returns an array of a given object own enumerable property values. You will get the same values as by using the for in loop but without the properties on the Prototype. This example will probably make things clearer:

_x000D_
_x000D_
function person (name) {_x000D_
  this.name = name;_x000D_
}_x000D_
_x000D_
person.prototype.age = 5;_x000D_
_x000D_
let dude = new person('dude');_x000D_
_x000D_
for(let prop in dude) {_x000D_
  console.log(dude[prop]);     // for in still shows age because this is on the prototype_x000D_
}                              // we can use hasOwnProperty but this is not very elegant_x000D_
_x000D_
// ES6 + _x000D_
console.log(Object.values(dude));_x000D_
// very concise and we don't show props on prototype
_x000D_
_x000D_
_x000D_

Using sed and grep/egrep to search and replace

I couldn't get any of the commands on this page to work for me: the sed solution added a newline to the end of all the files it processed, and the perl solution was unable to accept enough arguments from find. I found this solution which works perfectly:

find . -type f -name '*.[hm]' -print0 
    | xargs -0 perl -pi -e 's/search_regex/replacement_string/g'

This will recurse down the current directory tree and replace search_regex with replacement_string in any files ending in .h or .m.

I have also used rpl for this purpose in the past.

Sum all the elements java arraylist

Two ways:

Use indexes:

double sum = 0;
for(int i = 0; i < m.size(); i++)
    sum += m.get(i);
return sum;

Use the "for each" style:

double sum = 0;
for(Double d : m)
    sum += d;
return sum;

Setting paper size in FPDF

They say it right there in the documentation for the FPDF constructor:

FPDF([string orientation [, string unit [, mixed size]]])

This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...

size

The size used for pages. It can be either one of the following values (case insensitive):

A3 A4 A5 Letter Legal

or an array containing the width and the height (expressed in the unit given by unit).

They even give an example with custom size:

Example with a custom 100x150 mm page size:

$pdf = new FPDF('P','mm',array(100,150));

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

JavaScript is in array

a little bit code from my side (custom function for Array):

    Array.prototype.in_array = function (array) {
        var $i = 0;
        var type = typeof array;
        while (this[$i]) {
            if ((type == ('number') || type == ('string'))  && array == this[$i]) {
                return true;
            } else if (type == 'object' && array instanceof Array && array.in_array(this[$i])) {
                return true
            }
            $i++;
        }
        return false;
    };


    var array = [1, 2, 3, "a", "b", "c"];

    //if string in array
    if (array.in_array('b')) {
        console.log("in array");
    }

    //if number in array
    if (array.in_array(3)) {
        console.log("in array");
    }

    // if one from array in array
    if (array.in_array([1, 'b'])) {
        console.log("in array");
    }

Best way to change font colour halfway through paragraph?

<span> will allow you to style text, but it adds no semantic content.

As you're emphasizing some text, it sounds like you'd be better served by wrapping the text in <em></em> and using CSS to change the color of the <em> element. For example:

CSS

.description {
  color: #fff;
}

.description em {
  color: #ffa500;
}

Markup

<p class="description">Lorem ipsum dolor sit amet, consectetur 
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat 
massa, <em>eget vulputate tellus fermentum.</em></p>

In fact, I'd go to great pains to avoid the <span> element, as it's completely meaningless to everything that doesn't render your style sheet (bots, screen readers, luddites who disable styles, parsers, etc.) or renders it in unexpected ways (personal style sheets). In many ways, it's no better than using the <font> element.

_x000D_
_x000D_
.description {_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.description em {_x000D_
  color: #ffa500;_x000D_
}
_x000D_
<p class="description">Lorem ipsum dolor sit amet, consectetur _x000D_
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat _x000D_
massa, <em>eget vulputate tellus fermentum.</em></p>
_x000D_
_x000D_
_x000D_

Reloading submodules in IPython

I hate to add yet another answer to a long thread, but I found a solution that enables recursive reloading of submodules on %run() that others might find useful (I have anyway)

del the submodule you wish to reload on run from sys.modules in iPython:

In[1]: from sys import modules
In[2]: del modules["mymodule.mysubmodule"] # tab completion can be used like mymodule.<tab>!

Now your script will recursively reload this submodule:

In[3]: %run myscript.py

How do you make an array of structs in C?

Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.

Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:

typedef struct
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
}Body;

Then declare your array of structs. Initialization of each element goes along with the declaration:

Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};

To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.

How can I dismiss the on screen keyboard?

Following code helped me to hide keyboard

   void initState() {
   SystemChannels.textInput.invokeMethod('TextInput.hide');
   super.initState();
   }

What's the difference between console.dir and console.log?

In Firefox, these function behave quite differently: log only prints out a toString representation, whereas dir prints out a navigable tree.

In Chrome, log already prints out a tree -- most of the time. However, Chrome's log still stringifies certain classes of objects, even if they have properties. Perhaps the clearest example of a difference is a regular expression:

> console.log(/foo/);
/foo/

> console.dir(/foo/);
* /foo/
    global: false
    ignoreCase: false
    lastIndex: 0
    ...

You can also see a clear difference with arrays (e.g., console.dir([1,2,3])) which are logged differently from normal objects:

> console.log([1,2,3])
[1, 2, 3]

> console.dir([1,2,3])
* Array[3]
    0: 1
    1: 2
    2: 3
    length: 3
    * __proto__: Array[0]
        concat: function concat() { [native code] }
        constructor: function Array() { [native code] }
        entries: function entries() { [native code] }
        ...

DOM objects also exhibit differing behavior, as noted on another answer.

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

Openstreetmap: embedding map in webpage (like Google Maps)

If you just want to embed an OSM map on a webpage, the easiest way is to get the iframe code directly from the OSM website:

  1. Navigate to the map you want on https://www.openstreetmap.org
  2. On the right side, click the "Share" icon, then click "HTML"
  3. Copy the resulting iframe code directly into your webpage. It should look like this:

_x000D_
_x000D_
<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" _x000D_
src="https://www.openstreetmap.org/export/embed.html?bbox=-62.04673002474011%2C16.95487694424327%2C-61.60521696321666%2C17.196751341562923&amp;layer=mapnik" _x000D_
style="border: 1px solid black"></iframe>_x000D_
<br/><small><a href="https://www.openstreetmap.org/#map=12/17.0759/-61.8260">View Larger Map</a></small>
_x000D_
_x000D_
_x000D_

If you want to do something more elaborate, see OSM wiki "Deploying your own Slippy Map".

How can I manually generate a .pyc file from a .py file

I found several ways to compile python scripts into bytecode

  1. Using py_compile in terminal:

    python -m py_compile File1.py File2.py File3.py ...
    

    -m specifies the module(s) name to be compiled.

    Or, for interactive compilation of files

    python -m py_compile -
    File1.py
    File2.py
    File3.py
       .
       .
       .
    
  2. Using py_compile.compile:

    import py_compile
    py_compile.compile('YourFileName.py')
    
  3. Using py_compile.main():

    It compiles several files at a time.

    import py_compile
    py_compile.main(['File1.py','File2.py','File3.py'])
    

    The list can grow as long as you wish. Alternatively, you can obviously pass a list of files in main or even file names in command line args.

    Or, if you pass ['-'] in main then it can compile files interactively.

  4. Using compileall.compile_dir():

    import compileall
    compileall.compile_dir(direname)
    

    It compiles every single Python file present in the supplied directory.

  5. Using compileall.compile_file():

    import compileall
    compileall.compile_file('YourFileName.py')
    

Take a look at the links below:

https://docs.python.org/3/library/py_compile.html

https://docs.python.org/3/library/compileall.html

Where do I find the Instagram media ID of a image

Right click on a photo and open in a new tab/window. Right click on inspect element. Search for:

instagram://media?id=

This will give you:

instagram://media?id=############# /// the ID

The full id construct from

photoID_userID

To get the user id, search for:

instapp:owner_user_id Will be in content=

How to set a dropdownlist item as selected in ASP.NET?

This is a very nice and clean example:(check this great tutorial for a full explanation link)

public static IEnumerable<SelectListItem> ToSelectListItems(
              this IEnumerable<Album> albums, int selectedId)
{
    return 
        albums.OrderBy(album => album.Name)
              .Select(album => 
                  new SelectListItem
                  {
                    Selected = (album.ID == selectedId),
                    Text = album.Name,
                    Value = album.ID.ToString()
                   });
}

In this MSDN link you can read de DropDownList method documentation.

Hope it helps.

SQL Query to find the last day of the month

declare @date date=getdate()
declare @st_date date,@end_dt date
set @st_date=convert(varchar(5),year(@date))+'-'+convert(varchar(5),month(@date))+'-01'
set @end_dt=DATEADD(day,-1, DATEADD(month,1,@st_date))
---------**************--------------
select @st_date as [START DATE],@end_dt AS [END DATE]

Return the most recent record from ElasticSearch index

Since this question was originally asked and answered, some of the inner-workings of Elasticsearch have changed, particularly around timestamps. Here is a full example showing how to query for single latest record. Tested on ES 6/7.

1) Tell Elasticsearch to treat timestamp field as the timestamp

curl -XPUT "localhost:9200/my_index?pretty" -H 'Content-Type: application/json' -d '{"mappings":{"message":{"properties":{"timestamp":{"type":"date"}}}}}'

2) Put some test data into the index

curl -XPOST "localhost:9200/my_index/message/1" -H 'Content-Type: application/json' -d '{ "timestamp" : "2019-08-02T03:00:00Z", "message" : "hello world" }'
curl -XPOST "localhost:9200/my_index/message/2" -H 'Content-Type: application/json' -d '{ "timestamp" : "2019-08-02T04:00:00Z", "message" : "bye world" }'

3) Query for the latest record

curl -X POST "localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d '{"query": {"match_all": {}},"size": 1,"sort": [{"timestamp": {"order": "desc"}}]}'

4) Expected results

{
   "took":0,
   "timed_out":false,
   "_shards":{
      "total":5,
      "successful":5,
      "skipped":0,
      "failed":0
   },
   "hits":{
      "total":2,
      "max_score":null,
      "hits":[
         {
            "_index":"my_index",
            "_type":"message",
            "_id":"2",
            "_score":null,
            "_source":{
               "timestamp":"2019-08-02T04:00:00Z",
               "message":"bye world"
            },
            "sort":[
               1564718400000
            ]
         }
      ]
   }
}

$.focus() not working

I realize this is old, but came across it today. None of the answers worked for me, what I did find that worked was setTimeout. I wanted my focus to be placed on the input filed of a modal, using the setTimeout worked. Hope this helps!

How can I change the image displayed in a UIImageView programmatically?

This worked for me

[ImageViewName setImage:[UIImage imageNamed: @"ImageName.png"]];

Make sure that the ImageView is declared properly in the .h file and is linked with the IB element.

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

Run "setup_xampp.bat/.sh" and then Delete "\" at the end, so your ServerRoot should be like "C:.....\apache" NO "C:.....\apache\"

Change default timeout for mocha

Adding this for completeness. If you (like me) use a script in your package.json file, just add the --timeout option to mocha:

"scripts": {
  "test": "mocha 'test/**/*.js' --timeout 10000",
  "test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},

Then you can run npm run test to run your test suite with the timeout set to 10,000 milliseconds.

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

It’s the double colon operator :: (see list of parser tokens).

Pass multiple arguments into std::thread

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

How to convert integer to decimal in SQL Server query?

You can either cast Height as a decimal:

select cast(@height as decimal(10, 5))/10 as heightdecimal

or you place a decimal point in your value you are dividing by:

declare @height int
set @height = 1023

select @height/10.0 as heightdecimal

see sqlfiddle with an example

Codeigniter displays a blank page instead of error messages

This behavior occurs when you have basic php syntax error in your code. In case when you have syntax errors the php parser does not parse the code completely and didnot display anything so all of the above suggestion would work only if you have other than syntax errors.

PostgreSQL wildcard LIKE for any of a list of words

You can use Postgres' SIMILAR TO operator which supports alternations, i.e.

select * from table where lower(value) similar to '%(foo|bar|baz)%';

Case insensitive 'in'

My 5 (wrong) cents

'a' in "".join(['A']).lower()

UPDATE

Ouch, totally agree @jpp, I'll keep as an example of bad practice :(

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

Just iterate and add:

for(Map.Entry e : a.entrySet())
  if(!b.containsKey(e.getKey())
    b.put(e.getKey(), e.getValue());

Edit to add:

If you can make changes to a, you can also do:

a.putAll(b)

and a will have exactly what you need. (all the entries in b and all the entries in a that aren't in b)

mysql data directory location

If you are using Homebrew to install [email protected], the location is

/usr/local/Homebrew/var/mysql

I don't know if the location is the same for other versions.

HTTP status code for update and delete?

Here's some status code, which you should know for your kind of knowledge.

1XX Information Responses

  • 100 Continue
  • 101 Switching Protocols
  • 102 Processing
  • 103 Early Hints

2XX Success

  • 200 OK
  • 201 Created
  • 202 Accepted
  • 203 Non-Authoritative Information
  • 204 No Content
  • 205 Reset Content
  • 206 Partial Content
  • 207 Multi-Status
  • 208 Already Reported
  • 226 IM Used

3XX Redirection

  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found
  • 303 See Other
  • 304 Not Modified
  • 305 Use Proxy
  • 306 Switch Proxy
  • 307 Temporary Redirect
  • 308 Permanent Redirect

4XX Client errors

  • 400 Bad Request
  • 401 Unauthorized
  • 402 Payment Required
  • 403 Forbidden
  • 404 Not Found
  • 405 Method Not Allowed
  • 406 Not Acceptable
  • 407 Proxy Authentication Required
  • 408 Request Timeout
  • 409 Conflict
  • 410 Gone
  • 411 Length Required
  • 412 Precondition Failed
  • 413 Payload Too Large
  • 414 URI Too Long
  • 415 Unsupported Media Type
  • 416 Range Not Satisfiable
  • 417 Expectation Failed
  • 418 I'm a teapot
  • 420 Method Failure
  • 421 Misdirected Request
  • 422 Unprocessable Entity
  • 423 Locked
  • 424 Failed Dependency
  • 426 Upgrade Required
  • 428 Precondition Required
  • 429 Too Many Requests
  • 431 Request Header Fields Too Large
  • 451 Unavailable For Legal Reasons

5XX Server errors

  • 500 Internal Server error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 gateway Timeout
  • 505 Http version not supported
  • 506 Varient Also negotiate
  • 507 Insufficient Storage
  • 508 Loop Detected
  • 510 Not Extended
  • 511 Network Authentication Required

REST API - Use the "Accept: application/json" HTTP Header

Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.

For example, you can validate the content negotiation like this.

This Accept header prefers plain text so returns in that format:-

$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain

Whereas this one prefers JSON and so returns in that format:-

$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
   "Accept": "application/json,text/*;q=0.99"
}

Reading from file using read() function

Read Byte by Byte and check that each byte against '\n' if it is not, then store it into buffer
if it is '\n' add '\0' to buffer and then use atoi()

You can read a single byte like this

char c;
read(fd,&c,1);

See read()

Select multiple value in DropDownList using ASP.NET and C#

In that case you should use ListBox control instead of dropdown and Set the SelectionMode property to Multiple

<asp:ListBox runat="server" SelectionMode="Multiple" >
  <asp:ListItem Text="test1"></asp:ListItem>
  <asp:ListItem Text="test2"></asp:ListItem>
  <asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>

How do I write a custom init for a UIView subclass in Swift?

Here is how I do a Subview on iOS in Swift -

class CustomSubview : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        let windowHeight : CGFloat = 150;
        let windowWidth  : CGFloat = 360;

        self.backgroundColor = UIColor.whiteColor();
        self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
        self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);

        //for debug validation
        self.backgroundColor = UIColor.grayColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

How to print a stack trace in Node.js?

As already answered, you can simply use the trace command:

console.trace("I am here");

However, if you came to this question searching about how to log the stack trace of an exception, you can simply log the Exception object.

try {  
  // if something unexpected
  throw new Error("Something unexpected has occurred.");     

} catch (e) {
  console.error(e);
}

It will log:

Error: Something unexpected has occurred.
    at main (c:\Users\Me\Documents\MyApp\app.js:9:15)
    at Object. (c:\Users\Me\Documents\MyApp\app.js:17:1)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3


If your Node.js version is < than 6.0.0, logging the Exception object will not be enough. In this case, it will print only:

[Error: Something unexpected has occurred.]

For Node version < 6, use console.error(e.stack) instead of console.error(e) to print the error message plus the full stack, like the current Node version does.


Note: if the exception is created as a string like throw "myException", it's not possible to retrieve the stack trace and logging e.stack yields undefined.

To be safe, you can use

console.error(e.stack || e);

and it will work for old and new Node.js versions.

Extract a subset of a dataframe based on a condition involving a field

Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:

    bar <- foo[foo[ ,1] == "there", ]

This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).

This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:

    foo[foo[ ,c(1:N)], ]

Or specific columns, as you would expect.

    foo[foo[ ,c(1,5,9)], ]

How to detect DIV's dimension changed?

Long term, you will be able to use the ResizeObserver.

new ResizeObserver(callback).observe(element);

Unfortunately it is not currently supported by default in many browsers.

In the mean time, you can use function like the following. Since, the majority of element size changes will come from the window resizing or from changing something in the DOM. You can listen to window resizing with the window's resize event and you can listen to DOM changes using MutationObserver.

Here's an example of a function that will call you back when the size of the provided element changes as a result of either of those events:

var onResize = function(element, callback) {
  if (!onResize.watchedElementData) {
    // First time we are called, create a list of watched elements
    // and hook up the event listeners.
    onResize.watchedElementData = [];

    var checkForChanges = function() {
      onResize.watchedElementData.forEach(function(data) {
        if (data.element.offsetWidth !== data.offsetWidth ||
            data.element.offsetHeight !== data.offsetHeight) {
          data.offsetWidth = data.element.offsetWidth;
          data.offsetHeight = data.element.offsetHeight;
          data.callback();
        }
      });
    };

    // Listen to the window's size changes
    window.addEventListener('resize', checkForChanges);

    // Listen to changes on the elements in the page that affect layout 
    var observer = new MutationObserver(checkForChanges);
    observer.observe(document.body, { 
      attributes: true,
      childList: true,
      characterData: true,
      subtree: true 
    });
  }

  // Save the element we are watching
  onResize.watchedElementData.push({
    element: element,
    offsetWidth: element.offsetWidth,
    offsetHeight: element.offsetHeight,
    callback: callback
  });
};

How to filter WooCommerce products by custom attribute

On one of my sites I had to make a custom search by a lot of data some of it from custom fields here is how my $args look like for one of the options:

$args = array(
    'meta_query' => $meta_query,
    'tax_query' => array(
        $query_tax
    ),
    'posts_per_page' => 10,
    'post_type' => 'ad_listing',
    'orderby' => $orderby,
    'order' => $order,
    'paged' => $paged
);

where "$meta_query" is:

$key = "your_custom_key"; //custom_color for example
$value = "blue";//or red or any color
$query_color = array('key' => $key, 'value' => $value);
$meta_query[] = $query_color;

and after that:

query_posts($args);

so you would probably get more info here: http://codex.wordpress.org/Class_Reference/WP_Query and you can search for "meta_query" in the page to get to the info

When should I use the Visitor Design Pattern?

One way to look at it is that the visitor pattern is a way of letting your clients add additional methods to all of your classes in a particular class hierarchy.

It is useful when you have a fairly stable class hierarchy, but you have changing requirements of what needs to be done with that hierarchy.

The classic example is for compilers and the like. An Abstract Syntax Tree (AST) can accurately define the structure of the programming language, but the operations you might want to do on the AST will change as your project advances: code-generators, pretty-printers, debuggers, complexity metrics analysis.

Without the Visitor Pattern, every time a developer wanted to add a new feature, they would need to add that method to every feature in the base class. This is particularly hard when the base classes appear in a separate library, or are produced by a separate team.

(I have heard it argued that the Visitor pattern is in conflict with good OO practices, because it moves the operations of the data away from the data. The Visitor pattern is useful in precisely the situation that the normal OO practices fail.)

Looping through a Scripting.Dictionary using index/item number

According to the documentation of the Item property:

Sets or returns an item for a specified key in a Dictionary object.

In your case, you don't have an item whose key is 1 so doing:

s = d.Item(i)

actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem argument.

The Dictionary also has the Items method which allows looping over the indices:

a = d.Items
For i = 0 To d.Count - 1
    s = a(i)
Next i

Python time measure function

There is an easy tool for timing. https://github.com/RalphMao/PyTimer

It can work like a decorator:

from pytimer import Timer
@Timer(average=False)      
def matmul(a,b, times=100):
    for i in range(times):
        np.dot(a,b)        

Output:

matmul:0.368434
matmul:2.839355

It can also work like a plug-in timer with namespace control(helpful if you are inserting it to a function which has a lot of codes and may be called anywhere else).

timer = Timer()                                           
def any_function():                                       
    timer.start()                                         

    for i in range(10):                                   

        timer.reset()                                     
        np.dot(np.ones((100,1000)), np.zeros((1000,500)))
        timer.checkpoint('block1')                        

        np.dot(np.ones((100,1000)), np.zeros((1000,500)))
        np.dot(np.ones((100,1000)), np.zeros((1000,500)))
        timer.checkpoint('block2')                        
        np.dot(np.ones((100,1000)), np.zeros((1000,1000)))

    for j in range(20):                                   
        np.dot(np.ones((100,1000)), np.zeros((1000,500)))
    timer.summary()                                       

for i in range(2):                                        
    any_function()                                        

Output:

========Timing Summary of Default Timer========
block2:0.065062
block1:0.032529
========Timing Summary of Default Timer========
block2:0.065838
block1:0.032891

Hope it will help

Regular expression to match numbers with or without commas and decimals in text

EDIT: Since this has gotten a lot of views, let me start by giving everybody what they Googled for:

#ALL THESE REQUIRE THE WHOLE STRING TO BE A NUMBER
#For numbers embedded in sentences, see discussion below

#### NUMBERS AND DECIMALS ONLY ####
#No commas allowed
#Pass: (1000.0), (001), (.001)
#Fail: (1,000.0)
^\d*\.?\d+$

#No commas allowed
#Can't start with "."
#Pass: (0.01)
#Fail: (.01)
^(\d+\.)?\d+$

#### CURRENCY ####
#No commas allowed
#"$" optional
#Can't start with "."
#Either 0 or 2 decimal digits
#Pass: ($1000), (1.00), ($0.11)
#Fail: ($1.0), (1.), ($1.000), ($.11)
^\$?\d+(\.\d{2})?$

#### COMMA-GROUPED ####
#Commas required between powers of 1,000
#Can't start with "."
#Pass: (1,000,000), (0.001)
#Fail: (1000000), (1,00,00,00), (.001)
^\d{1,3}(,\d{3})*(\.\d+)?$

#Commas required
#Cannot be empty
#Pass: (1,000.100), (.001)
#Fail: (1000), ()
^(?=.)(\d{1,3}(,\d{3})*)?(\.\d+)?$

#Commas optional as long as they're consistent
#Can't start with "."
#Pass: (1,000,000), (1000000)
#Fail: (10000,000), (1,00,00)
^(\d+|\d{1,3}(,\d{3})*)(\.\d+)?$

#### LEADING AND TRAILING ZEROES ####
#No commas allowed
#Can't start with "."
#No leading zeroes in integer part
#Pass: (1.00), (0.00)
#Fail: (001)
^([1-9]\d*|0)(\.\d+)?$

#No commas allowed
#Can't start with "."
#No trailing zeroes in decimal part
#Pass: (1), (0.1)
#Fail: (1.00), (0.1000)
^\d+(\.\d*[1-9])?$

Now that that's out of the way, most of the following is meant as commentary on how complex regex can get if you try to be clever with it, and why you should seek alternatives. Read at your own risk.


This is a very common task, but all the answers I see here so far will accept inputs that don't match your number format, such as ,111, 9,9,9, or even .,,.. That's simple enough to fix, even if the numbers are embedded in other text. IMHO anything that fails to pull 1,234.56 and 1234—and only those numbers—out of abc22 1,234.56 9.9.9.9 def 1234 is a wrong answer.

First of all, if you don't need to do this all in one regex, don't. A single regex for two different number formats is hard to maintain even when they aren't embedded in other text. What you should really do is split the whole thing on whitespace, then run two or three smaller regexes on the results. If that's not an option for you, keep reading.

Basic pattern

Considering the examples you've given, here's a simple regex that allows pretty much any integer or decimal in 0000 format and blocks everything else:

^\d*\.?\d+$

Here's one that requires 0,000 format:

^\d{1,3}(,\d{3})*(\.\d+)?$

Put them together, and commas become optional as long as they're consistent:

^(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)$

Embedded numbers

The patterns above require the entire input to be a number. You're looking for numbers embedded in text, so you have to loosen that part. On the other hand, you don't want it to see catch22 and think it's found the number 22. If you're using something with lookbehind support (like .NET), this is pretty easy: replace ^ with (?<!\S) and $ with (?!\S) and you're good to go:

(?<!\S)(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)(?!\S)

If you're working with JavaScript or Ruby or something, things start looking more complex:

(?:^|\s)(\d*\.?\d+|\d{1,3}(?:,\d{3})*(?:\.\d+)?)(?!\S)

You'll have to use capture groups; I can't think of an alternative without lookbehind support. The numbers you want will be in Group 1 (assuming the whole match is Group 0).

Validation and more complex rules

I think that covers your question, so if that's all you need, stop reading now. If you want to get fancier, things turn very complex very quickly. Depending on your situation, you may want to block any or all of the following:

  • Empty input
  • Leading zeroes (e.g. 000123)
  • Trailing zeroes (e.g. 1.2340000)
  • Decimals starting with the decimal point (e.g. .001 as opposed to 0.001)

Just for the hell of it, let's assume you want to block the first 3, but allow the last one. What should you do? I'll tell you what you should do, you should use a different regex for each rule and progressively narrow down your matches. But for the sake of the challenge, here's how you do it all in one giant pattern:

(?<!\S)(?=.)(0|([1-9](\d*|\d{0,2}(,\d{3})*)))?(\.\d*[1-9])?(?!\S)

And here's what it means:

(?<!\S) to (?!\S) #The whole match must be surrounded by either whitespace or line boundaries. So if you see something bogus like :;:9.:, ignore the 9.
(?=.)             #The whole thing can't be blank.

(                    #Rules for the integer part:
  0                  #1. The integer part could just be 0...
  |                  #
  [1-9]              #   ...otherwise, it can't have leading zeroes.
  (                  #
    \d*              #2. It could use no commas at all...
    |                #
    \d{0,2}(,\d{3})* #   ...or it could be comma-separated groups of 3 digits each.
  )                  # 
)?                   #3. Or there could be no integer part at all.

(       #Rules for the decimal part:
  \.    #1. It must start with a decimal point...
  \d*   #2. ...followed by a string of numeric digits only.
  [1-9] #3. It can't be just the decimal point, and it can't end in 0.
)?      #4. The whole decimal part is also optional. Remember, we checked at the beginning to make sure the whole thing wasn't blank.

Tested here: http://rextester.com/YPG96786

This will allow things like:

100,000
999.999
90.0009
1,000,023.999
0.111
.111
0

It will block things like:

1,1,1.111
000,001.111
999.
0.
111.110000
1.1.1.111
9.909,888

There are several ways to make this regex simpler and shorter, but understand that changing the pattern will loosen what it considers a number.

Since many regex engines (e.g. JavaScript and Ruby) don't support the negative lookbehind, the only way to do this correctly is with capture groups:

(:?^|\s)(?=.)((?:0|(?:[1-9](?:\d*|\d{0,2}(?:,\d{3})*)))?(?:\.\d*[1-9])?)(?!\S)

The numbers you're looking for will be in capture group 1.

Tested here: http://rubular.com/r/3HCSkndzhT

One final note

Obviously, this is a massive, complicated, nigh-unreadable regex. I enjoyed the challenge, but you should consider whether you really want to use this in a production environment. Instead of trying to do everything in one step, you could do it in two: a regex to catch anything that might be a number, then another one to weed out whatever isn't a number. Or you could do some basic processing, then use your language's built-in number parsing functions. Your choice.

Should I use `import os.path` or `import os`?

Definitive answer: import os and use os.path. do not import os.path directly.

From the documentation of the module itself:

>>> import os
>>> help(os.path)
...
Instead of importing this module directly, import os and refer to
this module as os.path.  The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, and is an alias to another module (e.g. macpath, ntpath).
...

How to skip "are you sure Y/N" when deleting files in batch files

Use del /F /Q to force deletion of read-only files (/F) and directories and not ask to confirm (/Q) when deleting via wildcard.

ECONNREFUSED error when connecting to mongodb from node.js

you can go to mongoDB compass client and follow these steps: 1.Click Fill in connection fields individually: enter image description here

2.In hostname type : 127.0.0.1 enter image description here

3. Click CONNECT.

Eclipse error ... cannot be resolved to a type

  1. Right click your project name.

  2. Click Properties.

  3. Click Java Build Path.

  4. Click on Add Class Folder.

  5. Then choose your class.

Alternatively, Add Jars should work although you claim that you attempted that.

Also, "have you tried turning it off and back on again"? (Restart Eclipse).

How to merge rows in a column into one cell in excel?

For those who have Excel 2016 (and I suppose next versions), there is now directly the CONCAT function, which will replace the CONCATENATE function.

So the correct way to do it in Excel 2016 is :

=CONCAT(A1:A4)

which will produce :

Iamaboy

For users of olders versions of Excel, the other answers are relevant.

sass :first-child not working

While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.

As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:

div#top-level
  declarations: ...
  div.inside
    declarations: ...
    &:first-child
      declarations: ...

which compiles as one would expect:

div#top-level{
  declarations... }
div#top-level div.inside {
  declarations... }
div#top-level div.inside:first-child {
  declarations... }

I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything.

How do I pass command-line arguments to a WinForms application?

Consider you need to develop a program through which you need to pass two arguments. First of all, you need to open Program.cs class and add arguments in the Main method as like below and pass these arguments to the constructor of the Windows form.

static class Program
{    
   [STAThread]
   static void Main(string[] args)
   {            
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       Application.Run(new Form1(args[0], Convert.ToInt32(args[1])));           
   }
}

In windows form class, add a parameterized constructor which accepts the input values from Program class as like below.

public Form1(string s, int i)
{
    if (s != null && i > 0)
       MessageBox.Show(s + " " + i);
}

To test this, you can open command prompt and go to the location where this exe is placed. Give the file name then parmeter1 parameter2. For example, see below

C:\MyApplication>Yourexename p10 5

From the C# code above, it will prompt a Messagebox with value p10 5.

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

Java: How to convert List to Map

Here's a little method I wrote for exactly this purpose. It uses Validate from Apache Commons.

Feel free to use it.

/**
 * Converts a <code>List</code> to a map. One of the methods of the list is called to retrive
 * the value of the key to be used and the object itself from the list entry is used as the
 * objct. An empty <code>Map</code> is returned upon null input.
 * Reflection is used to retrieve the key from the object instance and method name passed in.
 *
 * @param <K> The type of the key to be used in the map
 * @param <V> The type of value to be used in the map and the type of the elements in the
 *            collection
 * @param coll The collection to be converted.
 * @param keyType The class of key
 * @param valueType The class of the value
 * @param keyMethodName The method name to call on each instance in the collection to retrieve
 *            the key
 * @return A map of key to value instances
 * @throws IllegalArgumentException if any of the other paremeters are invalid.
 */
public static <K, V> Map<K, V> asMap(final java.util.Collection<V> coll,
        final Class<K> keyType,
        final Class<V> valueType,
        final String keyMethodName) {

    final HashMap<K, V> map = new HashMap<K, V>();
    Method method = null;

    if (isEmpty(coll)) return map;
    notNull(keyType, Messages.getString(KEY_TYPE_NOT_NULL));
    notNull(valueType, Messages.getString(VALUE_TYPE_NOT_NULL));
    notEmpty(keyMethodName, Messages.getString(KEY_METHOD_NAME_NOT_NULL));

    try {
        // return the Method to invoke to get the key for the map
        method = valueType.getMethod(keyMethodName);
    }
    catch (final NoSuchMethodException e) {
        final String message =
            String.format(
                    Messages.getString(METHOD_NOT_FOUND),
                    keyMethodName,
                    valueType);
        e.fillInStackTrace();
        logger.error(message, e);
        throw new IllegalArgumentException(message, e);
    }
    try {
        for (final V value : coll) {

            Object object;
            object = method.invoke(value);
            @SuppressWarnings("unchecked")
            final K key = (K) object;
            map.put(key, value);
        }
    }
    catch (final Exception e) {
        final String message =
            String.format(
                    Messages.getString(METHOD_CALL_FAILED),
                    method,
                    valueType);
        e.fillInStackTrace();
        logger.error(message, e);
        throw new IllegalArgumentException(message, e);
    }
    return map;
}

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

MySQL SELECT only not null values

You can filter out rows that contain a NULL value in a specific column:

SELECT col1, col2, ..., coln
FROM yourtable
WHERE somecolumn IS NOT NULL

If you want to filter out rows that contain a null in any column then try this:

SELECT col1, col2, ..., coln
FROM yourtable
WHERE col1 IS NOT NULL
AND col2 IS NOT NULL
-- ...
AND coln IS NOT NULL

Update: Based on your comments, perhaps you want this?

SELECT * FROM
(
    SELECT col1 AS col FROM yourtable
    UNION
    SELECT col2 AS col FROM yourtable
    UNION
    -- ...
    UNION
    SELECT coln AS col FROM yourtable
) T1
WHERE col IS NOT NULL

And I agre with Martin that if you need to do this then you should probably change your database design.

C#: Dynamic runtime cast

You can use the expression pipeline to achieve this:

 public static Func<object, object> Caster(Type type)
 {
    var inputObject = Expression.Parameter(typeof(object));
    return Expression.Lambda<Func<object,object>>(Expression.Convert(inputObject, type), inputPara).Compile();
 }

which you can invoke like:

object objAsDesiredType = Caster(desiredType)(obj);

Drawbacks: The compilation of this lambda is slower than nearly all other methods mentioned already

Advantages: You can cache the lambda, then this should be actually the fastest method, it is identical to handwritten code at compile time

Spring Boot yaml configuration for a list of strings

In my case this was a syntax issue in the .yml file. I had:

@Value("${spring.kafka.bootstrap-servers}")
public List<String> BOOTSTRAP_SERVERS_LIST;

and the list in my .yml file:

bootstrap-servers:
  - s1.company.com:9092
  - s2.company.com:9092
  - s3.company.com:9092

was not reading into the @Value-annotated field. When I changed the syntax in the .yml file to:

bootstrap-servers >
  s1.company.com:9092
  s2.company.com:9092
  s3.company.com:9092

it worked fine.

C# get and set properties for a List Collection

It would be inappropriate for it to be part of the setter - it's not like you're really setting the whole list of strings - you're just trying to add one.

There are a few options:

  • Put AddSubheading and AddContent methods in your class, and only expose read-only versions of the lists
  • Expose the mutable lists just with getters, and let callers add to them
  • Give up all hope of encapsulation, and just make them read/write properties

In the second case, your code can be just:

public class Section
{
    public String Head { get; set; }
    private readonly List<string> _subHead = new List<string>();
    private readonly List<string> _content = new List<string>();

    // Note: fix to case to conform with .NET naming conventions
    public IList<string> SubHead { get { return _subHead; } }
    public IList<string> Content { get { return _content; } }
}

This is reasonably pragmatic code, although it does mean that callers can mutate your collections any way they want, which might not be ideal. The first approach keeps the most control (only your code ever sees the mutable list) but may not be as convenient for callers.

Making the setter of a collection type actually just add a single element to an existing collection is neither feasible nor would it be pleasant, so I'd advise you to just give up on that idea.

Initializing a static std::map<int, int> in C++

If you are stuck with C++98 and don't want to use boost, here there is the solution I use when I need to initialize a static map:

typedef std::pair< int, char > elemPair_t;
elemPair_t elemPairs[] = 
{
    elemPair_t( 1, 'a'), 
    elemPair_t( 3, 'b' ), 
    elemPair_t( 5, 'c' ), 
    elemPair_t( 7, 'd' )
};

const std::map< int, char > myMap( &elemPairs[ 0 ], &elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );

How to bind Dataset to DataGridView in windows application

use like this :-

gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();

I hope it helps!!

How to find the size of a table in SQL?

SQL Server provides a built-in stored procedure that you can run to easily show the size of a table, including the size of the indexes… which might surprise you.

Syntax:

 sp_spaceused 'Tablename'

see in :

http://www.howtogeek.com/howto/database/determine-size-of-a-table-in-sql-server/

"Invalid form control" only in Google Chrome

replace required by required="required"

Set angular scope variable in markup

Create a directive called myVar with

scope : { myVar: '@' }

and call it like this:

<div name="my_map" my-var="Richmond,VA">

Note in particular the camel case reference in the directive to the hyphenated tag name.

For more information see "Understanding Transclusion and Scopes" here:- http://docs.angularjs.org/guide/directive

Here's a Fiddle that shows how you can copy values from attributes to scope variables in various different ways within a directive.

How to get back to most recent version in Git?

With Git 2.23+ (August 2019), the best practice would be to use git switch instead of the confusing git checkout command.

To create a new branch based on an older version:

git switch -c temp_branch HEAD~2

To go back to the current master branch:

git switch master

What is the difference between require() and library()?

?library

and you will see:

library(package) and require(package) both load the package with name package and put it on the search list. require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist. Both functions check and update the list of currently loaded packages and do not reload a package which is already loaded. (If you want to reload such a package, call detach(unload = TRUE) or unloadNamespace first.) If you want to load a package without putting it on the search list, use requireNamespace.

Convert char to int in C#

Has anyone considered using int.Parse() and int.TryParse() like this

int bar = int.Parse(foo.ToString());

Even better like this

int bar;
if (!int.TryParse(foo.ToString(), out bar))
{
    //Do something to correct the problem
}

It's a lot safer and less error prone

Sort array of objects by string property value

I haven't seen this particular approach suggested, so here's a terse comparison method I like to use that works for both string and number types:

_x000D_
_x000D_
const objs = [ 
  { first_nom: 'Lazslo', last_nom: 'Jamf'     },
  { first_nom: 'Pig',    last_nom: 'Bodine'   },
  { first_nom: 'Pirate', last_nom: 'Prentice' }
];

const sortBy = fn => {
  const cmp = (a, b) => -(a < b) || +(a > b);
  return (a, b) => cmp(fn(a), fn(b));
};

const getLastName = o => o.last_nom;
const sortByLastName = sortBy(getLastName);

objs.sort(sortByLastName);
console.log(objs.map(getLastName));
_x000D_
_x000D_
_x000D_

Explanation of sortBy()

sortBy() accepts a fn that selects a value from an object to use in comparison, and returns a function that can be passed to Array.prototype.sort(). In this example, we're comparing o.last_nom. Whenever we receive two objects such as

a = { first_nom: 'Lazslo', last_nom: 'Jamf' }
b = { first_nom: 'Pig', last_nom: 'Bodine' }

we compare them with (a, b) => cmp(fn(a), fn(b)). Given that

fn = o => o.last_nom

we can expand the comparison function to (a, b) => cmp(a.last_nom, b.last_nom). Because of the way logical OR (||) works in JavaScript, cmp(a.last_nom, b.last_nom) is equivalent to

if (a.last_nom < b.last_nom) return -1;
if (a.last_nom > b.last_nom) return 1;
return 0;

Incidentally, this is called the three-way comparison "spaceship" (<=>) operator in other languages.

Finally, here's the ES5-compatible syntax without using arrow functions:

_x000D_
_x000D_
var objs = [ 
  { first_nom: 'Lazslo', last_nom: 'Jamf'     },
  { first_nom: 'Pig',    last_nom: 'Bodine'   },
  { first_nom: 'Pirate', last_nom: 'Prentice' }
];

function sortBy(fn) {
  function cmp(a, b) { return -(a < b) || +(a > b); }
  return function (a, b) { return cmp(fn(a), fn(b)); };
}

function getLastName(o) { return o.last_nom; }
var sortByLastName = sortBy(getLastName);

objs.sort(sortByLastName);
console.log(objs.map(getLastName));
_x000D_
_x000D_
_x000D_

Count the items from a IEnumerable<T> without iterating?

I used such way inside a method to check the passed in IEnumberable content

if( iEnum.Cast<Object>().Count() > 0) 
{

}

Inside a method like this:

GetDataTable(IEnumberable iEnum)
{  
    if (iEnum != null && iEnum.Cast<Object>().Count() > 0) //--- proceed further

}

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

Add element to a JSON file?

One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:

test_json = { "a": 1, "b": 2}

Once you do this, adding a json element only involves the following line:

test_json["c"] = 3

This will result in:

{'a': 1, 'b': 2, 'c': 3}

Afterwards, you can add that json back into an array or a list of that is desired.

Could not autowire field:RestTemplate in Spring boot application

Please make sure two things:

1- Use @Bean annotation with the method.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}

2- Scope of this method should be public not private.

Complete Example -

@Service
public class MakeHttpsCallImpl implements MakeHttpsCall {

@Autowired
private RestTemplate restTemplate;

@Override
public String makeHttpsCall() {
    return restTemplate.getForObject("https://localhost:8085/onewayssl/v1/test",String.class);
}

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}
}

Does a `+` in a URL scheme/host/path represent a space?

You can find a nice list of corresponding URL encoded characters on W3Schools.

  • + becomes %2B
  • space becomes %20

Label on the left side instead above an input field

I think this is what you want, from the bootstrap documentation "Horizontal form Use Bootstrap's predefined grid classes to align labels and groups of form controls in a horizontal layout by adding .form-horizontal to the form. Doing so changes .form-groups to behave as grid rows, so no need for .row". So:

<form class="form-horizontal" role="form">
<div class="form-group">
  <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
  <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group">
  <label for="inputPassword3" class="col-sm-2 control-label">Password</label>
  <div class="col-sm-10">
    <input type="password" class="form-control" id="inputPassword3" placeholder="Password">
  </div>
</div>
<div class="form-group">
  <div class="col-sm-offset-2 col-sm-10">
    <div class="checkbox">
      <label>
        <input type="checkbox"> Remember me
      </label>
    </div>
  </div>
</div>
<div class="form-group">
  <div class="col-sm-offset-2 col-sm-10">
    <button type="submit" class="btn btn-default">Sign in</button>
  </div>
</div>
</form>

Fiddle: http://jsfiddle.net/beewayne/B9jj2/29/

What are the parameters for the number Pipe - Angular 2

From the DOCS

Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.

SYNTAX:

number_expression | number[:digitInfo[:locale]]

where expression is a number:

digitInfo is a string which has a following format:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
  • minIntegerDigits is the minimum number of integer digits to use.Defaults to 1
  • minFractionDigits is the minimum number of digits
  • after fraction. Defaults to 0. maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.
  • locale is a string defining the locale to use (uses the current LOCALE_ID by default)

DEMO

How to increment datetime by custom months in python without using library

def month_sub(year, month, sub_month):
    result_month = 0
    result_year = 0
    if month > (sub_month % 12):
        result_month = month - (sub_month % 12)
        result_year = year - (sub_month / 12)
    else:
        result_month = 12 - (sub_month % 12) + month
        result_year = year - (sub_month / 12 + 1)
    return (result_year, result_month)

def month_add(year, month, add_month):
    return month_sub(year, month, -add_month)

>>> month_add(2015, 7, 1)                        
(2015, 8)
>>> month_add(2015, 7, 20)
(2017, 3)
>>> month_add(2015, 7, 12)
(2016, 7)
>>> month_add(2015, 7, 24)
(2017, 7)
>>> month_add(2015, 7, -2)
(2015, 5)
>>> month_add(2015, 7, -12)
(2014, 7)
>>> month_add(2015, 7, -13)
(2014, 6)

AttributeError: 'module' object has no attribute 'urlopen'

your code used in python2.x, you can use like this:

from urllib.request import urlopen
urlopen(url)

by the way, suggest another module called requests is more friendly to use, you can use pip install it, and use like this:

import requests
requests.get(url)
requests.post(url)

I thought it is easily to use, i am beginner too....hahah

How do I add a library path in cmake?

The simplest way of doing this would be to add

include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)

add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib

The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
  IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
  INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)

set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path

If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

What is the difference between concurrent programming and parallel programming?

Concurrency and Parallelism Source

In a multithreaded process on a single processor, the processor can switch execution resources between threads, resulting in concurrent execution.

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run on a separate processor at the same time, resulting in parallel execution.

When the process has fewer or as many threads as there are processors, the threads support system in conjunction with the operating environment ensure that each thread runs on a different processor.

For example, in a matrix multiplication that has the same number of threads and processors, each thread (and each processor) computes a row of the result.

Which UUID version to use?

There are two different ways of generating a UUID.

If you just need a unique ID, you want a version 1 or version 4.

  • Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.

  • Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.

If you need to always generate the same UUID from a given name, you want a version 3 or version 5.

  • Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.

  • Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.

Compile to a stand-alone executable (.exe) in Visual Studio

I've never had problems with deploying small console application made in C# as-is. The only problem you can bump into would be a dependency on the .NET framework, but even that shouldn't be a major problem. You could try using version 2.0 of the framework, which should already be on most PCs.

Using native, unmanaged C++, you should not have any dependencies on the .NET framework, so you really should be safe. Just grab the executable and any accompanying files (if there are any) and deploy them as they are; there's no need to install them if you don't want to.

Controlling fps with requestAnimationFrame?

The simplest way


const FPS = 30;
let lastTimestamp = 0;


function update(timestamp) {
  requestAnimationFrame(update);
  if (timestamp - lastTimestamp < 1000 / FPS) return;
  
  
   /* <<< PUT YOUR CODE HERE >>>  */

 
  lastTimestamp = timestamp;
}


update();

Printing list elements on separated lines in Python

Use the splat operator(*)

By default, * operator prints list separated by space. Use sep operator to specify the delimiter

print(*sys.path, sep = "\n")

How to install sklearn?

I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.

https://www.continuum.io

Multiline for WPF TextBox

Contrary to @Andre Luus, setting Height="Auto" will not make the TextBox stretch. The solution I found was to set VerticalAlignment="Stretch"

Jquery submit form

You can try like:

   $("#myformid").submit(function(){
        //perform anythng
   });

Or even you can try like

$(".nextbutton").click(function() { 
    $('#form1').submit();
});

C pass int array pointer as parameter into a function

Maybe you were trying to do this?

#include <stdio.h>

int func(int * B){

    /* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */
    *(B + 2) = 5;
}

int main(void) {

    int B[10];

    func(B);

    /* Let's say you edited only 2 and you want to show it. */
    printf("b[0] = %d\n\n", B[2]);

    return 0;
}

How to concatenate two numbers in javascript?

You can also use toString function to convert it to string and concatenate.

var a = 5;
var b = 6;
var value = a.toString() + b.toString();

How to Generate unique file names in C#

How about using Guid.NewGuid() to create a GUID and use that as the filename (or part of the filename together with your time stamp if you like).

psql: FATAL: database "<user>" does not exist

  1. Login as default user: sudo -i -u postgres
  2. Create new User: createuser --interactive
  3. When prompted for role name, enter linux username, and select Yes to superuser question.
  4. Still logged in as postgres user, create a database: createdb <username_from_step_3>
  5. Confirm error(s) are gone by entering: psql at the command prompt.
  6. Output should show psql (x.x.x) Type "help" for help.

How to paste text to end of every line? Sublime 2

You can use the Search & Replace feature with this regex ^([\w\d\_\.\s\-]*)$ to find text and the replaced text is "$1".

UIImageView - How to get the file name of the image assigned?

Neither UIImageView not UIImage holds on to the filename of the image loaded.

You can either

1: (as suggested by Kenny Winker above) subclass UIImageView to have a fileName property or

2: name the image files with numbers (image1.jpg, image2.jpg etc) and tag those images with the corresponding number (tag=1 for image1.jpg, tag=2 for image2.jpg etc) or

3: Have a class level variable (eg. NSString *currentFileName) which updates whenever you update the UIImageView's image

Stratified Train/Test-split in scikit-learn

[update for 0.17]

See the docs of sklearn.model_selection.train_test_split:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    stratify=y, 
                                                    test_size=0.25)

[/update for 0.17]

There is a pull request here. But you can simply do train, test = next(iter(StratifiedKFold(...))) and use the train and test indices if you want.

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

Cannot connect to MySQL 4.1+ using old authentication

On OSX, I used MacPorts to address the same problem when connecting to my siteground database. Siteground appears to be using 5.0.77mm0.1-log, but creating a new user account didn't fix the problem. This is what did

sudo port install php5-mysql -mysqlnd +mysql5

This downgrades the mysql driver that php will use.

How to print a specific row of a pandas DataFrame?

Sounds like you're calling df.plot(). That error indicates that you're trying to plot a frame that has no numeric data. The data types shouldn't affect what you print().

Use print(df.iloc[159220])

Twitter Bootstrap Button Text Word Wrap

You can add these style's and it works just as expected.

.btn {
    white-space:normal !important; 
    word-wrap: break-word; 
    word-break: normal;
}

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

How to use Python to login to a webpage and retrieve cookies for later usage?

Here's a version using the excellent requests library:

from requests import session

payload = {
    'action': 'login',
    'username': USERNAME,
    'password': PASSWORD
}

with session() as c:
    c.post('http://example.com/login.php', data=payload)
    response = c.get('http://example.com/protected_page.php')
    print(response.headers)
    print(response.text)

Difference between == and ===

In swift 3 and above

=== (or !==)

  • Checks if the values are identical (both point to the same memory address).
  • Comparing reference types.
  • Like == in Obj-C (pointer equality).

== (or !=)

  • Checks if the values are the same.
  • Comparing value types.
  • Like the default isEqual: in Obj-C behavior.

Here I compare three instances (class is a reference type)

class Person {}

let person = Person()
let person2 = person
let person3 = Person()

person === person2 // true
person === person3 // false

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

pass post data with window.location.href

You can use GET instead of pass, but don't use this method for important values,

function passIDto(IDval){    
window.location.href = "CustomerBasket.php?oridd=" +  IDval ;
}   

In the CustomerBasket.php

<?php
  $value = $_GET["oridd"];
  echo  $value;
?>

Copy text from nano editor to shell

Simply use Ctrl+Shift+6 to copy current line or you can set mark using Ctrl+6 and copy multiple lines using above command as well.

How to terminate a window in tmux?

ctrl + d kills a window in linux terminal, also works in tmux.

This is kind of a approach.

Jenkins Pipeline Wipe Out Workspace

Like @gotgenes pointed out with Jenkins Version. 2.74, the below works, not sure since when, maybe if some one can edit and add the version above

cleanWs()

With, Jenkins Version 2.16 and the Workspace Cleanup Plugin, that I have, I use

step([$class: 'WsCleanup'])

to delete the workspace.

You can view it by going to

JENKINS_URL/job/<any Pipeline project>/pipeline-syntax

Then selecting "step: General Build Step" from Sample step and then selecting "Delete workspace when build is done" from Build step

List of IP Space used by Facebook

The list from 2020-05-23 is:

31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22

The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:

whois -h whois.radb.net -- '-i origin AS32934' | grep ^route

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

How do I use a regular expression to match any string, but at least 3 characters?

You could try with simple 3 dots. refer to the code in perl below

$a =~ m /.../ #where $a is your string

Match exact string

Use the start and end delimiters: ^abc$

Table Naming Dilemma: Singular vs. Plural Names

I also would go with plurals, and with the aforementioned Users dilemma, we do take the square bracketing approach.

We do this to provide uniformity between both database architecture and application architecture, with the underlying understanding that the Users table is a collection of User values as much as a Users collection in a code artifact is a collection of User objects.

Having our data team and our developers speaking the same conceptual language (although not always the same object names) makes it easier to convey ideas between them.

Understanding Fragment's setRetainInstance(boolean)

SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.

Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html

How to remove jar file from local maven repository which was added with install:install-file?

While there is a maven command you can execute to do this, it's easier to just delete the files manually from the repository.

Like this on windows Documents and Settings\your username\.m2 or $HOME/.m2 on Linux

Regular Expression to match string starting with a specific word

Like @SharadHolani said. This won't match every word beginning with "stop"

. Only if it's at the beginning of a line like "stop going". @Waxo gave the right answer:

This one is slightly better, if you want to match any word beginning with "stop" and containing nothing but letters from A to Z.

\bstop[a-zA-Z]*\b

This would match all

stop (1)

stop random (2)

stopping (3)

want to stop (4)

please stop (5)

But

/^stop[a-zA-Z]*/

would only match (1) until (3), but not (4) & (5)

Setting onClickListener for the Drawable right of an EditText

You don't have access to the right image as far my knowledge, unless you override the onTouch event. I suggest to use a RelativeLayout, with one editText and one imageView, and set OnClickListener over the image view as below:

<RelativeLayout
        android:id="@+id/rlSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:drawable/edit_text"
        android:padding="5dip" >

        <EditText
            android:id="@+id/txtSearch"
            android:layout_width="match_parent"

            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@+id/imgSearch"
            android:background="#00000000"
            android:ems="10"/>

        <ImageView
            android:id="@+id/imgSearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@drawable/btnsearch" />
    </RelativeLayout>

Resizing SVG in html?

you can resize it by displaying svg in image tag and size image tag i.e.

<img width="200px" src="lion.svg"></img>

How do I change the owner of a SQL Server database?

To change database owner:

ALTER AUTHORIZATION ON DATABASE::YourDatabaseName TO sa

As of SQL Server 2014 you can still use sp_changedbowner as well, even though Microsoft promised to remove it in the "future" version after SQL Server 2012. They removed it from SQL Server 2014 BOL though.

Styling a disabled input with css only

Let's just say you have 3 buttons:

<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">

To style the disabled button you can use the following css:

input[type="button"]:disabled{
    color:#000;
}

This will only affect the button which is disabled.

To stop the color changing when hovering you can use this too:

input[type="button"]:disabled:hover{
    color:#000;
}

You can also avoid this by using a css-reset.

What is the copy-and-swap idiom?

Assignment, at its heart, is two steps: tearing down the object's old state and building its new state as a copy of some other object's state.

Basically, that's what the destructor and the copy constructor do, so the first idea would be to delegate the work to them. However, since destruction mustn't fail, while construction might, we actually want to do it the other way around: first perform the constructive part and, if that succeeded, then do the destructive part. The copy-and-swap idiom is a way to do just that: It first calls a class' copy constructor to create a temporary object, then swaps its data with the temporary's, and then lets the temporary's destructor destroy the old state.
Since swap() is supposed to never fail, the only part which might fail is the copy-construction. That is performed first, and if it fails, nothing will be changed in the targeted object.

In its refined form, copy-and-swap is implemented by having the copy performed by initializing the (non-reference) parameter of the assignment operator:

T& operator=(T tmp)
{
    this->swap(tmp);
    return *this;
}

PowerShell: Comparing dates

I wanted to show how powerful it can be aside from just checking "-lt".

Example: I used it to calculate time differences take from Windows event view Application log:

Get the difference between the two date times:

PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))

Object created:

PS> $Obj


Days              : 0
Hours             : 0
Minutes           : 31
Seconds           : 0
Milliseconds      : 0
Ticks             : 18600000000
TotalDays         : 0.0215277777777778
TotalHours        : 0.516666666666667
TotalMinutes      : 31
TotalSeconds      : 1860
TotalMilliseconds : 1860000

Access an item directly:

PS> $Obj.Minutes
31

What's causing my java.net.SocketException: Connection reset?

This error occurs on the server side when the client closed the socket connection before the response could be returned over the socket. In a web app scenario not all of these are dangerous, since they can be created manually. For example, by quitting the browser before the reponse was retrieved.

Disable EditText blinking cursor

If you want to ignore the Edittext from the starting of activity, android:focusable and android:focusableInTouchMode will help you inshallah.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout7" android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:focusable="true" android:focusableInTouchMode="true">

This LinearLayout with your Edittext.

New og:image size for Facebook share?

The aspect ratio for a Facebook post image is 41:20.

To find the appropriate widths and height for your photo, you can use the Aspect Ratio Calculator.

Here you can select different ratios under “Common ratios:” which includes the option “1200 x 630 (Facebook)". So if the width of your photo is 1800, plug that number into the “W2” slot and it will tell you what the respective height should be.

Razor-based view doesn't see referenced assemblies

None of the above worked for me either;

  • Dlls were set to Copy Local
  • Adding namespaces to both web.configs did nothing
  • Adding assembly references to system.web\compilation\assemblies also did not help (although I have not removed these references, so it may be that they are needed too)

But I finally found something that worked for me:

It was because I had my Build Output going to bin\Debug\ for Debug configuration and bin\Release\ for Release configuations. As soon as I changed the Build Configuation to "bin\" for All configuations (as per image below) then everything started working as it should!!!

Build Configuration

I have no idea why separating out your builds into Release and Debug folders should cause Razor syntax to break, but it seems to be because something couldn't find the assemblies. For me the projects that were having the razor syntax issues are actually my 'razor library' projects. They are set as Application Projects however I use them as class libraries with RazorGenerator to compile my views. When I actually tried to run one of these projects directly it caused the following Configuration error:

Could not load file or assembly 'System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

This lead me to trying to change the Build Output, as I notice that for all web projects the Build Output seems to always be directly to the bin folder, unlike the default for class libraries, which have both release and debug folders.

sqlalchemy filter multiple columns

A generic piece of code that will work for multiple columns. This can also be used if there is a need to conditionally implement search functionality in the application.

search_key = "abc"
search_args = [col.ilike('%%%s%%' % search_key) for col in ['col1', 'col2', 'col3']]
query = Query(table).filter(or_(*search_args))
session.execute(query).fetchall()

Note: the %% are important to skip % formatting the query.

Correct format specifier for double in printf

%Lf (note the capital L) is the format specifier for long doubles.

For plain doubles, either %e, %E, %f, %g or %G will do.

Pandas read_csv from url

In the latest version of pandas (0.19.2) you can directly pass the url

import pandas as pd

url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
c=pd.read_csv(url)

What MIME type should I use for CSV?

My users are allowed to upload CSV files and text/csv and application/csv did not appear by now. These are the ones identified through finfo():

text/plain
text/x-csv

And these are the ones transmitted through the browser:

text/plain
application/vnd.ms-excel
text/x-csv

The following types did not appear, but could:

application/csv
application/x-csv
text/csv
text/comma-separated-values
text/x-comma-separated-values
text/tab-separated-values

HTML text-overflow ellipsis detection

I think the better way to detect it is use getClientRects(), it seems each rect has the same height, so we can caculate lines number with the number of different top value.

getClientRects work like this

function getRowRects(element) {
    var rects = [],
        clientRects = element.getClientRects(),
        len = clientRects.length,
        clientRect, top, rectsLen, rect, i;

    for(i=0; i<len; i++) {
        has = false;
        rectsLen = rects.length;
        clientRect = clientRects[i];
        top = clientRect.top;
        while(rectsLen--) {
            rect = rects[rectsLen];
            if (rect.top == top) {
                has = true;
                break;
            }
        }
        if(has) {
            rect.right = rect.right > clientRect.right ? rect.right : clientRect.right;
            rect.width = rect.right - rect.left;
        }
        else {
            rects.push({
                top: clientRect.top,
                right: clientRect.right,
                bottom: clientRect.bottom,
                left: clientRect.left,
                width: clientRect.width,
                height: clientRect.height
            });
        }
    }
    return rects;
}

getRowRects work like this

you can detect like this

env: node: No such file or directory in mac

I re-installed node through this link and it fixed it.

I think the issue was that I somehow got node to be in my /usr/bin instead of /usr/local/bin.

What is the difference between include and require in Ruby?

If you're using a module, that means you're bringing all the methods into your class. If you extend a class with a module, that means you're "bringing in" the module's methods as class methods. If you include a class with a module, that means you're "bringing in" the module's methods as instance methods.

EX:

 module A
   def say
     puts "this is module A"
   end
 end

 class B
   include A
 end

 class C
   extend A
 end

B.say => undefined method 'say' for B:Class

B.new.say => this is module A

C.say => this is module A

C.new.say => undefined method 'say' for C:Class

How to convert current date into string in java?

Most of the answers are/were valid. The new JAVA API modification for Date handling made sure that some earlier ambiguity in java date handling is reduced.

You will get a deprecated message for similar calls.

new Date() // deprecated

The above call had the developer to assume that a new Date object will give the Date object with current timestamp. This behavior is not consistent across other Java API classes.

The new way of doing this is using the Calendar Instance.

new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()

Here too the naming convention is not perfect but this is much organised. For a person like me who has a hard time mugging up things but would never forget something if it sounds/appears logical, this is a good approach.

This is more synonymous to real life

  1. We get a Calendar object and we look for the time in it. ( you must be wondering no body gets time from a Calendar, that is why I said it is not perfect.But that is a different topic altogether)
  2. Then we want the date in a simple Text format so we use a SimpleDateFormat utility class which helps us in formatting the Date from Step 1. I have used yyyy, MM ,dd as parameters in the format. Supported date format parameters

One more way to do this is using Joda time API

new DateTime().toString("yyyy-MM-dd")

or the much obvious

new DateTime(Calendar.getInstance().getTime()).toString("yyyy-MM-dd")

both will return the same result.

Maximum and minimum values in a textbox

Yes it can! You might consider first to set the value of maxlength to 3 and then write an event handler for the keyup-event.

The function can evaluate the user input using regex or parseInt to validate the user input and set it to any desired value, if the input is incorrect.

How to calculate probability in a normal distribution given mean & standard deviation?

You can just use the error function that's built in to the math library, as stated on their website.

PowerShell script to return versions of .NET Framework on a machine?

[environment]::Version

Gives you an instance of Version for the CLR the current copy of PSH is using (as documented here).

How to split a single column values to multiple column values?

Here is how I did this on a SQLite database:

SELECT SUBSTR(name, 1,INSTR(name, " ")-1) as Firstname,
SUBSTR(name, INSTR(name," ")+1, LENGTH(name)) as Lastname
FROM YourTable;

Hope it helps.

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

CSS table-cell equal width

this will work for everyone

_x000D_
_x000D_
<table border="your val" cellspacing="your val" cellpadding="your val" role="grid" style="width=100%; table-layout=fixed">_x000D_
<!-- set the table td element roll attr to gridcell -->_x000D_
<tr>_x000D_
<td roll="gridcell"></td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This will also work for table data created by iteration

How to create an Excel File with Nodejs?

You should check ExcelJS

Works with CSV and XLSX formats.

Great for reading/writing XLSX streams. I've used it to stream an XLSX download to an Express response object, basically like this:

app.get('/some/route', function(req, res) {
  res.writeHead(200, {
    'Content-Disposition': 'attachment; filename="file.xlsx"',
    'Transfer-Encoding': 'chunked',
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  var workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: res })
  var worksheet = workbook.addWorksheet('some-worksheet')
  worksheet.addRow(['foo', 'bar']).commit()
  worksheet.commit()
  workbook.commit()
}

Works great for large files, performs much better than excel4node (got huge memory usage & Node process "out of memory" crash after nearly 5 minutes for a file containing 4 million cells in 20 sheets) since its streaming capabilities are much more limited (does not allows to "commit()" data to retrieve chunks as soon as they can be generated)

See also this SO answer.

Django set field value after a form is initialized

If you've already initialized the form, you can use the initial property of the field. For example,

form = CustomForm()
form.fields["Email"].initial = GetEmailString()

Spring Resttemplate exception handling

You should catch a HttpStatusCodeException exception:

try {
    restTemplate.exchange(...);
} catch (HttpStatusCodeException exception) {
    int statusCode = exception.getStatusCode().value();
    ...
}

How do I install Python packages in Google's Colab?

Joining the party late, but just as a complement, I ran into some problems with Seaborn not so long ago, because CoLab installed a version with !pip that wasn't updated. In my specific case, I couldn't use Scatterplot, for example. The answer to this is below:

To install the module, all you need is:

!pip install seaborn

To upgrade it to the most updated version:

!pip install --upgrade seaborn

If you want to install a specific version

!pip install seaborn==0.9.0

I believe all the rules common to pip apply normally, so that pretty much should work.

asp.net validation to make sure textbox has integer values

If all that you are concerned about is that the field contains an integer (i.e., not concerned with a range), then add a CompareValidator with it's Operator property set to DataTypeCheck:

<asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer" 
 ControlToValidate="ValueTextBox" ErrorMessage="Value must be a whole number" />

If there is a specific range of values that are valid (there probably are), then you can use a RangeValidator, like so:

<asp:RangeValidator runat="server" Type="Integer" 
MinimumValue="0" MaximumValue="400" ControlToValidate="ValueTextBox" 
ErrorMessage="Value must be a whole number between 0 and 400" />

These will only validate if there is text in the TextBox, so you will need to keep the RequiredFieldValidator there, too.

As @Mahin said, make sure you check the Page.IsValid property on the server side, otherwise the validator only works for users with JavaScript enabled.

SimpleXML - I/O warning : failed to load external entity

this also works:

$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);

then I just run a forloop to grab the stuff from the nodes.

like this:`

for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;

***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.

Two's Complement in Python

Since erikb85 brought up performance, here's travc's answer against Scott Griffiths':

In [534]: a = [0b111111111111, 0b100000000000, 0b1, 0] * 1000
In [535]: %timeit [twos_comp(x, 12) for x in a]
100 loops, best of 3: 8.8 ms per loop
In [536]: %timeit [bitstring.Bits(uint=x, length=12).int for x in a]
10 loops, best of 3: 55.9 ms per loop

So, bitstring is, as found in the other question, almost an order of magnitude slower than int. But on the other hand, it's hard to beat the simplicity—I'm converting a uint to a bit-string then to an int; you'd have to work hard not to understand this, or to find anywhere to introduce a bug. And as Scott Griffiths' answer implies, there's a lot more flexibility to the class which might be useful to the same app. But on the third hand, travc's answer makes it clear what's actually happening—even a novice should be able to understand what conversion from an unsigned int to a 2s complement signed int means just from reading 2 lines of code.

Anyway, unlike the other question, which was about directly manipulating bits, this one is all about doing arithmetic on fixed-length ints, just oddly-sized ones. So I'm guessing if you need performance, it's probably because you have a whole bunch of these things, so you probably want it to be vectorized. Adapting travc's answer to numpy:

def twos_comp_np(vals, bits):
    """compute the 2's compliment of array of int values vals"""
    vals[vals & (1<<(bits-1)) != 0] -= (1<<bits)
    return vals

Now:

In [543]: a = np.array(a)
In [544]: %timeit twos_comp_np(a.copy(), 12)
10000 loops, best of 3: 63.5 µs per loop

You could probably beat that with custom C code, but you probably don't have to.

Updating the value of data attribute using jQuery

$('.toggle img').each(function(index) { 
    if($(this).attr('data-id') == '4')
    {
        $(this).attr('data-block', 'something');
        $(this).attr('src', 'something.jpg');
    }
});

or

$('.toggle img[data-id="4"]').attr('data-block', 'something');
$('.toggle img[data-id="4"]').attr('src', 'something.jpg');

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you have a new database and you make a fresh clean import, the problem may come from inserting data that contains a '0' incrementation and this would transform to '1' with AUTO_INCREMENT and cause this error.

My solution was to use in the sql import file.

SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';

How to detect a remote side socket close?

The isConnected method won't help, it will return true even if the remote side has closed the socket. Try this:

public class MyServer {
    public static final int PORT = 12345;
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
        Socket s = ss.accept();
        Thread.sleep(5000);
        ss.close();
        s.close();
    }
}

public class MyClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
        System.out.println(" connected: " + s.isConnected());
        Thread.sleep(10000);
        System.out.println(" connected: " + s.isConnected());
    }
}

Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.

The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException (broken pipe) will be thrown) on the associated Input/OutputStreams.

Remove trailing newline from the elements of a string list

You can use lists comprehensions:

strip_list = [item.strip() for item in lines]

Or the map function:

# with a lambda
strip_list = map(lambda it: it.strip(), lines)

# without a lambda
strip_list = map(str.strip, lines)

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Answer : I found this and wants to share it with you.

Sub Copier4()
   Dim x As Integer

   For x = 1 To ActiveWorkbook.Sheets.Count
      'Loop through each of the sheets in the workbook
      'by using x as the sheet index number.
      ActiveWorkbook.Sheets(x).Copy _
         After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
         'Puts all copies after the last existing sheet.
   Next
End Sub

But the question, can we use it with following code to rename the sheets, if yes, how can we do so?

Sub CreateSheetsFromAList()
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Summary").Range("A10")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
Next MyCell
End Sub

Guid.NewGuid() vs. new Guid()

[I understand this is an old thread, just adding some more detail] The two answers by Mark and Jon Hanna sum up the differences, albeit it may interest some that

Guid.NewGuid()

Eventually calls CoCreateGuid (a COM call to Ole32) (reference here) and the actual work is done by UuidCreate.

Guid.Empty is meant to be used to check if a Guid contains all zeroes. This could also be done via comparing the value of the Guid in question with new Guid()

So, if you need a unique identifier, the answer is Guid.NewGuid()

Environment variables for java installation

Keep in mind that the %CLASSPATH% environment variable is ignored when you use java/javac in combination with one of the -cp, -classpath or -jar arguments. It is also ignored in an IDE like Netbeans/Eclipse/IntelliJ/etc. It is only been used when you use java/javac without any of the above mentioned arguments.

In case of JAR files, the classpath is to be defined as class-path entry in the manifest.mf file. It can be defined semicolon separated and relative to the JAR file's root.

In case of an IDE, you have the so-called 'build path' which is basically the classpath which is used at both compiletime and runtime. To add external libraries you usually drop the JAR file in a (either precreated by IDE or custom created) lib folder of the project which is added to the project's build path.

How can I use SUM() OVER()

Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID.

To obtain running totals with SUM() OVER (), you need to add an ORDER BY sub-clause after PARTITION BY …, like this:

SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)

But remember, not all database systems support ORDER BY in the OVER clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)

Is there a jQuery unfocus method?

So you can do this

$('#textarea').attr('enable',false)

try it and give feedback

LDAP Authentication using Java

You will have to provide the entire user dn in SECURITY_PRINCIPAL

like this

env.put(Context.SECURITY_PRINCIPAL, "cn=username,ou=testOu,o=test"); 

merge two object arrays with Angular 2 and TypeScript?

Assume i have two arrays. The first one has student details and the student marks details. Both arrays have the common key, that is ‘studentId’

let studentDetails = [
  { studentId: 1, studentName: 'Sathish', gender: 'Male', age: 15 },
  { studentId: 2, studentName: 'kumar', gender: 'Male', age: 16 },
  { studentId: 3, studentName: 'Roja', gender: 'Female', age: 15 },
  {studentId: 4, studentName: 'Nayanthara', gender: 'Female', age: 16},
];

let studentMark = [
  { studentId: 1, mark1: 80, mark2: 90, mark3: 100 },
  { studentId: 2, mark1: 80, mark2: 90, mark3: 100 },
  { studentId: 3, mark1: 80, mark2: 90, mark3: 100 },
  { studentId: 4, mark1: 80, mark2: 90, mark3: 100 },
];

I want to merge the two arrays based on the key ‘studentId’. I have created a function to merge the two arrays.

const mergeById = (array1, array2) =>
    array1.map(itm => ({
      ...array2.find((item) => (item.studentId === itm.studentId) && item),
      ...itm
    }));

here is the code to get the final result

let result = mergeById(studentDetails, studentMark);

[
{"studentId":1,"mark1":80,"mark2":90,"mark3":100,"studentName":"Sathish","gender":"Male","age":15},{"studentId":2,"mark1":80,"mark2":90,"mark3":100,"studentName":"kumar","gender":"Male","age":16},{"studentId":3,"mark1":80,"mark2":90,"mark3":100,"studentName":"Roja","gender":"Female","age":15},{"studentId":4,"mark1":80,"mark2":90,"mark3":100,"studentName":"Nayanthara","gender":"Female","age":16}
]

Regular expression that doesn't contain certain string

".*[^(\\.inc)]\\.ftl$"

In Java this will find all files ending in ".ftl" but not ending in ".inc.ftl", which is exactly what I wanted.

How to upgrade docker container after its image changed

Consider for this answers:

  • The database name is app_schema
  • The container name is app_db
  • The root password is root123

How to update MySQL when storing application data inside the container

This is considered a bad practice, because if you lose the container, you will lose the data. Although it is a bad practice, here is a possible way to do it:

1) Do a database dump as SQL:

docker exec app_db sh -c 'exec mysqldump app_schema -uroot -proot123' > database_dump.sql

2) Update the image:

docker pull mysql:5.6

3) Update the container:

docker rm -f app_db
docker run --name app_db --restart unless-stopped \
-e MYSQL_ROOT_PASSWORD=root123 \
-d mysql:5.6

4) Restore the database dump:

docker exec app_db sh -c 'exec mysql -uroot -proot123' < database_dump.sql

How to update MySQL container using an external volume

Using an external volume is a better way of managing data, and it makes easier to update MySQL. Loosing the container will not lose any data. You can use docker-compose to facilitate managing multi-container Docker applications in a single host:

1) Create the docker-compose.yml file in order to manage your applications:

version: '2'
services:
  app_db:
    image: mysql:5.6
    restart: unless-stopped
    volumes_from: app_db_data
  app_db_data:
    volumes: /my/data/dir:/var/lib/mysql

2) Update MySQL (from the same folder as the docker-compose.yml file):

docker-compose pull
docker-compose up -d

Note: the last command above will update the MySQL image, recreate and start the container with the new image.

How to comment out a block of Python code in Vim

A very minimal light weight plugin: vim-commentary.

gcc to comment a line
gcgc to uncomment. check out the plugin page for more.

v+k/j highlight the block then gcc to comment that block.

How to compare dates in Java?

Update for Java 8 and later

These methods exists in LocalDate, LocalTime, and LocalDateTime classes.

Those classes are built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

Elegant way to create empty pandas DataFrame with NaN of type float

Simply pass the desired value as first argument, like 0, math.inf or, here, np.nan. The constructor then initializes and fills the value array to the size specified by arguments index and columns:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])

>>> df.dtypes
A    float64
B    float64
dtype: object

>>> df.values
array([[nan, nan],
       [nan, nan],
       [nan, nan],
       [nan, nan]])

Very simple log4j2 XML configuration file using Console and File appender

Here is my simplistic log4j2.xml that prints to console and writes to a daily rolling file:

// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);


// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="logPath">target/cucumber-logs</Property>
        <Property name="rollingFileName">cucumber</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
        </Console>
        <RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
            <Policies>
                <!-- Causes a rollover if the log file is older than the current JVM's start time -->
                <OnStartupTriggeringPolicy />
                <!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
            <AppenderRef ref="rollingFile" />
        </Root>
    </Loggers>
</Configuration>

TimeBasedTriggeringPolicy

interval (integer) - How often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers would occur every 4 hours. The default value is 1.

modulate (boolean) - Indicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc.

Source: https://logging.apache.org/log4j/2.x/manual/appenders.html

Output:

[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000

A new log file will be created daily with previous day automatically renamed to:

cucumber_yyyy-MM-dd.log

In a Maven project, you would put the log4j2.xml in src/main/resources or src/test/resources.

PDO Prepared Inserts multiple rows in single query

Here is my solution: https://github.com/sasha-ch/Aura.Sql based on auraphp/Aura.Sql library.

Usage example:

$q = "insert into t2(id,name) values (?,?), ... on duplicate key update name=name"; 
$bind_values = [ [[1,'str1'],[2,'str2']] ];
$pdo->perform($q, $bind_values);

Bugreports are welcome.

Laravel - Form Input - Multiple select for a one to many relationship

A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...

Form::select('sports[]', $sports, null, array('multiple'))

The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').

The second parameter is an array of selectable options.

The third parameter is an array of options you want pre-selected.

The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..

Convert Rows to columns using 'Pivot' in SQL Server

select * from (select name, ID from Empoyee) Visits
    pivot(sum(ID) for name
    in ([Emp1],
    [Emp2],
    [Emp3]
    ) ) as pivottable;

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

I prefer this solution:

df = spark.table(selected_table).filter(condition)

counter = df.count()

df = df.select([(counter - count(c)).alias(c) for c in df.columns])

Can Powershell Run Commands in Parallel?

There's so many answers to this these days:

  1. jobs (or threadjobs in PS 6/7 or the module)
  2. start-process
  3. workflows
  4. powershell api with another runspace
  5. invoke-command with multiple computers, which can all be localhost (have to be admin)
  6. multiple session (runspace) tabs in the ISE, or remote powershell ISE tabs
  7. Powershell 7 has a foreach-object -parallel as an alternative for #4

Here's workflows with literally a foreach -parallel:

workflow work {
  foreach -parallel ($i in 1..3) { 
    sleep 5 
    "$i done" 
  }
}

work

3 done
1 done
2 done

Or a workflow with a parallel block:

function sleepfor($time) { sleep $time; "sleepfor $time done"}

workflow work {
  parallel {
    sleepfor 3
    sleepfor 2
    sleepfor 1
  }
  'hi'
}

work 

sleepfor 1 done
sleepfor 2 done
sleepfor 3 done
hi

Here's an api with runspaces example:

$a =  [PowerShell]::Create().AddScript{sleep 5;'a done'}
$b =  [PowerShell]::Create().AddScript{sleep 5;'b done'}
$c =  [PowerShell]::Create().AddScript{sleep 5;'c done'}
$r1,$r2,$r3 = ($a,$b,$c).begininvoke() # run in background
$a.EndInvoke($r1); $b.EndInvoke($r2); $c.EndInvoke($r3) # wait
($a,$b,$c).streams.error # check for errors
($a,$b,$c).dispose() # clean

a done
b done
c done

How to remove multiple indexes from a list at the same time?

Old question, but I have an answer.

First, peruse the elements of the list like so:

for x in range(len(yourlist)):
    print '%s: %s' % (x, yourlist[x])

Then, call this function with a list of the indexes of elements you want to pop. It's robust enough that the order of the list doesn't matter.

def multipop(yourlist, itemstopop):
    result = []
    itemstopop.sort()
    itemstopop = itemstopop[::-1]
    for x in itemstopop:
        result.append(yourlist.pop(x))
    return result

As a bonus, result should only contain elements you wanted to remove.

In [73]: mylist = ['a','b','c','d','charles']

In [76]: for x in range(len(mylist)):

      mylist[x])

....:

0: a

1: b

2: c

3: d

4: charles

...

In [77]: multipop(mylist, [0, 2, 4])

Out[77]: ['charles', 'c', 'a']

...

In [78]: mylist

Out[78]: ['b', 'd']