Programs & Examples On #Setjmp

javax.naming.NameNotFoundException

I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
+-- greetBean.java
+-- greetHome.java
+-- greetRemote.java
+-- META-INF
    +-- ejb-jar.xml
    +-- jboss.xml

But as already mentioned, this tutorial is full of mistakes:

  • there is an extra character (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)
  • a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)
  • the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:

<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.

copy-item With Alternate Credentials

I would try to map a drive to the remote system (using 'net use' or WshNetwork.MapNetworkDrive, both methods support credentials) and then use copy-item.

Select All checkboxes using jQuery

$(document).ready(function(){
$('#ckbCheckAll').click(function(event) { 
            if($(this).is(":checked")) {
                $('.checkBoxClass').each(function(){
                    $(this).prop("checked",true);
                });
            }
            else{
                $('.checkBoxClass').each(function(){
                    $(this).prop("checked",false);
                });
            }   
    }); 
    });

How to take off line numbers in Vi?

For turning off line numbers, any of these commands will work:

  1. :set nu!
  2. :set nonu
  3. :set number!
  4. :set nonumber

resize font to fit in a div (on one line)

Very simple. Create a span for the text, get the width and reduce font-size until the span has the same width of the div container:

while($("#container").find("span").width() > $("#container").width()) {
    var currentFontSize = parseInt($("#container").find("span").css("font-size")); 
    $("#container").find("span").css("font-size",currentFontSize-1); 
}

Access denied for root user in MySQL command-line

this might help on Ubuntu:

go to /etc/mysql/my.cnf and comment this line:

bind-address           = 127.0.0.1

Hope this helps someone, I've been searching for this a while too

Cheers

Remove element from JSON Object

To iterate through the keys of an object, use a for .. in loop:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.

Removing a property of an object can be done by using the delete keyword:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

Documentation:

Functions are not valid as a React child. This may happen if you return a Component instead of from render

In my case i forgot to add the () after the function name inside the render function of a react component

public render() {
       let ctrl = (
           <>
                <div className="aaa">
                    {this.renderView}
                </div>
            </>
       ); 

       return ctrl;
    };


    private renderView() : JSX.Element {
        // some html
    };

Changing the render method, as it states in the error message to

        <div className="aaa">
            {this.renderView()}
        </div>

fixed the problem

Install IPA with iTunes 11

For iTunes 11 and above version:

open your iTunes "Side Bar" by going to View -> Show Side Bar drag the mobileprovision and ipa files to your iTunes "Apps" under LIBRARY Then click on your device. open you device Apps from DEVICES and click install for the application and wait for iTunes to sync

How to write LDAP query to test if user is member of a group?

I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

How to solve "Connection reset by peer: socket write error"?

The socket has been closed by the client (browser).

A bug in your code:

byte[] outputByte=new byte[4096];
while(in.read(outputByte,0,4096)!=-1){
   output.write(outputByte,0,4096);
}

The last packet read, then write may have a length < 4096, so I suggest:

byte[] outputByte=new byte[4096];
int len;
while(( len = in.read(outputByte, 0, 4096 )) > 0 ) {
   output.write( outputByte, 0, len );
}

It's not your question, but it's my answer... ;-)

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

You could use RAISE_APPLICATION_ERROR like this:

DECLARE
    ex_custom       EXCEPTION;
BEGIN
    RAISE ex_custom;
EXCEPTION
    WHEN ex_custom THEN
        RAISE_APPLICATION_ERROR(-20001,'My exception was raised');
END;
/

That will raise an exception that looks like:

ORA-20001: My exception was raised

The error number can be anything between -20001 and -20999.

Division in Python 2.7. and 3.3

In Python 2.x, make sure to have at least one operand of your division in float. Multiple ways you may achieve this as the following examples:

20. / 15
20 / float(15)

Add some word to all or some rows in Excel?

Following Mike's answer, I'd also add another step. Let's imagine you have your data in column A.

  • Insert a column with the word you want to add (column B, with k)
  • apply the formula (as suggested by Mike) that merges both values in column C (C1=A1+B1)
  • Copy down the formula
  • Copy the values in column C (already merged)
  • Paste special as 'values'
  • Remove columns A and B

Hope it helps.

Ofc, if the word you want to add will always be the same, you won't need a column B (thus, C1="k"+A1)

Rgds

Newline character in StringBuilder

StringBuilder sb = new StringBuilder();

You can use sb.AppendLine() or sb.Append(Environment.NewLine);

What are .NumberFormat Options In Excel VBA?

The .NET Library EPPlus implements a conversation from the string definition to the built in number. See class ExcelNumberFormat:

internal static int GetFromBuildIdFromFormat(string format)
{
    switch (format)
    {
        case "General":
            return 0;
        case "0":
            return 1;
        case "0.00":
            return 2;
        case "#,##0":
            return 3;
        case "#,##0.00":
            return 4;
        case "0%":
            return 9;
        case "0.00%":
            return 10;
        case "0.00E+00":
            return 11;
        case "# ?/?":
            return 12;
        case "# ??/??":
            return 13;
        case "mm-dd-yy":
            return 14;
        case "d-mmm-yy":
            return 15;
        case "d-mmm":
            return 16;
        case "mmm-yy":
            return 17;
        case "h:mm AM/PM":
            return 18;
        case "h:mm:ss AM/PM":
            return 19;
        case "h:mm":
            return 20;
        case "h:mm:ss":
            return 21;
        case "m/d/yy h:mm":
            return 22;
        case "#,##0 ;(#,##0)":
            return 37;
        case "#,##0 ;[Red](#,##0)":
            return 38;
        case "#,##0.00;(#,##0.00)":
            return 39;
        case "#,##0.00;[Red](#,#)":
            return 40;
        case "mm:ss":
            return 45;
        case "[h]:mm:ss":
            return 46;
        case "mmss.0":
            return 47;
        case "##0.0":
            return 48;
        case "@":
            return 49;
        default:
            return int.MinValue;
    }
}

When you use one of these formats, Excel will automatically identify them as a standard format.

How to Convert a Text File into a List in Python

Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

Loading local JSON file

I haven't found any solution using Google's Closure library. So just to complete the list for future vistors, here's how you load a JSON from local file with Closure library:

goog.net.XhrIo.send('../appData.json', function(evt) {
  var xhr = evt.target;
  var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
  console.log(obj);
});

Best way to unselect a <select> in jQuery?

It's a been a while since asked, and I haven't tested this on older browsers but it seems to me a much simpler answer is

$("#selectID").val([]);

.val() works for select as well http://api.jquery.com/val/

Howto? Parameters and LIKE statement SQL

Well, I'd go with:

 Dim cmd as New SqlCommand(
 "SELECT * FROM compliance_corner"_
  + " WHERE (body LIKE @query )"_ 
  + " OR (title LIKE @query)")

 cmd.Parameters.Add("@query", "%" +searchString +"%")

How to run Node.js as a background process and never die?

Apart from cool solutions above I'd mention also about supervisord and monit tools which allow to start process, monitor its presence and start it if it died. With 'monit' you can also run some active checks like check if process responds for http request

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

  1. You seem to be including one C file from anther. #include should normally be used with header files only.

  2. Within the definition of struct ast_node you refer to struct AST_NODE, which doesn't exist. C is case-sensitive.

Get class name using jQuery

If you do not know the class name BUT you know the ID you can try this:

<div id="currentST" class="myclass"></div>

Then Call it using :

alert($('#currentST').attr('class'));

How to draw an empty plot?

How about something like:

plot.new()

Avoid Adding duplicate elements to a List C#

Use a HashSet<string> instead of a List<string>. It is prepared to perform a better performance because you don't need to provide checks for any items. The collection will manage it for you. That is the difference between a list and a set. For sample:

HashSet<string> set = new HashSet<string>();

set.Add("a");
set.Add("a");
set.Add("b");
set.Add("c");
set.Add("b");
set.Add("c");
set.Add("a");
set.Add("d");
set.Add("e");
set.Add("e");

var total = set.Count;

Total is 5 and the values are a, b, c, d, e.

The implemention of List<T> does not give you nativelly. You can do it, but you have to provide this control. For sample, this extension method:

public static class CollectionExtensions
{
    public static void AddItem<T>(this List<T> list, T item)
    {
       if (!list.Contains(item))
       {
          list.Add(item);
       }
    }
}

and use it:

var list = new List<string>();
list.AddItem(1);
list.AddItem(2);
list.AddItem(3);
list.AddItem(2);
list.AddItem(4);
list.AddItem(5);

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to @Boaz's and @vegemite4me's answers....

By implementing ImplicitNamingStrategy you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder during Hibernate's initialization:

metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());

It works for @UniqueConstraint, but not for @Column(unique = true), which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586

Thanks.

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

I got the same error today and discovered that the firewall was blocking the svn client

How to get a list of all valid IP addresses in a local network?

Try following steps:

  1. Type ipconfig (or ifconfig on Linux) at command prompt. This will give you the IP address of your own machine. For example, your machine's IP address is 192.168.1.6. So your broadcast IP address is 192.168.1.255.
  2. Ping your broadcast IP address ping 192.168.1.255 (may require -b on Linux)
  3. Now type arp -a. You will get the list of all IP addresses on your segment.

R apply function with multiple parameters

To further generalize @Alexander's example, outer is relevant in cases where a function must compute itself on each pair of vector values:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
outer(vars1,vars2,mult_one)

gives:

> outer(vars1, vars2, mult_one)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]   20   40   60
[3,]   30   60   90

Google Chrome default opening position and size

You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.

Firebase FCM force onTokenRefresh() to be called

    [Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
class MyFirebaseIIDService: FirebaseInstanceIdService
{
    const string TAG = "MyFirebaseIIDService";
    NotificationHub hub;

    public override void OnTokenRefresh()
    {
        var refreshedToken = FirebaseInstanceId.Instance.Token;
        Log.Debug(TAG, "FCM token: " + refreshedToken);
        SendRegistrationToServer(refreshedToken);
    }

    void SendRegistrationToServer(string token)
    {
        // Register with Notification Hubs
        hub = new NotificationHub(Constants.NotificationHubName,
                                    Constants.ListenConnectionString, this);
        Employee employee = JsonConvert.DeserializeObject<Employee>(Settings.CurrentUser);
        //if user is not logged in 
        if (employee != null)
        {
            var tags = new List<string>() { employee.Email};
            var regID = hub.Register(token, tags.ToArray()).RegistrationId;

            Log.Debug(TAG, $"Successful registration of ID {regID}");
        }
        else
        {
            FirebaseInstanceId.GetInstance(Firebase.FirebaseApp.Instance).DeleteInstanceId();
            hub.Unregister();
        }
    }
}

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

Injecting Mockito mocks into a Spring bean

I use a combination of the approach used in answer by Markus T and a simple helper implementation of ImportBeanDefinitionRegistrar that looks for a custom annotation (@MockedBeans) in which one can specify which classes are to be mocked. I believe that this approach results in a concise unit test with some of the boilerplate code related to mocking removed.

Here's how a sample unit test looks with that approach:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class ExampleServiceIntegrationTest {

    //our service under test, with mocked dependencies injected
    @Autowired
    ExampleService exampleService;

    //we can autowire mocked beans if we need to used them in tests
    @Autowired
    DependencyBeanA dependencyBeanA;

    @Test
    public void testSomeMethod() {
        ...
        exampleService.someMethod();
        ...
        verify(dependencyBeanA, times(1)).someDependencyMethod();
    }

    /**
     * Inner class configuration object for this test. Spring will read it thanks to
     * @ContextConfiguration(loader=AnnotationConfigContextLoader.class) annotation on the test class.
     */
    @Configuration
    @Import(TestAppConfig.class) //TestAppConfig may contain some common integration testing configuration
    @MockedBeans({DependencyBeanA.class, DependencyBeanB.class, AnotherDependency.class}) //Beans to be mocked
    static class ContextConfiguration {

        @Bean
        public ExampleService exampleService() {
            return new ExampleService(); //our service under test
        }
    }
}

