Programs & Examples On #Spring aop

Spring AOP is the Spring Framework's version of AOP, implemented in pure Java and using the @AspectJ annotations from the AspectJ project. Spring AOP works through dynamic JDK or CGLib Proxies.

@AspectJ pointcut for all methods of a class with specific annotation

You should combine a type pointcut with a method pointcut.

These pointcuts will do the work to find all public methods inside a class marked with an @Monitor annotation:

@Pointcut("within(@org.rejeev.Monitor *)")
public void beanAnnotatedWithMonitor() {}

@Pointcut("execution(public * *(..))")
public void publicMethod() {}

@Pointcut("publicMethod() && beanAnnotatedWithMonitor()")
public void publicMethodInsideAClassMarkedWithAtMonitor() {}

Advice the last pointcut that combines the first two and you're done!

If you're interested, I have written a cheat sheet with @AspectJ style here with a corresponding example document here.

Spring - @Transactional - What happens in background?

The simplest answer is:

On whichever method you declare @Transactional the boundary of transaction starts and boundary ends when method completes.

If you are using JPA call then all commits are with in this transaction boundary.

Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an exception occur, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be rollback with entity3.

Transaction :

  1. entity1.save
  2. entity2.save
  3. entity3.save

Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.

ASP.NET Web API : Correct way to return a 401/unauthorised response

You also follow this code:

var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
      Content = new StringContent("Users doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
      StatusCode = HttpStatusCode.NotFound
 }
 throw new HttpResponseException(response);

Log exception with traceback

maybe not as stylish, but easier:

#!/bin/bash
log="/var/log/yourlog"
/path/to/your/script.py 2>&1 | (while read; do echo "$REPLY" >> $log; done)

How to display an IFRAME inside a jQuery UI dialog

The problems were:

  1. iframe content comes from another domain
  2. iframe dimensions need to be adjusted for each video

The solution based on omerkirk's answer involves:

  • Creating an iframe element
  • Creating a dialog with autoOpen: false, width: "auto", height: "auto"
  • Specifying iframe source, width and height before opening the dialog

Here is a rough outline of code:

HTML

<div class="thumb">
    <a href="http://jsfiddle.net/yBNVr/show/"   data-title="Std 4:3 ratio video" data-width="512" data-height="384"><img src="http://dummyimage.com/120x90/000/f00&text=Std+4-3+ratio+video" /></a></li>
    <a href="http://jsfiddle.net/yBNVr/1/show/" data-title="HD 16:9 ratio video" data-width="512" data-height="288"><img src="http://dummyimage.com/120x90/000/f00&text=HD+16-9+ratio+video" /></a></li>
</div>

jQuery

$(function () {
    var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
    var dialog = $("<div></div>").append(iframe).appendTo("body").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        width: "auto",
        height: "auto",
        close: function () {
            iframe.attr("src", "");
        }
    });
    $(".thumb a").on("click", function (e) {
        e.preventDefault();
        var src = $(this).attr("href");
        var title = $(this).attr("data-title");
        var width = $(this).attr("data-width");
        var height = $(this).attr("data-height");
        iframe.attr({
            width: +width,
            height: +height,
            src: src
        });
        dialog.dialog("option", "title", title).dialog("open");
    });
});

Demo here and code here. And another example along similar lines

how to change text box value with jQuery?

$('#cd').click(function() {
  $(this).val('dasf');  // update the value of submit button
  $('#dsf').val('Changed Value') // update the text input value
});

textbox is not a valid selector.

Also, when you hit the submit button it will submit the form as default behavior. So don't forget to stop default form submission.

Better if you do like this:

$('form').on('submit', function() {

  // write all your codes

  return false; // Prevent default form submission
});

Don't forget to user jQuery DOM ready $(function() { .. });

How to print a number with commas as thousands separators in JavaScript

If you're looking for a short and sweet solution:

const number = 12345678.99;

const numberString = String(number).replace(
    /^\d+/,
    number => [...number].map(
        (digit, index, digits) => (
            !index || (digits.length - index) % 3 ? '' : ','
        ) + digit
    ).join('')
);

// numberString: 12,345,678.99

Does svn have a `revert-all` command?

You could do:

svn revert -R .

This will not delete any new file not under version control. But you can easily write a shell script to do that like:

for file in `svn status|grep "^ *?"|sed -e 's/^ *? *//'`; do rm $file ; done

Differences between Ant and Maven

I'd say it depends upon the size of your project... Personnally, I would use Maven for simple projects that need straightforward compiling, packaging and deployment. As soon as you need to do some more complicated things (many dependencies, creating mapping files...), I would switch to Ant...

Max retries exceeded with URL in requests

just import time and add :

time.sleep(6)

somewhere in the for loop, to avoid sending too many request to the server in a short time. the number 6 means: 6 seconds. keep testing numbers starting from 1, until you reach the minimum seconds that will help to avoid the problem.

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

I did this:

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>AutoDealer</title>
        <style>
        .container{
            width: 860px;
            height: 1074px;
            margin-right: auto;
            margin-left: auto;
            border: 1px solid red;

        }
        .nav{

        }
        .wrapper{
            display: block;
            overflow: hidden;
            border: 1px solid green;
        }
       .otherWrapper{
            display: block;
            overflow: hidden;
            border: 1px solid green;
            float:left;
        }
    .left{
        width: 399px;
        float: left;
        background-color: pink;
    }
            .bottom{
        clear: both;
        width: 399px;
        background-color: yellow;



    }
    .right{
        height:350px;
        width: 449px;
        overflow: hidden;
        background-color: blue;
        overflow: hidden;
        float:right;
    }

    </style>
</head>
<body>
    <div class="container">
        <div class="nav"></div>
        <div class="wrapper">
        <div class="otherWrapper">
            <div class="left">
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
            </div>
             <div class="bottom">
                <p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
             </div>

             <div class="right">
                <p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
             </div>
        </div>
    </div>
</body>

So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.

How to fetch JSON file in Angular 2

I needed to load the settings file synchronously, and this was my solution:

export function InitConfig(config: AppConfig) { return () => config.load(); }

import { Injectable } from '@angular/core';

@Injectable()
export class AppConfig {
    Settings: ISettings;

    constructor() { }

    load() {
        return new Promise((resolve) => {
            this.Settings = this.httpGet('assets/clientsettings.json');
            resolve(true);
        });
    }

    httpGet(theUrl): ISettings {
        const xmlHttp = new XMLHttpRequest();
        xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return JSON.parse(xmlHttp.responseText);
    }
}

This is then provided as a app_initializer which is loaded before the rest of the application.

app.module.ts

{
      provide: APP_INITIALIZER,
      useFactory: InitConfig,
      deps: [AppConfig],
      multi: true
    },

How do I make a new line in swift

You should be able to use \n inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n for proper formatting like so:

var example: String = "Hello World \nThis is a new line"

Which, if printed to the console, should become:

Hello World
This is a new line

However, there are some other considerations to make depending on how you will be using this string, such as:

  • If you are setting it to a UILabel's text property, make sure that the UILabel's numberOfLines = 0, which allows for infinite lines.
  • In some networking use cases, use \r\n instead, which is the Windows newline.

Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.

Getting value of HTML Checkbox from onclick/onchange events

For React.js, you can do this with more readable code. Hope it helps.

