Programs & Examples On #Livescribe

How to check if a user likes my Facebook Page or URL using Facebook's API

i use jquery to send the data when the user press the like button.

<script>
  window.fbAsyncInit = function() {
    FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
             xfbml: true});

                 FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() { 

var h_fbl=href.split("/");
var fbl_id= h_fbl[4]; 


 $.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )

}) });
  };

</script>

Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example: url: http://mywebsite.com/post/22/some-tittle

so i parse the url to get the id and then insert it to my databse in the like.php file. in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.

Consider defining a bean of type 'service' in your configuration [Spring boot]

You are trying to inject a bean in itself. That's obviously not going to work.

TopicServiceImplementation implements TopicService. That class attempts to autowire (by field!) a `TopicService. So you're essentially asking the context to inject itself.

It looks like you've edited the content of the error message: Field topicService in seconds47.restAPI.topics is not a class. Please be careful if you need to hide sensitive information as it makes it much harder for others to help you.

Back on the actual issue, it looks like injecting TopicService in itself is a glitch on your side.

Get URL of ASP.Net Page in code-behind

Using a js file you can capture the following, that can be used in the codebehind as well:

<script type="text/javascript">
    alert('Server: ' + window.location.hostname);
    alert('Full path: ' + window.location.href);
    alert('Virtual path: ' + window.location.pathname);
    alert('HTTP path: ' + 
        window.location.href.replace(window.location.pathname, ''));    
</script>

Tools to generate database tables diagram with Postgresql?

Inside Eclipse I've used the Clay plugin (ex Clay-Azurri). The free version allows to introspect ("reverse engineer") an existing DB schema (via JDBC) and make a diagram of some selected tables.

is there something like isset of php in javascript/jQuery?

http://phpjs.org/functions/isset:454

phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.

Get yesterday's date in bash on Linux, DST-safe

you can use

date -d "30 days ago" +"%d/%m/%Y"

to get the date from 30 days ago, similarly you can replace 30 with x amount of days

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

SQL Server SELECT INTO @variable?

It looks like your syntax is slightly out. This has some good examples

DECLARE @TempCustomer TABLE
(
   CustomerId uniqueidentifier,
   FirstName nvarchar(100),
   LastName nvarchar(100),
   Email nvarchar(100)
);
INSERT @TempCustomer 
SELECT 
    CustomerId, 
    FirstName, 
    LastName, 
    Email 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId

Then later

SELECT CustomerId FROM @TempCustomer

Convert string (without any separator) to list

''.join(filter(str.isdigit, "+123-456-7890"))

Steps to upload an iPhone application to the AppStore

Xcode 9

If this is your first time to submit an app, I recommend going ahead and reading through the full Apple iTunes Connect documentation or reading one of the following tutorials:

However, those materials are cumbersome when you just want a quick reminder of the steps. My answer to that is below:

Step 1: Create a new app in iTunes Connect

Sign in to iTunes Connect and go to My Apps. Then click the "+" button and choose New App.

enter image description here

Then fill out the basic information for a new app. The app bundle id needs to be the same as the one you are using in your Xcode project. There is probably a better was to name the SKU, but I've never needed it and I just use the bundle id.

enter image description here

Click Create and then go on to Step 2.

Step 2: Archive your app in Xcode

Choose the Generic iOS Device from the active scheme menu.

enter image description here

Then go to Product > Archive.

enter image description here

You may have to wait a little while for Xcode to finish archiving your project. After that you will be shown a dialog with your archived project. You can select Upload to the App Store... and follow the prompts.

I sometimes have to repeat this step a few times because I forgot to include something. Besides the upload wait, it isn't a big deal. Just keep doing it until you don't get any more errors.

Step 3: Finish filling out the iTunes Connect info

Back in iTunes Connect you will need to complete all the required information and resources.

enter image description here

Just go through all the menu options and make sure that you have everything entered that needs to be.

Step 4: Submit

In iTunes Connect, under your app's Prepare for Submission section, click Submit for Review. That's it. Give it about a week to be accepted (or rejected), but it might be faster.

Extract and delete all .gz in a directory- Linux

There's more than one way to do this obviously.

    # This will find files recursively (you can limit it by using some 'find' parameters. 
    # see the man pages
    # Final backslash required for exec example to work
    find . -name '*.gz' -exec gunzip '{}' \;

    # This will do it only in the current directory
    for a in *.gz; do gunzip $a; done

I'm sure there's other ways as well, but this is probably the simplest.

And to remove it, just do a rm -rf *.gz in the applicable directory

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

How to add a color overlay to a background image?

You can use a pseudo element to create the overlay.

.testclass {
  background-image: url("../img/img.jpg");
  position: relative;
}
.testclass:before {
  content: "";
  position: absolute;
  left: 0; right: 0;
  top: 0; bottom: 0;
  background: rgba(0,0,0,.5);
}

Comparing floating point number to zero

No.

Equality is equality.

The function you wrote will not test two doubles for equality, as its name promises. It will only test if two doubles are "close enough" to each other.

If you really want to test two doubles for equality, use this one:

inline bool isEqual(double x, double y)
{
   return x == y;
}

Coding standards usually recommend against comparing two doubles for exact equality. But that is a different subject. If you actually want to compare two doubles for exact equality, x == y is the code you want.

10.000000000000001 is not equal to 10.0, no matter what they tell you.

An example of using exact equality is when a particular value of a double is used as a synonym of some special state, such as "pending calulation" or "no data available". This is possible only if the actual numeric values after that pending calculation are only a subset of the possible values of a double. The most typical particular case is when that value is nonnegative, and you use -1.0 as an (exact) representation of a "pending calculation" or "no data available". You could represent that with a constant:

const double NO_DATA = -1.0;

double myData = getSomeDataWhichIsAlwaysNonNegative(someParameters);

if (myData != NO_DATA)
{
    ...
}

When to use: Java 8+ interface default method, vs. abstract method

Whenever we have a choice between abstract class and interface we should always (almost) prefer default (also known as defender or virtual extensions) methods.

  1. Default methods have put an end to classic pattern of interface and a companion class that implements most or all of the methods in that interface. An example is Collection and AbstractCollection. Now we should implement the methods in the interface itself to provide default functionality. The classes which implement the interface has choice to override the methods or inherit the default implementation.

  2. Another important use of default methods is interface evolution. Suppose I had a class Ball as:

    public class Ball implements Collection { ... }

Now in Java 8 a new feature streams in introduced. We can get a stream by using stream method added to the interface. If stream were not a default method all the implementations for Collection interface would have broken as they would not be implementing this new method. Adding a non-default method to an interface is not source-compatible.

But suppose we do not recompile the class and use an old jar file which contains this class Ball. The class will load fine without this missing method, instances can be created and it seems everything is working fine. BUT if program invokes stream method on instance of Ball we will get AbstractMethodError. So making method default solved both the problems.

Java 9 has got even private methods in interface which can be used to encapsulate the common code logic that was used in the interface methods that provided a default implementation.

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

It was happening to me in ZF2. I was trying to load the Modal content but I forgot to disable the layout before.

So:

$viewModel = new ViewModel();
$viewModel->setTerminal(true);
return $viewModel;

How to change the output color of echo in Linux

My riff on Tobias' answer:

# Color
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

function red {
    printf "${RED}$@${NC}\n"
}

function green {
    printf "${GREEN}$@${NC}\n"
}

function yellow {
    printf "${YELLOW}$@${NC}\n"
}

$ echo $(red apple) $(yellow banana) $(green kiwi)
apple banana kiwi

How to read file contents into a variable in a batch file?

You can read multiple variables from file like this:

for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H

where param.txt:

PARAM1=value1
PARAM2=value2
...

How to get Python requests to trust a self signed SSL certificate?

Incase anyone happens to land here (like I did) looking to add a CA (in my case Charles Proxy) for httplib2, it looks like you can append it to the cacerts.txt file included with the python package.

For example:

cat ~/Desktop/charles-ssl-proxying-certificate.pem >> /usr/local/google-cloud-sdk/lib/third_party/httplib2/cacerts.txt

The environment variables referenced in other solutions appear to be requests-specific and were not picked up by httplib2 in my testing.

Convert NSArray to NSString in Objective-C

NSString * str = [componentsJoinedByString:@""];

and you have dic or multiple array then used bellow

NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];   

jQuery get content between <div> tags

I suggest that you give an if to the div than:

$("#my_div_id").html();

There can be only one auto column

CREATE TABLE book (
   id INT AUTO_INCREMENT primary key NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Is there a function to split a string in PL/SQL?

If APEX_UTIL is not available, you have a solution using REGEXP_SUBSTR().

Inspired from http://nuijten.blogspot.fr/2009/07/splitting-comma-delimited-string-regexp.html :

DECLARE
  I INTEGER;
  TYPE T_ARRAY_OF_VARCHAR IS TABLE OF VARCHAR2(2000) INDEX BY BINARY_INTEGER;
  MY_ARRAY T_ARRAY_OF_VARCHAR;
  MY_STRING VARCHAR2(2000) := '123,456,abc,def';
BEGIN
  FOR CURRENT_ROW IN (
    with test as    
      (select MY_STRING from dual)
      select regexp_substr(MY_STRING, '[^,]+', 1, rownum) SPLIT
      from test
      connect by level <= length (regexp_replace(MY_STRING, '[^,]+'))  + 1)
  LOOP
    DBMS_OUTPUT.PUT_LINE(CURRENT_ROW.SPLIT);
    MY_ARRAY(MY_ARRAY.COUNT) := CURRENT_ROW.SPLIT;
  END LOOP;
END;
/

Android MediaPlayer Stop and Play

To stop the Media Player without the risk of an Illegal State Exception, you must do

  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }

rather than just

try {
       mp.stop();
       mp.release();
       mp=null;
    } 
catch (Exception e) 
    {
      e.printStackTrace();
    }

JSLint is suddenly reporting: Use the function form of "use strict"

There's nothing innately wrong with the string form.

Rather than avoid the "global" strict form for worry of concatenating non-strict javascript, it's probably better to just fix the damn non-strict javascript to be strict.

Using BeautifulSoup to search HTML for string

I have not used BeuatifulSoup but maybe the following can help in some tiny way.

import re
import urllib2
stuff = urllib2.urlopen(your_url_goes_here).read()  # stuff will contain the *entire* page

# Replace the string Python with your desired regex
results = re.findall('(Python)',stuff)

for i in results:
    print i

I'm not suggesting this is a replacement but maybe you can glean some value in the concept until a direct answer comes along.

Node.js spawn child process and get terminal output live

Adding an answer related to child_process.exec as I too had needed live feedback and wasn't getting any until after the script finished. This also supplements my comment to the accepted answer, but as it's formatted it will a bit more understandable and easier to read.

Basically, I have a npm script that calls Gulp, invoking a task which subsequently uses child_process.exec to execute a bash or batch script depending on the OS. Either script runs a build process via Gulp and then makes some calls to some binaries that work with the Gulp output.

It's exactly like the others (spawn, etc.), but for the sake of completion, here's exactly how to do it:

// INCLUDES
import * as childProcess from 'child_process'; // ES6 Syntax


// GLOBALS
let exec = childProcess.exec; // Or use 'var' for more proper 
                              // semantics, though 'let' is 
                              // true-to-scope


// Assign exec to a variable, or chain stdout at the end of the call
// to exec - the choice, yours (i.e. exec( ... ).stdout.on( ... ); )
let childProcess = exec
(
    './binary command -- --argument argumentValue',
    ( error, stdout, stderr ) =>
    {
        if( error )
        {
            // This won't show up until the process completes:
            console.log( '[ERROR]: "' + error.name + '" - ' + error.message );
            console.log( '[STACK]: ' + error.stack );

            console.log( stdout );
            console.log( stderr );
            callback();            // Gulp stuff
            return;
        }

        // Neither will this:
        console.log( stdout );
        console.log( stderr );
        callback();                // Gulp stuff
    }
);

Now its as simple as adding an event listener. For stdout:

childProcess.stdout.on
(
    'data',
    ( data ) =>
    {
        // This will render 'live':
        console.log( '[STDOUT]: ' + data );
    }
);

And for stderr:

childProcess.stderr.on
(
    'data',
    ( data ) =>
    {
        // This will render 'live' too:
        console.log( '[STDERR]: ' + data );
    }
);

Not too bad at all - HTH

CSS '>' selector; what is it?

> selects all direct descendants/children

A space selector will select all deep descendants whereas a greater than > selector will only select all immediate descendants. See fiddle for example.

_x000D_
_x000D_
div { border: 1px solid black; margin-bottom: 10px; }_x000D_
.a b { color: red; } /* every John is red */_x000D_
.b > b { color: blue; } /* Only John 3 and John 4 are blue */
_x000D_
<div class="a">_x000D_
  <p><b>John 1</b></p>_x000D_
  <p><b>John 2</b></p>_x000D_
  <b>John 3</b>_x000D_
  <b>John 4</b>_x000D_
</div>_x000D_
_x000D_
<div class="b">_x000D_
  <p><b>John 1</b></p>_x000D_
  <p><b>John 2</b></p>_x000D_
  <b>John 3</b>_x000D_
  <b>John 4</b>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to draw vectors (physical 2D/3D vectors) in MATLAB?

a = [2 3 5];
b = [1 1 0];
c = a+b;

starts = zeros(3,3);
ends = [a;b;c];

quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3))
axis equal

Downloading a picture via urllib and python

If you know that the files are located in the same directory dir of the website site and have the following format: filename_01.jpg, ..., filename_10.jpg then download all of them:

import requests

for x in range(1, 10):
    str1 = 'filename_%2.2d.jpg' % (x)
    str2 = 'http://site/dir/filename_%2.2d.jpg' % (x)

    f = open(str1, 'wb')
    f.write(requests.get(str2).content)
    f.close()

How to linebreak an svg text within javascript?

With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here: http://bl.ocks.org/mbostock/7555321

That automatically does line breaks for long text svg for a given width in pixel.

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

Angular 5 Button Submit On Enter Key Press

Another alternative can be to execute the Keydown or KeyUp in the tag of the Form

<form name="nameForm" [formGroup]="groupForm" (keydown.enter)="executeFunction()" >

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

ClusterIP: Services are reachable by pods/services in the Cluster
If I make a service called myservice in the default namespace of type: ClusterIP then the following predictable static DNS address for the service will be created:

myservice.default.svc.cluster.local (or just myservice.default, or by pods in the default namespace just "myservice" will work)

And that DNS name can only be resolved by pods and services inside the cluster.

NodePort: Services are reachable by clients on the same LAN/clients who can ping the K8s Host Nodes (and pods/services in the cluster) (Note for security your k8s host nodes should be on a private subnet, thus clients on the internet won't be able to reach this service)
If I make a service called mynodeportservice in the mynamespace namespace of type: NodePort on a 3 Node Kubernetes Cluster. Then a Service of type: ClusterIP will be created and it'll be reachable by clients inside the cluster at the following predictable static DNS address:

mynodeportservice.mynamespace.svc.cluster.local (or just mynodeportservice.mynamespace)

For each port that mynodeportservice listens on a nodeport in the range of 30000 - 32767 will be randomly chosen. So that External clients that are outside the cluster can hit that ClusterIP service that exists inside the cluster. Lets say that our 3 K8s host nodes have IPs 10.10.10.1, 10.10.10.2, 10.10.10.3, the Kubernetes service is listening on port 80, and the Nodeport picked at random was 31852.

A client that exists outside of the cluster could visit 10.10.10.1:31852, 10.10.10.2:31852, or 10.10.10.3:31852 (as NodePort is listened for by every Kubernetes Host Node) Kubeproxy will forward the request to mynodeportservice's port 80.

LoadBalancer: Services are reachable by everyone connected to the internet* (Common architecture is L4 LB is publicly accessible on the internet by putting it in a DMZ or giving it both a private and public IP and k8s host nodes are on a private subnet)
(Note: This is the only service type that doesn't work in 100% of Kubernetes implementations, like bare metal Kubernetes, it works when Kubernetes has cloud provider integrations.)

If you make mylbservice, then a L4 LB VM will be spawned (a cluster IP service, and a NodePort Service will be implicitly spawned as well). This time our NodePort is 30222. the idea is that the L4 LB will have a public IP of 1.2.3.4 and it will load balance and forward traffic to the 3 K8s host nodes that have private IP addresses. (10.10.10.1:30222, 10.10.10.2:30222, 10.10.10.3:30222) and then Kube Proxy will forward it to the service of type ClusterIP that exists inside the cluster.


You also asked: Does the NodePort service type still use the ClusterIP? Yes*
Or is the NodeIP actually the IP found when you run kubectl get nodes? Also Yes*

Lets draw a parrallel between Fundamentals:
A container is inside a pod. a pod is inside a replicaset. a replicaset is inside a deployment.
Well similarly:
A ClusterIP Service is part of a NodePort Service. A NodePort Service is Part of a Load Balancer Service.


In that diagram you showed, the Client would be a pod inside the cluster.

What is the function of the push / pop instructions used on registers in x86 assembly?

Where is it pushed on?

esp - 4. More precisely:

  • esp gets subtracted by 4
  • the value is pushed to esp

pop reverses this.

The System V ABI tells Linux to make rsp point to a sensible stack location when the program starts running: What is default register state when program launches (asm, linux)? which is what you should usually use.

How can you push a register?

Minimal GNU GAS example:

.data
    /* .long takes 4 bytes each. */
    val1:
        /* Store bytes 0x 01 00 00 00 here. */
        .long 1
    val2:
        /* 0x 02 00 00 00 */
        .long 2
.text
    /* Make esp point to the address of val2.
     * Unusual, but totally possible. */
    mov $val2, %esp

    /* eax = 3 */
    mov $3, %ea 

    push %eax
    /*
    Outcome:
    - esp == val1
    - val1 == 3
    esp was changed to point to val1,
    and then val1 was modified.
    */

    pop %ebx
    /*
    Outcome:
    - esp == &val2
    - ebx == 3
    Inverses push: ebx gets the value of val1 (first)
    and then esp is increased back to point to val2.
    */

The above on GitHub with runnable assertions.

Why is this needed?

It is true that those instructions could be easily implemented via mov, add and sub.

They reason they exist, is that those combinations of instructions are so frequent, that Intel decided to provide them for us.

The reason why those combinations are so frequent, is that they make it easy to save and restore the values of registers to memory temporarily so they don't get overwritten.

To understand the problem, try compiling some C code by hand.

A major difficulty, is to decide where each variable will be stored.

Ideally, all variables would fit into registers, which is the fastest memory to access (currently about 100x faster than RAM).

But of course, we can easily have more variables than registers, specially for the arguments of nested functions, so the only solution is to write to memory.

We could write to any memory address, but since the local variables and arguments of function calls and returns fit into a nice stack pattern, which prevents memory fragmentation, that is the best way to deal with it. Compare that with the insanity of writing a heap allocator.

Then we let compilers optimize the register allocation for us, since that is NP complete, and one of the hardest parts of writing a compiler. This problem is called register allocation, and it is isomorphic to graph coloring.

When the compiler's allocator is forced to store things in memory instead of just registers, that is known as a spill.

Does this boil down to a single processor instruction or is it more complex?

All we know for sure is that Intel documents a push and a pop instruction, so they are one instruction in that sense.

Internally, it could be expanded to multiple microcodes, one to modify esp and one to do the memory IO, and take multiple cycles.

But it is also possible that a single push is faster than an equivalent combination of other instructions, since it is more specific.

This is mostly un(der)documented:

How to call a method defined in an AngularJS directive?

How to get a directive's controller in a page controller:

  1. write a custom directive to get the reference to the directive controller from the DOM element:

    angular.module('myApp')
        .directive('controller', controller);
    
    controller.$inject = ['$parse'];
    
    function controller($parse) {
        var directive = {
            restrict: 'A',
            link: linkFunction
        };
        return directive;
    
        function linkFunction(scope, el, attrs) {
            var directiveName = attrs.$normalize(el.prop("tagName").toLowerCase());
            var directiveController = el.controller(directiveName);
    
            var model = $parse(attrs.controller);
            model.assign(scope, directiveController);
        }
    }
    
  2. use it in the page controller's html:

    <my-directive controller="vm.myDirectiveController"></my-directive>
    
  3. Use the directive controller in the page controller:

    vm.myDirectiveController.callSomeMethod();
    

Note: the given solution works only for element directives' controllers (tag name is used to get the name of the wanted directive).

How to remove a TFS Workspace Mapping?

I managed to remove the mapping using the /newowner command as suggested here:

How can I regain access to my Team Foundation Server Workspace?

The command opened an Edit Workspace windows where I removed the mapping. Afterwards I deleted the workspace I didn't need.

Get a list of resources from classpath directory

Custom Scanner

Implement your own scanner. For example:

(limitations of this solution are mentioned in the comments)

private List<String> getResourceFiles(String path) throws IOException {
    List<String> filenames = new ArrayList<>();

    try (
            InputStream in = getResourceAsStream(path);
            BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
        String resource;

        while ((resource = br.readLine()) != null) {
            filenames.add(resource);
        }
    }

    return filenames;
}

private InputStream getResourceAsStream(String resource) {
    final InputStream in
            = getContextClassLoader().getResourceAsStream(resource);

    return in == null ? getClass().getResourceAsStream(resource) : in;
}

private ClassLoader getContextClassLoader() {
    return Thread.currentThread().getContextClassLoader();
}

Spring Framework

Use PathMatchingResourcePatternResolver from Spring Framework.

Ronmamo Reflections

The other techniques might be slow at runtime for huge CLASSPATH values. A faster solution is to use ronmamo's Reflections API, which precompiles the search at compile time.

Automatic prune with Git fetch or pull

git config --global fetch.prune true

To always --prune for git fetch and git pull in all your Git repositories:

git config --global fetch.prune true

This above command appends in your global Git configuration (typically ~/.gitconfig) the following lines. Use git config -e --global to view your global configuration.

[fetch]
    prune = true

git config remote.origin.prune true

To always --prune but from one single repository:

git config remote.origin.prune true
                 #^^^^^^
                 #replace with your repo name

This above command adds in your local Git configuration (typically .git/config) the below last line. Use git config -e to view your local configuration.

[remote "origin"]
    url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    fetch = +refs/heads/*:refs/remotes/origin/*
    prune = true

You can also use --global within the second command or use instead --local within the first command.


git config --global gui.pruneDuringFetch true

If you use git gui you may also be interested by:

git config --global gui.pruneDuringFetch true

that appends:

[gui]
    pruneDuringFetch = true

References

The corresponding documentations from git help config:

--global

  For writing options: write to global ~/.gitconfig file rather than the repository .git/config, write to $XDG_CONFIG_HOME/git/config file if this file exists and the ~/.gitconfig file doesn’t.

 

--local

  For writing options: write to the repository .git/config file. This is the default behavior.

 

fetch.prune

  If true, fetch will automatically behave as if the --prune option was given on the command line. See also remote.<name>.prune.

 

gui.pruneDuringFetch

  "true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".

 

remote.<name>.prune

  When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the --prune option was given on the command line). Overrides fetch.prune settings, if any.

Updating address bar with new URL without hash or reloading the page

var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
window.history.pushState({path:newurl},'',newurl);

JavaScript: changing the value of onclick with or without jQuery

BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:

if(isie)
   tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
   $(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index

Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.

Uploading Laravel Project onto Web Server

No, but you have a couple of options:

The easiest is to upload all the files you have into that directory you're in (i.e. the cPanel user home directory), and put the contents of public into public_html. That way your directory structure will be something like this (slightly messy but it works):

/
    .composer/
    .cpanel/
    ...
    app/                 <- your laravel app directory
    etc/
    bootstrap/           <- your laravel bootstrap directory
    mail/
    public_html/         <- your laravel public directory
    vendor/
    artisan              <- your project's root files

You may also need to edit bootstrap/paths.php to point at the correct public directory.

The other solution, if you don't like having all these files in that 'root' directory would be to put them in their own directory (maybe 'laravel') that's still in the root directory and then edit the paths to work correctly. You'll still need to put the contents of public in public_html, though, and this time edit your public_html/index.php to correctly bootstrap the application. Your folder structure will be a lot tidier this way (though there could be some headaches with paths due to messing with the framework's designed structure more):

/
    .composer/
    .cpanel/
    ...
    etc/
    laravel/      <- a directory containing all your project files except public
        app/
        bootstrap/
        vendor/
        artisan
    mail/
    public_html/  <- your laravel public directory

How to mock void methods with Mockito

In Java 8 this can be made a little cleaner, assuming you have a static import for org.mockito.Mockito.doAnswer:

doAnswer(i -> {
  // Do stuff with i.getArguments() here
  return null;
}).when(*mock*).*method*(*methodArguments*);

The return null; is important and without it the compile will fail with some fairly obscure errors as it won't be able to find a suitable override for doAnswer.

For example an ExecutorService that just immediately executes any Runnable passed to execute() could be implemented using:

doAnswer(i -> {
  ((Runnable) i.getArguments()[0]).run();
  return null;
}).when(executor).execute(any());

Adding three months to a date in PHP

This answer is not exactly to this question. But I will add this since this question still searchable for how to add/deduct period from date.

$date = new DateTime('now');
$date->modify('+3 month'); // or you can use '-90 day' for deduct
$date = $date->format('Y-m-d h:i:s');
echo $date;

Getting the folder name from a path

Simple & clean. Only uses System.IO.FileSystem - works like a charm:

string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;

python: get directory two levels up

The best solution (for python >= 3.4) when executing from any directory is:

from pathlib import Path
two_up = Path(__file__).resolve().parents[1]

OS detecting makefile

The uname command (http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/uname.1.html) with no parameters should tell you the operating system name. I'd use that, then make conditionals based on the return value.

Example

UNAME := $(shell uname)

ifeq ($(UNAME), Linux)
# do something Linux-y
endif
ifeq ($(UNAME), Solaris)
# do something Solaris-y
endif

How can I stop a While loop?

just indent your code correctly:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            return period
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            return 0
        else:   
            return period

You need to understand that the break statement in your example will exit the infinite loop you've created with while True. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break statement by a return statement.

Following your idea to use an infinite loop, this is the best way to write it:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            break
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            period = 0
            break

    return period

how do I get the bullet points of a <ul> to center with the text?

I found the answer today. Maybe its too late but still I think its a much better one. Check this one https://jsfiddle.net/Amar_newDev/khb2oyru/5/

Try to change the CSS code : <ul> max-width:1%; margin:auto; text-align:left; </ul>

max-width:80% or something like that.

Try experimenting you might find something new.

Detecting when a div's height changes using jQuery

You can use the DOMSubtreeModified event

$(something).bind('DOMSubtreeModified' ...

But this will fire even if the dimensions don't change, and reassigning the position whenever it fires can take a performance hit. In my experience using this method, checking whether the dimensions have changed is less expensive and so you might consider combining the two.

Or if you are directly altering the div (rather than the div being altered by user input in unpredictable ways, like if it is contentEditable), you can simply fire a custom event whenever you do so.

Downside: IE and Opera don't implement this event.

Combining INSERT INTO and WITH/CTE

The WITH clause for Common Table Expressions go at the top.

Wrapping every insert in a CTE has the benefit of visually segregating the query logic from the column mapping.

Spot the mistake:

WITH _INSERT_ AS (
  SELECT
    [BatchID]      = blah
   ,[APartyNo]     = blahblah
   ,[SourceRowID]  = blahblahblah
  FROM Table1 AS t1
)
INSERT Table2
      ([BatchID], [SourceRowID], [APartyNo])
SELECT [BatchID], [APartyNo], [SourceRowID]   
FROM _INSERT_

Same mistake:

INSERT Table2 (
  [BatchID]
 ,[SourceRowID]
 ,[APartyNo]
)
SELECT
  [BatchID]      = blah
 ,[APartyNo]     = blahblah
 ,[SourceRowID]  = blahblahblah
FROM Table1 AS t1

A few lines of boilerplate make it extremely easy to verify the code inserts the right number of columns in the right order, even with a very large number of columns. Your future self will thank you later.

Div height 100% and expands to fit content

use flex

.parent{
    display: flex
}

.fit-parent{
    display: flex;
    flex-grow: 1
}

Remove credentials from Git

In case Git Credential Manager for Windows is used (which current versions usually do):

git credential-manager clear

This was added mid-2016. To check if credential manager is used:

git config --global credential.helper
? manager

Where are include files stored - Ubuntu Linux, GCC

Karl answered your search-path question, but as far as the "source of the files" goes, one thing to be aware of is that if you install the libfoo package and want to do some development with it (i.e., use its headers), you will also need to install libfoo-dev. The standard library header files are already in /usr/include, as you saw.

Note that some libraries with a lot of headers will install them to a subdirectory, e.g., /usr/include/openssl. To include one of those, just provide the path without the /usr/include part, for example:

#include <openssl/aes.h>

Get bytes from std::string in C++

From a std::string you can use the c_ptr() method if you want to get at the char_t buffer pointer.

It looks like you just want copy the characters of the string into a new buffer. I would simply use the std::string::copy function:

length = str.copy( buffer, str.size() );

How do I associate file types with an iPhone application?

To deal with any type of files for my own APP, I use this configuration for CFBundleDocumentTypes:

    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeName</key>
            <string>IPA</string>
            <key>LSItemContentTypes</key>
            <array>
                <string>public.item</string>
                <string>public.content</string>
                <string>public.data</string>
                <string>public.database</string>
                <string>public.composite-content</string>
                <string>public.contact</string>
                <string>public.archive</string>
                <string>public.url-name</string>
                <string>public.text</string>
                <string>public.plain-text</string>
                <string>public.source-code</string>
                <string>public.executable</string>
                <string>public.script</string>
                <string>public.shell-script</string>
                <string>public.xml</string>
                <string>public.symlink</string>
                <string>org.gnu.gnu-zip-archve</string>
                <string>org.gnu.gnu-tar-archive</string>
                <string>public.image</string>
                <string>public.movie</string>
                <string>public.audiovisual-?content</string>
                <string>public.audio</string>
                <string>public.directory</string>
                <string>public.folder</string>
                <string>com.apple.bundle</string>
                <string>com.apple.package</string>
                <string>com.apple.plugin</string>
                <string>com.apple.application-?bundle</string>
                <string>com.pkware.zip-archive</string>
                <string>public.filename-extension</string>
                <string>public.mime-type</string>
                <string>com.apple.ostype</string>
                <string>com.apple.nspboard-typ</string>
                <string>com.adobe.pdf</string>
                <string>com.adobe.postscript</string>
                <string>com.adobe.encapsulated-?postscript</string>
                <string>com.adobe.photoshop-?image</string>
                <string>com.adobe.illustrator.ai-?image</string>
                <string>com.compuserve.gif</string>
                <string>com.microsoft.word.doc</string>
                <string>com.microsoft.excel.xls</string>
                <string>com.microsoft.powerpoint.?ppt</string>
                <string>com.microsoft.waveform-?audio</string>
                <string>com.microsoft.advanced-?systems-format</string>
                <string>com.microsoft.advanced-?stream-redirector</string>
                <string>com.microsoft.windows-?media-wmv</string>
                <string>com.microsoft.windows-?media-wmp</string>
                <string>com.microsoft.windows-?media-wma</string>
                <string>com.apple.keynote.key</string>
                <string>com.apple.keynote.kth</string>
                <string>com.truevision.tga-image</string>
            </array>
            <key>CFBundleTypeIconFiles</key>
            <array>
                <string>Icon-76@2x</string>
            </array>
        </dict>
    </array>

How to call multiple JavaScript functions in onclick event?

This is alternative of brad anser - you can use comma as follows

onclick="funA(), funB(), ..."

however is better to NOT use this approach - for small projects you can use onclick only in case of one function calling (more: updated unobtrusive javascript).

_x000D_
_x000D_
function funA() {_x000D_
  console.log('A');_x000D_
}_x000D_
_x000D_
function funB(clickedElement) {_x000D_
  console.log('B: ' + clickedElement.innerText);_x000D_
}_x000D_
_x000D_
function funC(cilckEvent) {_x000D_
  console.log('C: ' +  cilckEvent.timeStamp);_x000D_
}
_x000D_
div {cursor:pointer}
_x000D_
<div onclick="funA(), funB(this), funC(event)">Click me</div>
_x000D_
_x000D_
_x000D_

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null
    }

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after && change.after.data){
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
}

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

What are Transient and Volatile Modifiers?

Volatile means other threads can edit that particular variable. So the compiler allows access to them.

http://www.javamex.com/tutorials/synchronization_volatile.shtml

Transient means that when you serialize an object, it will return its default value on de-serialization

http://www.geekinterview.com/question_details/2

Add line break within tooltips

AngularJS with Bootstrap UI Tolltip (uib-tooltip), has three versions of tool-tip:

uib-tooltip, uib-tooltip-template and uib-tooltip-html

- uib-tooltip takes only text and will escape any HTML provided
- uib-tooltip-html takes an expression that evaluates to an HTML string
- uib-tooltip-template takes a text that specifies the location of the template

In my case, I opted for uib-tooltip-html and there are three parts to it:

  1. configuration
  2. controller
  3. HTML

Example:

(function(angular) {

//Step 1: configure $sceProvider - this allows the configuration of $sce service.

angular.module('myApp', ['uib.bootstrap'])
       .config(function($sceProvider) {
           $sceProvider.enabled(false);
       });

//Step 2: Set the tooltip content in the controller

angular.module('myApp')
       .controller('myController', myController);

myController.$inject = ['$sce'];

function myController($sce) {
    var vm = this;
    vm.tooltipContent = $sce.trustAsHtml('I am the first line <br /><br />' +
                                         'I am the second line-break');

    return vm;
}

 })(window.angular);

//Step 3: Use the tooltip in HTML (UI)

<div ng-controller="myController as get">
     <span uib-tooltip-html="get.tooltipContent">other Contents</span>
</div>

For more information, please check here

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

Installing a dependency with Bower from URL and specify version

Just specifying the uri endpoint worked for me, bower 1.3.9

  "dependencies": {
    "jquery.cookie": "latest",
    "everestjs": "http://www.everestjs.net/static/st.v2.js"
  }

Running bower install, I received following output:

bower new           version for http://www.everestjs.net/static/st.v2.js#*
bower resolve       http://www.everestjs.net/static/st.v2.js#*
bower download      http://www.everestjs.net/static/st.v2.js

You could also try updating bower

  • npm update -g bower

According to documentation: the following types of urls are supported:

http://example.com/script.js
http://example.com/style.css
http://example.com/package.zip (contents will be extracted)
http://example.com/package.tar (contents will be extracted)

Could pandas use column as index?

You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.

Here is my solution:

  1. Firstly, import pandas as pd: import pandas as pd

  2. Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.

    df = pd.read_excel('testexcel.xlsx', index_col=0)

    At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd.

  3. For visual inspection, read the dataframe using df.head() which will print the following output sc

  4. Now you can fetch the values of the desired columns of the dataframe and print it

    sc2

Repeat each row of data.frame the number of times specified in a column

Another possibility is using tidyr::expand:

library(dplyr)
library(tidyr)

df %>% group_by_at(vars(-freq)) %>% expand(temp = 1:freq) %>% select(-temp)
#> # A tibble: 6 x 2
#> # Groups:   var1, var2 [3]
#>   var1  var2 
#>   <fct> <fct>
#> 1 a     d    
#> 2 b     e    
#> 3 b     e    
#> 4 c     f    
#> 5 c     f    
#> 6 c     f

One-liner version of vonjd's answer:

library(data.table)

setDT(df)[ ,list(freq=rep(1,freq)),by=c("var1","var2")][ ,freq := NULL][]
#>    var1 var2
#> 1:    a    d
#> 2:    b    e
#> 3:    b    e
#> 4:    c    f
#> 5:    c    f
#> 6:    c    f

Created on 2019-05-21 by the reprex package (v0.2.1)

Displaying a message in iOS which has the same functionality as Toast in Android

For the ones that using Xamarin.IOS you can do like this:

new UIAlertView(null, message, null, "OK", null).Show();

using UIKit; is required.

Use of Finalize/Dispose method in C#

Note that any IDisposable implementation should follow the below pattern (IMHO). I developed this pattern based on info from several excellent .NET "gods" the .NET Framework Design Guidelines (note that MSDN does not follow this for some reason!). The .NET Framework Design Guidelines were written by Krzysztof Cwalina (CLR Architect at the time) and Brad Abrams (I believe the CLR Program Manager at the time) and Bill Wagner ([Effective C#] and [More Effective C#] (just take a look for these on Amazon.com:

Note that you should NEVER implement a Finalizer unless your class directly contains (not inherits) UNmanaged resources. Once you implement a Finalizer in a class, even if it is never called, it is guaranteed to live for an extra collection. It is automatically placed on the Finalization Queue (which runs on a single thread). Also, one very important note...all code executed within a Finalizer (should you need to implement one) MUST be thread-safe AND exception-safe! BAD things will happen otherwise...(i.e. undetermined behavior and in the case of an exception, a fatal unrecoverable application crash).

The pattern I've put together (and written a code snippet for) follows:

#region IDisposable implementation

//TODO remember to make this class inherit from IDisposable -> $className$ : IDisposable

// Default initialization for a bool is 'false'
private bool IsDisposed { get; set; }

/// <summary>
/// Implementation of Dispose according to .NET Framework Design Guidelines.
/// </summary>
/// <remarks>Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </remarks>
public void Dispose()
{
    Dispose( true );

    // This object will be cleaned up by the Dispose method.
    // Therefore, you should call GC.SupressFinalize to
    // take this object off the finalization queue 
    // and prevent finalization code for this object
    // from executing a second time.

    // Always use SuppressFinalize() in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize( this );
}

/// <summary>
/// Overloaded Implementation of Dispose.
/// </summary>
/// <param name="isDisposing"></param>
/// <remarks>
/// <para><list type="bulleted">Dispose(bool isDisposing) executes in two distinct scenarios.
/// <item>If <paramref name="isDisposing"/> equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.</item>
/// <item>If <paramref name="isDisposing"/> equals false, the method has been called by the 
/// runtime from inside the finalizer and you should not reference 
/// other objects. Only unmanaged resources can be disposed.</item></list></para>
/// </remarks>
protected virtual void Dispose( bool isDisposing )
{
    // TODO If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    try
    {
        if( !this.IsDisposed )
        {
            if( isDisposing )
            {
                // TODO Release all managed resources here

                $end$
            }

            // TODO Release all unmanaged resources here



            // TODO explicitly set root references to null to expressly tell the GarbageCollector
            // that the resources have been disposed of and its ok to release the memory allocated for them.


        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );

        this.IsDisposed = true;
    }
}

//TODO Uncomment this code if this class will contain members which are UNmanaged
// 
///// <summary>Finalizer for $className$</summary>
///// <remarks>This finalizer will run only if the Dispose method does not get called.
///// It gives your base class the opportunity to finalize.
///// DO NOT provide finalizers in types derived from this class.
///// All code executed within a Finalizer MUST be thread-safe!</remarks>
//  ~$className$()
//  {
//     Dispose( false );
//  }
#endregion IDisposable implementation

Here is the code for implementing IDisposable in a derived class. Note that you do not need to explicitly list inheritance from IDisposable in the definition of the derived class.

public DerivedClass : BaseClass, IDisposable (remove the IDisposable because it is inherited from BaseClass)


protected override void Dispose( bool isDisposing )
{
    try
    {
        if ( !this.IsDisposed )
        {
            if ( isDisposing )
            {
                // Release all managed resources here

            }
        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );
    }
}

I've posted this implementation on my blog at: How to Properly Implement the Dispose Pattern

jQuery: Return data after ajax call success

Note: This answer was written in February 2010.
See updates from 2015, 2016 and 2017 at the bottom.

You can't return anything from a function that is asynchronous. What you can return is a promise. I explained how promises work in jQuery in my answers to those questions:

If you could explain why do you want to return the data and what do you want to do with it later, then I might be able to give you a more specific answer how to do it.

Generally, instead of:

function testAjax() {
  $.ajax({
    url: "getvalue.php",  
    success: function(data) {
      return data; 
    }
  });
}

you can write your testAjax function like this:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

Then you can get your promise like this:

var promise = testAjax();

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this:

promise.success(function (data) {
  alert(data);
});

(See updates below for simplified syntax.)

If your data is available at this point then this function will be invoked immediately. If it isn't then it will be invoked as soon as the data is available.

The whole point of doing all of this is that your data is not available immediately after the call to $.ajax because it is asynchronous. Promises is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it.

See this DEMO.

UPDATE (2015)

Currently (as of March, 2015) jQuery Promises are not compatible with the Promises/A+ specification which means that they may not cooperate very well with other Promises/A+ conformant implementations.

However jQuery Promises in the upcoming version 3.x will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out). Currently (as of May, 2015) the stable versions of jQuery are 1.x and 2.x.

What I explained above (in March, 2011) is a way to use jQuery Deferred Objects to do something asynchronously that in synchronous code would be achieved by returning a value.

But a synchronous function call can do two things - it can either return a value (if it can) or throw an exception (if it can't return a value). Promises/A+ addresses both of those use cases in a way that is pretty much as powerful as exception handling in synchronous code. The jQuery version handles the equivalent of returning a value just fine but the equivalent of complex exception handling is somewhat problematic.

In particular, the whole point of exception handling in synchronous code is not just giving up with a nice message, but trying to fix the problem and continue the execution, or possibly rethrowing the same or a different exception for some other parts of the program to handle. In synchronous code you have a call stack. In asynchronous call you don't and advanced exception handling inside of your promises as required by the Promises/A+ specification can really help you write code that will handle errors and exceptions in a meaningful way even for complex use cases.

For differences between jQuery and other implementations, and how to convert jQuery promises to Promises/A+ compliant, see Coming from jQuery by Kris Kowal et al. on the Q library wiki and Promises arrive in JavaScript by Jake Archibald on HTML5 Rocks.

How to return a real promise

The function from my example above:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

returns a jqXHR object, which is a jQuery Deferred Object.

To make it return a real promise, you can change it to - using the method from the Q wiki:

function testAjax() {
  return Q($.ajax({
      url: "getvalue.php"
  }));
}

or, using the method from the HTML5 Rocks article:

function testAjax() {
  return Promise.resolve($.ajax({
      url: "getvalue.php"
  }));
}

This Promise.resolve($.ajax(...)) is also what is explained in the promise module documentation and it should work with ES6 Promise.resolve().

To use the ES6 Promises today you can use es6-promise module's polyfill() by Jake Archibald.

To see where you can use the ES6 Promises without the polyfill, see: Can I use: Promises.

For more info see:

Future of jQuery

Future versions of jQuery (starting from 3.x - current stable versions as of May 2015 are 1.x and 2.x) will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out in the comments). "Two changes that we've already decided upon are Promise/A+ compatibility for our Deferred implementation [...]" (jQuery 3.0 and the future of Web development). For more info see: jQuery 3.0: The Next Generations by Dave Methvin and jQuery 3.0: More interoperability, less Internet Explorer by Paul Krill.

Interesting talks

UPDATE (2016)

There is a new syntax in ECMA-262, 6th Edition, Section 14.2 called arrow functions that may be used to further simplify the examples above.

Using the jQuery API, instead of:

promise.success(function (data) {
  alert(data);
});

you can write:

promise.success(data => alert(data));

or using the Promises/A+ API:

promise.then(data => alert(data));

Remember to always use rejection handlers either with:

promise.then(data => alert(data), error => alert(error));

or with:

promise.then(data => alert(data)).catch(error => alert(error));

See this answer to see why you should always use rejection handlers with promises:

Of course in this example you could use just promise.then(alert) because you're just calling alert with the same arguments as your callback, but the arrow syntax is more general and lets you write things like:

promise.then(data => alert("x is " + data.x));

Not every browser supports this syntax yet, but there are certain cases when you're sure what browser your code will run on - e.g. when writing a Chrome extension, a Firefox Add-on, or a desktop application using Electron, NW.js or AppJS (see this answer for details).

For the support of arrow functions, see:

UPDATE (2017)

There is an even newer syntax right now called async functions with a new await keyword that instead of this code:

functionReturningPromise()
    .then(data => console.log('Data:', data))
    .catch(error => console.log('Error:', error));

lets you write:

try {
    let data = await functionReturningPromise();
    console.log('Data:', data);
} catch (error) {
    console.log('Error:', error);
}

You can only use it inside of a function created with the async keyword. For more info, see:

For support in browsers, see:

For support in Node, see:

In places where you don't have native support for async and await you can use Babel:

or with a slightly different syntax a generator based approach like in co or Bluebird coroutines:

More info

Some other questions about promises for more details:

Pass a JavaScript function as parameter

To pass the function as parameter, simply remove the brackets!

function ToBeCalled(){
  alert("I was called");
}

function iNeedParameter( paramFunc) {
   //it is a good idea to check if the parameter is actually not null
   //and that it is a function
   if (paramFunc && (typeof paramFunc == "function")) {
      paramFunc();   
   }
}

//this calls iNeedParameter and sends the other function to it
iNeedParameter(ToBeCalled); 

The idea behind this is that a function is quite similar to a variable. Instead of writing

function ToBeCalled() { /* something */ }

you might as well write

var ToBeCalledVariable = function () { /* something */ }

There are minor differences between the two, but anyway - both of them are valid ways to define a function. Now, if you define a function and explicitly assign it to a variable, it seems quite logical, that you can pass it as parameter to another function, and you don't need brackets:

anotherFunction(ToBeCalledVariable);

How can INSERT INTO a table 300 times within a loop in SQL?

In ssms we can use GO to execute same statement

Edit This mean if you put

 some query

 GO n

Some query will be executed n times

How to make a form close when pressing the escape key?

Paste this code into the "On Key Down" Property of your form, also make sure you set "Key Preview" Property to "Yes".

If KeyCode = vbKeyEscape Then DoCmd.Close acForm, "YOUR FORM NAME"

Java equivalent to C# extension methods

Java 8 now supports default methods, which are similar to C#'s extension methods.

Can you target an elements parent element using event.target?

I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.

Otherwise parentNode might be what you're looking for.

link to currentTarget
link to parentNode

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Problem solved.

Just drop down status bar, touch Choose input method, then change to another input method, type the password again. And everything is OK.

So weird...

Solution from a Chinese BBS. Thanks for the answer's author and all above who try to provide a solution, thanks!

How to build a DataTable from a DataGridView?

Well, you can do

DataTable data = (DataTable)(dgvMyMembers.DataSource);

and then use

data.Columns.Remove(...);

I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource is not necessarily of DataTable type.

What is offsetHeight, clientHeight, scrollHeight?

Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :

  • offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :

  • clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:

  • scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

Is there a way to represent a directory tree in a Github README.md?

I made a node module to automate this task: mddir

Usage

node mddir "../relative/path/"

To install: npm install mddir -g

To generate markdown for current directory: mddir

To generate for any absolute path: mddir /absolute/path

To generate for a relative path: mddir ~/Documents/whatever.

The md file gets generated in your working directory.

Currently ignores node_modules, and .git folders.

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

Line endings fix

Get npm bin folder path with:

npm config get prefix

Cd into that folder

brew install dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

This converts line endings to Unix instead of Dos

Then run as normal with: node mddir "../relative/path/".

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js

What is "Advanced" SQL?

Basics


  1. SELECTing columns from a table
  2. Aggregates Part 1: COUNT, SUM, MAX/MIN
  3. Aggregates Part 2: DISTINCT, GROUP BY, HAVING

Intermediate


  1. JOINs, ANSI-89 and ANSI-92 syntax
  2. UNION vs UNION ALL
  3. NULL handling: COALESCE & Native NULL handling
  4. Subqueries: IN, EXISTS, and inline views
  5. Subqueries: Correlated
  6. WITH syntax: Subquery Factoring/CTE
  7. Views

Advanced Topics


  • Functions, Stored Procedures, Packages
  • Pivoting data: CASE & PIVOT syntax
  • Hierarchical Queries
  • Cursors: Implicit and Explicit
  • Triggers
  • Dynamic SQL
  • Materialized Views
  • Query Optimization: Indexes
  • Query Optimization: Explain Plans
  • Query Optimization: Profiling
  • Data Modelling: Normal Forms, 1 through 3
  • Data Modelling: Primary & Foreign Keys
  • Data Modelling: Table Constraints
  • Data Modelling: Link/Corrollary Tables
  • Full Text Searching
  • XML
  • Isolation Levels
  • Entity Relationship Diagrams (ERDs), Logical and Physical
  • Transactions: COMMIT, ROLLBACK, Error Handling

python list by value not by reference

If you want to copy a one-dimensional list, use

b = a[:]

However, if a is a 2-dimensional list, this is not going to work for you. That is, any changes in a will also be reflected in b. In that case, use

b = [[a[x][y] for y in range(len(a[0]))] for x in range(len(a))]

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

None of these answers worked for me, I had to do the following:

  1. Start Menu > type 'Internet Options'.
  2. Select Local intranet zone on the Security tab then click the Sites button
  3. Click Advanced button
  4. Enter file://[computer name]
  5. Make sure 'Require server verification...' is unticked

Source: https://superuser.com/q/44503

MySQL - How to select rows where value is in array?

If you use the FIND_IN_SET function:

FIND_IN_SET(a, columnname) yields all the records that have "a" in them, alone or with others

AND

FIND_IN_SET(columnname, a) yields only the records that have "a" in them alone, NOT the ones with the others

So if record1 is (a,b,c) and record2 is (a)

FIND_IN_SET(columnname, a) yields only record2 whereas FIND_IN_SET(a, columnname) yields both records.

How to set focus on an input field after rendering?

The simplest answer is add the ref="some name" in the input text element and call the below function.

componentDidMount(){
   this.refs.field_name.focus();
}
// here field_name is ref name.

<input type="text" ref="field_name" />

Selenium webdriver click google search

Based on quick inspection of google web, this would be CSS path to links in page list

ol[id="rso"] h3[class="r"] a

So you should do something like

String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();

However you could also use xpath which is not really recommended as a best practice and also JQuery locators but I am not sure if you can use them aynywhere else except inArquillian Graphene

Convert a python dict to a string and back

If in Chinses

import codecs
fout = codecs.open("xxx.json", "w", "utf-8")
dict_to_json = json.dumps({'text':"??"},ensure_ascii=False,indent=2)
fout.write(dict_to_json + '\n')

How to convert IPython notebooks to PDF and HTML?

If you are using sagemath cloud version, you can simply go to the left corner,
select File ? Download as ? Pdf via LaTeX (.pdf)
Check the screenshot if you want.

Screenshot Convert ipynb to pdf

If it dosn't work for any reason, you can try another way.
select File ? Print Preview and then on the preview
right click ? Print and then select save as pdf.

How can I draw vertical text with CSS cross-browser?

If you use Bootstrap 3, you can use one of it's mixins:

.rotate(degrees);

Example:

.rotate(-90deg);

Downloading MySQL dump from command line

For those who wants to type password within the command line. It is possible but recommend to pass it inside quotes so that the special character won't cause any issue.

mysqldump -h'my.address.amazonaws.com' -u'my_username' -p'password' db_name > /path/backupname.sql

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

How to replace a substring of a string

You are probably not assigning it after doing the replacement or replacing the wrong thing. Try :

String haystack = "abcd=0; efgh=1";
String result = haystack.replaceAll("abcd","dddd");

Textarea to resize based on content length

One method is to do it without JavaScript and this is something like this:

    <textarea style="overflow: visible" />

How to check if the key pressed was an arrow key in Java KeyListener?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code
    }

    repaint();
}

The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

Char array in a struct - incompatible assignment?

The Sara structure is a memory block containing the variables inside. There is nearly no difference between a classic declarations :

char first[20];
int age;

and a structure :

struct Person{
char first[20];
int age;
};

In both case, you are just allocating some memory to store variables, and in both case there will be 20+4 bytes reserved. In your case, Sara is just a memory block of 2x20 bytes.

The only difference is that with a structure, the memory is allocated as a single block, so if you take the starting address of Sara and jump 20 bytes, you'll find the "last" variable. This can be useful sometimes.

check http://publications.gbdirect.co.uk/c_book/chapter6/structures.html for more :) .

Show special characters in Unix while using 'less' Command

All special, nonprintable characters are displayed using ^ notation in less. However, line feed is actually printable (just make a new line), so not considered special, so you'll have problems replacing it. If you just want to see line endings, the easiest way might be

sed -e 's/$/$/' | less

Asynchronous Process inside a javascript for loop

ES2017: You can wrap the async code inside a function(say XHRPost) returning a promise( Async code inside the promise).

Then call the function(XHRPost) inside the for loop but with the magical Await keyword. :)

_x000D_
_x000D_
let http = new XMLHttpRequest();_x000D_
let url = 'http://sumersin/forum.social.json';_x000D_
_x000D_
function XHRpost(i) {_x000D_
  return new Promise(function(resolve) {_x000D_
    let params = 'id=nobot&%3Aoperation=social%3AcreateForumPost&subject=Demo' + i + '&message=Here%20is%20the%20Demo&_charset_=UTF-8';_x000D_
    http.open('POST', url, true);_x000D_
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');_x000D_
    http.onreadystatechange = function() {_x000D_
    console.log("Done " + i + "<<<<>>>>>" + http.readyState);_x000D_
          if(http.readyState == 4){_x000D_
              console.log('SUCCESS :',i);_x000D_
              resolve();_x000D_
          }_x000D_
         }_x000D_
    http.send(params);       _x000D_
    });_x000D_
 }_x000D_
 _x000D_
(async () => {_x000D_
    for (let i = 1; i < 5; i++) {_x000D_
        await XHRpost(i);_x000D_
       }_x000D_
})();
_x000D_
_x000D_
_x000D_

What are the differences between normal and slim package of jquery?

The jQuery blog, jQuery 3.1.1 Released!, says,

Slim build

Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for all your web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version – 23.6k vs 30k.

How do I plot in real-time in a while loop using matplotlib?

I know this question is old, but there's now a package available called drawnow on GitHub as "python-drawnow". This provides an interface similar to MATLAB's drawnow -- you can easily update a figure.

An example for your use case:

import matplotlib.pyplot as plt
from drawnow import drawnow

def make_fig():
    plt.scatter(x, y)  # I think you meant this

plt.ion()  # enable interactivity
fig = plt.figure()  # make a figure

x = list()
y = list()

for i in range(1000):
    temp_y = np.random.random()
    x.append(i)
    y.append(temp_y)  # or any arbitrary update to your figure's data
    i += 1
    drawnow(make_fig)

python-drawnow is a thin wrapper around plt.draw but provides the ability to confirm (or debug) after figure display.

How to crop an image using PIL?

There is a crop() method:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)

Android: How to detect double-tap?

Equivalent C# code which i used to implement same functionality and can even customize to accept N number of Taps

public interface IOnTouchInterface
{
    void ViewTapped();
}

public class MultipleTouchGestureListener : Java.Lang.Object, View.IOnTouchListener
{
    int clickCount = 0;
    long startTime;
    static long MAX_DURATION = 500;
    public int NumberOfTaps { get; set; } = 7;

    readonly IOnTouchInterface interfc;

    public MultipleTouchGestureListener(IOnTouchInterface tch)
    {
        this.interfc = tch;
    }

    public bool OnTouch(View v, MotionEvent e)
    {
        switch (e.Action)
        {
            case MotionEventActions.Down:
                clickCount++;
                if(clickCount == 1)
                    startTime = Utility.CurrentTimeSince1970;
                break;
            case MotionEventActions.Up:
                var currentTime = Utility.CurrentTimeSince1970;
                long time = currentTime - startTime;
                if(time <= MAX_DURATION * NumberOfTaps)
                {
                    if (clickCount == NumberOfTaps)
                    {
                        this.interfc.ViewTapped();
                        clickCount = 0;
                    }
                }
                else
                {
                    clickCount = 0;
                }
                break;
        }
        return true;
    }
}

public static class Utility
{
    public static long CurrentTimeSince1970
    {
        get
        {
            DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
            DateTime dtNow = DateTime.Now;
            TimeSpan result = dtNow.Subtract(dt);
            long seconds = (long)result.TotalMilliseconds;
            return seconds;
        }
    }
}

Currently Above code accepts 7 as number of taps before it raises the View Tapped event. But it can be customized with any number

addEventListener for keydown on Canvas

Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex attribute on the canvas element (as suggested by hobberwickey).

You can't focus a canvas element. A simple work around this, would be to make your "own" focus.

var lastDownTarget, canvas;
window.onload = function() {
    canvas = document.getElementById('canvas');

    document.addEventListener('mousedown', function(event) {
        lastDownTarget = event.target;
        alert('mousedown');
    }, false);

    document.addEventListener('keydown', function(event) {
        if(lastDownTarget == canvas) {
            alert('keydown');
        }
    }, false);
}

JSFIDDLE

Insert data to MySql DB and display if insertion is success or failure

According to the book PHP and MySQL for Dynamic Web Sites (4th edition)

Example:

$r = mysqli_query($dbc, $q);

For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $r variable—short for result—will be either TRUE or FALSE, depending upon whether the query executed successfully.

Keep in mind that “executed successfully” means that it ran without error; it doesn’t mean that the query’s execution necessarily had the desired result; you’ll need to test for that.

Then how to test?

While the mysqli_num_rows() function will return the number of rows generated by a SELECT query, mysqli_affected_rows() returns the number of rows affected by an INSERT, UPDATE, or DELETE query. It’s used like so:

$num = mysqli_affected_rows($dbc);

Unlike mysqli_num_rows(), the one argument the function takes is the database connection ($dbc), not the results of the previous query ($r).

Create aar file in Android Studio

just like user hcpl said but if you want to not worry about the version of the library you can do this:

dependencies {
    compile(name:'mylibrary', ext:'aar')
}

as its kind of annoying to have to update the version everytime. Also it makes the not worrying about the name space easier this way.

This app won't run unless you update Google Play Services (via Bazaar)

I've been trying to run an Android Google Maps v2 under an emulator, and I found many ways to do that, but none of them worked for me. I have always this warning in the Logcat Google Play services out of date. Requires 3025100 but found 2010110 and when I want to update Google Play services on the emulator nothing happened. The problem was that the com.google.android.gms APK was not compatible with the version of the library in my Android SDK.

I installed these files "com.google.android.gms.apk", "com.android.vending.apk" on my emulator and my app Google Maps v2 worked fine. None of the other steps regarding /system/app were required.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric

Optimum way to compare strings in JavaScript?

You can use the comparison operators to compare strings. A strcmp function could be defined like this:

function strcmp(a, b) {
    if (a.toString() < b.toString()) return -1;
    if (a.toString() > b.toString()) return 1;
    return 0;
}

Edit    Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:

function strcmp(a, b) {
    a = a.toString(), b = b.toString();
    for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
    if (i === n) return 0;
    return a.charAt(i) > b.charAt(i) ? -1 : 1;
}

Fetching data from MySQL database to html dropdown list

# here database details      
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";

# here username is the column of my table(userregistration)
# it works perfectly

How to increase request timeout in IIS?

In IIS >= 7, a <webLimits> section has replaced ConnectionTimeout, HeaderWaitTimeout, MaxGlobalBandwidth, and MinFileBytesPerSec IIS 6 metabase settings.

Example Configuration:

<configuration>
   <system.applicationHost>
      <webLimits connectionTimeout="00:01:00"
         dynamicIdleThreshold="150"
         headerWaitTimeout="00:00:30"
         minBytesPerSecond="500"
      />
   </system.applicationHost>
</configuration>

For reference: more information regarding these settings in IIS can be found here. Also, I was unable to add this section to the web.config via the IIS manager's "configuration editor", though it did show up once I added it and searched the configuration.

#1292 - Incorrect date value: '0000-00-00'

You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.

How to find the nearest parent of a Git branch?

Here's my Powershell Version:

function Get-GHAParentBranch {
    [CmdletBinding()]
    param(
        $Name = (git branch --show-current)
    )
    git show-branch | 
      Select-String '^[^\[]*\*' | 
      Select-String -NotMatch -Pattern "\[$([Regex]::Escape($Name)).*?\]" |
      Select-Object -First 1 |
      Foreach-Object {$PSItem -replace '^.+?\[(.+)\].+$','$1'}
}

What are the differences between Mustache.js and Handlebars.js?

You've pretty much nailed it, however Mustache templates can also be compiled.

Mustache is missing helpers and the more advanced blocks because it strives to be logicless. Handlebars' custom helpers can be very useful, but often end up introducing logic into your templates.

Mustache has many different compilers (JavaScript, Ruby, Python, C, etc.). Handlebars began in JavaScript, now there are projects like django-handlebars, handlebars.java, handlebars-ruby, lightncandy (PHP), and handlebars-objc.

Is there a shortcut to make a block comment in Xcode?

There is now an Xcode plugin that allows this: CComment.

The easiest way to install this is to use the amazing Alcatraz plugin manager for Xcode.

EDIT Apple has sadly (and wrongly, IMHO) retired the old plugin model with Xcode 8. The new plugin system is quite limited, but should allow development of a plugin like this again. For anyone interested in doing this, watch WWDC 2016 session 414. Also, please file radars for API for plugins you'd like to write or see.

Error In PHP5 ..Unable to load dynamic library

I had enabled the extension_dir in php.ini by uncommenting,

  extension_dir = "ext"
  extension=phpchartdir550.dll

and copying phpchartdir550 dll to the extension_dir (/usr/lib/php5/20121212), resulted in the same error.

  PHP Warning:  PHP Startup: Unable to load dynamic library 'ext/phpchartdir550.dll' - ext/phpchartdir550.dll: cannot open shared object file: No such file or directory in Unknown on line 0
  PHP Warning:  PHP Startup: Unable to load dynamic library 'ext/pdo.so' - ext/pdo.so: cannot open shared object file: No such file or directory in Unknown on line 0
  PHP Warning:  PHP Startup: Unable to load dynamic library 'ext/gd.so' - ext/gd.so: cannot open shared object file: No such file or directory in Unknown on line 0

As @Mike pointed out, it is not necessary to install all the stuff when they are not actually required in the application.

The easier way is to provide the full path to the extensions to be loaded after copying the libraries to the correct location.

Copy phpchartdir550.dll to /usr/lib/php5/20121212, which is the extension_dir in my Ubuntu 14.04 (this can be seen using phpinfo()) and then provide full path to the library in php.ini,

;   extension=/path/to/extension/msql.so
extension=/usr/lib/php5/20121212/phpchartdir550.dll

restart apache: sudo service apache2 restart

even though other .so's are present in the same directory, only the required ones can be selectively loaded.

Most efficient way to get table row count

if you directly get get max number by writing select query then there may chance that your query will give wrong value. e.g. if your table has 5 records so your increment id will be 6 and if I delete record no 5 the your table has 4 records with max id is 4 in this case you will get 5 as next increment id. insted to that you can get info from mysql defination itself. by writing following code in php

<?
$tablename      = "tablename";
$next_increment     = 0;
$qShowStatus        = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult  = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );

$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];

echo "next increment number: [$next_increment]";
?>

How to include (source) R script in other scripts

You could write a function that takes a filename and an environment name, checks to see if the file has been loaded into the environment and uses sys.source to source the file if not.

Here's a quick and untested function (improvements welcome!):

include <- function(file, env) {
  # ensure file and env are provided
  if(missing(file) || missing(env))
    stop("'file' and 'env' must be provided")
  # ensure env is character
  if(!is.character(file) || !is.character(env))
    stop("'file' and 'env' must be a character")

  # see if env is attached to the search path
  if(env %in% search()) {
    ENV <- get(env)
    files <- get(".files",ENV)
    # if the file hasn't been loaded
    if(!(file %in% files)) {
      sys.source(file, ENV)                        # load the file
      assign(".files", c(file, files), envir=ENV)  # set the flag
    }
  } else {
    ENV <- attach(NULL, name=env)      # create/attach new environment
    sys.source(file, ENV)              # load the file
    assign(".files", file, envir=ENV)  # set the flag
  }
}

What is the difference between And and AndAlso in VB.NET?

A simple way to think about it is using even plainer English

If Bool1 And Bool2 Then
If [both are true] Then


If Bool1 AndAlso Bool2 Then
If [first is true then evaluate the second] Then

Get the Query Executed in Laravel 3/4

I would recommend using the Chrome extension Clockwork with the Laravel package https://github.com/itsgoingd/clockwork. It's easy to install and use.

Clockwork is a Chrome extension for PHP development, extending Developer Tools with a new panel providing all kinds of information useful for debugging and profiling your PHP scripts, including information on request, headers, GET and POST data, cookies, session data, database queries, routes, visualisation of application runtime and more. Clockwork includes out of the box support for Laravel 4 and Slim 2 based applications, you can add support for any other or custom framework via an extensible API.

enter image description here

How to get Client location using Google Maps API v3?

A bit late but I got something similar that I'm busy building and here is the code to get current location - be sure to use local server to test.

Include relevant scripts from CDN:

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap">

HTML

<div id="map"></div>

CSS

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}
#map {
    height: 100%;
}

JS

var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});

// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };

        infoWindow.setPosition(pos);
        infoWindow.setContent('Location found.');
        map.setCenter(pos);
    }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
}

DEMO

https://jsfiddle.net/ToreanJoel/4ythpy02/

Why when I transfer a file through SFTP, it takes longer than FTP?

There are all sorts of things which can do this. One possiblity is "Traffic Shaping". This is commonly done in office environments to reserve bandwidth for business critical activities. It may also be done by the web hosting company, or by your ISP, for very similar reasons.

You can also set it up at home very simply.

For example there may be a rule reserving minimum bandwidth for FTP, while SFTP might be falling under an "everything else" rule. Or there might be a rule capping bandwidth for SFTP, but someone else is also using SFTP at the same time as you.

So: Where are you tranferring the file from and to?

Set Content-Type to application/json in jsp file

You can do via Page directive.

For example:

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

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

cURL POST command line on WINDOWS RESTful service

Alternative solution: A More Userfriendly solution than command line:

If you are looking for a user friendly way to send and request data using HTTP Methods other than simple GET's probably you are looking for a chrome extention just like this one http://goo.gl/rVW22f called AVANCED REST CLIENT

For guys looking to stay with command-line i recommend cygwin:

I ended up installing cygwin with CURL which allow us to Get that Linux feeling - on Windows!

Using Cygwin command line this issues have stopped and most important, the request syntax used on 1. worked fine.

Useful links:

Where i was downloading the curl for windows command line?

For more information on how to install and get curl working with cygwin just go here

I hope it helps someone because i spent all morning on this.

Error: Can't set headers after they are sent to the client

In my case it happens due to multiple callbacks. I have called next() method multiple time during the code

Retrieve a single file from a repository

If you want to get a file from a specific hash + a remote repository I've tried git-archive and it didn't work.

You would have to use git clone and once the repository is cloned you would have then to use git-archive to make it work.

I post a question about how to do it more simpler in git archive from a specific hash from remote

How do we check if a pointer is NULL pointer?

Well, this question was asked and answered way back in 2011, but there is nullptrin C++11. That's all I'm using currently.

You can read more from Stack Overflow and also from this article.

Html.HiddenFor value property not getting set

A simple answer is to use @Html.TextboxFor but place it in a div that is hidden with style. Example: In View:

<div style="display:none"> @Html.TextboxFor(x=>x.CRN) </div>

Excel plot time series frequency with continuous xaxis

I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog

Non-uniformly distributed data can be plotted in excel in

  • X Y (Scatter Plots)
  • Linear plots with Date axis
    • These don't take time into account, only days.
    • This method is quite cumbersome as it requires translating your time units to days, months, or years.. then change the axis labels... Not Recommended

Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.

1- Add the center point to your data series

+---------------+-------+------+
|    Time       | Time  | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 |  12  |
| 09:00 - 10:00 | 09:30 |  13  |
| 10:00 - 11:00 | 10:30 |  10  |
| 13:00 - 14:00 | 13:30 |   5  |
| 14:00 - 15:00 | 14:30 |  14  |
+---------------+-------+------+

2- Create a Scatter Plot

3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:

  • Minimum : Fix : 0.33333
  • Maximum : Fix : 0.625
  • Major unit : Fix : 0.041667

Line Scatter Plot


Alternative Display:

Make the points turn into columns:

To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.

1- You're going to need to add several rows where we draw the line and disjoint the data

+-------+------+
| Time  | Freq |
+-------+------+
| 08:30 |   0  |
| 08:30 |  12  |
|       |      |
| 09:30 |   0  |
| 09:30 |  13  |
|       |      |
| 10:30 |   0  |
| 10:30 |  10  |
|       |      |
| 13:30 |   0  |
| 13:30 |   5  |
|       |      |
| 14:30 |   0  |
| 14:30 |  14  |
+-------+------+

2- Plot an X Y (Scatter) Chart with Lines.

3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.

Bar-Line Scatter Plot

Find files in created between a date range

Script oldfiles

I've tried to answer this question in a more complete way, and I ended up creating a complete script with options to help you understand the find command.

The script oldfiles is in this repository

To "create" a new find command you run it with the option -n (dry-run), and it will print to you the correct find command you need to use.

Of course, if you omit the -n it will just run, no need to retype the find command.

Usage:

$ oldfiles [-v...] ([-h|-V|-n] | {[(-a|-u) | (-m|-t) | -c] (-i | -d | -o| -y | -g) N (-\> | -\< | -\=) [-p "pat"]})

  • Where the options are classified in the following groups:
    • Help & Info:

      -h, --help : Show this help.
      -V, --version : Show version.
      -v, --verbose : Turn verbose mode on (cumulative).
      -n, --dry-run : Do not run, just explain how to create a "find" command

    • Time type (access/use, modification time or changed status):

      -a or -u : access (use) time
      -m or -t : modification time (default)
      -c : inode status change

    • Time range (where N is a positive integer):

      -i N : minutes (default, with N equal 1 min)
      -d N : days
      -o N : months
      -y N : years
      -g N : N is a DATE (example: "2017-07-06 22:17:15")

    • Tests:

      -p "pat" : optional pattern to match (example: -p "*.c" to find c files) (default -p "*")
      -\> : file is newer than given range, ie, time modified after it.
      -\< : file is older than given range, ie, time is from before it. (default)
      -\= : file that is exactly N (min, day, month, year) old.

Example:

  • Find C source files newer than 10 minutes (access time) (with verbosity 3):

$ oldfiles -a -i 10 -p"*.c" -\> -nvvv Starting oldfiles script, by beco, version 20170706.202054... $ oldfiles -vvv -a -i 10 -p "*.c" -\> -n Looking for "*.c" files with (a)ccess time newer than 10 minute(s) find . -name "*.c" -type f -amin -10 -exec ls -ltu --time-style=long-iso {} + Dry-run

  • Find H header files older than a month (modification time) (verbosity 2):

$ oldfiles -m -o 1 -p"*.h" -\< -nvv Starting oldfiles script, by beco, version 20170706.202054... $ oldfiles -vv -m -o 1 -p "*.h" -\< -n find . -name "*.h" -type f -mtime +30 -exec ls -lt --time-style=long-iso {} + Dry-run

  • Find all (*) files within a single day (Dec, 1, 2016; no verbosity, dry-run):

$ oldfiles -mng "2016-12-01" -\= find . -name "*" -type f -newermt "2016-11-30 23:59:59" ! -newermt "2016-12-01 23:59:59" -exec ls -lt --time-style=long-iso {} +

Of course, removing the -n the program will run the find command itself and save you the trouble.

I hope this helps everyone finally learn this {a,c,t}{time,min} options.

the LS output:

You will also notice that the "ls" option ls OPT changes to match the type of time you choose.

Link for clone/download of the oldfiles script:

https://github.com/drbeco/oldfiles

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

The answer is:

gcc --version

Rather than searching on forums, for any possible option you can always type:

gcc --help

haha! :)

How to find path of active app.config file?

Make sure you click the properties on the file and set it to "copy always" or it will not be in the Debug\ folder with your happy lil dll's to configure where it needs to be and add more cowbell

Given an array of numbers, return array of products of all other numbers (no division)

Here is my concise solution using python.

from functools import reduce

def excludeProductList(nums_):
    after = [reduce(lambda x, y: x*y, nums_[i:]) for i in range(1, len(nums_))] + [1]
    before = [1] + [reduce(lambda x, y: x*y, nums_[:i]) for i in range(1, len(nums_))]
    zippedList =  list(zip(before, after))
    finalList = list(map(lambda x: x[0]*x[1], zippedList))
    return finalList

Jackson: how to prevent field serialization

You can mark it as @JsonIgnore.

With 1.9, you can add @JsonIgnore for getter, @JsonProperty for setter, to make it deserialize but not serialize.

run program in Python shell

If you want to avoid writing all of this everytime, you can define a function :

def run(filename):
    exec(open(filename).read())

and then call it

run('filename.py')

Maven: How to change path to target directory from command line?

Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:

    <profile>
        <id>alternateBuildDir</id>
        <activation>
            <property>
                <name>alt.build.dir</name>
            </property>
        </activation>
        <build>
            <directory>${alt.build.dir}</directory>
        </build>
    </profile>

Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.

What is the apply function in Scala?

TLDR for people comming from c++

It's just overloaded operator of ( ) parentheses

So in scala:

class X {
   def apply(param1: Int, param2: Int, param3: Int) : Int = {
     // Do something
   }
}

Is same as this in c++:

class X {
   int operator()(int param1, int param2, int param3) {
      // do something
   }
};

How do I automatically resize an image for a mobile site?

For me, it worked best to add this in image css: max-width:100%; and NOT specify image width and height in html parameters. This adjusted the width to fit in device screen while adjusting height automatically. Otherwise height might be distorted.

Convert factor to integer

You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2

javascript regular expression to check for IP addresses

/^(?!.*\.$)((?!0\d)(1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/

Full credit to oriadam. I would have commented below his/her answer to suggest the double zero change I made, but I do not have enough reputation here yet...

change:

mysqli_real_connect(): (HY000/2002): No such file or directory

If your website was running fine and now unexpected ERROR: (HY000/2002): No such file or directory

Then you should NOT CHANGE any configuration file!

First check server error.log file, for Nginx it's located:

/var/log/nginx/error.log

Or for Apache try:

/var/log/apache2/error_log

In my case I could see PHP Fatal error: OUT OF MEMORY in error.log for nginx.

The solution: Add more RAM to server.


I tried to reboot the web server first before upgrading/adding RAM. Then I got rid of ERROR (HY000/2002) but got some ERROR 50X: Connection Error...

At this point I added 2GB RAM, rebooted the web server and all was working fine!

When the web server was up I noticed 200+ cron-jobs was stuck due to a loop bug in 1 PHP script.

So check which script is consuming memory.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

You're mixing up HTML with XHTML.

Usually a <!DOCTYPE> declaration is used to distinguish between versions of HTMLish languages (in this case, HTML or XHTML).

Different markup languages will behave differently. My favorite example is height:100%. Look at the following in a browser:

XHTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <style type="text/css">
    table { height:100%;background:yellow; }
  </style>
</head>
<body>
  <table>
    <tbody>
      <tr><td>How tall is this?</td></tr>
    </tbody>
  </table>
</body>
</html>

... and compare it to the following: (note the conspicuous lack of a <!DOCTYPE> declaration)

HTML (quirks mode)

<html>
<head>
  <style type="text/css">
    table { height:100%;background:yellow; }
  </style>
</head>
<body>
  <table>
    <tbody>
      <tr><td>How tall is this?</td></tr>
    </tbody>
  </table>
</body>
</html>

You'll notice that the height of the table is drastically different, and the only difference between the 2 documents is the type of markup!

That's nice... now, what does <html xmlns="http://www.w3.org/1999/xhtml"> do?

That doesn't answer your question though. Technically, the xmlns attribute is used by the root element of an XHTML document: (according to Wikipedia)

The root element of an XHTML document must be html, and must contain an xmlns attribute to associate it with the XHTML namespace.

You see, it's important to understand that XHTML isn't HTML but XML - a very different creature. (ok, a kind of different creature) The xmlns attribute is just one of those things the document needs to be valid XML. Why? Because someone working on the standard said so ;) (you can read more about XML namespaces on Wikipedia but I'm omitting that info 'cause it's not actually relevant to your question!)

But then why is <html xmlns="http://www.w3.org/1999/xhtml"> fixing the CSS?

If structuring your document like so... (as you suggest in your comment)

<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
[...]

... is fixing your document, it leads me to believe that you don't know that much about CSS and HTML (no offense!) and that the truth is that without <html xmlns="http://www.w3.org/1999/xhtml"> it's behaving normally and with <html xmlns="http://www.w3.org/1999/xhtml"> it's not - and you just think it is, because you're used to writing invalid HTML and thus working in quirks mode.

The above example I provided is an example of that same problem; most people think height:100% should result in the height of the <table> being the whole window, and that the DOCTYPE is actually breaking their CSS... but that's not really the case; rather, they just don't understand that they need to add a html, body { height:100%; } CSS rule to achieve their desired effect.

What is the order of precedence for CSS?

First of all, based on your @extend directive, it seems you're not using pure CSS, but a preprocessor such as SASS os Stylus.

Now, when we talk about "order of precedence" in CSS, there is a general rule involved: whatever rules set after other rules (in a top-down fashion) are applied. In your case, just by specifying .smallbox after .smallbox-paysummary you would be able to change the precedence of your rules.

However, if you wanna go a bit further, I suggest this reading: CSS cascade W3C specification. You will find that the precedence of a rule is based on:

  1. The current media type;
  2. Importance;
  3. Origin;
  4. Specificity of the selector, and finally our well-known rule:
  5. Which one is latter specified.

Pygame mouse clicking detection

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked. Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseClick

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.click_image, color, (25, 25), 25)
        pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

        self.image = self.click_image if self.clicked else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

See further Creating multiple sprites with different update()'s from the same sprite class in Pygame


The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ??that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.

Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        if  self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
            # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseHover

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.hover_image, color, (25, 25), 25)
        pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        #self.hover = self.rect.collidepoint(mouse_pos)
        self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)

        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    group.update()

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

jquery - How to determine if a div changes its height or any css attribute?

Another simple example.

For this sample we can use 100x100 DIV-box:

<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
 // Red box contents here...
</div>

And small jQuery trick:

<script type="text/javascript">
  jQuery("#box").bind("resize", function() {
    alert("Box was resized from 100x100 to 200x200");
  });
  jQuery("#box").width(200).height(200).trigger("resize");
</script>

Steps:

  1. We created DIV block element for resizing operatios
  2. Add simple JavaScript code with:
    • jQuery bind
    • jQuery resizer with trigger action "resize" - trigger is most important thing in my example
  3. After resize you can check the browser alert information

That's all. ;-)

EditorFor() and html properties

As at MVC 5, if you wish to add any attributes you can simply do

 @Html.EditorFor(m => m.Name, new { htmlAttributes = new { @required = "true", @anotherAttribute = "whatever" } })

Information found from this blog

python object() takes no parameters error

You've mixed tabs and spaces. __init__ is actually defined nested inside another method, so your class doesn't have its own __init__ method, and it inherits object.__init__ instead. Open your code in Notepad instead of whatever editor you're using, and you'll see your code as Python's tab-handling rules see it.

This is why you should never mix tabs and spaces. Stick to one or the other. Spaces are recommended.

Drop a temporary table if it exists

What you asked for is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##CLIENTS_KEYWORD

       CREATE TABLE ##CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##TEMP_CLIENTS_KEYWORD

       CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##CLIENTS_KEYWORD

CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##TEMP_CLIENTS_KEYWORD

CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Bootstrap modal - close modal when "call to action" button is clicked

Remove your script, and change the HTML:

<a id="closemodal" href="https://www.google.com" class="btn btn-primary close" data-dismiss="modal" target="_blank">Launch google.com</a>

EDIT: Please note that currently this will not work as this functionality does not yet exist in bootstrap. See issue here.

Why does the arrow (->) operator in C exist?

C also does a good job at not making anything ambiguous.

Sure the dot could be overloaded to mean both things, but the arrow makes sure that the programmer knows that he's operating on a pointer, just like when the compiler won't let you mix two incompatible types.

How to automatically close cmd window after batch file execution?

Sometimes you can reference a Windows "shortcut" file to launch an application instead of using a ".bat" file, and it won't have the residual prompt problem. But it's not as flexible as bat files.

Oracle PL Sql Developer cannot find my tnsnames.ora file

I had the same problema, but as described in the manual.pdf, you have to:

You are using an Oracle Instant Client but have not set all required environment variables:

  • PATH: Needs to include the Instant Client directory where oci.dll is located
  • TNS_ADMIN: Needs to point to the directory where tnsnames.ora is located.
  • NLS_LANG: Defines the language, territory, and character set for the client.

Regards

How to install XNA game studio on Visual Studio 2012?

On codeplex was released new XNA Extension for Visual Studio 2012/2013. You can download it from: https://msxna.codeplex.com/releases

Error Message : Cannot find or open the PDB file

The PDB file is a Visual Studio specific file that has the debugging symbols for your project. You can ignore those messages, unless you're hoping to step into the code for those dlls with the debugger (which is doubtful, as those are system dlls). In other words, you can and should ignore them, as you won't have the PDB files for any of those dlls (by default at least, it turns out you can actually obtain them when debugging via the Microsoft Symbol Server). All it means is that when you set a breakpoint and are stepping through the code, you won't be able to step into any of those dlls (which you wouldn't want to do anyways).

Just for completeness, here's the official PDB description from MSDN:

A program database (PDB) file holds debugging and project state information that allows incremental linking of a Debug configuration of your program. A PDB file is created when you compile a C/C++ program with /ZI or /Zi

Also for future reference, if you want to have PDB files for your own code, you would would have to build your project with either the /ZI or /Zi options enabled (you can set them via project properties --> C/C++ --> General, then set the field for "Debug Information Format"). Not relevant to your situation, but I figured it might be useful in the future

Converting String to Double in Android

String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());

Can't concat bytes to str

subprocess.check_output() returns bytes.

so you need to convert '\n' to bytes as well:

 f.write (plaintext + b'\n')

hope this helps

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

How can I check for NaN values?

I actually just ran into this, but for me it was checking for nan, -inf, or inf. I just used

if float('-inf') < float(num) < float('inf'):

This is true for numbers, false for nan and both inf, and will raise an exception for things like strings or other types (which is probably a good thing). Also this does not require importing any libraries like math or numpy (numpy is so damn big it doubles the size of any compiled application).

jQuery UI autocomplete with item and id

Auto Complete Text box binding using Jquery

  ## HTML Code For Text Box and For Handling UserID use Hidden value ##
  <div class="ui-widget">
@Html.TextBox("userName")  
    @Html.Hidden("userId")
    </div>

Below Library's is Required

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Jquery Script

$("#userName").autocomplete(
{

    source: function (request,responce)
    {
        debugger
        var Name = $("#userName").val();

        $.ajax({
            url: "/Dashboard/UserNames",
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                Name: Name

            }),
            dataType: 'json',
            success: function (data) {
                debugger
                responce(data);
            },
            error: function (err) {
                alert(err);
            }
        });
    },
    select: function (event, ui) {

        $("#userName").val(ui.item.label); // display the selected text
        $("#userId").val(ui.item.value); // save selected id to hidden input
        return false;
    }
})

Return data Should be below format


 label = u.person_full_name,
 value = u.user_id

Count number of matches of a regex in Javascript

('my string'.match(/\s/g) || []).length;

Get index of array element faster than O(n)

Still I wonder if there's a more convenient way of finding index of en element without caching (or there's a good caching technique that will boost up the performance).

You can use binary search (if your array is ordered and the values you store in the array are comparable in some way). For that to work you need to be able to tell the binary search whether it should be looking "to the left" or "to the right" of the current element. But I believe there is nothing wrong with storing the index at insertion time and then using it if you are getting the element from the same array.

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Make sure it's not redefined again lower down in your settings.py. The default settings has:

ALLOWED_HOSTS = []

How can I define colors as variables in CSS?

Not PHP I'm afraid, but Zope and Plone use something similar to SASS called DTML to achieve this. It's incredibly useful in CMS's.

Upfront Systems has a good example of its use in Plone.

ImportError: No module named 'MySQL'

I tried all the answers but not worked for me. It is a python version problem, in the end, I realized that python 3 scripts need explicit pip command for python 3, at least on ubuntu 18.

python3 -m pip install mysql-connector

How to grep and replace

I got the answer.

grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'

How do I get this javascript to run every second?

Use setInterval() to run a piece of code every x milliseconds.

You can wrap the code you want to run every second in a function called runFunction.

So it would be:

var t=setInterval(runFunction,1000);

And to stop it, you can run:

clearInterval(t);

Datagridview: How to set a cell in editing mode?

I know this question is pretty old, but figured I'd share some demo code this question helped me with.

  • Create a Form with a Button and a DataGridView
  • Register a Click event for button1
  • Register a CellClick event for DataGridView1
  • Set DataGridView1's property EditMode to EditProgrammatically
  • Paste the following code into Form1:
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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        DataTable m_dataTable;
        DataTable table { get { return m_dataTable; } set { m_dataTable = value; } }

        private const string m_nameCol = "Name";
        private const string m_choiceCol = "Choice";

        public Form1()
        {
            InitializeComponent();
        }

        class Options
        {
            public int m_Index { get; set; }
            public string m_Text { get; set; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            table = new DataTable();
            table.Columns.Add(m_nameCol);
            table.Rows.Add(new object[] { "Foo" });
            table.Rows.Add(new object[] { "Bob" });
            table.Rows.Add(new object[] { "Timn" });
            table.Rows.Add(new object[] { "Fred" });

            dataGridView1.DataSource = table;

            if (!dataGridView1.Columns.Contains(m_choiceCol))
            {
                DataGridViewTextBoxColumn txtCol = new DataGridViewTextBoxColumn();
                txtCol.Name = m_choiceCol;
                dataGridView1.Columns.Add(txtCol);
            }

            List<Options> oList = new List<Options>();
            oList.Add(new Options() { m_Index = 0, m_Text = "None" });
            for (int i = 1; i < 10; i++)
            {
                oList.Add(new Options() { m_Index = i, m_Text = "Op" + i });
            }

            for (int i = 0; i < dataGridView1.Rows.Count - 1; i += 2)
            {
                DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();

                //Setup A
                c.DataSource = oList;
                c.Value = oList[0].m_Text;
                c.ValueMember = "m_Text";
                c.DisplayMember = "m_Text";
                c.ValueType = typeof(string);

                ////Setup B
                //c.DataSource = oList;
                //c.Value = 0;
                //c.ValueMember = "m_Index";
                //c.DisplayMember = "m_Text";
                //c.ValueType = typeof(int);

                //Result is the same A or B
                dataGridView1[m_choiceCol, i] = c;
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.Columns.IndexOf(dataGridView1.Columns[m_choiceCol]))
                {
                    DataGridViewCell cell = dataGridView1[m_choiceCol, e.RowIndex];
                    dataGridView1.CurrentCell = cell;
                    dataGridView1.BeginEdit(true);
                }
            }
        }
    }
}

Note that the column index numbers can change from multiple button presses of button one, so I always refer to the columns by name not index value. I needed to incorporate David Hall's answer into my demo that already had ComboBoxes so his answer worked really well.

Add a dependency in Maven

I'd do this:

  1. add the dependency as you like in your pom:

    <dependency>
            <groupId>com.stackoverflow...</groupId>
            <artifactId>artifactId...</artifactId>
            <version>1.0</version>
    </dependency>
    

  2. run mvn install it will try to download the jar and fail. On the process, it will give you the complete command of installing the jar with the error message. Copy that command and run it! easy huh?!

Scrolling to element using webdriver?

In addition to move_to_element() and scrollIntoView() I wanted to pose the following code which attempts to center the element in the view:

desired_y = (element.size['height'] / 2) + element.location['y']
window_h = driver.execute_script('return window.innerHeight')
window_y = driver.execute_script('return window.pageYOffset')
current_y = (window_h / 2) + window_y
scroll_y_by = desired_y - current_y

driver.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by)

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

symfony 2 twig limit the length of the text and put three dots

Bugginess* in the new Drupal 8 capabilities here inspired us to write our own:

<a href="{{ view_node }}">{% if title|length > 32 %}{% set title_array = title|split(' ') %}{% set title_word_count = 0 %}{% for ta in title_array %}{% set word_count = ta|length %}{% if title_word_count < 32 %}{% set title_word_count = title_word_count + word_count %}{{ ta }} {% endif %}{% endfor %}...{% else %}{{ title }}{% endif %}</a>

This takes into consideration both words and characters (*the "word boundary" setting in D8 was displaying nothing).

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

Since PHP 5.5, there is a separate php.ini file for CLI interface. If You use symfony console from command line, then this specific php.ini is used.

In Ubuntu 13.10 check file:

/etc/php5/cli/php.ini

What is newline character -- '\n'

NewLine (\n) is 10 (0xA) and CarriageReturn (\r) is 13 (0xD).

Different operating systems picked different end of line representations for files. Windows uses CRLF (\r\n). Unix uses LF (\n). Older Mac OS versions use CR (\r), but OS X switched to the Unix character.

Here is a relatively useful FAQ.

A fast way to delete all rows of a datatable at once

Here we have same question. You can use the following code:

SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["yourconnectionstringnamehere"].ConnectionString;
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "DELETE FROM [tablenamehere]";
SqlDataReader data = com.ExecuteReader();
con.Close();

But before you need to import following code to your project:

using System.Configuration;
using System.Data.SqlClient;

This is the specific part of the code that can delete all rows is a table:

DELETE FROM [tablenamehere]

This must be your table name:tablenamehere - This can delete all rows in table: DELETE FROM

Kotlin unresolved reference in IntelliJ

A possible solution for standalone Kotlin projects is to include Kotlin standard libs explicitliy inside the root project.

To do that in IntelliJ IDEA:

  • press Ctrl+Shift+A (Search actions or options)
  • type in "Configure kotlin in project" and let it include standard libs for you

WCF named pipe minimal example

I just found this excellent little tutorial. broken link (Cached version)

I also followed Microsoft's tutorial which is nice, but I only needed pipes as well.

As you can see, you don't need configuration files and all that messy stuff.

By the way, he uses both HTTP and pipes. Just remove all code lines related to HTTP, and you'll get a pure pipe example.

Removing index column in pandas when reading a csv

you can specify which column is an index in your csv file by using index_col parameter of from_csv function if this doesn't solve you problem please provide example of your data

Is there any way to install Composer globally on Windows?

Install Composer

On Windows, you can use the Composer Windows Installer.

Clear dropdown using jQuery Select2

This is the proper one, select2 will clear the selected value and show the placeholder back .

$remote.select2('data', null)

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

Select a row from html table and send values onclick of a button

You can access the first element adding the following code to the highlight function

$(this).find(".selected td:first").html()

Working Code:JSFIDDLE

Unable to compile simple Java 10 / Java 11 project with Maven

As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the maven-compiler-plugin:3.8.0 to specify a release of either 9,10,11 without any explicit dependencies.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>11</release>  <!--or <release>10</release>-->
    </configuration>
</plugin>

Note:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- release notes.


Edit [30.12.2018]

In fact, you can make use of the same version of maven-compiler-plugin while compiling the code against JDK/12 as well.

More details and a sample configuration in how to Compile and execute a JDK preview feature with Maven.

AJAX Mailchimp signup form integration

You don't need an API key, all you have to do is plop the standard mailchimp generated form into your code ( customize the look as needed ) and in the forms "action" attribute change post?u= to post-json?u= and then at the end of the forms action append &c=? to get around any cross domain issue. Also it's important to note that when you submit the form you must use GET rather than POST.

Your form tag will look something like this by default:

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post?u=xxxxx&id=xxxx" method="post" ... >

change it to look something like this

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="get" ... >

Mail Chimp will return a json object containing 2 values: 'result' - this will indicate if the request was successful or not ( I've only ever seen 2 values, "error" and "success" ) and 'msg' - a message describing the result.

I submit my forms with this bit of jQuery:

$(document).ready( function () {
    // I only have one form on the page but you can be more specific if need be.
    var $form = $('form');

    if ( $form.length > 0 ) {
        $('form input[type="submit"]').bind('click', function ( event ) {
            if ( event ) event.preventDefault();
            // validate_input() is a validation function I wrote, you'll have to substitute this with your own.
            if ( validate_input($form) ) { register($form); }
        });
    }
});

function register($form) {
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        cache       : false,
        dataType    : 'json',
        contentType: "application/json; charset=utf-8",
        error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
        success     : function(data) {
            if (data.result != "success") {
                // Something went wrong, do something to notify the user. maybe alert(data.msg);
            } else {
                // It worked, carry on...
            }
        }
    });
}

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

Why I've got no crontab entry on OS X when using vim?

The use of cron on OS X is discouraged. launchd is used instead. Try man launchctl to get started. You have to create special XML files that define your jobs and put them in a special place with certain permissions.

You'll usually just need to figure out launchctl load

http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/launchctl.1.html

http://nb.nathanamy.org/2012/07/schedule-jobs-using-launchd/

Edit

If you really do want to use cron on OS X, check out this answer: https://superuser.com/a/243944/2449

"Default Activity Not Found" on Android Studio upgrade

If the options above do not work, try deleting the .gradle folder.

I am using Android Studio 3.3.1. All my projects were fine, when they all suddenly stopped working saying that there was no activity. Even brand new projects were showing the same error. After hours invalidating cache, trying to fix the Manifest file. I've noticed that it had some relationship with androidx libraries like (androidx.core:core-ktx). In some projects, just updating the libs fix the problem, but what actually worked was deleting the .gradle folder.

Shell script to copy files from one location to another location and rename add the current date to every file

In bash, provided you files names have no spaces:

cd /home/webapps/project1/folder1
for f in *.csv
do 
   cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv
done

Given URL is not allowed by the Application configuration

The other answers here are excellent and accurate. In the interest of adding to the list of things to try:

Double and triple-check that your app is using the right application ID and secret key. In my case, after trying many other things, I checked the application ID and secret key and found that I was using our production settings on our development system. Doh!

Using the correct application ID and secret key fixed the problem.

Calling javascript function in iframe

The first and foremost condition that needs to be met is that both the parent and iframe should belong to the same origin. Once that is done the child can invoke the parent using window.opener method and the parent can do the same for the child as mentioned above

Javascript switch vs. if...else if...else

Answering in generalities:

  1. Yes, usually.
  2. See More Info Here
  3. Yes, because each has a different JS processing engine, however, in running a test on the site below, the switch always out performed the if, elseif on a large number of iterations.

Test site

Get height and width of a layout programmatically

Check behavior Very Simple Solution

  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.d(LOG, "MainActivity - onCreate() called")

        fragments_frame.post {
            Log.d(LOG, " fragments_frame.height:${fragments_frame.width}")
            Log.d(LOG, " fragments_frame.height:${fragments_frame.measuredWidth}")
        }
}

Converting Select results into Insert script - SQL Server

It's possible to do via Visual Studio SQL Server Object Explorer.

You can click "View Data" from context menu for necessary table, filter results and save result as script.

How do I convert a single character into it's hex ascii value in python

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

Jquery $(this) Child Selector

http://jqapi.com/ Traversing--> Tree Traversal --> Children

Converting from a string to boolean in Python?

This version keeps the semantics of constructors like int(value) and provides an easy way to define acceptable string values.

def to_bool(value):
    valid = {'true': True, 't': True, '1': True,
             'false': False, 'f': False, '0': False,
             }   

    if isinstance(value, bool):
        return value

    if not isinstance(value, basestring):
        raise ValueError('invalid literal for boolean. Not a string.')

    lower_value = value.lower()
    if lower_value in valid:
        return valid[lower_value]
    else:
        raise ValueError('invalid literal for boolean: "%s"' % value)


# Test cases
assert to_bool('true'), '"true" is True' 
assert to_bool('True'), '"True" is True' 
assert to_bool('TRue'), '"TRue" is True' 
assert to_bool('TRUE'), '"TRUE" is True' 
assert to_bool('T'), '"T" is True' 
assert to_bool('t'), '"t" is True' 
assert to_bool('1'), '"1" is True' 
assert to_bool(True), 'True is True' 
assert to_bool(u'true'), 'unicode "true" is True'

assert to_bool('false') is False, '"false" is False' 
assert to_bool('False') is False, '"False" is False' 
assert to_bool('FAlse') is False, '"FAlse" is False' 
assert to_bool('FALSE') is False, '"FALSE" is False' 
assert to_bool('F') is False, '"F" is False' 
assert to_bool('f') is False, '"f" is False' 
assert to_bool('0') is False, '"0" is False' 
assert to_bool(False) is False, 'False is False'
assert to_bool(u'false') is False, 'unicode "false" is False'

# Expect ValueError to be raised for invalid parameter...
try:
    to_bool('')
    to_bool(12)
    to_bool([])
    to_bool('yes')
    to_bool('FOObar')
except ValueError, e:
    pass

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute Xpath: It uses Complete path from the Root Element to the desire element.

Relative Xpath: You can simply start by referencing the element you want and go from there.

Relative Xpaths are always preferred as they are not the complete paths from the root element. (//html//body). Because in future, if any webelement is added/removed, then the absolute Xpath changes. So Always use Relative Xpaths in your Automation.

Below are Some Links which you can Refer for more Information on them.

How do you run your own code alongside Tkinter's event loop?

Use the after method on the Tk object:

from tkinter import *

root = Tk()

def task():
    print("hello")
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)
root.mainloop()

Here's the declaration and documentation for the after method:

def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

when exactly are we supposed to use "public static final String"?

You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.

Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.

An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).

Here's why:

  1. Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
  2. What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.

What are the consequences?

Imagine you have this:

class Foo {
  public static final String VERSION = "1.0";
}

class Bar {
  public static void main(String[] args) {
    System.out.println("I am using version " + Foo.VERSION);
  }
}

After compiling and running Bar, you'll get:

I am using version 1.0

Now, you improve Foo and change the version to "1.1". After recompiling Foo, you run Bar and get this wrong output:

I am using version 1.0

This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.

I've seen this a couple of times and it is really hard to debug.

If by final you mean a constant that might change in later versions of your program, a better solution would be this:

class Foo {
  private static String version = "1.0";
  public static final String getVersion() {
    return version;
  }
}

The performance penalty of this is negligible, since JIT code generator will inline it at run-time.

How to map a composite key with JPA and Hibernate?

To map a composite key, you can use the EmbeddedId or the IdClass annotations. I know this question is not strictly about JPA but the rules defined by the specification also applies. So here they are:

2.1.4 Primary Keys and Entity Identity

...

A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described below. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The EmbeddedId and IdClass annotations are used to denote composite primary keys. See sections 9.1.14 and 9.1.15.

...

The following rules apply for composite primary keys:

  • The primary key class must be public and must have a public no-arg constructor.
  • If property-based access is used, the properties of the primary key class must be public or protected.
  • The primary key class must be serializable.
  • The primary key class must define equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
  • A composite primary key must either be represented and mapped as an embeddable class (see Section 9.1.14, “EmbeddedId Annotation”) or must be represented and mapped to multiple fields or properties of the entity class (see Section 9.1.15, “IdClass Annotation”).
  • If the composite primary key class is mapped to multiple fields or properties of the entity class, the names of primary key fields or properties in the primary key class and those of the entity class must correspond and their types must be the same.

With an IdClass

The class for the composite primary key could look like (could be a static inner class):

public class TimePK implements Serializable {
    protected Integer levelStation;
    protected Integer confPathID;

    public TimePK() {}

    public TimePK(Integer levelStation, Integer confPathID) {
        this.levelStation = levelStation;
        this.confPathID = confPathID;
    }
    // equals, hashCode
}

And the entity:

@Entity
@IdClass(TimePK.class)
class Time implements Serializable {
    @Id
    private Integer levelStation;
    @Id
    private Integer confPathID;

    private String src;
    private String dst;
    private Integer distance;
    private Integer price;

    // getters, setters
}

The IdClass annotation maps multiple fields to the table PK.

With EmbeddedId

The class for the composite primary key could look like (could be a static inner class):

@Embeddable
public class TimePK implements Serializable {
    protected Integer levelStation;
    protected Integer confPathID;

    public TimePK() {}

    public TimePK(Integer levelStation, Integer confPathID) {
        this.levelStation = levelStation;
        this.confPathID = confPathID;
    }
    // equals, hashCode
}

And the entity:

@Entity
class Time implements Serializable {
    @EmbeddedId
    private TimePK timePK;

    private String src;
    private String dst;
    private Integer distance;
    private Integer price;

    //...
}

The @EmbeddedId annotation maps a PK class to table PK.

Differences:

  • From the physical model point of view, there are no differences
  • @EmbeddedId somehow communicates more clearly that the key is a composite key and IMO makes sense when the combined pk is either a meaningful entity itself or it reused in your code.
  • @IdClass is useful to specify that some combination of fields is unique but these do not have a special meaning.

They also affect the way you write queries (making them more or less verbose):

  • with IdClass

    select t.levelStation from Time t
    
  • with EmbeddedId

    select t.timePK.levelStation from Time t
    

References

  • JPA 1.0 specification
    • Section 2.1.4 "Primary Keys and Entity Identity"
    • Section 9.1.14 "EmbeddedId Annotation"
    • Section 9.1.15 "IdClass Annotation"

swift 3.0 Data to String?

Swift 4 version of 4redwings's answer:

let testString = "This is a test string"
let somedata = testString.data(using: String.Encoding.utf8)
let backToString = String(data: somedata!, encoding: String.Encoding.utf8)

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

Datatables - Setting column width

I set the column widths in the HTML markup like so:

    <thead>
        <tr>

            <th style='width: 5%;'>ProjectId</th>
            <th style='width: 15%;'>Title</th>
            <th style='width: 40%;'>Abstract</th>
            <th style='width: 20%;'>Keywords</th>
            <th style='width: 10%;'>PaperName</th>
            <th style='width: 10%;'>PaperURL</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr id="@item.ID">
                <td>@item.ProjectId</td>
                <td>@item.Title</td>
                <td>@item.Abstract</td>
                <td>@item.Keywords</td>
                <td>@item.PaperName</td>
                <td>@item.PaperURL</td>
            </tr>
        }
    </tbody>
</table>

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

Previous answers are correct: adding the line...

Response.AddHeader("Content-Disposition", "inline; filename=[filename]");

...will causing multiple Content-Disposition headers to be sent down to the browser. This happens b/c FileContentResult internally applies the header if you supply it with a file name. An alternative, and pretty simple, solution is to simply create a subclass of FileContentResult and override its ExecuteResult() method. Here's an example that instantiates an instance of the System.Net.Mime.ContentDisposition class (the same object used in the internal FileContentResult implementation) and passes it into the new class:

public class FileContentResultWithContentDisposition : FileContentResult
{
    private const string ContentDispositionHeaderName = "Content-Disposition";

    public FileContentResultWithContentDisposition(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
        : base(fileContents, contentType)
    {
        // check for null or invalid ctor arguments
        ContentDisposition = contentDisposition;
    }

    public ContentDisposition ContentDisposition { get; private set; }

    public override void ExecuteResult(ControllerContext context)
    {
        // check for null or invalid method argument
        ContentDisposition.FileName = ContentDisposition.FileName ?? FileDownloadName;
        var response = context.HttpContext.Response;
        response.ContentType = ContentType;
        response.AddHeader(ContentDispositionHeaderName, ContentDisposition.ToString());
        WriteFile(response);
    }
}

In your Controller, or in a base Controller, you can write a simple helper to instantiate a FileContentResultWithContentDisposition and then call it from your action method, like so:

protected virtual FileContentResult File(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
{
    var result = new FileContentResultWithContentDisposition(fileContents, contentType, contentDisposition);
    return result;
}

public ActionResult Report()
{
    // get a reference to your document or file
    // in this example the report exposes properties for
    // the byte[] data and content-type of the document
    var report = ...
    return File(report.Data, report.ContentType, new ContentDisposition {
        Inline = true,
        FileName = report.FileName
    });
}

Now the file will be sent to the browser with the file name you choose and with a content-disposition header of "inline; filename=[filename]".

I hope that helps!

ggplot2: sorting a plot

You need to make the x-factor into an ordered factor with the ordering you want, e.g

x <- data.frame("variable"=letters[1:5], "value"=rnorm(5)) ## example data
x <- x[with(x,order(-value)), ] ## Sorting
x$variable <- ordered(x$variable, levels=levels(x$variable)[unclass(x$variable)])

ggplot(x, aes(x=variable,y=value)) + geom_bar() +
   scale_y_continuous("",formatter="percent") + coord_flip()

I don't know any better way to do the ordering operation. What I have there will only work if there are no duplicate levels for x$variable.

How do you round a number to two decimal places in C#?

Had a weird situation where I had a decimal variable, when serializing 55.50 it always sets default value mathematically as 55.5. But whereas, our client system is seriously expecting 55.50 for some reason and they definitely expected decimal. Thats when I had write the below helper, which always converts any decimal value padded to 2 digits with zeros instead of sending a string.

public static class DecimalExtensions
{
    public static decimal WithTwoDecimalPoints(this decimal val)
    {
        return decimal.Parse(val.ToString("0.00"));
    }
}

Usage should be

var sampleDecimalValueV1 = 2.5m;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());

decimal sampleDecimalValueV1 = 2;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());

Output:

2.50
2.00

MySQL date formats - difficulty Inserting a date

An add-on to the previous answers since I came across this concern:

If you really want to insert something like 24-May-2005 to your DATE column, you could do something like this:

INSERT INTO someTable(Empid,Date_Joined)
VALUES
    ('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));

In the above query please note that if it's May(ie: the month in letters) the format should be %M.

NOTE: I tried this with the latest MySQL version 8.0 and it works!