To make this happen you need to define two simple helper classes - custom annotation (@MockedBeans) and a custom ImportBeanDefinitionRegistrar implementation. @MockedBeans annotation definition needs to be annotated with @Import(CustomImportBeanDefinitionRegistrar.class) and the ImportBeanDefinitionRgistrar needs to add mocked beans definitions to the configuration in it's registerBeanDefinitions method.

If you like the approach you can find sample implementations on my blogpost.

Loading all images using imread from a given folder

You can also use matplotlib for this, try this out:

import matplotlib.image as mpimg

def load_images(folder):
    images = []
    for filename in os.listdir(folder):
        img = mpimg.imread(os.path.join(folder, filename))
        if img is not None:
            images.append(img)
    return images

Practical uses of git reset --soft?

One possible usage would be when you want to continue your work on a different machine. It would work like this:

  1. Checkout a new branch with a stash-like name,

    git checkout -b <branchname>_stash
    
  2. Push your stash branch up,

    git push -u origin <branchname>_stash
    
  3. Switch to your other machine.

  4. Pull down both your stash and existing branches,

    git checkout <branchname>_stash; git checkout <branchname>
    
  5. You should be on your existing branch now. Merge in the changes from the stash branch,

    git merge <branchname>_stash
    
  6. Soft reset your existing branch to 1 before your merge,

    git reset --soft HEAD^
    
  7. Remove your stash branch,

    git branch -d <branchname>_stash
    
  8. Also remove your stash branch from origin,

    git push origin :<branchname>_stash
    
  9. Continue working with your changes as if you had stashed them normally.

I think, in the future, GitHub and co. should offer this "remote stash" functionality in fewer steps.

How to get the background color code of an element in hex?

Check example link below and click on the div to get the color value in hex.

_x000D_
_x000D_
var color = '';_x000D_
$('div').click(function() {_x000D_
  var x = $(this).css('backgroundColor');_x000D_
  hexc(x);_x000D_
  console.log(color);_x000D_
})_x000D_
_x000D_
function hexc(colorval) {_x000D_
  var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);_x000D_
  delete(parts[0]);_x000D_
  for (var i = 1; i <= 3; ++i) {_x000D_
    parts[i] = parseInt(parts[i]).toString(16);_x000D_
    if (parts[i].length == 1) parts[i] = '0' + parts[i];_x000D_
  }_x000D_
  color = '#' + parts.join('');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class='div' style='background-color: #f5b405'>Click me!</div>
_x000D_
_x000D_
_x000D_

Check working example at http://jsfiddle.net/DCaQb/

How add "or" in switch statements?

You may do this as of C# 9.0:

switch(myvar)
{
    case 2 or 5:
        // ...
        break;

    case 7 or 12:
        // ...
        break;
    // ...
}

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

My case on Ubuntu 14.04.2 LTS was similar to others with my.cnf, but for me the cause was a ~/.my.cnf that was leftover from a previous installation. After deleting that file and purging/re-installing mysql-server, it worked fine.

Get the content of a sharepoint folder with Excel VBA

I spent some time on this very problem - I was trying to verify a file existed before opening it.

Eventually, I came up with a solution using XML and SOAP - use the EnumerateFolder method and pull in an XML response with the folder's contents.

I blogged about it here.

textarea character limit

using maxlength attribute of textarea would do the trick ... simple html code .. not JS or JQuery or Server Side Check Required....

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

I had the same problem and none of these solutions worked and I don't know why, they worked for me in the past for similar problems.

Anyway to solve the problem I've just manually rebuild the package using node-pre-gyp

cd node_modules/bcrypt
node-pre-gyp rebuild

And everything worked as expected.

Hope this helps

Way to go from recursion to iteration

Search google for "Continuation passing style." There is a general procedure for converting to a tail recursive style; there is also a general procedure for turning tail recursive functions into loops.

Call a function from another file?

Came across the same feature but I had to do the below to make it work.

If you are seeing 'ModuleNotFoundError: No module named', you probably need the dot(.) in front of the filename as below;

from .file import funtion

What uses are there for "placement new"?

It's useful if you want to separate allocation from initialization. STL uses placement new to create container elements.

How to measure elapsed time in Python?

Kind of a super later response, but maybe it serves a purpose for someone. This is a way to do it which I think is super clean.

import time

def timed(fun, *args):
    s = time.time()
    r = fun(*args)
    print('{} execution took {} seconds.'.format(fun.__name__, time.time()-s))
    return(r)

timed(print, "Hello")

Keep in mind that "print" is a function in Python 3 and not Python 2.7. However, it works with any other function. Cheers!

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

I took @jaytrixz's answer/comment one step further and added "text/html" to the existing set of types. That way when they fix it on the server side to "application/json" or "text/json" I claim it'll work seamlessly.

  manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

How to use the divide function in the query?

Assuming all of these columns are int, then the first thing to sort out is converting one or more of them to a better data type - int division performs truncation, so anything less than 100% would give you a result of 0:

select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)
from 
CSPGI09_OVERSHIPMENT 

Here, I've mutiplied one of the numbers by 100.0 which will force the result of the calculation to be done with floats rather than ints. By choosing 100, I'm also getting it ready to be treated as a %.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (- and /) at the same level, and so were relying on the precedence rules to define which operator applied first.

Concatenate two slices in Go

append([]int{1,2}, []int{3,4}...) will work. Passing arguments to ... parameters.

If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T.

If f is invoked with no actual arguments for p, the value passed to p is nil.

Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.

Given the function and calls

func Greeting(prefix string, who ...string)
Greeting("nobody")
Greeting("hello:", "Joe", "Anna", "Eileen")

Putting a password to a user in PhpMyAdmin in Wamp

my config.inc.php file in the phpmyadmin folder. Change username and password to the one you have set for your database.

    <?php
/*
 * This is needed for cookie based authentication to encrypt password in
 * cookie
 */
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */

/*
 * Servers configuration
 */
$i = 0;

/*
 * First server
 */
$i++;

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'enter_username_here';
$cfg['Servers'][$i]['password'] = 'enter_password_here';
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';

/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';

/*
 * End of servers configuration
 */

?>

Test if string is URL encoded in PHP

You'll never know for sure if a string is URL-encoded or if it was supposed to have the sequence %2B in it. Instead, it probably depends on where the string came from, i.e. if it was hand-crafted or from some application.

Is it better to search the string for characters which would be encoded, which aren't, and if any exist then its not encoded.

I think this is a better approach, since it would take care of things that have been done programmatically (assuming the application would not have left a non-encoded character behind).

One thing that will be confusing here... Technically, the % "should be" encoded if it will be present in the final value, since it is a special character. You might have to combine your approaches to look for should-be-encoded characters as well as validating that the string decodes successfully if none are found.

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

Unfortunately none of the solutions worked for me. I used Internet Explorer 8 on Windows 7. When I was looking for a solution, I found the settings about login information in the control panel. So I added a new entry under the certificate based information with the address of my server and I chose my prefered certificate.

After a clear of the SSL cache in Internet Explorer 8 I just refreshed the site and the right certificate was sent to the server.

This isn't the solution which I wanted, but it works.

Get keys of a Typescript interface as array of strings

Can't. Interfaces don't exist at runtime.

workaround

Create a variable of the type and use Object.keys on it

Can't accept license agreement Android SDK Platform 24

Go to Android\sdk\tools\bin

None of the above solutions worked for me and finally this single line accepted all android licences.

yes | sdkmanager --licenses && sdkmanager --update

Convert command line arguments into an array in Bash

Maybe this can help:

myArray=("$@") 

also you can iterate over arguments by omitting 'in':

for arg; do
   echo "$arg"
done

will be equivalent

for arg in "${myArray[@]}"; do
   echo "$arg"
done

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

Adding <validation validateIntegratedModeConfiguration="false"/> addresses the symptom, but is not appropriate for all circumstances. Having ran around this issue a few times, I hope to help others not only overcome the problem but understand it. (Which becomes more and more important as IIS 6 fades into myth and rumor.)

Background:

This issue and the confusion surrounding it started with the introduction of ASP.NET 2.0 and IIS 7. IIS 6 had and continues to have only one pipeline mode, and it is equivalent to what IIS 7+ calls "Classic" mode. The second, newer, and recommended pipeline mode for all applications running on IIS 7+ is called "Integrated" mode.

So, what's the difference? The key difference is how ASP.NET interacts with IIS.

  • Classic mode is limited to an ASP.NET pipeline that cannot interact with the IIS pipeline. Essentially a request comes in and if IIS 6/Classic has been told, through server configuration, that ASP.NET can handle it then IIS hands off the request to ASP.NET and moves on. The significance of this can be gleaned from an example. If I were to authorize access to static image files, I would not be able to do it with an ASP.NET module because the IIS 6 pipeline will handle those requests itself and ASP.NET will never see those requests because they were never handed off.* On the other hand, authorizing which users can access a .ASPX page such as a request for Foo.aspx is trivial even in IIS 6/Classic because IIS always hands those requests off to the ASP.NET pipeline. In Classic mode ASP.NET does not know what it hasn't been told and there is a lot that IIS 6/Classic may not be telling it.

  • Integrated mode is recommended because ASP.NET handlers and modules can interact directly with the IIS pipeline. No longer does the IIS pipeline simply hand off the request to the ASP.NET pipeline, now it allows ASP.NET code to hook directly into the IIS pipeline and all the requests that hit it. This means that an ASP.NET module can not only observe requests to static image files, but can intercept those requests and take action by denying access, logging the request, etc.

Overcoming the error:

  1. If you are running an older application that was originally built for IIS 6, perhaps you moved it to a new server, there may be absolutely nothing wrong with running the application pool of that application in Classic mode. Go ahead you don't have to feel bad.
  2. Then again maybe you are giving your application a face-lift or it was chugging along just fine until you installed a 3rd party library via NuGet, manually, or by some other means. In that case it is entirely possible httpHandlers or httpModules have been added to system.web. The outcome is the error that you are seeing because validateIntegratedModeConfiguration defaults true. Now you have two choices:

    1. Remove the httpHandlers and httpModules elements from system.web. There are a couple possible outcomes from this:
      • Everything works fine, a common outcome;
      • Your application continues to complain, there may be a web.config in a parent folder you are inheriting from, consider cleaning up that web.config too;
      • You grow tired of removing the httpHandlers and httpModules that NuGet packages keep adding to system.web, hey do what you need to.
  3. If those options do not work or are more trouble than it is worth then I'm not going to tell you that you can't set validateIntegratedModeConfiguration to false, but at least you know what you're doing and why it matters.

Good reads:

*Of course there are ways to get all kind of strange things into the ASP.NET pipeline from IIS 6/Classic via incantations like wildcard mappings, if you like that sort of thing.

jQuery bind to Paste Event, how to get the content of the paste

I recently needed to accomplish something similar to this. I used the following design to access the paste element and value. jsFiddle demo