handleCheckboxChange(e) {
  console.log('value of checkbox : ', e.target.checked);
}
render() {
  return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

If using win7 64 bit OS:

After installing the latest JDK make sure you copy the jre folder from the install location {C:\Program Files\Java\jdk1.7.0_40} directly to your eclipse folder as even pathing it apparently does nothing on win7.

Mad

edit:

Actual jdk version number on folder name will vary as newer versions are released

One line ftp server in python

Obligatory Twisted example:

twistd -n ftp

And probably useful:

twistd ftp --help

Usage: twistd [options] ftp [options].
WARNING: This FTP server is probably INSECURE do not use it.
Options:
  -p, --port=           set the port number [default: 2121]
  -r, --root=           define the root of the ftp-site. [default:
                    /usr/local/ftp]
  --userAnonymous=  Name of the anonymous user. [default: anonymous]
  --password-file=  username:password-style credentials database
  --version         
  --help            Display this help and exit.

What does the [Flags] Enum Attribute mean in C#?

There's something overly verbose to me about the if ((x & y) == y)... construct, especially if x AND y are both compound sets of flags and you only want to know if there's any overlap.

In this case, all you really need to know is if there's a non-zero value[1] after you've bitmasked.

[1] See Jaime's comment. If we were authentically bitmasking, we'd only need to check that the result was positive. But since enums can be negative, even, strangely, when combined with the [Flags] attribute, it's defensive to code for != 0 rather than > 0.

Building off of @andnil's setup...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BitFlagPlay
{
    class Program
    {
        [Flags]
        public enum MyColor
        {
            Yellow = 0x01,
            Green = 0x02,
            Red = 0x04,
            Blue = 0x08
        }

        static void Main(string[] args)
        {
            var myColor = MyColor.Yellow | MyColor.Blue;
            var acceptableColors = MyColor.Yellow | MyColor.Red;

            Console.WriteLine((myColor & MyColor.Blue) != 0);     // True
            Console.WriteLine((myColor & MyColor.Red) != 0);      // False                
            Console.WriteLine((myColor & acceptableColors) != 0); // True
            // ... though only Yellow is shared.

            Console.WriteLine((myColor & MyColor.Green) != 0);    // Wait a minute... ;^D

            Console.Read();
        }
    }
}

How to make my layout able to scroll down?

For using scroll view along with Relative layout :

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"> <!--IMPORTANT otherwise backgrnd img. will not fill the whole screen -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@drawable/background_image"
    >

    <!-- Bla Bla Bla i.e. Your Textviews/Buttons etc. -->
    </RelativeLayout>
</ScrollView>

How can I remove an SSH key?

I opened "Passwords and Keys" application in my Unity and removed unwanted keys from Secure Keys -> OpenSSH keys And they automatically had been removed from ssh-agent -l as well.

How to delete shared preferences data from App in Android

In the class definitions:

private static final String PREFERENCES = "shared_prefs";

private static final SharedPreferences sharedPreferences  = getApplicationContext().getSharedPreferences(PREFERENCES, MODE_PRIVATE);

Inside the class:

public static void deleteAllSharedPrefs(){
    sharedPreferences.edit().clear().commit();
}

Jquery UI datepicker. Disable array of Dates

$('input').datepicker({
   beforeShowDay: function(date){
       var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
       return [ array.indexOf(string) == -1 ]
   }
});

JQuery Ajax POST in Codeigniter

In codeigniter there is no need to sennd "data" in ajax post method.. here is the example .

   searchThis = 'This text will be search';
    $.ajax({
      type: "POST",
      url: "<?php echo site_url();?>/software/search/"+searchThis,
      dataType: "html",
      success:function(data){
        alert(data);
      },

    });

Note : in url , software is the controller name , search is the function name and searchThis is the variable that i m sending.

Here is the controller.

    public function search(){
    $search = $this->uri->segment(3);
      echo '<p>'.$search.'</p>';
    }

I hope you can get idea for your work .

How to run the sftp command with a password from Bash script?

I was recently asked to switch over from ftp to sftp, in order to secure the file transmission between servers. We are using Tectia SSH package, which has an option --password to pass the password on the command line.

example : sftp --password="password" "userid"@"servername"

Batch example :

(
  echo "
  ascii
  cd pub
  lcd dir_name
  put filename
  close
  quit
    "
) | sftp --password="password" "userid"@"servername"

I thought I should share this information, since I was looking at various websites, before running the help command (sftp -h), and was i surprised to see the password option.

Graph implementation C++

It really depends on what algorithms you need to implement, there is no silver bullet (and that's shouldn't be a surprise... the general rule about programming is that there's no general rule ;-) ).

I often end up representing directed multigraphs using node/edge structures with pointers... more specifically:

struct Node
{
    ... payload ...
    Link *first_in, *last_in, *first_out, *last_out;
};

struct Link
{
    ... payload ...
    Node *from, *to;
    Link *prev_same_from, *next_same_from,
         *prev_same_to, *next_same_to;
};

In other words each node has a doubly-linked list of incoming links and a doubly-linked list of outgoing links. Each link knows from and to nodes and is at the same time in two different doubly-linked lists: the list of all links coming out from the same from node and the list of all links arriving at the same to node.

The pointers prev_same_from and next_same_from are used when following the chain of all the links coming out from the same node; the pointers prev_same_to and next_same_to are instead used when managing the chain of all the links pointing to the same node.

Data structure diagram

It's a lot of pointer twiddling (so unless you love pointers just forget about this) but query and update operations are efficient; for example adding a node or a link is O(1), removing a link is O(1) and removing a node x is O(deg(x)).

Of course depending on the problem, payload size, graph size, graph density this approach can be way overkilling or too much demanding for memory (in addition to payload you've 4 pointers per node and 6 pointers per link).

A similar structure full implementation can be found here.

JSON to TypeScript class instance?

This question is quite broad, so I'm going to give a couple of solutions.

Solution 1: Helper Method

Here's an example of using a Helper Method that you could change to fit your needs:

class SerializationHelper {
    static toInstance<T>(obj: T, json: string) : T {
        var jsonObj = JSON.parse(json);

        if (typeof obj["fromJSON"] === "function") {
            obj["fromJSON"](jsonObj);
        }
        else {
            for (var propName in jsonObj) {
                obj[propName] = jsonObj[propName]
            }
        }

        return obj;
    }
}

Then using it:

var json = '{"name": "John Doe"}',
    foo = SerializationHelper.toInstance(new Foo(), json);

foo.GetName() === "John Doe";

Advanced Deserialization

This could also allow for some custom deserialization by adding your own fromJSON method to the class (this works well with how JSON.stringify already uses the toJSON method, as will be shown):

interface IFooSerialized {
    nameSomethingElse: string;
}

class Foo {
  name: string;
  GetName(): string { return this.name }

  toJSON(): IFooSerialized {
      return {
          nameSomethingElse: this.name
      };
  }

  fromJSON(obj: IFooSerialized) {
        this.name = obj.nameSomethingElse;
  }
}

Then using it:

var foo1 = new Foo();
foo1.name = "John Doe";

var json = JSON.stringify(foo1);

json === '{"nameSomethingElse":"John Doe"}';

var foo2 = SerializationHelper.toInstance(new Foo(), json);

foo2.GetName() === "John Doe";

Solution 2: Base Class

Another way you could do this is by creating your own base class:

class Serializable {
    fillFromJSON(json: string) {
        var jsonObj = JSON.parse(json);
        for (var propName in jsonObj) {
            this[propName] = jsonObj[propName]
        }
    }
}

class Foo extends Serializable {
    name: string;
    GetName(): string { return this.name }
}

Then using it:

var foo = new Foo();
foo.fillFromJSON(json);

There's too many different ways to implement a custom deserialization using a base class so I'll leave that up to how you want it.

How to use onSavedInstanceState example please

This is for extra information.

Imagine this scenario

  1. ActivityA launch ActivityB.
  2. ActivityB launch a new ActivityAPrime by

    Intent intent = new Intent(getApplicationContext(), ActivityA.class);
    startActivity(intent);
    
  3. ActivityAPrime has no relationship with ActivityA.
    In this case the Bundle in ActivityAPrime.onCreate() will be null.

If ActivityA and ActivityAPrime should be the same activity instead of different activities, ActivityB should call finish() than using startActivity().

Why does configure say no C compiler found when GCC is installed?

The below packages are also helps you,

yum install gcc glibc glibc-common gd gd-devel -y

How to fix 'Microsoft Excel cannot open or save any more documents'

Go to this key on Registry Editor (Run | Regedit) HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

change key Cache to something like C:\Windows\Temp

My similar problem was solved like this.

Regards,

Ripley

java.net.ConnectException: Connection refused

I had the same problem, but running the Server before running the Client fixed it.

Find the differences between 2 Excel worksheets?

Use conditional formatting to highlight the differences in excel.

Here's an example.

How to properly set the 100% DIV height to match document/window height?

Use #element{ height:100vh}

This will set the height of the #element to 100% of viewport. Hope this helps.

How to stop C# console applications from closing automatically?

Console.ReadLine();

or

Console.ReadKey();

ReadLine() waits for ?, ReadKey() waits for any key (except for modifier keys).

Edit: stole the key symbol from Darin.

Postgres: check if array field contains value?

This should work:

select * from mytable where 'Journal'=ANY(pub_types);

i.e. the syntax is <value> = ANY ( <array> ). Also notice that string literals in postresql are written with single quotes.

Can you set a border opacity in CSS?

Other answers deal with the technical aspect of the border-opacity issue, while I'd like to present a hack(pure CSS and HTML only). Basically create a container div, having a border div and then the content div.

<div class="container">
  <div class="border-box"></div>
  <div class="content-box"></div>
</div>

And then the CSS:(set content border to none, take care of positioning such that border thickness is accounted for)

.container {
  width: 20vw;
  height: 20vw;
  position: relative;
}
.border-box {
  width: 100%;
  height: 100%;
  border: 5px solid black;
  position: absolute;
  opacity: 0.5;
}
.content-box {
  width: 100%;
  height: 100%;
  border: none;
  background: green;
  top: 5px;
  left: 5px;
  position: absolute;
}

ExecuteReader: Connection property has not been initialized

All of the answers is true.This is another way. And I like this One

SqlCommand cmd = conn.CreateCommand()

you must notice that strings concat have a sql injection problem. Use the Parameters http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx

How to clear the text of all textBoxes in the form?

private void CleanForm(Control ctrl)
{
    foreach (var c in ctrl.Controls)
    {
        if (c is TextBox)
        {
            ((TextBox)c).Text = String.Empty;
        }

        if( c.Controls.Count > 0)
        {
           CleanForm(c);
        }
    }
}

When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).

Executing Shell Scripts from the OS X Dock?

I think this thread may be helpful: http://forums.macosxhints.com/archive/index.php/t-70973.html

To paraphrase, you can rename it with the .command extension or create an AppleScript to run the shell.

Python error: "IndexError: string index out of range"

It looks like you indented so_far = new too much. Try this:

if guess in word:
    print("\nYes!", guess, "is in the word!")

    # Create a new variable (so_far) to contain the guess
    new = ""
    i = 0
    for i in range(len(word)):
        if guess == word[i]:
            new += guess
        else:
            new += so_far[i]
    so_far = new # unindented this

Converting milliseconds to minutes and seconds with Javascript

There is probably a better way to do this, but it gets the job done:

var ms = 298999;
var min = ms / 1000 / 60;
var r = min % 1;
var sec = Math.floor(r * 60);
if (sec < 10) {
    sec = '0'+sec;
}
min = Math.floor(min);
console.log(min+':'+sec);

Not sure why you have the << operator in your minutes line, I don't think it's needed just floor the minutes before you display.

Getting the remainder of the minutes with % gives you the percentage of seconds elapsed in that minute, so multiplying it by 60 gives you the amount of seconds and flooring it makes it more fit for display although you could also get sub-second precision if you want.

If seconds are less than 10 you want to display them with a leading zero.

Image overlay on responsive sized images bootstrap

I had a bit of trouble getting this to work as well. Using brouxhaha's answer got me 90% of the way to what I was looking for. But the padding adjust wouldn't allow me to put the text anywhere I wanted. Using top and left seemed to work better for my purposes.

.project-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    color: #fff;
    top: 80%;
    left: 20%;
}

http://jsfiddle.net/1rz0b7d8/1/

How to delete rows in tables that contain foreign keys to other tables

First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.

DELETE 
  FROM ReferencingTable 
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM MainTable AS T1
                    WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
                  );

Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.

ALTER TABLE ReferencingTable DROP 
   CONSTRAINT fk__ReferencingTable__MainTable;

ALTER TABLE ReferencingTable ADD 
   CONSTRAINT fk__ReferencingTable__MainTable 
      FOREIGN KEY (pk_col_1)
      REFERENCES MainTable (pk_col_1)
      ON DELETE CASCADE;

Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

How to source virtualenv activate in a Bash script

You should call the bash script using source.

Here is an example:

#!/bin/bash
# Let's call this script venv.sh
source "<absolute_path_recommended_here>/.env/bin/activate"

On your shell just call it like that:

> source venv.sh

Or as @outmind suggested: (Note that this does not work with zsh)

> . venv.sh

There you go, the shell indication will be placed on your prompt.

How to find encoding of a file via script on Linux?

here is an example script using file -I and iconv which works on MacOsX For your question you need to use mv instead of iconv

#!/bin/bash
# 2016-02-08
# check encoding and convert files
for f in *.java
do
  encoding=`file -I $f | cut -f 2 -d";" | cut -f 2 -d=`
  case $encoding in
    iso-8859-1)
    iconv -f iso8859-1 -t utf-8 $f > $f.utf8
    mv $f.utf8 $f
    ;;
  esac
done

Python: For each list element apply a function across the list

If working with Python =2.6 (including 3.x), you can:

from __future__ import division
import operator, itertools

def getmin(alist):
    return min(
        (operator.div(*pair), pair)
        for pair in itertools.product(alist, repeat=2)
    )[1]

getmin([1, 2, 3, 4, 5])

EDIT: Now that I think of it and if I remember my mathematics correctly, this should also give the answer assuming that all numbers are non-negative:

def getmin(alist):
    return min(alist), max(alist)

How to get df linux command output always in GB

You can use the -B option.

Man page of df:

-B, --block-size=SIZE use SIZE-byte blocks

All together,

df -BG

Unique constraint violation during insert: why? (Oracle)

Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.

CREATE TABLE [DB] (
    [DBId] bigint NOT NULL IDENTITY,
    ...

    CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),

); 

How to filter (key, value) with ng-repeat in AngularJs?

Or simply use

ng-show="v.hasOwnProperty('secId')"

See updated solution here:

http://jsfiddle.net/RFontana/WA2BE/93/

How to center form in bootstrap 3

I tried this and it worked

_x000D_
_x000D_
<div class="container">_x000D_
 <div class="row justify-content-center">_x000D_
  <div class="form-group col-md-4 col-md-offset-5 align-center ">_x000D_
       <input type="text" name="username" placeholder="Username" >_x000D_
  </div>_x000D_
 </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

What are the differences between WCF and ASMX web services?

Keith Elder nicely compares ASMX to WCF here. Check it out.

Another comparison of ASMX and WCF can be found here - I don't 100% agree with all the points there, but it might give you an idea.

WCF is basically "ASMX on stereoids" - it can be all that ASMX could - plus a lot more!.

ASMX is:

  • easy and simple to write and configure
  • only available in IIS
  • only callable from HTTP

WCF can be:

  • hosted in IIS, a Windows Service, a Winforms application, a console app - you have total freedom
  • used with HTTP (REST and SOAP), TCP/IP, MSMQ and many more protocols

In short: WCF is here to replace ASMX fully.

Check out the WCF Developer Center on MSDN.

Update: link seems to be dead - try this: What Is Windows Communication Foundation?

Sorting a list using Lambda/Linq to objects

This is how I solved my problem:

List<User> list = GetAllUsers();  //Private Method

if (!sortAscending)
{
    list = list
           .OrderBy(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
           .ToList();
}
else
{
    list = list
           .OrderByDescending(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
           .ToList();
}

How do I programmatically set the value of a select box element using JavaScript?

If using PHP you could try something like this:

$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';

switch($value) {
            case '10' :
                $first = 'selected';
            break;
            case '11' :
                $second = 'selected';
            break;
            case '14' :
                $third = 'selected';
            break;
            case '17' :
                $fourth = 'selected';
            break;
        }

echo'
<select id="leaveCode" name="leaveCode">
  <option value="10" '. $first .'>Annual Leave</option>
  <option value="11" '. $second .'>Medical Leave</option>
  <option value="14" '. $third .'>Long Service</option>
  <option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';

Incorrect integer value: '' for column 'id' at row 1

This is because your data sending column type is integer and your are sending a string value to it.

So, the following way worked for me. Try with this one.

$insertQuery = "INSERT INTO workorders VALUES (
                    null,
                    '$priority',
                    '$requestType',
                    '$purchaseOrder',
                    '$nte',
                    '$jobSiteNumber'
                )";

Don't use 'null'. use it as null without single quotes.

Class file has wrong version 52.0, should be 50.0

Select "File" -> "Project Structure".

Under "Project Settings" select "Project"

From there you can select the "Project SDK".

Convert blob to base64

Most easiest way in a single line of code

var base64Image = new Buffer( blob, 'binary' ).toString('base64');

How to "fadeOut" & "remove" a div in jQuery?

you really should try to use jQuery in a separate file, not inline. Here is what you need:

<a class="notificationClose "><img src="close.png"/></a>

And then this at the bottom of your page in <script> tags at the very least or in a external JavaScript file.

$(".notificationClose").click(function() {
    $("#notification").fadeOut("normal", function() {
        $(this).remove();
    });
});

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)

modify list of host names for your system:

C:\Windows\System32\drivers\etc\hosts

Make sure that you have the following entry:

127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem

(you may need to change modify permission to modify this file)

This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.

Convert char array to a int number in C

It isn't that hard to deal with the character array itself without converting the array to a string. Especially in the case where the length of the character array is know or can be easily found. With the character array, the length must be determined in the same scope as the array definition, e.g.:

size_t len sizeof myarray/sizeof *myarray;

For strings you, of course, have strlen available.

With the length known, regardless of whether it is a character array or a string, you can convert the character values to a number with a short function similar to the following:

/* convert character array to integer */
int char2int (char *array, size_t n)
{    
    int number = 0;
    int mult = 1;

    n = (int)n < 0 ? -n : n;       /* quick absolute value check  */

    /* for each character in array */
    while (n--)
    {
        /* if not digit or '-', check if number > 0, break or continue */
        if ((array[n] < '0' || array[n] > '9') && array[n] != '-') {
            if (number)
                break;
            else
                continue;
        }

        if (array[n] == '-') {      /* if '-' if number, negate, break */
            if (number) {
                number = -number;
                break;
            }
        }
        else {                      /* convert digit to numeric value   */
            number += (array[n] - '0') * mult;
            mult *= 10;
        }
    }

    return number;
}

Above is simply the standard char to int conversion approach with a few additional conditionals included. To handle stray characters, in addition to the digits and '-', the only trick is making smart choices about when to start collecting digits and when to stop.

If you start collecting digits for conversion when you encounter the first digit, then the conversion ends when you encounter the first '-' or non-digit. This makes the conversion much more convenient when interested in indexes such as (e.g. file_0127.txt).

A short example of its use:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int char2int (char *array, size_t n);

int main (void) {

    char myarray[4] = {'-','1','2','3'}; 
    char *string = "some-goofy-string-with-123-inside";
    char *fname = "file-0123.txt";

    size_t mlen = sizeof myarray/sizeof *myarray;
    size_t slen = strlen (string);
    size_t flen = strlen (fname);

    printf ("\n myarray[4] = {'-','1','2','3'};\n\n");
    printf ("   char2int (myarray, mlen):  %d\n\n", char2int (myarray, mlen));

    printf (" string = \"some-goofy-string-with-123-inside\";\n\n");
    printf ("   char2int (string, slen) :  %d\n\n", char2int (string, slen));

    printf (" fname = \"file-0123.txt\";\n\n");
    printf ("   char2int (fname, flen)  :  %d\n\n", char2int (fname, flen));

    return 0;
}

Note: when faced with '-' delimited file indexes (or the like), it is up to you to negate the result. (e.g. file-0123.txt compared to file_0123.txt where the first would return -123 while the second 123).

Example Output

$ ./bin/atoic_array

 myarray[4] = {'-','1','2','3'};

   char2int (myarray, mlen):  -123

 string = "some-goofy-string-with-123-inside";

   char2int (string, slen) :  -123

 fname = "file-0123.txt";

   char2int (fname, flen)  :  -123

Note: there are always corner cases, etc. that can cause problems. This isn't intended to be 100% bulletproof in all character sets, etc., but instead work an overwhelming majority of the time and provide additional conversion flexibility without the initial parsing or conversion to string required by atoi or strtol, etc.

In a Dockerfile, How to update PATH environment variable?

Although the answer that Gunter posted was correct, it is not different than what I already had posted. The problem was not the ENV directive, but the subsequent instruction RUN export $PATH

There's no need to export the environment variables, once you have declared them via ENV in your Dockerfile.

As soon as the RUN export ... lines were removed, my image was built successfully

Removing u in list

Please Use map() python function.

Input: In case of list of values

index = [u'CARBO1004' u'CARBO1006' u'CARBO1008' u'CARBO1009' u'CARBO1020']

encoded_string = map(str, index)

Output: ['CARBO1004', 'CARBO1006', 'CARBO1008', 'CARBO1009', 'CARBO1020']

For a Single string input:

index = u'CARBO1004'
# Use Any one of the encoding scheme.
index.encode("utf-8")  # To utf-8 encoding scheme
index.encode('ascii', 'ignore')  # To Ignore Encoding Errors and set to default scheme

Output: 'CARBO1004'

Debugging WebSocket in Google Chrome

If you don't have a page which is accessing the websocket, you can open up the Chrome console and type your JavaScript in:

var webSocket = new WebSocket('ws://address:port');
webSocket.onmessage = function(data) { console.log(data); }

This will open up the web socket so you can see it in the network tab and in the console.

Generate Java classes from .XSD files...?

the easiest way is using command line. Just type in directory of your .xsd file:

xjc myFile.xsd.

So, the java will generate all Pojos.

Eclipse hangs on loading workbench

Pretty old question but the most simple answer isn't yet posted.
Here it is :
1) In [workspace]\.metadata\.plugins\org.eclipse.e4.workbench delete workbench.xmi file.
In most cases it's enough - try to load Eclipse.
Still you have to re-configure your specific perspective settings (if any)

2) Now getting problems with building projects that worked perfectly? As of my experience following steps help:
- uncheck Projects->Build automatically
- switch to Java perspective (if not yet): Window -> Open perspective -> Java
- locate Problems view or open it: Window -> Show view -> Problems
- right-click on problem groups and select Delete. Be sure to delete Lint errors
- clean the workspace: Project -> Clean... with option Clean all projects
- check Projects->Build automatically
- if problems persist for some projects: right-click project, select Properties -> Android and make sure appropriate Project Build Target is chosen

3) It was always sufficient for me. But if you still get problems - try @george post recommendations

scroll up and down a div on button click using jquery

Scrolling div on click of button.

Html Code:-

 <div id="textBody" style="height:200px; width:600px; overflow:auto;">
    <!------Your content---->
 </div>

JQuery code for scrolling div:-

$(function() {
   $( "#upBtn" ).click(function(){
      $('#textBody').scrollTop($('#textBody').scrollTop()-20);
 }); 

 $( "#downBtn" ).click(function(){
     $('#textBody').scrollTop($('#textBody').scrollTop()+20);;
 }); 

});

What is the purpose of flush() in Java streams?

When you write data to a stream, it is not written immediately, and it is buffered. So use flush() when you need to be sure that all your data from buffer is written.

We need to be sure that all the writes are completed before we close the stream, and that is why flush() is called in file/buffered writer's close().

But if you have a requirement that all your writes be saved anytime before you close the stream, use flush().

How to convert column with string type to int form in pyspark data frame?

from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))

You can run loop for each column but this is the simplest way to convert string column into integer.

Where to place JavaScript in an HTML file?

The answer to the question depends. There are 2 scenarios in this situation and you'll need to make a choice based on your appropriate scenario.

Scenario 1 - Critical script / Must needed script

In case the script you are using is important to load the website, it is recommended to be placed at the top of your HTML document i.e, <head>. Some examples include - application code, bootstrap, fonts, etc.

Scenario 2 - Less important / analytics scripts

There are also scripts used which do not affect the website's view. Such scripts are recommended to be loaded after all the important segments are loaded. And the answer to that will be bottom of the document i.e, bottom of your <body> before the closing tag. Some examples include - Google analytics, hotjar, etc.

Bonus - async / defer

You can also tell the browsers that the script loading can be done simultaneously with others and can be loaded based on the browser's choice using a defer / async argument in the script code.

eg. <script async src="script.js"></script>

glob exclude pattern

You can use the below method:

# Get all the files
allFiles = glob.glob("*")
# Files starting with eph
ephFiles = glob.glob("eph*")
# Files which doesnt start with eph
noephFiles = []
for file in allFiles:
    if file not in ephFiles:
        noephFiles.append(file)
# noepchFiles has all the file which doesnt start with eph.

Thank you.  

Import regular CSS file in SCSS file?

Good news everyone, Chris Eppstein created a compass plugin with inline css import functionality:

https://github.com/chriseppstein/sass-css-importer

Now, importing a CSS file is as easy as:

@import "CSS:library/some_css_file"

linux shell script: split string, put them in an array then loop through them

Here is an example code that you may use:

$ STR="String;1;2;3"
$ for EACH in `echo "$STR" | grep -o -e "[^;]*"`; do
    echo "Found: \"$EACH\"";
done

grep -o -e "[^;]*" will select anything that is not ';', therefore spliting the string by ';'.

Hope that help.

How do you add UI inside cells in a google spreadsheet using app script?

The apps UI only works for panels.

The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.

Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.

Alternatively you can also draw the button somewhere else and insert it as an image.

More info: https://developers.google.com/apps-script/guides/menus

enter image description here enter image description here enter image description here

TypeScript and array reduce function

It's actually the JavaScript array reduce function rather than being something specific to TypeScript.

As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.

Here's an example which sums up the values of an array:

_x000D_
_x000D_
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);_x000D_
console.log(total);
_x000D_
_x000D_
_x000D_

The snippet should produce 6.

How to return the current timestamp with Moment.js?

moment().unix() you will get a unix timestamp

moment().valueOf() you will get a full timestamp

Failed Apache2 start, no error log

On XAMPP use

D:\xampp\apache\bin>httpd -t -D DUMP_VHOSTS

This will yield errors in your configuration of the virtual hosts

switch() statement usage

Well, timing to the rescue again. It seems switch is generally faster than if statements. So that, and the fact that the code is shorter/neater with a switch statement leans in favor of switch:

# Simplified to only measure the overhead of switch vs if

test1 <- function(type) {
 switch(type,
        mean = 1,
        median = 2,
        trimmed = 3)
}

test2 <- function(type) {
 if (type == "mean") 1
 else if (type == "median") 2
 else if (type == "trimmed") 3
}

system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs

Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:

> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
           expr  min   lq median   uq      max
1 test1("mean")  709  771    864  951 16122411
2 test2("mean") 1007 1073   1147 1223  8012202

> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
              expr  min   lq median   uq      max
1 test1("trimmed")  733  792    843  944 60440833
2 test2("trimmed") 2022 2133   2203 2309 60814430

Final Update Here's showing how versatile switch is:

switch(type, case1=1, case2=, case3=2.5, 99)

This maps case2 and case3 to 2.5 and the (unnamed) default to 99. For more information, try ?switch

HTTP GET Request in Node.js Express

If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:

var get = require('simple-get');

get('http://example.com', function (err, res) {
  if (err) throw err;
  console.log(res.statusCode); // 200
  res.pipe(process.stdout); // `res` is a stream
});

How do I get the YouTube video ID from a URL?

videoId = videoUrl.split('v=')[1].substring(0,11);

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

How do I install opencv using pip?

  1. Open terminal
  2. Run the following command pip install --trusted-host=pypi.org --trusted-host=files.pythonhosted.org opencv-python.
  3. Hope it will work.

Generate a dummy-variable

Using dummies::dummy():

library(dummies)

# example data
df1 <- data.frame(id = 1:4, year = 1991:1994)

df1 <- cbind(df1, dummy(df1$year, sep = "_"))

df1
#   id year df1_1991 df1_1992 df1_1993 df1_1994
# 1  1 1991        1        0        0        0
# 2  2 1992        0        1        0        0
# 3  3 1993        0        0        1        0
# 4  4 1994        0        0        0        1

Javascript Array.sort implementation?

I've just had a look at the WebKit (Chrome, Safari …) source. Depending on the type of array, different sort methods are used:

Numeric arrays (or arrays of primitive type) are sorted using the C++ standard library function std::qsort which implements some variation of quicksort (usually introsort).

Contiguous arrays of non-numeric type are stringified and sorted using mergesort, if available (to obtain a stable sorting) or qsort if no merge sort is available.

For other types (non-contiguous arrays and presumably for associative arrays) WebKit uses either selection sort (which they call “min” sort) or, in some cases, it sorts via an AVL tree. Unfortunately, the documentation here is rather vague so you’d have to trace the code paths to actually see for which types which sort method is used.

And then there are gems like this comment:

// FIXME: Since we sort by string value, a fast algorithm might be to use a
// radix sort. That would be O(N) rather than O(N log N).

– Let’s just hope that whoever actually “fixes” this has a better understanding of asymptotic runtime than the writer of this comment, and realises that radix sort has a slightly more complex runtime description than simply O(N).

(Thanks to phsource for pointing out the error in the original answer.)

Getting value of selected item in list box as string

string textValue = ((ListBoxItem)listBox1.SelectedItem).Content.ToString();

Detect & Record Audio in Python

import pyaudio
import wave
from array import array

FORMAT=pyaudio.paInt16
CHANNELS=2
RATE=44100
CHUNK=1024
RECORD_SECONDS=15
FILE_NAME="RECORDING.wav"

audio=pyaudio.PyAudio() #instantiate the pyaudio

#recording prerequisites
stream=audio.open(format=FORMAT,channels=CHANNELS, 
                  rate=RATE,
                  input=True,
                  frames_per_buffer=CHUNK)

#starting recording
frames=[]

for i in range(0,int(RATE/CHUNK*RECORD_SECONDS)):
    data=stream.read(CHUNK)
    data_chunk=array('h',data)
    vol=max(data_chunk)
    if(vol>=500):
        print("something said")
        frames.append(data)
    else:
        print("nothing")
    print("\n")


#end of recording
stream.stop_stream()
stream.close()
audio.terminate()
#writing to file
wavfile=wave.open(FILE_NAME,'wb')
wavfile.setnchannels(CHANNELS)
wavfile.setsampwidth(audio.get_sample_size(FORMAT))
wavfile.setframerate(RATE)
wavfile.writeframes(b''.join(frames))#append frames recorded to file
wavfile.close()

I think this will help.It is a simple script which will check if there is a silence or not.If silence is detected it will not record otherwise it will record.

Addressing localhost from a VirtualBox virtual machine