$('body').on('paste', 'input, textarea', function (e)
{
    setTimeout(function ()
    {
        //currentTarget added in jQuery 1.3
        alert($(e.currentTarget).val());
        //do stuff
    },0);
});

sass --watch with automatic minify?

There are some different way to do that

sass --watch --style=compressed main.scss main.css

or

sass --watch a.scss:a.css --style compressed

or

By Using visual studio code extension live sass compiler

see more

Node.js + Nginx - What now?

You can also have different urls for apps in one server configuration:

In /etc/nginx/sites-enabled/yourdomain:

server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.com;

    location ^~ /app1/{
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass    http://127.0.0.1:3000/;
    }

    location ^~ /app2/{
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass    http://127.0.0.1:4000/;
    }
}

Restart nginx:

sudo service nginx restart

Starting applications.

node app1.js

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello from app1!\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

node app2.js

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello from app2!\n');
}).listen(4000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:4000/');

Calculating sum of repeated elements in AngularJS ng-repeat

Simple Solution

Here is a simple solution. No additional for loop required.

HTML part

         <table ng-init="ResetTotalAmt()">
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>

                <tr ng-repeat="product in cart.products">
                    <td ng-init="CalculateSum(product)">{{product.name}}</td>
                    <td>{{product.quantity}}</td>
                    <td>{{product.price * product.quantity}} €</td>
                </tr>

                <tr>
                    <td></td>
                    <td>Total :</td>
                    <td>{{cart.TotalAmt}}</td> // Here is the total value of my cart
                </tr>

           </table>

Script Part

 $scope.cart.TotalAmt = 0;
 $scope.CalculateSum= function (product) {
   $scope.cart.TotalAmt += (product.price * product.quantity);
 }
//It is enough to Write code $scope.cart.TotalAmt =0; in the function where the cart.products get allocated value. 
$scope.ResetTotalAmt = function (product) {
   $scope.cart.TotalAmt =0;
 }

Can't drop table: A foreign key constraint fails

This probably has the same table to other schema the reason why you're getting that error.

You need to drop first the child row then the parent row.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Update 2015-06

Based on antoinepairet's comment/example:

Using uib-collapse attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview

<nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">

        <!-- note the ng-init and ng-click here: -->
        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
    </div>

    <div class="collapse navbar-collapse" uib-collapse="navCollapsed">
        <ul class="nav navbar-nav">
        ...
        </ul>
    </div>
</nav>

Ancient..

I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:

The only variation from the official bootstrap example is the addition of ng- attributes noted by comments, below:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">

    <!-- note the ng-init and ng-click here: -->
    <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- note the ng-class here -->
  <div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">

    <ul class="nav navbar-nav">
    ...

Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)

This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!

What's the best way to dedupe a table?

SELECT DISTINCT <insert all columns but the PK here> FROM foo. Create a temp table using that query (the syntax varies by RDBMS but there's typically a SELECT … INTO or CREATE TABLE AS pattern available), then blow away the old table and pump the data from the temp table back into it.

Django set default form values

I had this other solution (I'm posting it in case someone else as me is using the following method from the model):

class onlyUserIsActiveField(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(onlyUserIsActiveField, self).__init__(*args, **kwargs)
        self.fields['is_active'].initial = False

    class Meta:
        model = User
        fields = ['is_active']
        labels = {'is_active': 'Is Active'}
        widgets = {
            'is_active': forms.CheckboxInput( attrs={
                            'class':          'form-control bootstrap-switch',
                            'data-size':      'mini',
                            'data-on-color':  'success',
                            'data-on-text':   'Active',
                            'data-off-color': 'danger',
                            'data-off-text':  'Inactive',
                            'name':           'is_active',

            })
        }

The initial is definded on the __init__ function as self.fields['is_active'].initial = False

how to check for datatype in node js- specifically for integer

I just made some tests in node.js v4.2.4 (but this is true in any javascript implementation):

> typeof NaN
'number'
> isNaN(NaN)
true
> isNaN("hello")
true

the surprise is the first one as type of NaN is "number", but that is how it is defined in javascript.

So the next test brings up unexpected result

> typeof Number("hello")
"number"

because Number("hello") is NaN

The following function makes results as expected:

function isNumeric(n){
  return (typeof n == "number" && !isNaN(n));
}

Turning off hibernate logging console output

Replace slf4j-jdk14-xxx.jar with slf4j-log4j12-xxx.jar. If you have both, delete slf4j-jdk14-xxx.jar. Found this solution at https://forum.hibernate.org/viewtopic.php?f=1&t=999623

Batch script: how to check for admin rights

Another way to do this.

REM    # # # #      CHECKING OR IS STARTED AS ADMINISTRATOR     # # # # #

FSUTIL | findstr /I "volume" > nul&if not errorlevel 1  goto Administrator_OK

cls
echo *******************************************************
echo ***    R U N    A S    A D M I N I S T R A T O R    ***
echo *******************************************************
echo.
echo.
echo Call up just as the Administrator. Abbreviation can be done to the script and set:
echo.
echo      Shortcut ^> Advanced ^> Run as Administrator
echo.
echo.
echo Alternatively, a single run "Run as Administrator"
echo or in the Schedule tasks with highest privileges
pause > nul
goto:eof
:Administrator_OK

REM Some next lines code ...

How to debug a bash script?

I've used the following methods to debug my script.

set -e makes the script stop immediately if any external program returns a non-zero exit status. This is useful if your script attempts to handle all error cases and where a failure to do so should be trapped.

set -x was mentioned above and is certainly the most useful of all the debugging methods.

set -n might also be useful if you want to check your script for syntax errors.

strace is also useful to see what's going on. Especially useful if you haven't written the script yourself.

How to wait for a number of threads to complete?

The join() was not helpful to me. see this sample in Kotlin:

    val timeInMillis = System.currentTimeMillis()
    ThreadUtils.startNewThread(Runnable {
        for (i in 1..5) {
            val t = Thread(Runnable {
                Thread.sleep(50)
                var a = i
                kotlin.io.println(Thread.currentThread().name + "|" + "a=$a")
                Thread.sleep(200)
                for (j in 1..5) {
                    a *= j
                    Thread.sleep(100)
                    kotlin.io.println(Thread.currentThread().name + "|" + "$a*$j=$a")
                }
                kotlin.io.println(Thread.currentThread().name + "|TaskDurationInMillis = " + (System.currentTimeMillis() - timeInMillis))
            })
            t.start()
        }
    })

The result:

Thread-5|a=5
Thread-1|a=1
Thread-3|a=3
Thread-2|a=2
Thread-4|a=4
Thread-2|2*1=2
Thread-3|3*1=3
Thread-1|1*1=1
Thread-5|5*1=5
Thread-4|4*1=4
Thread-1|2*2=2
Thread-5|10*2=10
Thread-3|6*2=6
Thread-4|8*2=8
Thread-2|4*2=4
Thread-3|18*3=18
Thread-1|6*3=6
Thread-5|30*3=30
Thread-2|12*3=12
Thread-4|24*3=24
Thread-4|96*4=96
Thread-2|48*4=48
Thread-5|120*4=120
Thread-1|24*4=24
Thread-3|72*4=72
Thread-5|600*5=600
Thread-4|480*5=480
Thread-3|360*5=360
Thread-1|120*5=120
Thread-2|240*5=240
Thread-1|TaskDurationInMillis = 765
Thread-3|TaskDurationInMillis = 765
Thread-4|TaskDurationInMillis = 765
Thread-5|TaskDurationInMillis = 765
Thread-2|TaskDurationInMillis = 765

Now let me use the join() for threads:

    val timeInMillis = System.currentTimeMillis()
    ThreadUtils.startNewThread(Runnable {
        for (i in 1..5) {
            val t = Thread(Runnable {
                Thread.sleep(50)
                var a = i
                kotlin.io.println(Thread.currentThread().name + "|" + "a=$a")
                Thread.sleep(200)
                for (j in 1..5) {
                    a *= j
                    Thread.sleep(100)
                    kotlin.io.println(Thread.currentThread().name + "|" + "$a*$j=$a")
                }
                kotlin.io.println(Thread.currentThread().name + "|TaskDurationInMillis = " + (System.currentTimeMillis() - timeInMillis))
            })
            t.start()
            t.join()
        }
    })

And the result:

Thread-1|a=1
Thread-1|1*1=1
Thread-1|2*2=2
Thread-1|6*3=6
Thread-1|24*4=24
Thread-1|120*5=120
Thread-1|TaskDurationInMillis = 815
Thread-2|a=2
Thread-2|2*1=2
Thread-2|4*2=4
Thread-2|12*3=12
Thread-2|48*4=48
Thread-2|240*5=240
Thread-2|TaskDurationInMillis = 1568
Thread-3|a=3
Thread-3|3*1=3
Thread-3|6*2=6
Thread-3|18*3=18
Thread-3|72*4=72
Thread-3|360*5=360
Thread-3|TaskDurationInMillis = 2323
Thread-4|a=4
Thread-4|4*1=4
Thread-4|8*2=8
Thread-4|24*3=24
Thread-4|96*4=96
Thread-4|480*5=480
Thread-4|TaskDurationInMillis = 3078
Thread-5|a=5
Thread-5|5*1=5
Thread-5|10*2=10
Thread-5|30*3=30
Thread-5|120*4=120
Thread-5|600*5=600
Thread-5|TaskDurationInMillis = 3833

As it's clear when we use the join:

  1. The threads are running sequentially.
  2. The first sample takes 765 Milliseconds while the second sample takes 3833 Milliseconds.

Our solution to prevent blocking other threads was creating an ArrayList:

val threads = ArrayList<Thread>()

Now when we want to start a new thread we most add it to the ArrayList:

addThreadToArray(
    ThreadUtils.startNewThread(Runnable {
        ...
    })
)

The addThreadToArray function:

@Synchronized
fun addThreadToArray(th: Thread) {
    threads.add(th)
}

The startNewThread funstion:

fun startNewThread(runnable: Runnable) : Thread {
    val th = Thread(runnable)
    th.isDaemon = false
    th.priority = Thread.MAX_PRIORITY
    th.start()
    return th
}

Check the completion of the threads as below everywhere it's needed:

val notAliveThreads = ArrayList<Thread>()
for (t in threads)
    if (!t.isAlive)
        notAliveThreads.add(t)
threads.removeAll(notAliveThreads)
if (threads.size == 0){
    // The size is 0 -> there is no alive threads.
}

What is the difference between const and readonly in C#?

Constants

  • Constants are static by default
  • They must have a value at compilation-time (you can have e.g. 3.14 * 2, but cannot call methods)
  • Could be declared within functions
  • Are copied into every assembly that uses them (every assembly gets a local copy of values)
  • Can be used in attributes

Readonly instance fields

  • Must have set value, by the time constructor exits
  • Are evaluated when instance is created

Static readonly fields

  • Are evaluated when code execution hits class reference (when new instance is created or a static method is executed)
  • Must have an evaluated value by the time the static constructor is done
  • It's not recommended to put ThreadStaticAttribute on these (static constructors will be executed in one thread only and will set the value for its thread; all other threads will have this value uninitialized)

List append() in for loop

You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = []
for i in range(5):    
    a.append(i)
print(a)

is all you need. This works because lists are mutable.

Also see the docs on data structures.

The activity must be exported or contain an intent-filter

Double check your manifest, your first activity should have tag

    <intent-filter>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

inside of activity tag.

If that doesn't work, look for target build, which located in the left of run button (green-colored play button), it should be targeting "app" folder, not a particular activity. if it doesn't targeting "app", just click it and choose "app" from drop down list.

Hope it helps!

ERROR 1064 (42000) in MySQL

For me I had a

create table mytable ( 
    dadada 
)

and forgot the semicolon at the end.

So looks like this error can occur after simple syntax errors. Just like it says.. I guess you can never read the helpful compiler comments closely enough.

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

I was also facing the same error in my node application today.

enter image description here

Below was my node API.

app.get('azureTable', (req, res) => {
  const tableSvc = azure.createTableService(config.azureTableAccountName, config.azureTableAccountKey);
  const query = new azure.TableQuery().top(1).where('PartitionKey eq ?', config.azureTablePartitionKey);
  tableSvc.queryEntities(config.azureTableName, query, null, (error, result, response) => {
    if (error) { return; }
    res.send(result);
    console.log(result)
  });
});

The fix was very simple, I was missing a slash "/" before my API. So after changing the path from 'azureTable' to '/azureTable', the issue was resolved.

How to check queue length in Python

it is simple just use .qsize() example:

a=Queue()
a.put("abcdef")
print a.qsize() #prints 1 which is the size of queue

The above snippet applies for Queue() class of python. Thanks @rayryeng for the update.

for deque from collections we can use len() as stated here by K Z.

CSS-Only Scrollable Table with fixed headers

Surprised a solution using flexbox hasn't been posted yet.

Here's my solution using display: flex and a basic use of :after (thanks to Luggage) to maintain the alignment even with the scrollbar padding the tbody a bit. This has been verified in Chrome 45, Firefox 39, and MS Edge. It can be modified with prefixed properties to work in IE11, and further in IE10 with a CSS hack and the 2012 flexbox syntax.

Note the table width can be modified; this even works at 100% width.

The only caveat is that all table cells must have the same width. Below is a clearly contrived example, but this works fine when cell contents vary (table cells all have the same width and word wrapping on, forcing flexbox to keep them the same width regardless of content). Here is an example where cell contents are different.

Just apply the .scroll class to a table you want scrollable, and make sure it has a thead:

_x000D_
_x000D_
.scroll {_x000D_
  border: 0;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.scroll tr {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.scroll td {_x000D_
  padding: 3px;_x000D_
  flex: 1 auto;_x000D_
  border: 1px solid #aaa;_x000D_
  width: 1px;_x000D_
  word-wrap: break-word;_x000D_
}_x000D_
_x000D_
.scroll thead tr:after {_x000D_
  content: '';_x000D_
  overflow-y: scroll;_x000D_
  visibility: hidden;_x000D_
  height: 0;_x000D_
}_x000D_
_x000D_
.scroll thead th {_x000D_
  flex: 1 auto;_x000D_
  display: block;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.scroll tbody {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
  height: 200px;_x000D_
}
_x000D_
<table class="scroll" width="400px">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

array filter in python?

>>> A           = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A  = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>> 

Error In PHP5 ..Unable to load dynamic library

sudo apt-get install php5-mcrypt
sudo apt-get install php5-mysql

...etc resolved it for me :)

hope it helps

How to check if a std::string is set or not?

The default constructor for std::string always returns an object that is set to a null string.

REST API Authentication

For e.g. when a user has login.Now lets say the user want to create a forum topic, How will I know that the user is already logged in?

Think about it - there must be some handshake that tells your "Create Forum" API that this current request is from an authenticated user. Since REST APIs are typically stateless, the state must be persisted somewhere. Your client consuming the REST APIs is responsible for maintaining that state. Usually, it is in the form of some token that gets passed around since the time the user was logged in. If the token is good, your request is good.

Check how Amazon AWS does authentications. That's a perfect example of "passing the buck" around from one API to another.

*I thought of adding some practical response to my previous answer. Try Apache Shiro (or any authentication/authorization library). Bottom line, try and avoid custom coding. Once you have integrated your favorite library (I use Apache Shiro, btw) you can then do the following:

  1. Create a Login/logout API like: /api/v1/login and api/v1/logout
  2. In these Login and Logout APIs, perform the authentication with your user store
  3. The outcome is a token (usually, JSESSIONID) that is sent back to the client (web, mobile, whatever)
  4. From this point onwards, all subsequent calls made by your client will include this token
  5. Let's say your next call is made to an API called /api/v1/findUser
  6. The first thing this API code will do is to check for the token ("is this user authenticated?")
  7. If the answer comes back as NO, then you throw a HTTP 401 Status back at the client. Let them handle it.
  8. If the answer is YES, then proceed to return the requested User

That's all. Hope this helps.

Hive insert query like SQL

You still can insert into complex type in Hive - it works (id is int, colleagues array)

insert into emp (id,colleagues) select 11, array('Alex','Jian') from (select '1')

How to write macro for Notepad++?

This post can help you as a little bit related :

Using RegEX To Prefix And Append In Notepad++

Assuming alphanumeric words, you can use:

Search = ^([A-Za-z0-9]+)$ Replace = able:"\1"

Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):

Search = ^(.+)$

^ points to the start of the line. $ points to the end of the line.

\1 will be the source match within the parentheses.

Calculate difference between two datetimes in MySQL

my two cents about logic:

syntax is "old date" - :"new date", so:

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:00', '2018-11-15 15:00:30')

gives 30,

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:55', '2018-11-15 15:00:15')

gives: -40

How to show a confirm message before delete?

For "confirmation message on delete" use:

                       $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "Searching.aspx/Delete_Student_Data",
                        data: "{'StudentID': '" + studentID + "'}",
                        dataType: "json",
                        success: function (data) {
                            alert("Delete StudentID Successfully");
                            return true;
                        }

what is the difference between GROUP BY and ORDER BY in sql

ORDER BY alters the order in which items are returned.

GROUP BY will aggregate records by the specified columns which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc).

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Enter the original date into a Date object and then print out the result with a DateFormat. You may have to split up the string into smaller pieces to create the initial Date object, if the automatic parse method does not accept your format.

Pseudocode:

Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);

Remove Project from Android Studio

Select your project in the projects window > File > Project Structure > (in the Modules section) select your project and click the minus button.

How to implement a queue using two stacks?

Let queue to be implemented be q and stacks used to implement q be stack1 and stack2.

q can be implemented in two ways:

Method 1 (By making enQueue operation costly)

This method makes sure that newly entered element is always at the top of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used.

enQueue(q, x)
1) While stack1 is not empty, push everything from stack1 to stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.
deQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it.

Method 2 (By making deQueue operation costly)

In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned.

enQueue(q,  x)
 1) Push x to stack1 (assuming size of stacks is unlimited).