On Windows with a virtual Windows 7 the only thing that worked for me was using NAT and port-forwarding (couldn't get bridged connection running). I found a tutorial here: http://www.howtogeek.com/122641/how-to-forward-ports-to-a-virtual-machine-and-use-it-as-a-server/ (scroll down to the part with "Forwarding Ports to a Virtual Machine").

With this changes I could reach the xampp website with "http://192.168.xx.x:8888/mywebsite" in internet explorer 10 on my virtual machine.

I found the IP in XAMPP Control Panel > Netstat ("System").

How to convert a datetime to string in T-SQL

This has been answered by a lot of people, but I feel like the simplest solution has been left out.

SQL SERVER (I believe its 2012+) has implicit string equivalents for DATETIME2 as shown here

Look at the section on "Supported string literal formats for datetime2"

To answer the OPs question explicitly:

DECLARE @myVar NCHAR(32)
DECLARE @myDt DATETIME2
SELECT @myVar = @GETDATE()
SELECT @myDt = @myVar
PRINT(@myVar)
PRINT(@myDt)

output:

Jan 23 2019 12:24PM             
2019-01-23 12:24:00.0000000

Note: The first variable (myVar) is actually holding the value '2019-01-23 12:24:00.0000000' as well. It just gets formatted to Jan 23 2019 12:24PM due to default formatting set for SQL SERVER that gets called on when you use PRINT. Don't get tripped up here by that, the actual string in (myVer) = '2019-01-23 12:24:00.0000000'

jQuery slide left and show

And if you want to vary the speed and include callbacks simply add them like this :

        jQuery.fn.extend({
            slideRightShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftHide: function(speed,callback) {
                return this.each(function() {
                    $(this).hide('slide', {direction: 'left'}, speed, callback);
                });
            },
            slideRightHide: function(speed,callback) {
                return this.each(function() {  
                    $(this).hide('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'left'}, speed, callback);
                });
            }
        });

The service cannot accept control messages at this time

I had this issue recently,

Problem statement: Mine was a windows service that I run locally by attaching VS debugger. When I stop debugging and try to restart/stop the service (under services.msc) I used to get the mentioned error.

Solution:

  1. Open up Task manager.
  2. Search for the service (based on the exe name and not service name, for those that are different).
  3. Kill the service.

On doing the above the service is stopped.

Generating random numbers with Swift

you can use this in specific rate:

let die = [1, 2, 3, 4, 5, 6]
 let firstRoll = die[Int(arc4random_uniform(UInt32(die.count)))]
 let secondRoll = die[Int(arc4random_uniform(UInt32(die.count)))]

Border in shape xml

If you want make a border in a shape xml. You need to use:

For the external border,you need to use:

<stroke/>

For the internal background,you need to use:

<solid/>

If you want to set corners,you need to use:

<corners/>

If you want a padding betwen border and the internal elements,you need to use:

<padding/>

Here is a shape xml example using the above items. It works for me

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="2dp" android:color="#D0CFCC" /> 
  <solid android:color="#F8F7F5" /> 
  <corners android:radius="10dp" />
  <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" />
</shape>

Set Content-Type to application/json in jsp file

You can do via Page directive.

For example:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

Automatically create an Enum based on values in a database lookup table?

Let's say you have the following in your DB:

table enums
-----------------
| id | name     |
-----------------
| 0  | MyEnum   |
| 1  | YourEnum |
-----------------

table enum_values
----------------------------------
| id | enums_id | value | key    |
----------------------------------
| 0  | 0        | 0     | Apple  |
| 1  | 0        | 1     | Banana |
| 2  | 0        | 2     | Pear   |
| 3  | 0        | 3     | Cherry |
| 4  | 1        | 0     | Red    |
| 5  | 1        | 1     | Green  |
| 6  | 1        | 2     | Yellow |
----------------------------------

Construct a select to get the values you need:

select * from enums e inner join enum_values ev on ev.enums_id=e.id where e.id=0

Construct the source code for the enum and you'll get something like:

String enumSourceCode = "enum " + enumName + "{" + enumKey1 + "=" enumValue1 + "," + enumKey2 + ... + "}";

(obviously this is constructed in a loop of some kind.)

Then comes the fun part, Compiling your enum and using it:

CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters cs = new CompilerParameters();
cp.GenerateInMemory = True;

CompilerResult result = provider.CompileAssemblyFromSource(cp, enumSourceCode);

Type enumType = result.CompiledAssembly.GetType(enumName);

Now you have the type compiled and ready for use.
To get a enum value stored in the DB you can use:

[Enum].Parse(enumType, value);

where value can be either the integer value (0, 1, etc.) or the enum text/key (Apple, Banana, etc.)

How to get the wsdl file from a webservice's URL

to get the WSDL (Web Service Description Language) from a Web Service URL.

Is possible from SOAP Web Services:

http://www.w3schools.com/xml/tempconvert.asmx

to get the WSDL we have only to add ?WSDL , for example:

http://www.w3schools.com/xml/tempconvert.asmx?WSDL

Confused by python file mode "w+"

The file is truncated, so you can call read() (no exceptions raised, unlike when opened using 'w') but you'll get an empty string.

C - gettimeofday for computing time?

If you want to measure code efficiency, or in any other way measure time intervals, the following will be easier:

#include <time.h>

int main()
{
   clock_t start = clock();
   //... do work here
   clock_t end = clock();
   double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
   return 0;
}

hth

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

This is the way JNA solves this with Platform.is64Bit() (https://github.com/java-native-access/jna/blob/master/src/com/sun/jna/Platform.java)

 public static final boolean is64Bit() {
        String model = System.getProperty("sun.arch.data.model",
                                          System.getProperty("com.ibm.vm.bitmode"));
        if (model != null) {
            return "64".equals(model);
        }
        if ("x86-64".equals(ARCH)
            || "ia64".equals(ARCH)
            || "ppc64".equals(ARCH) || "ppc64le".equals(ARCH)
            || "sparcv9".equals(ARCH)
            || "mips64".equals(ARCH) || "mips64el".equals(ARCH)
            || "amd64".equals(ARCH)
            || "aarch64".equals(ARCH)) {
            return true;
        }
        return Native.POINTER_SIZE == 8;
}

ARCH = getCanonicalArchitecture(System.getProperty("os.arch"), osType);

static String getCanonicalArchitecture(String arch, int platform) {
        arch = arch.toLowerCase().trim();
        if ("powerpc".equals(arch)) {
            arch = "ppc";
        }
        else if ("powerpc64".equals(arch)) {
            arch = "ppc64";
        }
        else if ("i386".equals(arch) || "i686".equals(arch)) {
            arch = "x86";
        }
        else if ("x86_64".equals(arch) || "amd64".equals(arch)) {
            arch = "x86-64";
        }
        // Work around OpenJDK mis-reporting os.arch
        // https://bugs.openjdk.java.net/browse/JDK-8073139
        if ("ppc64".equals(arch) && "little".equals(System.getProperty("sun.cpu.endian"))) {
            arch = "ppc64le";
        }
        // Map arm to armel if the binary is running as softfloat build
        if("arm".equals(arch) && platform == Platform.LINUX && isSoftFloat()) {
            arch = "armel";
        }

        return arch;
    }

static {
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Linux")) {
            if ("dalvik".equals(System.getProperty("java.vm.name").toLowerCase())) {
                osType = ANDROID;
                // Native libraries on android must be bundled with the APK
                System.setProperty("jna.nounpack", "true");
            }
            else {
                osType = LINUX;
            }
        }
        else if (osName.startsWith("AIX")) {
            osType = AIX;
        }
        else if (osName.startsWith("Mac") || osName.startsWith("Darwin")) {
            osType = MAC;
        }
        else if (osName.startsWith("Windows CE")) {
            osType = WINDOWSCE;
        }
        else if (osName.startsWith("Windows")) {
            osType = WINDOWS;
        }
        else if (osName.startsWith("Solaris") || osName.startsWith("SunOS")) {
            osType = SOLARIS;
        }
        else if (osName.startsWith("FreeBSD")) {
            osType = FREEBSD;
        }
        else if (osName.startsWith("OpenBSD")) {
            osType = OPENBSD;
        }
        else if (osName.equalsIgnoreCase("gnu")) {
            osType = GNU;
        }
        else if (osName.equalsIgnoreCase("gnu/kfreebsd")) {
            osType = KFREEBSD;
        }
        else if (osName.equalsIgnoreCase("netbsd")) {
            osType = NETBSD;
        }
        else {
            osType = UNSPECIFIED;
        }
}

RESTful URL design for search

For the searching, use querystrings. This is perfectly RESTful:

/cars?color=blue&type=sedan&doors=4

An advantage to regular querystrings is that they are standard and widely understood and that they can be generated from form-get.

Is there a way to take the first 1000 rows of a Spark Dataframe?

The method you are looking for is .limit.

Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.

Example usage:

df.limit(1000)

Why call super() in a constructor?

We can Access SuperClass members using super keyword

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

// Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass.
Printed in Subclass

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->

return .Cell(i,1) <> Empty

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Is it possible to output a SELECT statement from a PL/SQL block?

Cursors are used when your select query returns multiple rows. So, rather using cursor in case when you want aggregates or single rowdata you could use a procedure/function without cursor as well like

  Create Procedure sample(id 
    varchar2(20))as 
    Select count(*) into x from table 
    where 
       Userid=id;
     End ;

And then simply call the procedure

   Begin
   sample(20);
   End

This is the actual use of procedure/function mostly wrapping and storing queries that are complex or that requires repeated manipulation with same logic but different data

HTML anchor tag with Javascript onclick event

From what I understand you do not want to redirect when the link is clicked. You can do :

<a href='javascript:;' onclick='show_more_menu();'>More ></a>

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

FFmpeg does not write to a specific log file, but rather sends its output to standard error. To capture that, you need to either

  • capture and parse it as it is generated
  • redirect standard error to a file and read that afterward the process is finished

Example for std error redirection:

ffmpeg -i myinput.avi {a-bunch-of-important-params} out.flv 2> /path/to/out.txt

Once the process is done, you can inspect out.txt.

It's a bit trickier to do the first option, but it is possible. (I've done it myself. So have others. Have a look around SO and the net for details.)

SQL subquery with COUNT help

SELECT e.*,
       cnt.colCount 
FROM eventsTable e
INNER JOIN (
           select columnName,count(columnName) as colCount
           from eventsTable e2 
          group by columnName
           ) as cnt on cnt.columnName = e.columnName
WHERE e.columnName='Business'

-- Added space

How to extract a value from a string using regex and a shell?

You can do this with GNU grep's perl mode:

echo "12 BBQ ,45 rofl, 89 lol"|grep -P '\d+ (?=rofl)' -o

-P means Perl-style, and -o means match only.

How to Bootstrap navbar static to fixed on scroll?

Here is my implementation using the Affix Bootstrap plugin http://getbootstrap.com/javascript/#affix

It includes some extra affix problems solved (see below).

HTML:

<nav class="navbar navbar-inverse navbar-fixed-top" id="top_navbar">
  <div class="container-fluid">
... (typical Bootstrap top navbar)
  </div>
</div>

...
...
...

<div id="parent-navbar-main" >
  <div id="navbar-main">
... (here is your nav panel to get sticky on scroll)
  </div>
</div>

Javascript:

function set_sticky_panel()  {

  var affixElement = $('#navbar-main');

  var navbarElementHeight = $('#top_navbar').height();

// http://stackoverflow.com/questions/18683303/bootstrap-3-0-affix-with-list-changes-width
  var width = affixElement.parent().width();
  affixElement.width(width);

// http://stackoverflow.com/questions/3410765/get-full-height-of-element
  var affixElementHeight = $('#navbar-main').outerHeight(true);

// https://finiteheap.com/webdev/2014/12/26/bootstrap-affix-flickering.html  
  affixElement.parent().height(affixElementHeight);

// http://stackoverflow.com/questions/23797241/resetting-changing-the-offset-of-bootstrap-affix
  $(window).off('.affix')
  affixElement.removeData('bs.affix').removeClass('affix affix-top affix-bottom')


  affixElement.affix({
    offset: {
    // Distance of between element and top page
      top: function () {
      // how much scrolling is done until sticking the panel
        return (this.top = affixElement.offset().top - parseInt(navbarElementHeight,10))
      }
    }
  });

  // The replacement for the css-file.
  affixElement.on('affix.bs.affix', function (){
  // the absolute position where the sticked panel is to be placed when the fixing event fires (e.g. the panel reached the top of the page).
    affixElement.css('top', navbarElementHeight + 'px');
    affixElement.css('z-index', 10);
  });

}

$(document).on('ready', set_sticky_panel);

$(window).resize(set_sticky_panel);

CSS:

No css is required.

If to compare with the standart implementation my code additionaly solves these problems:

  1. The width of the sticky panel does not break at the fixing event anymore.
  2. The need in the CSS-file usage is eliminated.
  3. Reformatting the sticky panel size on the window change size event (responsiveness) is done now.
  4. No more affix flittering / jumping at the fixing event.

Close Android Application

You could close your Android Application by calling System.exit(0).

How to switch activity without animation in Android?

The line in the theme style works fine, yet that replaces the animation with a white screen. Especially on a slower phone - it is really annoying. So, if you want an instant transition - you could use this in the theme style:

<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

As an alternative you may want to check out BridgeIt at bridgeit.mobi. Open source, it has resolved the browser performance / consistency issue discussed above in that it leverages the standard browser on the device vs. the web-view browser. It also allows you to access the native features without having to worry about app store deployments and/or native containers.

I've used if for simple camera based access and scanner access and it works well for simple apps. Documentation is a bit light. Not sure how it would do on more complex apps.

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

Pointer arithmetic for void pointer in C

cast it to a char pointer an increment your pointer forward x bytes ahead.

Shortcut to open file in Vim

Use tabs, they work when inputting file paths in vim escape mode!

How do I get a list of installed CPAN modules?

Here's a really hacky way to do it in *nix, you'll get some stuff you don't really care about (ie: warnings::register etc), but it should give you a list of every .pm file that's accessible via perl.


for my $path (@INC) {
    my @list = `ls -R $path/**/*.pm`;
    for (@list) {
        s/$path\///g;
        s/\//::/g;
        s/\.pm$//g;
        print;
    }
}

How do I look inside a Python object?

Try ppretty

from ppretty import ppretty


class A(object):
    s = 5

    def __init__(self):
        self._p = 8

    @property
    def foo(self):
        return range(10)


print ppretty(A(), indent='    ', depth=2, width=30, seq_length=6,
              show_protected=True, show_private=False, show_static=True,
              show_properties=True, show_address=True)

Output:

__main__.A at 0x1debd68L (
    _p = 8, 
    foo = [0, 1, 2, ..., 7, 8, 9], 
    s = 5
)

Javascript - Open a given URL in a new tab by clicking a button

Use window.open instead of window.location to open a new window or tab (depending on browser settings).

Your fiddle does not work because there is no button element to select. Try input[type=button] or give the button an id and use #buttonId.

How to clear radio button in Javascript?

YES<input type="radio" name="group1" id="sal" value="YES" >

NO<input type="radio" name="group1" id="sal1" value="NO" >

<input type="button" onclick="document.getElementById('sal').checked=false;document.getElementById('sal1').checked=false">

c# write text on bitmap

If you want wrap your text, then you should draw your text in a rectangle:

RectangleF rectF1 = new RectangleF(30, 10, 100, 122);
e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1);