deQueue(q)
 1) If both stacks are empty then error.
 2) If stack2 is empty
   While stack1 is not empty, push everything from stack1 to stack2.
 3) Pop the element from stack2 and return it.

Method 2 is definitely better than method 1. Method 1 moves all the elements twice in enQueue operation, while method 2 (in deQueue operation) moves the elements once and moves elements only if stack2 empty.

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

In our case this error was caused by marking entities as modified when none of their properties 'really' changed. For example when you assign same value to a property, context may see that as an update where database doesn't.

Basically we ran a script to repopulate one property with concatenated values from other properties. For a lot of records that meant no change, but it flagged them as modified. DB returned different number of updated objects which presumably triggered that exception.

We solved it by checking the property value and only assigning new one if different.

How to tell when UITableView has completed ReloadData?

Details

  • Xcode Version 10.2.1 (10E1001), Swift 5

Solution

import UIKit

// MARK: - UITableView reloading functions

protocol ReloadCompletable: class { func reloadData() }

extension ReloadCompletable {
    func run(transaction closure: (() -> Void)?, completion: (() -> Void)?) {
        guard let closure = closure else { return }
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        closure()
        CATransaction.commit()
    }

    func run(transaction closure: (() -> Void)?, completion: ((Self) -> Void)?) {
        run(transaction: closure) { [weak self] in
            guard let self = self else { return }
            completion?(self)
        }
    }

    func reloadData(completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadData() }, completion: closure)
    }
}

// MARK: - UITableView reloading functions

extension ReloadCompletable where Self: UITableView {
    func reloadRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation, completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadRows(at: indexPaths, with: animation) }, completion: closure)
    }

    func reloadSections(_ sections: IndexSet, with animation: UITableView.RowAnimation, completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadSections(sections, with: animation) }, completion: closure)
    }
}

// MARK: - UICollectionView reloading functions

extension ReloadCompletable where Self: UICollectionView {

    func reloadSections(_ sections: IndexSet, completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadSections(sections) }, completion: closure)
    }

    func reloadItems(at indexPaths: [IndexPath], completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadItems(at: indexPaths) }, completion: closure)
    }
}

Usage

UITableView

// Activate
extension UITableView: ReloadCompletable { }

// ......
let tableView = UICollectionView()

// reload data
tableView.reloadData { tableView in print(collectionView) }

// or
tableView.reloadRows(at: indexPathsToReload, with: rowAnimation) { tableView in print(tableView) }

// or
tableView.reloadSections(IndexSet(integer: 0), with: rowAnimation) { _tableView in print(tableView) }

UICollectionView

// Activate
extension UICollectionView: ReloadCompletable { }

// ......
let collectionView = UICollectionView()

// reload data
collectionView.reloadData { collectionView in print(collectionView) }

// or
collectionView.reloadItems(at: indexPathsToReload) { collectionView in print(collectionView) }

// or
collectionView.reloadSections(IndexSet(integer: 0)) { collectionView in print(collectionView) }

Full sample

Do not forget to add the solution code here

import UIKit

class ViewController: UIViewController {

    private weak var navigationBar: UINavigationBar?
    private weak var tableView: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationItem()
        setupTableView()
    }
}
// MARK: - Activate UITableView reloadData with completion functions

extension UITableView: ReloadCompletable { }

// MARK: - Setup(init) subviews

extension ViewController {

    private func setupTableView() {
        guard let navigationBar = navigationBar else { return }
        let tableView = UITableView()
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.dataSource = self
        self.tableView = tableView
    }

    private func setupNavigationItem() {
        let navigationBar = UINavigationBar()
        view.addSubview(navigationBar)
        self.navigationBar = navigationBar
        navigationBar.translatesAutoresizingMaskIntoConstraints = false
        navigationBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        navigationBar.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        navigationBar.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        let navigationItem = UINavigationItem()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "all", style: .plain, target: self, action: #selector(reloadAllCellsButtonTouchedUpInside(source:)))
        let buttons: [UIBarButtonItem] = [
                                            .init(title: "row", style: .plain, target: self,
                                                  action: #selector(reloadRowButtonTouchedUpInside(source:))),
                                            .init(title: "section", style: .plain, target: self,
                                                  action: #selector(reloadSectionButtonTouchedUpInside(source:)))
                                            ]
        navigationItem.leftBarButtonItems = buttons
        navigationBar.items = [navigationItem]
    }
}

// MARK: - Buttons actions

extension ViewController {

    @objc func reloadAllCellsButtonTouchedUpInside(source: UIBarButtonItem) {
        let elementsName = "Data"
        print("-- Reloading \(elementsName) started")
        tableView?.reloadData { taleView in
            print("-- Reloading \(elementsName) stopped \(taleView)")
        }
    }

    private var randomRowAnimation: UITableView.RowAnimation {
        return UITableView.RowAnimation(rawValue: (0...6).randomElement() ?? 0) ?? UITableView.RowAnimation.automatic
    }

    @objc func reloadRowButtonTouchedUpInside(source: UIBarButtonItem) {
        guard let tableView = tableView else { return }
        let elementsName = "Rows"
        print("-- Reloading \(elementsName) started")
        let indexPathToReload = tableView.indexPathsForVisibleRows?.randomElement() ?? IndexPath(row: 0, section: 0)
        tableView.reloadRows(at: [indexPathToReload], with: randomRowAnimation) { _tableView in
            //print("-- \(taleView)")
            print("-- Reloading \(elementsName) stopped in \(_tableView)")
        }
    }

    @objc func reloadSectionButtonTouchedUpInside(source: UIBarButtonItem) {
        guard let tableView = tableView else { return }
        let elementsName = "Sections"
        print("-- Reloading \(elementsName) started")
        tableView.reloadSections(IndexSet(integer: 0), with: randomRowAnimation) { _tableView in
            //print("-- \(taleView)")
            print("-- Reloading \(elementsName) stopped in \(_tableView)")
        }
    }
}

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { return 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(Date())"
        return cell
    }
}

Results

enter image description here

How to show Bootstrap table with sort icon

You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).

To do so, you would

  1. need to include fontawesome:

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    
  2. and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th's:

    <th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
    

Hope that helps.

Javascript: 'window' is not defined

It is from an external js file and it is the only file linked to the page.

OK.

When I double click this file I get the following error

Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:

Windows Script Host Error: 'window' is not defined Code: 800A1391

... not an error you'll see in a browser. And of course, the browser is what supplies the window object.

ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload definition is simply being hit after the browser fires the window.onload event.

How to get dictionary values as a generic list

Off course, myDico.Values is List<List<MyType>>.

Use Linq if you want to flattern your lists

var items = myDico.SelectMany (d => d.Value).ToList();

How to redirect cin and cout to files?

Try this to redirect cout to file.

#include <iostream>
#include <fstream>

int main()
{
    /** backup cout buffer and redirect to out.txt **/
    std::ofstream out("out.txt");

    auto *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    std::cout << "This will be redirected to file out.txt" << std::endl;

    /** reset cout buffer **/
    std::cout.rdbuf(coutbuf);

    std::cout << "This will be printed on console" << std::endl;

    return 0;
}

Read full article Use std::rdbuf to Redirect cin and cout

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

How can I count the occurrences of a list item?

May not be the most efficient, requires an extra pass to remove duplicates.

Functional implementation :

arr = np.array(['a','a','b','b','b','c'])
print(set(map(lambda x  : (x , list(arr).count(x)) , arr)))

returns :

{('c', 1), ('b', 3), ('a', 2)}

or return as dict :

print(dict(map(lambda x  : (x , list(arr).count(x)) , arr)))

returns :

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

Java division by zero doesnt throw an ArithmeticException - why?

When divided by zero

  1. If you divide double by 0, JVM will show Infinity.

    public static void main(String [] args){ double a=10.00; System.out.println(a/0); }
    

    Console: Infinity

  2. If you divide int by 0, then JVM will throw Arithmetic Exception.

    public static void main(String [] args){
        int a=10;
        System.out.println(a/0);
    }
    

    Console: Exception in thread "main" java.lang.ArithmeticException: / by zero

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

What does 'git blame' do?

The command explains itself quite well. It's to figure out which co-worker wrote the specific line or ruined the project, so you can blame them :)

Convert textbox text to integer

Suggest do this in your code-behind before sending down to SQL Server.

 int userVal = int.Parse(txtboxname.Text);

Perhaps try to parse and optionally let the user know.

int? userVal;
if (int.TryParse(txtboxname.Text, out userVal) 
{
  DoSomething(userVal.Value);
}
else
{ MessageBox.Show("Hey, we need an int over here.");   }

The exception you note means that you're not including the value in the call to the stored proc. Try setting a debugger breakpoint in your code at the time you call down into the code that builds the call to SQL Server.

Ensure you're actually attaching the parameter to the SqlCommand.

using (SqlConnection conn = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.Add("@ParamName", SqlDbType.Int);
    cmd.Parameters["@ParamName"].Value = newName;        
    conn.Open();
    string someReturn = (string)cmd.ExecuteScalar();        
}

Perhaps fire up SQL Profiler on your database to inspect the SQL statement being sent/executed.

How can I open multiple files using "with open" in Python?

With python 2.6 It will not work, we have to use below way to open multiple files:

with open('a', 'w') as a:
    with open('b', 'w') as b:

Check/Uncheck a checkbox on datagridview

Try the below code it should work

private void checkBox2_CheckedChanged(object sender, EventArgs e) 
{
    if (checkBox2.Checked == false)
    {
        foreach (DataGridViewRow row in dGV1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
            chk.Value = chk.TrueValue;
        }
    }
   else if (checkBox2.Checked == true)
    {
        foreach (DataGridViewRow row in dGV1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
            chk.Value = 1;
            if (row.IsNewRow)
            {
                chk.Value = 0;
            }
        }
    }
}

Could not find method android() for arguments

You are using the wrong build.gradle file.

In your top-level file you can't define an android block.

Just move this part inside the module/build.gradle file.

android {
    compileSdkVersion 17
    buildToolsVersion '23.0.0'
}
dependencies {
    compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'

Iterating through array - java

If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.

If this is something that is invoked repeatedly, place it in a function:

private boolean inArray(int[] array, int value)
{  
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value) 
        {
            return true;
        }
     }
    return false;  
}  

Set the location in iPhone Simulator

  1. Run project in iPhone Simulator
  2. Create in TextEdit file following file, call it MyOffice for example. Make extension as .gpx enter image description here

    <?xml version="1.0"?> <gpx version="1.0" creator="MyName"> <wpt lat="53.936166" lon="27.565370"> <name>MyOffice</name> </wpt> </gpx>

  3. Select in Xcode at the Simulate area Add GPX File to Project...enter image description here

  4. Add created file from menu to project.
  5. Now you can see your location in Simulate area:enter image description here

How to bind a List to a ComboBox?

public MainWindow(){
    List<person> personList = new List<person>();

    personList.Add(new person { name = "rob", age = 32 } );
    personList.Add(new person { name = "annie", age = 24 } );
    personList.Add(new person { name = "paul", age = 19 } );

    comboBox1.DataSource = personList;
    comboBox1.DisplayMember = "name";

    comboBox1.SelectionChanged += new SelectionChangedEventHandler(comboBox1_SelectionChanged);
}


void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    person selectedPerson = comboBox1.SelectedItem as person;
    messageBox.Show(selectedPerson.name, "caption goes here");
}

boom.

Display Image On Text Link Hover CSS Only

CSS isn't going to be able to call other elements like that, you'll need to use JavaScript to reach beyond a child or sibling selector.

You could try something like this:

<a>Some Link
<div><img src="/you/image" /></div>
</a>

then...

a>div { display: none; }
a:hover>div { display: block; }

How to git clone a specific tag

Use --single-branch option to only clone history leading to tip of the tag. This saves a lot of unnecessary code from being cloned.

git clone <repo_url> --branch <tag_name> --single-branch

How to create unit tests easily in eclipse

You can use my plug-in to create tests easily:

  1. highlight the method
  2. press Ctrl+Alt+Shift+U
  3. it will create the unit test for it.

The plug-in is available here. Hope this helps.

How can I generate a tsconfig.json file?

You need to have typescript library installed and then you can use

npx tsc --init 

If the response is error TS5023: Unknown compiler option 'init'. that means the library is not installed

yarn add --dev typescript

and run npx command again

hadoop copy a local file system folder to HDFS

If you copy a folder from local then it will copy folder with all its sub folders to HDFS.

For copying a folder from local to hdfs, you can use

hadoop fs -put localpath

or

hadoop fs -copyFromLocal localpath

or

hadoop fs -put localpath hdfspath

or

hadoop fs -copyFromLocal localpath hdfspath

Note:

If you are not specified hdfs path then folder copy will be copy to hdfs with the same name of that folder.

To copy from hdfs to local

 hadoop fs -get hdfspath localpath

Reload content in modal (twitter bootstrap)

You can force Modal to refresh the popup by adding this line at the end of the hide method of the Modal plugin (If you are using bootstrap-transition.js v2.1.1, it should be at line 836)

this.$element.removeData()

Or with an event listener

$('#modal').on('hidden', function() {
    $(this).data('modal').$element.removeData();
})

80-characters / right margin line in Sublime Text 3

For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.

This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.

Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts

On stackoverflow, see:

Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?

MattDMo's answer here: What is the default font of Sublime Text?

I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)

Other viewing environments that benefit from shorter lines: github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.

How To Get Selected Value From UIPickerView

You will need to ask the picker's delegate, in the same way your application does. Here is how I do it from within my UIPickerViewDelegate:

func selectedRowValue(picker : UIPickerView, ic : Int) -> String {

    //Row Index
    let ir  = picker.selectedRow(inComponent: ic);

    //Value
    let val = self.pickerView(picker,
                              titleForRow:  ir,
                              forComponent: ic);
    return val!;
}

Different CURRENT_TIMESTAMP and SYSDATE in oracle

SYSDATE, SYSTIMESTAMP returns the Database's date and timestamp, whereas current_date, current_timestamp returns the date and timestamp of the location from where you work.

For eg. working from India, I access a database located in Paris. at 4:00PM IST:

select sysdate,systimestamp from dual;

This returns me the date and Time of Paris:

RESULT

12-MAY-14   12-MAY-14 12.30.03.283502000 PM +02:00

select current_date,current_timestamp from dual;

This returns me the date and Time of India:

RESULT

12-MAY-14   12-MAY-14 04.00.03.283520000 PM ASIA/CALCUTTA

Please note the 3:30 time difference.

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

I have added below code to terminate tasks you can use it. You may change the retry numbers.

package com.xxx.test.schedulers;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import com.xxx.core.XProvLogger;