See: https://msdn.microsoft.com/en-us/library/baw6k39s(v=vs.110).aspx

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

You can track all calls to [ASIdentifierManager advertisingIdentifier] with symbolic breakpoint in Xcode: enter image description here

concatenate two strings

You need to use the string concatenation operator +

String both = name + "-" + dest;

How do I change JPanel inside a JFrame on the fly?

It all depends on how its going to be used. If you will want to switch back and forth between these two panels then use a CardLayout. If you are only switching from the first to the second once and (and not going back) then I would use telcontars suggestion and just replace it. Though if the JPanel isn't the only thing in your frame I would use remove(java.awt.Component) instead of removeAll.

If you are somewhere in between these two cases its basically a time-space tradeoff. The CardLayout will save you time but take up more memory by having to keep this whole other panel in memory at all times. But if you just replace the panel when needed and construct it on demand, you don't have to keep that meory around but it takes more time to switch.

Also you can try a JTabbedPane to use tabs instead (its even easier than CardLayout because it handles the showing/hiding automitically)

Cannot GET / Nodejs Error

Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js

node_modules/
app/
  index.html
  server.js

After printing out the __dirname path, I realized that the __dirname path was where my server was running (app/).

So, the answer to your question is this:

If your server.js file is in the same folder as the files you are trying to render, then

app.use( express.static( path.join( application_root, 'site') ) );

should actually be

app.use(express.static(application_root));

The only time you would want to use the original syntax that you had would be if you had a folder tree like so:

app/
  index.html
node_modules
server.js

where index.html is in the app/ directory, whereas server.js is in the root directory (i.e. the same level as the app/ directory).

Side note: Intead of calling the path utility, you can use the syntax application_root + 'site' to join a path.

Overall, your code could look like:

// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration

//Create server
var app = express();

// Configure server
app.configure( function() {

    //Don't change anything here...

    //Where to serve static content
    app.use( express.static( application_root ) );

    //Nothing changes here either...
});

//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
    console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});

Force update of an Android app when a new version is available

try this: First you need to make a request call to the playstore link, fetch current version from there and then compare it with your current version.

String currentVersion, latestVersion;
Dialog dialog;
private void getCurrentVersion(){
 PackageManager pm = this.getPackageManager();
        PackageInfo pInfo = null;

        try {
            pInfo =  pm.getPackageInfo(this.getPackageName(),0);

        } catch (PackageManager.NameNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        currentVersion = pInfo.versionName;

   new GetLatestVersion().execute();

}

private class GetLatestVersion extends AsyncTask<String, String, JSONObject> {

        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected JSONObject doInBackground(String... params) {
            try {
//It retrieves the latest version by scraping the content of current version from play store at runtime
                Document doc = Jsoup.connect(urlOfAppFromPlayStore).get();
                latestVersion = doc.getElementsByClass("htlgb").get(6).text();

            }catch (Exception e){
                e.printStackTrace();

            }

            return new JSONObject();
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            if(latestVersion!=null) {
                if (!currentVersion.equalsIgnoreCase(latestVersion)){
                   if(!isFinishing()){ //This would help to prevent Error : BinderProxy@45d459c0 is not valid; is your activity running? error
                    showUpdateDialog();
                    }
                }
            }
            else
                background.start();
            super.onPostExecute(jsonObject);
        }
    }

private void showUpdateDialog(){
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("A New Update is Available");
        builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse
                        ("market://details?id=yourAppPackageName")));
                dialog.dismiss();
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                background.start();
            }
        });

        builder.setCancelable(false);
        dialog = builder.show();
    }

How does origin/HEAD get set?

Note first that your question shows a bit of misunderstanding. origin/HEAD represents the default branch on the remote, i.e. the HEAD that's in that remote repository you're calling origin. When you switch branches in your repo, you're not affecting that. The same is true for remote branches; you might have master and origin/master in your repo, where origin/master represents a local copy of the master branch in the remote repository.

origin's HEAD will only change if you or someone else actually changes it in the remote repository, which should basically never happen - you want the default branch a public repo to stay constant, on the stable branch (probably master). origin/HEAD is a local ref representing a local copy of the HEAD in the remote repository. (Its full name is refs/remotes/origin/HEAD.)

I think the above answers what you actually wanted to know, but to go ahead and answer the question you explicitly asked... origin/HEAD is set automatically when you clone a repository, and that's about it. Bizarrely, that it's not set by commands like git remote update - I believe the only way it will change is if you manually change it. (By change I mean point to a different branch; obviously the commit it points to changes if that branch changes, which might happen on fetch/pull/remote update.)


Edit: The problem discussed below was corrected in Git 1.8.4.3; see this update.


There is a tiny caveat, though. HEAD is a symbolic ref, pointing to a branch instead of directly to a commit, but the git remote transfer protocols only report commits for refs. So Git knows the SHA1 of the commit pointed to by HEAD and all other refs; it then has to deduce the value of HEAD by finding a branch that points to the same commit. This means that if two branches happen to point there, it's ambiguous. (I believe it picks master if possible, then falls back to first alphabetically.) You'll see this reported in the output of git remote show origin:

$ git remote show origin
* remote origin
  Fetch URL: ...
  Push  URL: ...
  HEAD branch (remote HEAD is ambiguous, may be one of the following):
    foo
    master

Oddly, although the notion of HEAD printed this way will change if things change on the remote (e.g. if foo is removed), it doesn't actually update refs/remotes/origin/HEAD. This can lead to really odd situations. Say that in the above example origin/HEAD actually pointed to foo, and origin's foo branch was then removed. We can then do this:

$ git remote show origin
...
HEAD branch: master
$ git symbolic-ref refs/remotes/origin/HEAD
refs/remotes/origin/foo
$ git remote update --prune origin
Fetching origin
 x [deleted]         (none)     -> origin/foo
   (refs/remotes/origin/HEAD has become dangling)

So even though remote show knows HEAD is master, it doesn't update anything. The stale foo branch is correctly pruned, and HEAD becomes dangling (pointing to a nonexistent branch), and it still doesn't update it to point to master. If you want to fix this, use git remote set-head origin -a, which automatically determines origin's HEAD as above, and then actually sets origin/HEAD to point to the appropriate remote branch.

How to open warning/information/error dialog in Swing?

JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....

Have a look on this tutorial on how to make dialogs.

How to check the multiple permission at single request in Android M?

As said earlier, currently every permission group has own permission dialog which must be called separately.

You will have different dialog boxes for each permission group but you can surely check the result together in onRequestPermissionsResult() callback method.

Here is a working example link, may be useful for someone.

How do I copy SQL Azure database to my local development server?

Now you can use the SQL Server Management Studio to do this.

  • Connect to the SQL Azure database.
  • Right click the database in Object Explorer.
  • Choose the option "Tasks" / "Deploy Database to SQL Azure".
  • In the step named "Deployment Settings", select your local database connection.
  • "Next" / "Next" / "Finish"...

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

It seems you are connecting to the wrong database. R u sure "jdbc:postgresql://localhost/testDB" will connect you to the actual datasource ?

Generally they are of the form "jdbc://hostname/databasename". Look into Postgresql log file.

enable or disable checkbox in html

In jsp you can do it like this:

<%
boolean checkboxDisabled = true; //do your logic here
String checkboxState = checkboxDisabled ? "disabled" : "";
%>
<input type="checkbox" <%=checkboxState%>>

Fill formula down till last row in column

Alternatively, you may use FillDown

Range("M3") = "=G3&"",""&L3": Range("M3:M" & LastRow).FillDown

MySQL date format DD/MM/YYYY select query?

If the hour is important, I used str_to_date(date, '%d/%m/%Y %T' ), the %T shows the hour in the format hh:mm:ss.

When to use Interface and Model in TypeScript / Angular

Use Class instead of Interface that is what I discovered after all my research.

Why? A class alone is less code than a class-plus-interface. (anyway you may require a Class for data model)

Why? A class can act as an interface (use implements instead of extends).

Why? An interface-class can be a provider lookup token in Angular dependency injection.

from Angular Style Guide

Basically a Class can do all, what an Interface will do. So may never need to use an Interface.

Reading a string with spaces with sscanf

I guess this is what you want, it does exactly what you specified.

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char** argv) {
    int age;
    char* buffer;
    buffer = malloc(200 * sizeof(char));
    sscanf("19 cool kid", "%d cool %s", &age, buffer);
    printf("cool %s is %d years old\n", buffer, age);
    return 0;
}

The format expects: first a number (and puts it at where &age points to), then whitespace (zero or more), then the literal string "cool", then whitespace (zero or more) again, and then finally a string (and put that at whatever buffer points to). You forgot the "cool" part in your format string, so the format then just assumes that is the string you were wanting to assign to buffer. But you don't want to assign that string, only skip it.

Alternative, you could also have a format string like: "%d %s %s", but then you must assign another buffer for it (with a different name), and print it as: "%s %s is %d years old\n".

Remove header and footer from window.print()

 <html>
<head>
    <title>Print</title>
    <script type="text/javascript">
window.print();
document.margin='none';
</script>
</head>
<body>
  <p>hello</p>
  <p>hi</p>
</body>
</html>

//place it in a script file or in the script tag.

This will remove all the margins and you won't be able to see the headers and footers.

Evaluating a mathematical expression in a string

eval is evil

eval("__import__('os').remove('important file')") # arbitrary commands
eval("9**9**9**9**9**9**9**9", {'__builtins__': None}) # CPU, memory

Note: even if you use set __builtins__ to None it still might be possible to break out using introspection:

eval('(1).__class__.__bases__[0].__subclasses__()', {'__builtins__': None})

Evaluate arithmetic expression using ast

import ast
import operator as op

# supported operators
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
             ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
             ast.USub: op.neg}

def eval_expr(expr):
    """
    >>> eval_expr('2^6')
    4
    >>> eval_expr('2**6')
    64
    >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
    -5.0
    """
    return eval_(ast.parse(expr, mode='eval').body)

def eval_(node):
    if isinstance(node, ast.Num): # <number>
        return node.n
    elif isinstance(node, ast.BinOp): # <left> <operator> <right>
        return operators[type(node.op)](eval_(node.left), eval_(node.right))
    elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
        return operators[type(node.op)](eval_(node.operand))
    else:
        raise TypeError(node)

You can easily limit allowed range for each operation or any intermediate result, e.g., to limit input arguments for a**b:

def power(a, b):
    if any(abs(n) > 100 for n in [a, b]):
        raise ValueError((a,b))
    return op.pow(a, b)
operators[ast.Pow] = power

Or to limit magnitude of intermediate results:

import functools