@Component
class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> , ApplicationContextAware,BeanPostProcessor{


private ApplicationContext context;

public Logger logger = XProvLogger.getInstance().x;

public void onApplicationEvent(ContextClosedEvent event) {


    Map<String, ThreadPoolTaskScheduler> schedulers = context.getBeansOfType(ThreadPoolTaskScheduler.class);

    for (ThreadPoolTaskScheduler scheduler : schedulers.values()) {         
        scheduler.getScheduledExecutor().shutdown();
        try {
            scheduler.getScheduledExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
            if(scheduler.getScheduledExecutor().isTerminated() || scheduler.getScheduledExecutor().isShutdown())
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has stoped");
            else{
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has not stoped normally and will be shut down immediately");
                scheduler.getScheduledExecutor().shutdownNow();
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has shut down immediately");
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Map<String, ThreadPoolTaskExecutor> executers = context.getBeansOfType(ThreadPoolTaskExecutor.class);

    for (ThreadPoolTaskExecutor executor: executers.values()) {
        int retryCount = 0;
        while(executor.getActiveCount()>0 && ++retryCount<51){
            try {
                logger.info("Executer "+executor.getThreadNamePrefix()+" is still working with active " + executor.getActiveCount()+" work. Retry count is "+retryCount);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(!(retryCount<51))
            logger.info("Executer "+executor.getThreadNamePrefix()+" is still working.Since Retry count exceeded max value "+retryCount+", will be killed immediately");
        executor.shutdown();
        logger.info("Executer "+executor.getThreadNamePrefix()+" with active " + executor.getActiveCount()+" work has killed");
    }
}


@Override
public void setApplicationContext(ApplicationContext context)
        throws BeansException {
    this.context = context;

}


@Override
public Object postProcessAfterInitialization(Object object, String arg1)
        throws BeansException {
    return object;
}


@Override
public Object postProcessBeforeInitialization(Object object, String arg1)
        throws BeansException {
    if(object instanceof ThreadPoolTaskScheduler)
        ((ThreadPoolTaskScheduler)object).setWaitForTasksToCompleteOnShutdown(true);
    if(object instanceof ThreadPoolTaskExecutor)
        ((ThreadPoolTaskExecutor)object).setWaitForTasksToCompleteOnShutdown(true);
    return object;
}

}

Python Pandas Replacing Header with Top Row

Another one-liner using Python swapping:

df, df.columns = df[1:] , df.iloc[0]

This won't reset the index

Although, the opposite won't work as expected df.columns, df = df.iloc[0], df[1:]

Declaring static constants in ES6 classes?

The cleanest way I've found of doing this is with TypeScript - see How to implement class constants?

class MyClass {
    static readonly CONST1: string = "one";
    static readonly CONST2: string = "two";
    static readonly CONST3: string = "three";
}

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

We faced this issue, when the windowsuser detaching the database and windowsuser attaching the database are different. When the windowsuser detaching the database, tried to attach it, it worked fine without issues.

Convert sqlalchemy row object to python dict

As per @zzzeek in comments:

note that this is the correct answer for modern versions of SQLAlchemy, assuming "row" is a core row object, not an ORM-mapped instance.

for row in resultproxy:
    row_as_dict = dict(row)

sql query to return differences between two tables

There is a performance issue related with the left join as well as full join with large data.

In my opinion this is the best solution:

select [First Name], count(1) e from (select * from [Temp Test Data] union all select * from [Temp Test Data 2]) a group by [First Name] having e = 1

Set a border around a StackPanel.

You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.

If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

Anaconda Navigator won't launch (windows 10)

You need to update Anaconda using:

conda update

and

conda update anaconda-navigator

Try these commands on anaconda prompt and then try to launch navigator from the prompt itself using following command:

anaconda-navigator

If still the problem doesn't get solved, share the anaconda prompt logs here if they have any errors.

Multiple returns from a function

The answer is no. When the parser reaches the first return statement, it will direct control back to the calling function - your second return statement will never be executed.

Converting from hex to string

Like so?

static void Main()
{
    byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
    string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
    hex = hex.Replace("-", "");
    byte[] raw = new byte[hex.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return raw;
}

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

I would always use sp_executesql these days, all it really is is a wrapper for EXEC which handles parameters & variables.

However do not forget about OPTION RECOMPILE when tuning queries on very large databases, especially where you have data spanned over more than one database and are using a CONSTRAINT to limit index scans.

Unless you use OPTION RECOMPILE, SQL server will attempt to create a "one size fits all" execution plan for your query, and will run a full index scan each time it is run.

This is much less efficient than a seek, and means it is potentially scanning entire indexes which are constrained to ranges which you are not even querying :@

Where does Oracle SQL Developer store connections?

Assuming you have lost these while upgrading versions like I did, follow these steps to restore:

  1. Open SQL Developer
  2. Right click on Connections
  3. Chose Import Connections...
  4. Click Browse (should open to your SQL Developer directory)
  5. Drill down to "systemx.x.xx.xx" (replace x's with your previous version of SQL Developer)
  6. Find and drill into a folder that has ".db.connection." in it (for me, it was in o.jdeveloper.db.connection.11.1.1.4.37.59.48)
  7. select connections.xml and click open

You should then see the list of connections that will be imported

Sum rows in data.frame or matrix

I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind function:

cbind(data, total = rowSums(data))

This method adds a total column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).

Adding a new column to matrix error

Xcode Product -> Archive disabled

Select active scheme to Generic iOs Device.

select to Generic iOs Device

How to run docker-compose up -d at system start up?

As an addition to user39544's answer, one more type of syntax for crontab -e:

@reboot sleep 60 && /usr/local/bin/docker-compose -f /path_to_your_project/docker-compose.yml up -d

How does the bitwise complement operator (~ tilde) work?


The Bitwise complement operator(~) is a unary operator.

It works as per the following methods

First it converts the given decimal number to its corresponding binary value.That is in case of 2 it first convert 2 to 0000 0010 (to 8 bit binary number).

Then it converts all the 1 in the number to 0,and all the zeros to 1;then the number will become 1111 1101.

that is the 2's complement representation of -3.

In order to find the unsigned value using complement,i.e. simply to convert 1111 1101 to decimal (=4294967293) we can simply use the %u during printing.

How to create a directory using Ansible

To check if directory exists and then run some task (e.g. create directory) use the following

- name: Check if output directory exists
    stat:
    path: /path/to/output
    register: output_folder

- name: Create output directory if not exists
    file:
    path: /path/to/output
    state: directory
    owner: user
    group: user
    mode: 0775
    when: output_folder.stat.exists == false

Is there an ignore command for git like there is for svn?

On Linux/Unix, you can append files to the .gitignore file with the echo command. For example if you want to ignore all .svn folders, run this from the root of the project:

echo .svn/ >> .gitignore

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Or you can just create your own MediaTypeFormatter. I use this for text/html. If you add text/plain to it, it'll work for you too:

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        using (var streamReader = new StreamReader(readStream))
        {
            return await streamReader.ReadToEndAsync();
        }
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}

Finally you have to assign this to the HttpMethodContext.ResponseFormatter property.

C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops:

for (auto &attack : m_attack) // access by reference to avoid copying
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

You should use const auto &attack depending on the behavior of makeDamage().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
        [](Attack * attack)
        {
            if (attack->m_num == input)
            {
                attack->makeDamage();
            }
        }
);

If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

Use m_attack.cbegin() and m_attack.cend() to get const iterators.

jQuery: Best practice to populate drop down?

Or maybe:

var options = $("#options");
$.each(data, function() {
    options.append(new Option(this.text, this.value));
});

How to clear Facebook Sharer cache?

I just posted a simple solution that takes 5 seconds here on a related post here - Facebook debugger: Clear whole site cache

short answer... change your permalinks on a worpdress site in the permalinks settings to a custom one. I just added an underscore.
/_%postname%/
then facebook scrapes them all as new urls, new posts.

How to fix docker: Got permission denied issue

It only requires the changes in permission of sock file.

sudo chmod 666 /var/run/docker.sock

this will work definately.

How to undo a SQL Server UPDATE query?

If you can catch this in time and you don't have the ability to ROLLBACK or use the transaction log, you can take a backup immediately and use a tool like Redgate's SQL Data Compare to generate a script to "restore" the affected data. This worked like a charm for me. :)

Filter df when values matches part of a string in pyspark

Spark 2.2 onwards

df.filter(df.location.contains('google.com'))

Spark 2.2 documentation link


Spark 2.1 and before

You can use plain SQL in filter

df.filter("location like '%google.com%'")

or with DataFrame column methods

df.filter(df.location.like('%google.com%'))

Spark 2.1 documentation link

check android application is in foreground or not?

Try ActivityLifecycleCallbacks in your Application class.

understanding private setters

I don't understand the need of having private setters which started with C# 2.

For example, the invoice class allows the user to add or remove items from the Items property but it does not allow the user from changing the Items reference (ie, the user cannot assign Items property to another item list object instance).


public class Item
{
  public string item_code;
  public int qty;

  public Item(string i, int q)
  {
    this.item_code = i;
    this.qty = q;
  }
}

public class Invoice
{
  public List Items { get; private set; }

  public Invoice()
  {
    this.Items = new List();
  }
}

public class TestInvoice
{
  public void Test()
  {
    Invoice inv = new Invoice();
    inv.Items.Add(new Item("apple", 10));

    List my_items = new List();
    my_items.Add(new Item("apple", 10));

    inv.Items = my_items;   // compilation error here.
  }
}

How to add new DataRow into DataTable?

This works for me:

var table = new DataTable();
table.Rows.Add();

Check if number is decimal

I was passed a string, and wanted to know if it was a decimal or not. I ended up with this:

function isDecimal($value) 
{
     return ((float) $value !== floor($value));
}

I ran a bunch of test including decimals and non-decimals on both sides of zero, and it seemed to work.

Replace multiple strings with multiple other strings

by using prototype function we can replace easily by passing object with keys and values and replacable text

_x000D_
_x000D_
String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
 return Object.entries(obj).reduce((a,[key,val])=> a.replace(`${keys[0]}${key}${keys[1]}`,val),this)
}

const data='hids dv sdc sd ${yathin} ${ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'${key}'))
_x000D_
_x000D_
_x000D_

How can I make an svg scale with its parent container?

Adjusting the currentScale attribute works in IE ( I tested with IE 11), but not in Chrome.

Is there a way to add a gif to a Markdown file?

Showing gifs need two things

1- Use this syntax as in these examples

![Alt Text](https://media.giphy.com/media/vFKqnCdLPNOKc/giphy.gif)

Yields:

Alt Text

2- The image url must end with gif

3- For posterity: if the .gif link above ever goes bad, you will not see the image and instead see the alt-text and URL, like this:

Alt Text

4- for resizing the gif you can use this syntax as in this Github tutorial link

<img src="https://media.giphy.com/media/vFKqnCdLPNOKc/giphy.gif" width="40" height="40" />

Yields:

Best way to check if column returns a null value (from database to .net application)

Just check for

if(table.rows[0][0] == null)
{
     //Whatever I want to do
}

or you could

if(t.Rows[0].IsNull(0))
{
     //Whatever I want to do
}

How good is Java's UUID.randomUUID?

The original generation scheme for UUIDs was to concatenate the UUID version with the MAC address of the computer that is generating the UUID, and with the number of 100-nanosecond intervals since the adoption of the Gregorian calendar in the West. By representing a single point in space (the computer) and time (the number of intervals), the chance of a collision in values is effectively nil.

Finding an element in an array in Java

Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.

Chrome ignores autocomplete="off"

None of the solutions worked except for giving it a fake field to autocomplete. I made a React component to address this issue.

import React from 'react'

// Google Chrome stubbornly refuses to respect the autocomplete="off" HTML attribute so
// we have to give it a "fake" field for it to autocomplete that never gets "used".

const DontBeEvil = () => (
  <div style={{ display: 'none' }}>
    <input type="text" name="username" />
    <input type="password" name="password" />
  </div>
)

export default DontBeEvil

Java escape JSON String?

The JSON specification at https://www.json.org/ is very simple by design. Escaping characters in JSON strings is not hard. This code works for me:

private String escape(String raw) {
    String escaped = raw;
    escaped = escaped.replace("\\", "\\\\");
    escaped = escaped.replace("\"", "\\\"");
    escaped = escaped.replace("\b", "\\b");
    escaped = escaped.replace("\f", "\\f");
    escaped = escaped.replace("\n", "\\n");
    escaped = escaped.replace("\r", "\\r");
    escaped = escaped.replace("\t", "\\t");
    // TODO: escape other non-printing characters using uXXXX notation
    return escaped;
}

CodeIgniter htaccess and URL rewrite issues

Your .htaccess is slightly off. Look at mine:

 RewriteEngine On
 RewriteBase /codeigniter  

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond $1 !^(index\.php|images|robots\.txt|css|docs|js|system)
  RewriteRule ^(.*)$ /codeigniter/index.php?/$1 [L]

Notice "codeigniter" in two places.

after that, in your config:

base_url = "http://localhost/codeigniter"
index = ""

Change codeigniter to "ci" whereever appropriate

Resize image in the wiki of GitHub using Markdown

Almost 5 years after only the direct HTML formatting works for images on GitHub and other markdown options still prevent images from loading when specifying some custom sizes even with the wrong dimensions. I prefer to specify the desired width and get the height calculated automatically, for example,

_x000D_
_x000D_
<img src="https://github.com/your_image.png" alt="Your image title" width="250"/>
_x000D_
_x000D_
_x000D_

How can I get a precise time, for example in milliseconds in Objective-C?

I know this is an old one but even I found myself wandering past it again, so I thought I'd submit my own option here.

Best bet is to check out my blog post on this: Timing things in Objective-C: A stopwatch

Basically, I wrote a class that does stop watching in a very basic way but is encapsulated so that you only need to do the following:

[MMStopwatchARC start:@"My Timer"];
// your work here ...
[MMStopwatchARC stop:@"My Timer"];

And you end up with:

MyApp[4090:15203]  -> Stopwatch: [My Timer] runtime: [0.029]

in the log...

Again, check out my post for a little more or download it here: MMStopwatch.zip

On Selenium WebDriver how to get Text from Span Tag

Maybe the span element is hidden. If that's the case then use the innerHtml property:

By.css:

String kk = wd.findElement(By.cssSelector("#customSelect_3 span.selectLabel"))
              .getAttribute("innerHTML");

By.xpath:

String kk = wd.findElement(By.xpath(
                   "//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel')]"))
              .getAttribute("innerHTML");

"/.//" means "look under the selected element".

Opening a new tab to read a PDF file

Try this, it worked for me.

<td><a href="Docs/Chapter 1_ORG.pdf" target="pdf-frame">Chapter-1 Organizational</a></td>

How to enable mod_rewrite for Apache 2.2

Use below command

sudo a2enmod rewrite

And the restart apache through below command

sudo service apache2 restart

How can I set multiple CSS styles in JavaScript?

Using Object.assign:

Object.assign(yourelement.style,{fontsize:"12px",left:"200px",top:"100px"});

This also gives you ability to merge styles, instead of rewriting the CSS style.

You can also make a shortcut function:

const setStylesOnElement = function(styles, element){
    Object.assign(element.style, styles);
}

How to get a random value from dictionary?

If you don't want to use random.choice() you can try this way:

>>> list(myDictionary)[i]
'VENEZUELA'
>>> myDictionary = {'VENEZUELA':'CARACAS', 'IRAN' : 'TEHRAN'}
>>> import random
>>> i = random.randint(0, len(myDictionary) - 1)
>>> myDictionary[list(myDictionary)[i]]
'TEHRAN'
>>> list(myDictionary)[i]
'IRAN'

How to customize message box

Here is the code needed to create your own message box:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyStuff
{
    public class MyLabel : Label
    {
        public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Label l = new Label();
            l.Text = Text;
            l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            l.AutoSize = true;
            return l;
        }
    }
    public class MyButton : Button
    {
        public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Button b = new Button();
            b.Text = Text;
            b.Width = Width;
            b.Height = Height;
            b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
            return b;
        }
    }
    public class MyImage : PictureBox
    {
        public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
        {
            PictureBox i = new PictureBox();
            if (ImagePath != null)
            {
                i.BackgroundImageLayout = ImageLayout.Zoom;
                i.Location = new Point(9, 9);
                i.Margin = new Padding(3, 3, 2, 3);
                i.Size = new Size(Width, Height);
                i.TabStop = false;
                i.Visible = true;
                i.BackgroundImage = Image.FromFile(ImagePath);
            }
            else
            {
                i.Visible = true;
                i.Size = new Size(0, 0);
            }
            return i;
        }
    }
    public partial class MyMessageBox : Form
    {
        private MyMessageBox()
        {
            this.panText = new FlowLayoutPanel();
            this.panButtons = new FlowLayoutPanel();
            this.SuspendLayout();
            // 
            // panText
            // 
            this.panText.Parent = this;
            this.panText.AutoScroll = true;
            this.panText.AutoSize = true;
            this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            //this.panText.Location = new Point(90, 90);
            this.panText.Margin = new Padding(0);
            this.panText.MaximumSize = new Size(500, 300);
            this.panText.MinimumSize = new Size(108, 50);
            this.panText.Size = new Size(108, 50);
            // 
            // panButtons
            // 
            this.panButtons.AutoSize = true;
            this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            this.panButtons.FlowDirection = FlowDirection.RightToLeft;
            this.panButtons.Location = new Point(89, 89);
            this.panButtons.Margin = new Padding(0);
            this.panButtons.MaximumSize = new Size(580, 150);
            this.panButtons.MinimumSize = new Size(108, 0);
            this.panButtons.Size = new Size(108, 35);
            // 
            // MyMessageBox
            // 
            this.AutoScaleDimensions = new SizeF(8F, 19F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(206, 133);
            this.Controls.Add(this.panButtons);
            this.Controls.Add(this.panText);
            this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.Margin = new Padding(4);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.MinimumSize = new Size(168, 132);
            this.Name = "MyMessageBox";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(Label);
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(MyLabel.Set(Label));
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            if (Labels == null) Labels = new List<Label>();
            if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
            if (Buttons == null) Buttons = new List<Button>();
            if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
            List<Button> buttons = new List<Button>(Buttons);
            buttons.Reverse();

            int ImageWidth = 0;
            int ImageHeight = 0;
            int LabelWidth = 0;
            int LabelHeight = 0;
            int ButtonWidth = 0;
            int ButtonHeight = 0;
            int TotalWidth = 0;
            int TotalHeight = 0;

            MyMessageBox mb = new MyMessageBox();

            mb.Text = Title;

            //Image
            if (Image != null)
            {
                mb.Controls.Add(Image);
                Image.MaximumSize = new Size(150, 300);
                ImageWidth = Image.Width + Image.Margin.Horizontal;
                ImageHeight = Image.Height + Image.Margin.Vertical;
            }

            //Labels
            List<int> il = new List<int>();
            mb.panText.Location = new Point(9 + ImageWidth, 9);
            foreach (Label l in Labels)
            {
                mb.panText.Controls.Add(l);
                l.Location = new Point(200, 50);
                l.MaximumSize = new Size(480, 2000);
                il.Add(l.Width);
            }
            int mw = Labels.Max(x => x.Width);
            il.ToString();
            Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
            mb.panText.Height = Labels.Sum(l => l.Height);
            mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
            mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
            LabelWidth = mb.panText.Width;
            LabelHeight = mb.panText.Height;

            //Buttons
            foreach (Button b in buttons)
            {
                mb.panButtons.Controls.Add(b);
                b.Location = new Point(3, 3);
                b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
                b.Click += new EventHandler(mb.Button_Click);
            }
            ButtonWidth = mb.panButtons.Width;
            ButtonHeight = mb.panButtons.Height;

            //Set Widths
            if (ButtonWidth > ImageWidth + LabelWidth)
            {
                Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
                mb.panText.Height = Labels.Sum(l => l.Height);
                mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
                mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
                LabelWidth = mb.panText.Width;
                LabelHeight = mb.panText.Height;
            }
            TotalWidth = ImageWidth + LabelWidth;

            //Set Height
            TotalHeight = LabelHeight + ButtonHeight;

            mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);

            mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
            mb.ShowDialog();
            return mb.Result;
        }

        private FlowLayoutPanel panText;
        private FlowLayoutPanel panButtons;
        private int ScrollBarWidth(List<Label> Labels)
        {
            return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Result = ((Button)sender).Text;
            Close();
        }

        private string Result = "";
    }
}   

jQuery Loop through each div

Like this:

$(".target").each(function(){
    var images = $(this).find(".scrolling img");
    var width = images.width();
    var imgLength = images.length;
    $(this).find(".scrolling").width( width * imgLength * 1.2 );
});

The $(this) refers to the current .target which will be looped through. Within this .target I'm looking for the .scrolling img and get the width. And then keep on going...

Images with different widths

If you want to calculate the width of all images (when they have different widths) you can do it like this:

// Get the total width of a collection.
$.fn.getTotalWidth = function(){
    var width = 0;
    this.each(function(){
        width += $(this).width();
    });
    return width;
}

$(".target").each(function(){
    var images = $(this).find(".scrolling img");
    var width = images.getTotalWidth();
    $(this).find(".scrolling").width( width * 1.2 );
});

Change Circle color of radio button

There is an xml attribute for it:

android:buttonTint="yourcolor"

Recursively find files with a specific extension

As a script you can use:

find "${2:-.}" -iregex ".*${1:-Robert}\.\(h\|cpp\)$" -print
  • save it as findcc
  • chmod 755 findcc

and use it as

findcc [name] [[search_direcory]]

e.g.

findcc                 # default name 'Robert' and directory .
findcc Joe             # default directory '.'
findcc Joe /somewhere  # no defaults

note you cant use

findcc /some/where    #eg without the name...

also as alternative, you can use

find "$1" -print | grep "$@" 

and

findcc directory grep_options

like

findcc . -P '/Robert\.(h|cpp)$'

How to secure MongoDB with username and password

You'll need to switch to the database you want the user on (not the admin db) ...

use mydatabase

See this post for more help ... https://web.archive.org/web/20140316031938/http://learnmongo.com/posts/quick-tip-mongodb-users/

Simple dictionary in C++

This is the fastest, simplest, smallest space solution I can think of. A good optimizing compiler will even remove the cost of accessing the pair and name arrays. This solution works equally well in C.

#include <iostream>

enum Base_enum { A, C, T, G };
typedef enum Base_enum Base;
static const Base pair[4] = { T, G, A, C };
static const char name[4] = { 'A', 'C', 'T', 'G' };
static const Base base[85] = 
  { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1,  A, -1,  C, -1, -1,
    -1,  G, -1, -1, -1, -1, -1, -1, -1, -1, 
    -1, -1, -1, -1,  T };

const Base
base2 (const char b)
{
  switch (b)
    {
    case 'A': return A;
    case 'C': return C;
    case 'T': return T;
    case 'G': return G;
    default: abort ();
    }
}

int
main (int argc, char *args) 
{
  for (Base b = A; b <= G; b++)
    {
      std::cout << name[b] << ":" 
                << name[pair[b]] << std::endl;
    }
  for (Base b = A; b <= G; b++)
    {
      std::cout << name[base[name[b]]] << ":" 
                << name[pair[base[name[b]]]] << std::endl;
    }
  for (Base b = A; b <= G; b++)
    {
      std::cout << name[base2(name[b])] << ":" 
                << name[pair[base2(name[b])]] << std::endl;
    }
};

base[] is a fast ascii char to Base (i.e. int between 0 and 3 inclusive) lookup that is a bit ugly. A good optimizing compiler should be able to handle base2() but I'm not sure if any do.

What is the difference between HAVING and WHERE in SQL?

HAVING is used when you are using an aggregate such as GROUP BY.

SELECT edc_country, COUNT(*)
FROM Ed_Centers
GROUP BY edc_country
HAVING COUNT(*) > 1
ORDER BY edc_country;

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Just edit your your catalina/bin/startup.sh script. Add the following commands in it:

#Adjust it to the size you want. Ignore the from bit.
export CATALINA_OPTS="-Xmx1024m"
#This should point to your catalina base directory 
export CATALINA_BASE=/usr/local/tomcat
#This is only used if you editing the instance of your tomcat
/usr/share/tomcat6/bin/startup.sh

Sailab: http://www.facejar.com/member/page-id-477.html

changing visibility using javascript

function loadpage (page_request, containerid)
{
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 )
      loading.style.visibility = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
  {
      document.getElementById(containerid).innerHTML=page_request.responseText ;
      loading.style.visibility = "hidden" ;
  }
}

Split Div Into 2 Columns Using CSS

Divide a division in two columns is very easy, just specify the width of your column better if you put this (like width:50%) and set the float:left for left column and float:right for right column.

Laravel: Get base url

Laravel < 5.2

echo url();

Laravel >= 5.2

echo url('/');

Hope this helps you

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

Python debugging tips

In Vim, I have these three bindings:

map <F9> Oimport rpdb2; rpdb2.start_embedded_debugger("asdf") #BREAK<esc>
map <F8> Ofrom nose.tools import set_trace; set_trace() #BREAK<esc>
map <F7> Oimport traceback, sys; traceback.print_exception(*sys.exc_info()) #TRACEBACK<esc>

rpdb2 is a Remote Python Debugger, which can be used with WinPDB, a solid graphical debugger. Because I know you'll ask, it can do everything I expect a graphical debugger to do :)

I use pdb from nose.tools so that I can debug unit tests as well as normal code.

Finally, the F7 mapping will print a traceback (similar to the kind you get when an exception bubbles to the top of the stack). I've found it really useful more than a few times.

I lose my data when the container exits

When you use docker run to start a container, it actually creates a new container based on the image you have specified.

Besides the other useful answers here, note that you can restart an existing container after it exited and your changes are still there.

docker start f357e2faab77 # restart it in the background
docker attach f357e2faab77 # reattach the terminal & stdin