def limit(max_=None):
    """Return decorator that limits allowed returned values."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            ret = func(*args, **kwargs)
            try:
                mag = abs(ret)
            except TypeError:
                pass # not applicable
            else:
                if mag > max_:
                    raise ValueError(ret)
            return ret
        return wrapper
    return decorator

eval_ = limit(max_=10**100)(eval_)

Example

>>> evil = "__import__('os').remove('important file')"
>>> eval_expr(evil) #doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:
>>> eval_expr("9**9")
387420489
>>> eval_expr("9**9**9**9**9**9**9**9") #doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError:

Can we pass parameters to a view in SQL?

we can write a stored procedure with input parameters and then use that stored procedure to get a result set from the view. see example below.

the stored procedure is

CREATE PROCEDURE [dbo].[sp_Report_LoginSuccess] -- [sp_Report_LoginSuccess] '01/01/2010','01/30/2010'
@fromDate datetime,
@toDate datetime,
@RoleName varchar(50),
@Success int
as
If @RoleName != 'All'
Begin
   If @Success!=2
   Begin
   --fetch based on true or false
  Select * from vw_Report_LoginSuccess
  where logindatetime between  dbo.DateFloor(@fromDate) and dbo.DateSieling(@toDate)
  And RTrim(Upper(RoleName)) = RTrim(Upper(@RoleName)) and Success=@Success
   End
   Else
   Begin
    -- fetch all
  Select * from vw_Report_LoginSuccess
  where logindatetime between  dbo.DateFloor(@fromDate) and dbo.DateSieling(@toDate)
  And RTrim(Upper(RoleName)) = RTrim(Upper(@RoleName))
   End

End
Else
Begin
   If @Success!=2
   Begin
  Select * from vw_Report_LoginSuccess
  where logindatetime between  dbo.DateFloor(@fromDate) and dbo.DateSieling(@toDate)
  and Success=@Success
 End
 Else
 Begin
  Select * from vw_Report_LoginSuccess
  where logindatetime between  dbo.DateFloor(@fromDate) and dbo.DateSieling(@toDate)
 End

End

and the view from which we can get the result set is

CREATE VIEW [dbo].[vw_Report_LoginSuccess]
AS
SELECT     '3' AS UserDetailID, dbo.tblLoginStatusDetail.Success, CONVERT(varchar, dbo.tblLoginStatusDetail.LoginDateTime, 101) AS LoginDateTime,
                      CONVERT(varchar, dbo.tblLoginStatusDetail.LogoutDateTime, 101) AS LogoutDateTime, dbo.tblLoginStatusDetail.TokenID,
                      dbo.tblUserDetail.SubscriberID, dbo.aspnet_Roles.RoleId, dbo.aspnet_Roles.RoleName
FROM         dbo.tblLoginStatusDetail INNER JOIN
                      dbo.tblUserDetail ON dbo.tblLoginStatusDetail.UserDetailID = dbo.tblUserDetail.UserDetailID INNER JOIN
                      dbo.aspnet_UsersInRoles ON dbo.tblUserDetail.UserID = dbo.aspnet_UsersInRoles.UserId INNER JOIN
                      dbo.aspnet_Roles ON dbo.aspnet_UsersInRoles.RoleId = dbo.aspnet_Roles.RoleId
WHERE     (dbo.tblLoginStatusDetail.Success = 0)
UNION all
SELECT     dbo.tblLoginStatusDetail.UserDetailID, dbo.tblLoginStatusDetail.Success, CONVERT(varchar, dbo.tblLoginStatusDetail.LoginDateTime, 101)
                      AS LoginDateTime, CONVERT(varchar, dbo.tblLoginStatusDetail.LogoutDateTime, 101) AS LogoutDateTime, dbo.tblLoginStatusDetail.TokenID,
                      dbo.tblUserDetail.SubscriberID, dbo.aspnet_Roles.RoleId, dbo.aspnet_Roles.RoleName
FROM         dbo.tblLoginStatusDetail INNER JOIN
                      dbo.tblUserDetail ON dbo.tblLoginStatusDetail.UserDetailID = dbo.tblUserDetail.UserDetailID INNER JOIN
                      dbo.aspnet_UsersInRoles ON dbo.tblUserDetail.UserID = dbo.aspnet_UsersInRoles.UserId INNER JOIN
                      dbo.aspnet_Roles ON dbo.aspnet_UsersInRoles.RoleId = dbo.aspnet_Roles.RoleId
WHERE     (dbo.tblLoginStatusDetail.Success = 1) AND (dbo.tblUserDetail.SubscriberID LIKE N'P%')  

Weird PHP error: 'Can't use function return value in write context'

Correct syntax (you had a missing parentheses in the end):

if (isset($_POST['sms_code']) == TRUE ) {
                            ^

p.s. you dont need == TRUE part, because BOOLEAN (true/false) is returned already.

How to fix "unable to open stdio.h in Turbo C" error?

Just Re install the turbo C++ from your Computer and install again in the Directory C:\TC\ Folder.

Again The Problem exists ,then change the directory from FILE>>CHANGE DIRECTORY to C:\TC\BIN\

Is there a way to list all resources in AWS

I think this may help! Here, you need to enter the region name and you have to configure AWS CLI before try this.

aws resourcegroupstaggingapi get-resources --region region_name

It will list all the recourses in the region by the following format.

- ResourceARN: arn:aws:cloudformation:eu-west-1:5524534535:stack/auction-services-dev/*******************************
  Tags:
  - Key: STAGE
    Value: dev
- ResourceARN: arn:aws:cloudformation:eu-west-1:********************
Tags:
-- More  --

how to align img inside the div to the right?

<div style="width:300px; text-align:right;">
        <img src="someimgage.gif">
</div>

How to get numeric position of alphabets in java?

Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.

This sounds like homework. If so, please tag it as such.

Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.

Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.

How do you Change a Package's Log Level using Log4j?

I just encountered the issue and couldn't figure out what was going wrong even after reading all the above and everything out there. What I did was

  1. Set root logger level to WARN
  2. Set package log level to DEBUG

Each logging implementation has it's own way of setting it via properties or via code(lot of help available on this)

Irrespective of all the above I would not get the logs in my console or my log file. What I had overlooked was the below...


enter image description here


All I was doing with the above jugglery was controlling only the production of the logs(at root/package/class etc), left of the red line in above image. But I was not changing the way displaying/consumption of the logs of the same, right of the red line in above image. Handler(Consumption) is usually defaulted at INFO, therefore your precious debug statements wouldn't come through. Consumption/displaying is controlled by setting the log levels for the Handlers(ConsoleHandler/FileHandler etc..) So I went ahead and set the log levels of all my handlers to finest and everything worked.

This point was not made clear in a precise manner in any place.

I hope someone scratching their head, thinking why the properties are not working will find this bit helpful.

node.js require all files in a folder?

Can use : https://www.npmjs.com/package/require-file-directory

  • Require selected files with name only or all files.
  • No need of absoulute path.
  • Easy to understand and use.

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

Generally you should also override hashCode() each time you override equals(), even if just for the performance boost. HashCode() decides which 'bucket' your object gets sorted into when doing a comparison, so any two objects which equal() evaluates to true should return the same hashCode value(). I cannot remember the default behavior of hashCode() (if it returns 0 then your code should work but slowly, but if it returns the address then your code will fail). I do remember a bunch of times when my code failed because I forgot to override hashCode() though. :)

How to get a path to a resource in a Java JAR file

You need to understand the path within the jar file.
Simply refer to it relative. So if you have a file (myfile.txt), located in foo.jar under the \src\main\resources directory (maven style). You would refer to it like:

src/main/resources/myfile.txt

If you dump your jar using jar -tvf myjar.jar you will see the output and the relative path within the jar file, and use the FORWARD SLASHES.

Split (explode) pandas dataframe string entry to separate rows

UPDATE2: more generic vectorized function, which will work for multiple normal and multiple list columns

def explode(df, lst_cols, fill_value='', preserve_index=False):
    # make sure `lst_cols` is list-alike
    if (lst_cols is not None
        and len(lst_cols) > 0
        and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):
        lst_cols = [lst_cols]
    # all columns except `lst_cols`
    idx_cols = df.columns.difference(lst_cols)
    # calculate lengths of lists
    lens = df[lst_cols[0]].str.len()
    # preserve original index values    
    idx = np.repeat(df.index.values, lens)
    # create "exploded" DF
    res = (pd.DataFrame({
                col:np.repeat(df[col].values, lens)
                for col in idx_cols},
                index=idx)
             .assign(**{col:np.concatenate(df.loc[lens>0, col].values)
                            for col in lst_cols}))
    # append those rows that have empty lists
    if (lens == 0).any():
        # at least one list in cells is empty
        res = (res.append(df.loc[lens==0, idx_cols], sort=False)
                  .fillna(fill_value))
    # revert the original index order
    res = res.sort_index()
    # reset index if requested
    if not preserve_index:        
        res = res.reset_index(drop=True)
    return res

Demo:

Multiple list columns - all list columns must have the same # of elements in each row:

In [134]: df
Out[134]:
   aaa  myid        num          text
0   10     1  [1, 2, 3]  [aa, bb, cc]
1   11     2         []            []
2   12     3     [1, 2]      [cc, dd]
3   13     4         []            []

In [135]: explode(df, ['num','text'], fill_value='')
Out[135]:
   aaa  myid num text
0   10     1   1   aa
1   10     1   2   bb
2   10     1   3   cc
3   11     2
4   12     3   1   cc
5   12     3   2   dd
6   13     4

preserving original index values:

In [136]: explode(df, ['num','text'], fill_value='', preserve_index=True)
Out[136]:
   aaa  myid num text
0   10     1   1   aa
0   10     1   2   bb
0   10     1   3   cc
1   11     2
2   12     3   1   cc
2   12     3   2   dd
3   13     4

Setup:

df = pd.DataFrame({
 'aaa': {0: 10, 1: 11, 2: 12, 3: 13},
 'myid': {0: 1, 1: 2, 2: 3, 3: 4},
 'num': {0: [1, 2, 3], 1: [], 2: [1, 2], 3: []},
 'text': {0: ['aa', 'bb', 'cc'], 1: [], 2: ['cc', 'dd'], 3: []}
})

CSV column:

In [46]: df
Out[46]:
        var1  var2 var3
0      a,b,c     1   XX
1  d,e,f,x,y     2   ZZ

In [47]: explode(df.assign(var1=df.var1.str.split(',')), 'var1')
Out[47]:
  var1  var2 var3
0    a     1   XX
1    b     1   XX
2    c     1   XX
3    d     2   ZZ
4    e     2   ZZ
5    f     2   ZZ
6    x     2   ZZ
7    y     2   ZZ

using this little trick we can convert CSV-like column to list column:

In [48]: df.assign(var1=df.var1.str.split(','))
Out[48]:
              var1  var2 var3
0        [a, b, c]     1   XX
1  [d, e, f, x, y]     2   ZZ

UPDATE: generic vectorized approach (will work also for multiple columns):

Original DF:

In [177]: df
Out[177]:
        var1  var2 var3
0      a,b,c     1   XX
1  d,e,f,x,y     2   ZZ

Solution:

first let's convert CSV strings to lists:

In [178]: lst_col = 'var1' 

In [179]: x = df.assign(**{lst_col:df[lst_col].str.split(',')})

In [180]: x
Out[180]:
              var1  var2 var3
0        [a, b, c]     1   XX
1  [d, e, f, x, y]     2   ZZ

Now we can do this:

In [181]: pd.DataFrame({
     ...:     col:np.repeat(x[col].values, x[lst_col].str.len())
     ...:     for col in x.columns.difference([lst_col])
     ...: }).assign(**{lst_col:np.concatenate(x[lst_col].values)})[x.columns.tolist()]
     ...:
Out[181]:
  var1  var2 var3
0    a     1   XX
1    b     1   XX
2    c     1   XX
3    d     2   ZZ
4    e     2   ZZ
5    f     2   ZZ
6    x     2   ZZ
7    y     2   ZZ

OLD answer:

Inspired by @AFinkelstein solution, i wanted to make it bit more generalized which could be applied to DF with more than two columns and as fast, well almost, as fast as AFinkelstein's solution):

In [2]: df = pd.DataFrame(
   ...:    [{'var1': 'a,b,c', 'var2': 1, 'var3': 'XX'},
   ...:     {'var1': 'd,e,f,x,y', 'var2': 2, 'var3': 'ZZ'}]
   ...: )

In [3]: df
Out[3]:
        var1  var2 var3
0      a,b,c     1   XX
1  d,e,f,x,y     2   ZZ

In [4]: (df.set_index(df.columns.drop('var1',1).tolist())
   ...:    .var1.str.split(',', expand=True)
   ...:    .stack()
   ...:    .reset_index()
   ...:    .rename(columns={0:'var1'})
   ...:    .loc[:, df.columns]
   ...: )
Out[4]:
  var1  var2 var3
0    a     1   XX
1    b     1   XX
2    c     1   XX
3    d     2   ZZ
4    e     2   ZZ
5    f     2   ZZ
6    x     2   ZZ
7    y     2   ZZ

getMinutes() 0-9 - How to display two digit numbers?

Using ECMAScript Internationalization API, more info:

const twoDigitMinutes = date.toLocaleString('en-us', { minute: '2-digit' });

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.

The full shortcut target is:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

So I put the following at the start of my script and it seemed to function as expected:

. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto

Notes:

  • Has to be run in 64bit PS
  • This was tested on a server with just the Management Tools installed. It automatically connected to our existing Exchange infrastructure.
  • No extensive testing has been done, so I do not know if this method is viable. I will edit this post if I run into any issues.

How can I scale an entire web page with CSS?

This is a rather late answer, but you can use

body {
   transform: scale(1.1);
   transform-origin: 0 0;
   // add prefixed versions too.
}

to zoom the page by 110%. Although the zoom style is there, Firefox still does not support it sadly.

Also, this is slightly different than your zoom. The css transform works like an image zoom, so it will enlarge your page but not cause reflow, etc.


Edit updated the transform origin.

Heap space out of memory

Are you keeping references to variables that you no longer need (e.g. data from the previous simulations)? If so, you have a memory leak. You just need to find where that is happening and make sure that you remove the references to the variables when they are no longer needed (this would automatically happen if they go out of scope).

If you actually need all that data from previous simulations in memory, you need to increase the heap size or change your algorithm.

How can I specify the default JVM arguments for programs I run from eclipse?

As far as I know there is no option to create global configuration for java applications. You always create a duplicate of the configuration.

enter image description here

Also, if you are using PDE (for plugin development), you can create target platform using windows -> Preferences -> Plug-in development -> Target Platform. Edit has options for program/vm arguments.

Hope this helps

How can I convert spaces to tabs in Vim or Linux?

Simple Python Script:

import os

SOURCE_ROOT = "ROOT DIRECTORY - WILL CONVERT ALL UNDERNEATH"

for root, dirs, files in os.walk(SOURCE_ROOT):
    for f in files:
        fpath = os.path.join(root,f)
        assert os.path.exists(fpath)
        data = open(fpath, "r").read()
        data = data.replace("    ", "\t")
        outfile = open(fpath, "w")
        outfile.write(data)
        outfile.close()

git ignore vim temporary files

If You are using source control. vim temp files are quite useless.
So You might want to configure vim not to create them.

Just edit Your ~/.vimrc and add these lines:

set nobackup
set noswapfile

Programmatically generate video or animated GIF in Python?

With windows7, python2.7, opencv 3.0, the following works for me:

import cv2
import os

vvw           =   cv2.VideoWriter('mymovie.avi',cv2.VideoWriter_fourcc('X','V','I','D'),24,(640,480))
frameslist    =   os.listdir('.\\frames')
howmanyframes =   len(frameslist)
print('Frames count: '+str(howmanyframes)) #just for debugging

for i in range(0,howmanyframes):
    print(i)
    theframe = cv2.imread('.\\frames\\'+frameslist[i])
    vvw.write(theframe)

Java ArrayList replace at specific index

Use the set() method: see doc

arraylist.set(index,newvalue);

jQuery Ajax error handling, show custom exception messages

This function basically generates unique random API key's and in case if it doesn't then pop-up dialog box with error message appears

In View Page:

<div class="form-group required">
    <label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
    <div class="col-sm-6">
        <input type="text" class="apivalue"  id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />                                                                    
        <button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
    </div>
</div>

<script>
$(document).ready(function(){
    $('.changeKey1').click(function(){
          debugger;
        $.ajax({
                url  :"index.php?route=account/apiaccess/regenerate",
                type :'POST',
                dataType: "json",
                async:false,
                contentType: "application/json; charset=utf-8",
                success: function(data){
                  var result =  data.sync_id.toUpperCase();
                        if(result){
                          $('#api_text').val(result);
                        }
                  debugger;
                  },
                error: function(xhr, ajaxOptions, thrownError) {
                  alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                }

        });
    });
  });
</script>

From Controller:

public function regenerate(){
    $json = array();
    $api_key = substr(md5(rand(0,100).microtime()), 0, 12);
    $json['sync_id'] = $api_key; 
    $json['message'] = 'Successfully API Generated';
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}

The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:

Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

Postman: How to make multiple requests at the same time

I guess there's no such feature in postman as to run concurrent tests.

If i were you i would consider Apache jMeter which is used exactly for such scenarios.

Regarding Postman, the only thing that could more or less meet your needs is - Postman Runner. enter image description here There you can specify the details:

  • number of iterations,
  • upload csv file with data for different test runs, etc.

The runs won't be concurrent, only consecutive.

Hope that helps. But do consider jMeter (you'll love it).

How can I check for "undefined" in JavaScript?

Update 2018-07-25

It's been nearly five years since this post was first made, and JavaScript has come a long way. In repeating the tests in the original post, I found no consistent difference between the following test methods:

  • abc === undefined
  • abc === void 0
  • typeof abc == 'undefined'
  • typeof abc === 'undefined'

Even when I modified the tests to prevent Chrome from optimizing them away, the differences were insignificant. As such, I'd now recommend abc === undefined for clarity.

Relevant content from chrome://version:

  • Google Chrome: 67.0.3396.99 (Official Build) (64-bit) (cohort: Stable)
  • Revision: a337fbf3c2ab8ebc6b64b0bfdce73a20e2e2252b-refs/branch-heads/3396@{#790}
  • OS: Windows
  • JavaScript: V8 6.7.288.46
  • User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36

Original post 2013-11-01

In Google Chrome, the following was ever so slightly faster than a typeof test:

if (abc === void 0) {
    // Undefined
}

The difference was negligible. However, this code is more concise, and clearer at a glance to someone who knows what void 0 means. Note, however, that abc must still be declared.

Both typeof and void were significantly faster than comparing directly against undefined. I used the following test format in the Chrome developer console:

var abc;
start = +new Date();
for (var i = 0; i < 10000000; i++) {
    if (TEST) {
        void 1;
    }
}
end = +new Date();
end - start;

The results were as follows:

Test: | abc === undefined      abc === void 0      typeof abc == 'undefined'
------+---------------------------------------------------------------------
x10M  |     13678 ms               9854 ms                 9888 ms
  x1  |    1367.8 ns              985.4 ns                988.8 ns

Note that the first row is in milliseconds, while the second row is in nanoseconds. A difference of 3.4 nanoseconds is nothing. The times were pretty consistent in subsequent tests.

Disable and enable buttons in C#

button2.Enabled == true ;

should be

button2.Enabled = true ;

How to use ternary operator in razor (specifically on HTML attributes)?

I have a field named IsActive in table rows that's True when an item has been deleted. This code applies a CSS class named strikethrough only to deleted items. You can see how it uses the C# Ternary Operator:

<tr class="@(@businesstypes.IsActive ? "" : "strikethrough")">

How can I find matching values in two arrays?

Done as a answer so I can do formatting...

This is the the process you need to go through. Looping through an array for the specifics.

create an empty array
loop through array1, element by element. {
  loop through array2, element by element {
    if array1.element == array2.element {
      add to your new array
    }
  }
}

Boolean checking in the 'if' condition

This is more readable and good practice too.

if(!status){
//do sth
}else{
//do sth
}

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        HTMLParser.__init__(self)
        if output_list is None:
            self.output_list = []
        else:
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.output_list.append(dict(attrs).get('href'))

Test:

>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

How to pass a null variable to a SQL Stored Procedure from C#.net code

Use DBNull.Value Better still, make your stored procedure parameters have defaults of NULL. Or use a Nullable<DateTime> parameter if the parameter will sometimes be a valid DateTime object

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

Rails 3: I want to list all paths defined in my rails application

rake routes | grep <specific resource name>

displays resource specific routes, if it is a pretty long list of routes.

Multiple modals overlay

When solving Stacking modals scrolls the main page when one is closed i found that newer versions of Bootstrap (at least since version 3.0.3) do not require any additional code to stack modals.

You can add more than one modal (of course having a different ID) to your page. The only issue found when opening more than one modal will be that closing one remove the modal-open class for the body selector.

You can use the following Javascript code to re-add the modal-open :

$('.modal').on('hidden.bs.modal', function (e) {
    if($('.modal').hasClass('in')) {
    $('body').addClass('modal-open');
    }    
});

In the case that do not need the backdrop effect for the stacked modal you can set data-backdrop="false".

Version 3.1.1. fixed Fix modal backdrop overlaying the modal's scrollbar, but the above solution seems also to work with earlier versions.

How to add/subtract dates with JavaScript?

You can use the native javascript Date object to keep track of dates. It will give you the current date, let you keep track of calendar specific stuff and even help you manage different timezones. You can add and substract days/hours/seconds to change the date you are working with or to calculate new dates.

take a look at this object reference to learn more:

Date

Hope that helps!

Spring Boot application can't resolve the org.springframework.boot package

I have this problem when using STS. After edited something, I see that, some workspaces when create a project will happen this problem, and others will not. So I just create a new project in workspaces will not happen.

What does "hard coded" mean?

Scenario

In a college there are many students doing different courses, and after an examination we have to prepare a marks card showing grade. I can calculate grade two ways

1. I can write some code like this

    if(totalMark <= 100 && totalMark > 90) { grade = "A+"; }
    else if(totalMark <= 90 && totalMark > 80) { grade = "A"; }
    else if(totalMark <= 80 && totalMark > 70) { grade = "B"; }
    else if(totalMark <= 70 && totalMark > 60) { grade = "C"; }

2. You can ask user to enter grade definition some where and save that data

Something like storing into a database table enter image description here

In the first case the grade is common for all the courses and if the rule changes the code needs to be changed. But for second case we are giving user the provision to enter grade based on their requirement. So the code will be not be changed when the grade rules changes.

That's the important thing when you give more provision for users to define business logic. The first case is nothing but Hard Coding.

So in your question if you ask the user to enter the path of the file at the start, then you can remove the hard coded path in your code.

Get yesterday's date using Date

You can do following:

private Date getMeYesterday(){
     return new Date(System.currentTimeMillis()-24*60*60*1000);
}

Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:

private Date getPreviousWeekDate(){
     return new Date(System.currentTimeMillis()-7*24*60*60*1000);
}

Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:

private Date getMeTomorrow(){
     return new Date(System.currentTimeMillis()+24*60*60*1000);
}

How to parse JSON data with jQuery / JavaScript?

 $(document).ready(function () {
    $.ajax({ 
        url: '/functions.php', 
        type: 'GET',
        data: { get_param: 'value' }, 
        success: function (data) { 
         for (var i=0;i<data.length;++i)
         {
         $('#cand').append('<div class="name">data[i].name</>');
         }
        }
    });
});

How to remove numbers from string using Regex.Replace?

var result = Regex.Replace("123- abcd33", @"[0-9\-]", string.Empty);

php timeout - set_time_limit(0); - don't work

Checkout this, This is from PHP MANUAL, This may help you.

If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:

<?php

require_once('db.php');

$stmt = $db->query($sql);

while ($row = $stmt->fetchRow()) {
    set_time_limit(0);
    // your code here
}

?>

C++ Pass A String

Well, std::string is a class, const char * is a pointer. Those are two different things. It's easy to get from string to a pointer (since it typically contains one that it can just return), but for the other way, you need to create an object of type std::string.

My recommendation: Functions that take constant strings and don't modify them should always take const char * as an argument. That way, they will always work - with string literals as well as with std::string (via an implicit c_str()).

Select row on click react-table

Multiple rows with checkboxes and select all using useState() hooks. Requires minor implementation to adjust to own project.

    const data;
    const [ allToggled, setAllToggled ] = useState(false);
    const [ toggled, setToggled ] = useState(Array.from(new Array(data.length), () => false));
    const [ selected, setSelected ] = useState([]);

    const handleToggleAll = allToggled => {
        let selectAll = !allToggled;
        setAllToggled(selectAll);
        let toggledCopy = [];
        let selectedCopy = [];
        data.forEach(function (e, index) {
            toggledCopy.push(selectAll);
            if(selectAll) {
                selectedCopy.push(index);
            }
        });
        setToggled(toggledCopy);
        setSelected(selectedCopy);
    };

    const handleToggle = index => {
        let toggledCopy = [...toggled];
        toggledCopy[index] = !toggledCopy[index];
        setToggled(toggledCopy);
        if( toggledCopy[index] === false ){
            setAllToggled(false);
        }
        else if (allToggled) {
            setAllToggled(false);
        }
    };

....


                Header: state => (
                    <input
                        type="checkbox"
                        checked={allToggled}
                        onChange={() => handleToggleAll(allToggled)}
                    />
                ),
                Cell: row => (
                    <input
                        type="checkbox"
                        checked={toggled[row.index]}
                        onChange={() => handleToggle(row.index)}
                    />
                ),

....

<ReactTable

...
                    getTrProps={(state, rowInfo, column, instance) => {
                        if (rowInfo && rowInfo.row) {
                            return {
                                onClick: (e, handleOriginal) => {
                                    let present = selected.indexOf(rowInfo.index);
                                    let selectedCopy = selected;

                                    if (present === -1){
                                        selected.push(rowInfo.index);
                                        setSelected(selected);
                                    }

                                    if (present > -1){
                                        selectedCopy.splice(present, 1);
                                        setSelected(selectedCopy);
                                    }

                                    handleToggle(rowInfo.index);
                                },
                                style: {
                                    background: selected.indexOf(rowInfo.index)  > -1 ? '#00afec' : 'white',
                                    color: selected.indexOf(rowInfo.index) > -1 ? 'white' : 'black'
                                },
                            }
                        }
                        else {
                            return {}
                        }
                    }}
/>

Subscripts in plots in R

See ?expression

plot(1:10,main=expression("This is a subscript "[2]))

enter image description here

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Execution failed for task :':app:mergeDebugResources'. Android Studio

In My case, I've written below code in build.gradle

android {
// ...
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false
// ...
}

It's work for me!...

Transposing a 2D-array in JavaScript

A library-free implementation in TypeScript that works for any matrix shape that won't truncate your arrays:

const rotate2dArray = <T>(array2d: T[][]) => {
    const rotated2d: T[][] = []

    return array2d.reduce((acc, array1d, index2d) => {
        array1d.forEach((value, index1d) => {
            if (!acc[index1d]) acc[index1d] = []

            acc[index1d][index2d] = value
        })

        return acc
    }, rotated2d)
}

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

I needed to use this as a cell function (like SUM or VLOOKUP) and found that it was easy to:

  1. Make sure you are in a Macro Enabled Excel File (save as xlsm).
  2. Open developer tools Alt + F11
  3. Add Microsoft VBScript Regular Expressions 5.5 as in other answers
  4. Create the following function either in workbook or in its own module:

    Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
        Dim regex As New VBScript_RegExp_55.RegExp
        Dim strInput As String
    
        strInput = myRange.Value
    
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
    
        REGPLACE = regex.Replace(strInput, outputPattern)
    
    End Function
    
  5. Then you can use in cell with =REGPLACE(B1, "(\w) (\d+)", "$1$2") (ex: "A 243" to "A243")

.keyCode vs. .which

If you are staying in vanilla Javascript, please note keyCode is now deprecated and will be dropped:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any tim

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Instead use either: .key or .code depending on what behavior you want: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

Both are implemented on modern browsers.

How do I set up access control in SVN?

You can use svn+ssh:, and then it's based on access control to the repository at the given location.

This is how I host a project group repository at my uni, where I can't set up anything else. Just having a directory that the group owns, and running svn-admin (or whatever it was) in there means that I didn't need to do any configuration.

accessing a variable from another class

I've tried making an object and tried using .getWidth and .getHeight but can't get it to work.

That´s because you are not setting the width and height fields in JFrame, but you are setting them on local variables. Fields HEIGHT and WIDTH are inhereted from ImageObserver

Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

See http://java.sun.com/javase/6/docs/api/javax/swing/JFrame.html

If width and height represent state of the frame, then you could refactorize them to fields, and write getters for them.

Then, you could create a Constructor that receives both values as parameters

public class DrawFrame extends JFrame {
 private int width;
 private int height;

 DrawFrame(int _width, int _height){

   this.width = _width;
   this.height = _height;

   //other stuff here
}
 public int getWidth(){}
 public int getHeight(){}

 //other methods
}

If widht and height are going to be constant (after created) then you should use the final modifier. This way, once they are assigned a value, they can´t be modified.

Also, the variables i use in DrawCircle, should I have them in the constructor or not?

The way it is writen now, will only allow you to create one type of circle. If you wan´t to create different circles, you should overload the constructor with one with arguments).

For example, if you want to change the attributes xPoint and yPoint, you could have a constructor

public DrawCircle(int _xpoint, int _ypoint){
  //build circle here.
 }

EDIT:

Where does _width and _height come from?

Those are arguments to constructors. You set values on them when you call the Constructor method.

In DrawFrame I set width and height. In DrawCircle I need to access the width and height of DrawFrame. How do I do this?

DrawFrame(){
   int width = 400;
   int height =400;

   /*
   * call DrawCircle constructor
   */
   content.pane(new DrawCircle(width,height));

   // other stuff

}

Now when the DrawCircle constructor executes, it will receive the values you used in DrawFrame as _width and _height respectively.

EDIT:

Try doing

 DrawFrame frame = new DrawFrame();//constructor contains code on previous edit.
 frame.setPreferredSize(new Dimension(400,400));

http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html

Resizing SVG in html?

Use the following code:

<g transform="scale(0.1)">
...
</g>

error: command 'gcc' failed with exit status 1 while installing eventlet

On MacOS I also had problems trying to install fbprophet which had gcc as one of its dependencies.

After trying several steps as recommended by @Boris the command below from the Facebook Prophet project page worked for me in the end.

conda install -c conda-forge fbprophet

It installed all the needed dependencies for fbprophet. Make sure you have anaconda installed.

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The reject actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject() the exception value is undefined, hence the "undefined" part in the error that you get.

You do not show the code that uses the promise, but I reckon it is something like this:

var promise = doSth();
promise.then(function() { doSthHere(); });

Try adding an empty failure call, like this:

promise.then(function() { doSthHere(); }, function() {});

This will prevent the error to appear.

However, I would consider calling reject only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.

Javascript call() & apply() vs bind()?

bind: It binds the function with provided value and context but it does not executes the function. To execute function you need to call the function.

call: It executes the function with provided context and parameter.

apply: It executes the function with provided context and parameter as array.

Java 8 Stream and operation on arrays

Please note that Arrays.stream(arr) create a LongStream (or IntStream, ...) instead of Stream so the map function cannot be used to modify the type. This is why .mapToLong, mapToObject, ... functions are provided.

Take a look at why-cant-i-map-integers-to-strings-when-streaming-from-an-array

React Native Border Radius with background color

Never give borderRadius to your <Text /> always wrap that <Text /> inside your <View /> or in your <TouchableOpacity/>.

borderRadius on <Text /> will work perfectly on Android devices. But on IOS devices it won't work.

So keep this in your practice to wrap your <Text/> inside your <View/> or on <TouchableOpacity/> and then give the borderRadius to that <View /> or <TouchableOpacity /> so that it will work on both Android as well as on IOS devices.

For example:-

<TouchableOpacity style={{borderRadius: 15}}>
   <Text>Button Text</Text>
</TouchableOpacity>

-Thanks

CASE WHEN statement for ORDER BY clause

CASE is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY clause of a SELECT statement.

It looks like you just need:

ORDER BY 
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc, 
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

Or possibly:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.


This may be the answer we're looking for:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN 5
   WHEN TblList.HighCallAlertCount <> 0 THEN 4
   WHEN TblList.HighAlertCount <> 0 THEN 3
   WHEN TblList.MediumCallAlertCount <> 0 THEN 2
   WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

how to draw a rectangle in HTML or CSS?

I do the following in my eBay listings:

<p style="border:solid thick darkblue; border-radius: 1em; 
          border-width:3px; padding-left:9px; padding-top:6px; 
          padding-bottom:6px; margin:2px; width:980px;">

This produces a box border with rounded corners.You can play with the variables.

How to set socket timeout in C when making multiple connections?

Can't you implement your own timeout system?

Keep a sorted list, or better yet a priority heap as Heath suggests, of timeout events. In your select or poll calls use the timeout value from the top of the timeout list. When that timeout arrives, do that action attached to that timeout.

That action could be closing a socket that hasn't connected yet.

How do I make a list of data frames?

The other answers show you how to make a list of data.frames when you already have a bunch of data.frames, e.g., d1, d2, .... Having sequentially named data frames is a problem, and putting them in a list is a good fix, but best practice is to avoid having a bunch of data.frames not in a list in the first place.

The other answers give plenty of detail of how to assign data frames to list elements, access them, etc. We'll cover that a little here too, but the Main Point is to say don't wait until you have a bunch of a data.frames to add them to a list. Start with the list.

The rest of the this answer will cover some common cases where you might be tempted to create sequential variables, and show you how to go straight to lists. If you're new to lists in R, you might want to also read What's the difference between [[ and [ in accessing elements of a list?.


Lists from the start

Don't ever create d1 d2 d3, ..., dn in the first place. Create a list d with n elements.

Reading multiple files into a list of data frames

This is done pretty easily when reading in files. Maybe you've got files data1.csv, data2.csv, ... in a directory. Your goal is a list of data.frames called mydata. The first thing you need is a vector with all the file names. You can construct this with paste (e.g., my_files = paste0("data", 1:5, ".csv")), but it's probably easier to use list.files to grab all the appropriate files: my_files <- list.files(pattern = "\\.csv$"). You can use regular expressions to match the files, read more about regular expressions in other questions if you need help there. This way you can grab all CSV files even if they don't follow a nice naming scheme. Or you can use a fancier regex pattern if you need to pick certain CSV files out from a bunch of them.

At this point, most R beginners will use a for loop, and there's nothing wrong with that, it works just fine.

my_data <- list()
for (i in seq_along(my_files)) {
    my_data[[i]] <- read.csv(file = my_files[i])
}

A more R-like way to do it is with lapply, which is a shortcut for the above

my_data <- lapply(my_files, read.csv)

Of course, substitute other data import function for read.csv as appropriate. readr::read_csv or data.table::fread will be faster, or you may also need a different function for a different file type.

Either way, it's handy to name the list elements to match the files

names(my_data) <- gsub("\\.csv$", "", my_files)
# or, if you prefer the consistent syntax of stringr
names(my_data) <- stringr::str_replace(my_files, pattern = ".csv", replacement = "")

Splitting a data frame into a list of data frames

This is super-easy, the base function split() does it for you. You can split by a column (or columns) of the data, or by anything else you want

mt_list = split(mtcars, f = mtcars$cyl)
# This gives a list of three data frames, one for each value of cyl

This is also a nice way to break a data frame into pieces for cross-validation. Maybe you want to split mtcars into training, test, and validation pieces.

groups = sample(c("train", "test", "validate"),
                size = nrow(mtcars), replace = TRUE)
mt_split = split(mtcars, f = groups)
# and mt_split has appropriate names already!

Simulating a list of data frames

Maybe you're simulating data, something like this:

my_sim_data = data.frame(x = rnorm(50), y = rnorm(50))

But who does only one simulation? You want to do this 100 times, 1000 times, more! But you don't want 10,000 data frames in your workspace. Use replicate and put them in a list:

sim_list = replicate(n = 10,
                     expr = {data.frame(x = rnorm(50), y = rnorm(50))},
                     simplify = F)

In this case especially, you should also consider whether you really need separate data frames, or would a single data frame with a "group" column work just as well? Using data.table or dplyr it's quite easy to do things "by group" to a data frame.

I didn't put my data in a list :( I will next time, but what can I do now?

If they're an odd assortment (which is unusual), you can simply assign them:

mylist <- list()
mylist[[1]] <- mtcars
mylist[[2]] <- data.frame(a = rnorm(50), b = runif(50))
...

If you have data frames named in a pattern, e.g., df1, df2, df3, and you want them in a list, you can get them if you can write a regular expression to match the names. Something like

df_list = mget(ls(pattern = "df[0-9]"))
# this would match any object with "df" followed by a digit in its name
# you can test what objects will be got by just running the
ls(pattern = "df[0-9]")
# part and adjusting the pattern until it gets the right objects.

Generally, mget is used to get multiple objects and return them in a named list. Its counterpart get is used to get a single object and return it (not in a list).

Combining a list of data frames into a single data frame

A common task is combining a list of data frames into one big data frame. If you want to stack them on top of each other, you would use rbind for a pair of them, but for a list of data frames here are three good choices:

# base option - slower but not extra dependencies
big_data = do.call(what = rbind, args = df_list)

# data table and dplyr have nice functions for this that
#  - are much faster
#  - add id columns to identify the source
#  - fill in missing values if some data frames have more columns than others
# see their help pages for details
big_data = data.table::rbindlist(df_list)
big_data = dplyr::bind_rows(df_list)

(Similarly using cbind or dplyr::bind_cols for columns.)

To merge (join) a list of data frames, you can see these answers. Often, the idea is to use Reduce with merge (or some other joining function) to get them together.

Why put the data in a list?

Put similar data in lists because you want to do similar things to each data frame, and functions like lapply, sapply do.call, the purrr package, and the old plyr l*ply functions make it easy to do that. Examples of people easily doing things with lists are all over SO.

Even if you use a lowly for loop, it's much easier to loop over the elements of a list than it is to construct variable names with paste and access the objects with get. Easier to debug, too.

Think of scalability. If you really only need three variables, it's fine to use d1, d2, d3. But then if it turns out you really need 6, that's a lot more typing. And next time, when you need 10 or 20, you find yourself copying and pasting lines of code, maybe using find/replace to change d14 to d15, and you're thinking this isn't how programming should be. If you use a list, the difference between 3 cases, 30 cases, and 300 cases is at most one line of code---no change at all if your number of cases is automatically detected by, e.g., how many .csv files are in your directory.

You can name the elements of a list, in case you want to use something other than numeric indices to access your data frames (and you can use both, this isn't an XOR choice).

Overall, using lists will lead you to write cleaner, easier-to-read code, which will result in fewer bugs and less confusion.

How to post JSON to PHP with curl

Normally the parameter -d is interpreted as form-encoded. You need the -H parameter:

curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

Issue in installing php7.2-mcrypt

As an alternative, you can install 7.1 version of mcrypt and create a symbolic link to it:

Install php7.1-mcrypt:

sudo apt install php7.1-mcrypt

Create a symbolic link:

sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available

After enabling mcrypt by sudo phpenmod mcrypt, it gets available.

Convert bytes to a string

I made a function to clean a list

def cleanLists(self, lista):
    lista = [x.strip() for x in lista]
    lista = [x.replace('\n', '') for x in lista]
    lista = [x.replace('\b', '') for x in lista]
    lista = [x.encode('utf8') for x in lista]
    lista = [x.decode('utf8') for x in lista]

    return lista

How to set div's height in css and html

<div style="height: 100px;"> </div>

OR

<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px;  }

Create a asmx web service in C# using visual studio 2013

Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.