Codeigniter $this->db->order_by(' ','desc') result is not complete

$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();

In Rails, how do you render JSON using a view?

This is potentially a better option and faster than ERB: https://github.com/dewski/json_builder

get list of pandas dataframe columns based on data type

If after 6 years you still have the issue, this should solve it :)

cols = [c for c in df.columns if df[c].dtype in ['object', 'datetime64[ns]']]

How to instantiate a javascript class in another js file?

You can export your methods to access from other files like this:

file1.js

var name = "Jhon";
exports.getName = function() {
  return name;
}

file2.js

var instance = require('./file1.js');
var name = instance.getName();

remove double quotes from Json return data using Jquery

For niche needs when you know your data like your example ... this works :

JSON.parse(this_is_double_quoted);

JSON.parse("House");  // for example

Setting DEBUG = False causes 500 Error

Thanks to @squarebear, in the log file, I found the error: ValueError: The file 'myapp/styles.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage ...>.

I had a few problems in my django app. I removed the line
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' which I found from the heroku's documentation.

I also had to add extra directory (thanks to another SO answer) static in the root of django application as myapp/static even though I wasn't using it. Then running the command python manage.py collectstatic before running the server solved the problem. Finally, it started working fine.

Use basic authentication with jQuery and Ajax

According to SharkAlley answer it works with nginx too.

I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:

server {
    server_name example.com;

    location / {
        if ($request_method = OPTIONS ) {
            add_header Access-Control-Allow-Origin "*";
            add_header Access-Control-Allow-Methods "GET, OPTIONS";
            add_header Access-Control-Allow-Headers "Authorization";

            # Not necessary
            #            add_header Access-Control-Allow-Credentials "true";
            #            add_header Content-Length 0;
            #            add_header Content-Type text/plain;

            return 200;
        }

        auth_basic "Restricted";
        auth_basic_user_file /var/.htpasswd;

        proxy_pass http://127.0.0.1:8100;
    }
}

And the JavaScript code is:

var auth = btoa('username:password');
$.ajax({
    type: 'GET',
    url: 'http://example.com',
    headers: {
        "Authorization": "Basic " + auth
    },
    success : function(data) {
    },
});

Article that I find useful:

  1. This topic's answers
  2. http://enable-cors.org/server_nginx.html
  3. http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method/

Windows 7 - Add Path

Another method that worked for me on Windows 7 that did not require administrative privileges:

Click on the Start menu, search for "environment," click "Edit environment variables for your account."

In the window that opens, select "PATH" under "User variables for username" and click the "Edit..." button. Add your new path to the end of the existing Path, separated by a semi-colon (%PATH%;C:\Python27;...;C:\NewPath). Click OK on all the windows, open a new CMD window, and test the new variable.

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

Drop unused factor levels in a subsetted data frame

This is obnoxious. This is how I usually do it, to avoid loading other packages:

levels(subdf$letters)<-c("a","b","c",NA,NA)

which gets you:

> subdf$letters
[1] a b c
Levels: a b c

Note that the new levels will replace whatever occupies their index in the old levels(subdf$letters), so something like:

levels(subdf$letters)<-c(NA,"a","c",NA,"b")

won't work.

This is obviously not ideal when you have lots of levels, but for a few, it's quick and easy.

Eclipse Error: "Failed to connect to remote VM"

The solution that worked for me is weird

  1. Simply remove the all the break points
  2. Restart tomcat in debug mode (using catalina.sh jpda start)
  3. Now try to connect and it worked!!!!

How to use radio on change event?

Use onchage function

<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot" onchange="my_function('allot')">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer" onchange="my_function('transfer')">Transfer

<script>
 function my_function(val){
    alert(val);
 }
</script>

How do I remove repeated elements from ArrayList?

If you are using model type List< T>/ArrayList< T> . Hope,it's help you.

Here is my code without using any other data structure like set or hashmap

for (int i = 0; i < Models.size(); i++){
for (int j = i + 1; j < Models.size(); j++) {       
 if (Models.get(i).getName().equals(Models.get(j).getName())) {    
 Models.remove(j);
   j--;
  }
 }
}

Cocoa: What's the difference between the frame and the bounds?

frame is the origin (top left corner) and size of the view in its super view's coordinate system , this means that you translate the view in its super view by changing the frame origin , bounds on the other hand is the size and origin in its own coordinate system , so by default the bounds origin is (0,0).

most of the time the frame and bounds are congruent , but if you have a view of frame ((140,65),(200,250)) and bounds ((0,0),(200,250))for example and the view was tilted so that it stands on its bottom right corner , then the bounds will still be ((0,0),(200,250)) , but the frame is not .

enter image description here

the frame will be the smallest rectangle that encapsulates/surrounds the view , so the frame (as in the photo) will be ((140,65),(320,320)).

another difference is for example if you have a superView whose bounds is ((0,0),(200,200)) and this superView has a subView whose frame is ((20,20),(100,100)) and you changed the superView bounds to ((20,20),(200,200)) , then the subView frame will be still ((20,20),(100,100)) but offseted by (20,20) because its superview coordinate system was offseted by (20,20).

i hope this helps somebody.

Assigning strings to arrays of characters

You can use this:

yylval.sval=strdup("VHDL + Volcal trance...");

Where yylval is char*. strdup from does the job.

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

Save attachments to a folder and rename them

See ReceivedTime Property

http://msdn.microsoft.com/en-us/library/office/aa171873(v=office.11).aspx

You added another \ to the end of C:\Temp\ in the SaveAs File line. Could be a problem. Do a test first before adding a path separator.

dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  
saveFolder = "C:\Temp"

You have not set objAtt so there is no need for "Set objAtt = Nothing". If there was it would be just before End Sub not in the loop.


Public Sub saveAttachtoDisk (itm As Outlook.MailItem) 
    Dim objAtt As Outlook.Attachment 
    Dim saveFolder As String Dim dateFormat
    dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  saveFolder = "C:\Temp"
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
    Next
End Sub

Re: It worked the first day I started tinkering but after that it stopped saving files.

This is usually due to Security settings. It is a "trap" set for first time users to allow macros then take it away. http://www.slipstick.com/outlook-developer/how-to-use-outlooks-vba-editor/

Android - shadow on text?

You should be able to add the style, like this (taken from source code for Ringdroid):

  <style name="AudioFileInfoOverlayText">
    <item name="android:paddingLeft">4px</item>
    <item name="android:paddingBottom">4px</item>
    <item name="android:textColor">#ffffffff</item>
    <item name="android:textSize">12sp</item>
    <item name="android:shadowColor">#000000</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>
  </style>

And in your layout, use the style like this:

 <TextView android:id="@+id/info"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       style="@style/AudioFileInfoOverlayText"
       android:gravity="center" />

Edit: the source code can be viewed here: https://github.com/google/ringdroid

Edit2: To set this style programmatically, you'd do something like this (modified from this example to match ringdroid's resources from above)

TextView infoTextView = (TextView) findViewById(R.id.info);
infoTextView.setTextAppearance(getApplicationContext(),  
       R.style.AudioFileInfoOverlayText);

The signature for setTextAppearance is

public void setTextAppearance (Context context, int resid)

Since: API Level 1
Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance resource.

How do I use boolean variables in Perl?

My favourites have always been

use constant FALSE => 1==0;
use constant TRUE => not FALSE;

which is completely independent from the internal representation.

How to Specify "Vary: Accept-Encoding" header in .htaccess

To gzip up your font files as well!

add "x-font/otf x-font/ttf x-font/eot"

as in:

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml x-font/otf x-font/ttf x-font/eot

How to get the current TimeStamp?

I think you are looking for this function:

http://doc.qt.io/qt-5/qdatetime.html#toTime_t

uint QDateTime::toTime_t () const

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).

On systems that do not support time zones, this function will behave as if local time were Qt::UTC.

See also setTime_t().

How to send image to PHP file using Ajax?

Here is code that will upload multiple images at once, into a specific folder!

The HTML:

<form method="post" enctype="multipart/form-data" id="image_upload_form" action="submit_image.php">
<input type="file" name="images" id="images" multiple accept="image/x-png, image/gif, image/jpeg, image/jpg" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">

</ul>

The PHP:

<?php
$errors = $_FILES["images"]["error"];
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
    $name = $_FILES["images"]["name"][$key];
    //$ext = pathinfo($name, PATHINFO_EXTENSION);
    $name = explode("_", $name);
    $imagename='';
    foreach($name as $letter){
        $imagename .= $letter;
    }

    move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" .  $imagename);

}
}


echo "<h2>Successfully Uploaded Images</h2>";

And finally, the JavaSCript/Ajax:

(function () {
var input = document.getElementById("images"), 
    formdata = false;

function showUploadedItem (source) {
    var list = document.getElementById("image-list"),
        li   = document.createElement("li"),
        img  = document.createElement("img");
    img.src = source;
    li.appendChild(img);
    list.appendChild(li);
}   

if (window.FormData) {
    formdata = new FormData();
    document.getElementById("btn").style.display = "none";
}

input.addEventListener("change", function (evt) {
    document.getElementById("response").innerHTML = "Uploading . . ."
    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];

        if (!!file.type.match(/image.*/)) {
            if ( window.FileReader ) {
                reader = new FileReader();
                reader.onloadend = function (e) { 
                    showUploadedItem(e.target.result, file.fileName);
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("images[]", file);
            }
        }   
    }

    if (formdata) {
        $.ajax({
            url: "submit_image.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                document.getElementById("response").innerHTML = res;
            }
        });
    }
}, false);
}());

Hope this helps