Programs & Examples On #Testtrack

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

#!/bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

What is the best JavaScript code to create an img element

As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).

Spring jUnit Testing properties file

As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:

@TestPropertySource("classpath:application-test.properties")

Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

How to apply multiple transforms in CSS?

You can apply more than one transform like this:

li:nth-of-type(2){
    transform : translate(-20px, 0px) rotate(15deg);
}

Gradle proxy configuration

This is my gradle.properties, please note those HTTPS portion

systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=8118
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=8118

How does Junit @Rule work?

Rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way.

For instance, ExternalResource executes code before and after a test method, without having to use @Before and @After. Using an ExternalResource rather than @Before and @After gives opportunities for better code reuse; the same rule can be used from two different test classes.

The design was based upon: Interceptors in JUnit

For more information see JUnit wiki : Rules.

android - listview get item view by position

You can get only visible View from ListView because row views in ListView are reuseable. If you use mListView.getChildAt(0) you get first visible view. This view is associated with item from adapter at position mListView.getFirstVisiblePosition().

html5: display video inside canvas

Using canvas to display Videos

Displaying a video is much the same as displaying an image. The minor differences are to do with onload events and the fact that you need to render the video every frame or you will only see one frame not the animated frames.

The demo below has some minor differences to the example. A mute function (under the video click mute/sound on to toggle sound) and some error checking to catch IE9+ and Edge if they don't have the correct drivers.

Keeping answers current.

The previous answers by user372551 is out of date (December 2010) and has a flaw in the rendering technique used. It uses the setTimeout and a rate of 33.333..ms which setTimeout will round down to 33ms this will cause the frames to be dropped every two seconds and may drop many more if the video frame rate is any higher than 30. Using setTimeout will also introduce video shearing created because setTimeout can not be synced to the display hardware.

There is currently no reliable method that can determine a videos frame rate unless you know the video frame rate in advance you should display it at the maximum display refresh rate possible on browsers. 60fps

The given top answer was for the time (6 years ago) the best solution as requestAnimationFrame was not widely supported (if at all) but requestAnimationFrame is now standard across the Major browsers and should be used instead of setTimeout to reduce or remove dropped frames, and to prevent shearing.

The example demo.

Loads a video and set it to loop. The video will not play until the you click on it. Clicking again will pause. There is a mute/sound on button under the video. The video is muted by default.

Note users of IE9+ and Edge. You may not be able to play the video format WebM as it needs additional drivers to play the videos. They can be found at tools.google.com Download IE9+ WebM support

_x000D_
_x000D_
// This code is from the example document on stackoverflow documentation. See HTML for link to the example._x000D_
// This code is almost identical to the example. Mute has been added and a media source. Also added some error handling in case the media load fails and a link to fix IE9+ and Edge support._x000D_
// Code by Blindman67._x000D_
_x000D_
_x000D_
// Original source has returns 404_x000D_
// var mediaSource = "http://video.webmfiles.org/big-buck-bunny_trailer.webm";_x000D_
// New source from wiki commons. Attribution in the leading credits._x000D_
var mediaSource = "http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv"_x000D_
_x000D_
var muted = true;_x000D_
var canvas = document.getElementById("myCanvas"); // get the canvas from the page_x000D_
var ctx = canvas.getContext("2d");_x000D_
var videoContainer; // object to hold video and associated info_x000D_
var video = document.createElement("video"); // create a video element_x000D_
video.src = mediaSource;_x000D_
// the video will now begin to load._x000D_
// As some additional info is needed we will place the video in a_x000D_
// containing object for convenience_x000D_
video.autoPlay = false; // ensure that the video does not auto play_x000D_
video.loop = true; // set the video to loop._x000D_
video.muted = muted;_x000D_
videoContainer = {  // we will add properties as needed_x000D_
     video : video,_x000D_
     ready : false,   _x000D_
};_x000D_
// To handle errors. This is not part of the example at the moment. Just fixing for Edge that did not like the ogv format video_x000D_
video.onerror = function(e){_x000D_
    document.body.removeChild(canvas);_x000D_
    document.body.innerHTML += "<h2>There is a problem loading the video</h2><br>";_x000D_
    document.body.innerHTML += "Users of IE9+ , the browser does not support WebM videos used by this demo";_x000D_
    document.body.innerHTML += "<br><a href='https://tools.google.com/dlpage/webmmf/'> Download IE9+ WebM support</a> from tools.google.com<br> this includes Edge and Windows 10";_x000D_
    _x000D_
 }_x000D_
video.oncanplay = readyToPlayVideo; // set the event to the play function that _x000D_
                                  // can be found below_x000D_
function readyToPlayVideo(event){ // this is a referance to the video_x000D_
    // the video may not match the canvas size so find a scale to fit_x000D_
    videoContainer.scale = Math.min(_x000D_
                         canvas.width / this.videoWidth, _x000D_
                         canvas.height / this.videoHeight); _x000D_
    videoContainer.ready = true;_x000D_
    // the video can be played so hand it off to the display function_x000D_
    requestAnimationFrame(updateCanvas);_x000D_
    // add instruction_x000D_
    document.getElementById("playPause").textContent = "Click video to play/pause.";_x000D_
    document.querySelector(".mute").textContent = "Mute";_x000D_
}_x000D_
_x000D_
function updateCanvas(){_x000D_
    ctx.clearRect(0,0,canvas.width,canvas.height); _x000D_
    // only draw if loaded and ready_x000D_
    if(videoContainer !== undefined && videoContainer.ready){ _x000D_
        // find the top left of the video on the canvas_x000D_
        video.muted = muted;_x000D_
        var scale = videoContainer.scale;_x000D_
        var vidH = videoContainer.video.videoHeight;_x000D_
        var vidW = videoContainer.video.videoWidth;_x000D_
        var top = canvas.height / 2 - (vidH /2 ) * scale;_x000D_
        var left = canvas.width / 2 - (vidW /2 ) * scale;_x000D_
        // now just draw the video the correct size_x000D_
        ctx.drawImage(videoContainer.video, left, top, vidW * scale, vidH * scale);_x000D_
        if(videoContainer.video.paused){ // if not playing show the paused screen _x000D_
            drawPayIcon();_x000D_
        }_x000D_
    }_x000D_
    // all done for display _x000D_
    // request the next frame in 1/60th of a second_x000D_
    requestAnimationFrame(updateCanvas);_x000D_
}_x000D_
_x000D_
function drawPayIcon(){_x000D_
     ctx.fillStyle = "black";  // darken display_x000D_
     ctx.globalAlpha = 0.5;_x000D_
     ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
     ctx.fillStyle = "#DDD"; // colour of play icon_x000D_
     ctx.globalAlpha = 0.75; // partly transparent_x000D_
     ctx.beginPath(); // create the path for the icon_x000D_
     var size = (canvas.height / 2) * 0.5;  // the size of the icon_x000D_
     ctx.moveTo(canvas.width/2 + size/2, canvas.height / 2); // start at the pointy end_x000D_
     ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 + size);_x000D_
     ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 - size);_x000D_
     ctx.closePath();_x000D_
     ctx.fill();_x000D_
     ctx.globalAlpha = 1; // restore alpha_x000D_
}    _x000D_
_x000D_
function playPauseClick(){_x000D_
     if(videoContainer !== undefined && videoContainer.ready){_x000D_
          if(videoContainer.video.paused){                                 _x000D_
                videoContainer.video.play();_x000D_
          }else{_x000D_
                videoContainer.video.pause();_x000D_
          }_x000D_
     }_x000D_
}_x000D_
function videoMute(){_x000D_
    muted = !muted;_x000D_
 if(muted){_x000D_
         document.querySelector(".mute").textContent = "Mute";_x000D_
    }else{_x000D_
         document.querySelector(".mute").textContent= "Sound on";_x000D_
    }_x000D_
_x000D_
_x000D_
}_x000D_
// register the event_x000D_
canvas.addEventListener("click",playPauseClick);_x000D_
document.querySelector(".mute").addEventListener("click",videoMute)
_x000D_
body {_x000D_
    font :14px  arial;_x000D_
    text-align : center;_x000D_
    background : #36A;_x000D_
}_x000D_
h2 {_x000D_
    color : white;_x000D_
}_x000D_
canvas {_x000D_
    border : 10px white solid;_x000D_
    cursor : pointer;_x000D_
}_x000D_
a {_x000D_
  color : #F93;_x000D_
}_x000D_
.mute {_x000D_
    cursor : pointer;_x000D_
    display: initial;   _x000D_
}
_x000D_
<h2>Basic Video & canvas example</h2>_x000D_
<p>Code example from Stackoverflow Documentation HTML5-Canvas<br>_x000D_
<a href="https://stackoverflow.com/documentation/html5-canvas/3689/media-types-and-the-canvas/14974/basic-loading-and-playing-a-video-on-the-canvas#t=201607271638099201116">Basic loading and playing a video on the canvas</a></p>_x000D_
<canvas id="myCanvas" width = "532" height ="300" ></canvas><br>_x000D_
<h3><div id = "playPause">Loading content.</div></h3>_x000D_
<div class="mute"></div><br>_x000D_
<div style="font-size:small">Attribution in the leading credits.</div><br>
_x000D_
_x000D_
_x000D_

Canvas extras

Using the canvas to render video gives you additional options in regard to displaying and mixing in fx. The following image shows some of the FX you can get using the canvas. Using the 2D API gives a huge range of creative possibilities.

Image relating to answer Fade canvas video from greyscale to color Video filters "Lighten", "Black & white", "Sepia", "Saturate", and "Negative"

See video title in above demo for attribution of content in above inmage.

string.split - by multiple character delimiter

To show both string.Split and Regex usage:

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This happens when Elasticsearch thinks the disk is running low on space so it puts itself into read-only mode.

By default Elasticsearch's decision is based on the percentage of disk space that's free, so on big disks this can happen even if you have many gigabytes of free space.

The flood stage watermark is 95% by default, so on a 1TB drive you need at least 50GB of free space or Elasticsearch will put itself into read-only mode.

For docs about the flood stage watermark see https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html.

The right solution depends on the context - for example a production environment vs a development environment.

Solution 1: free up disk space

Freeing up enough disk space so that more than 5% of the disk is free will solve this problem. Elasticsearch won't automatically take itself out of read-only mode once enough disk is free though, you'll have to do something like this to unlock the indices:

$ curl -XPUT -H "Content-Type: application/json" https://[YOUR_ELASTICSEARCH_ENDPOINT]:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Solution 2: change the flood stage watermark setting

Change the "cluster.routing.allocation.disk.watermark.flood_stage" setting to something else. It can either be set to a lower percentage or to an absolute value. Here's an example of how to change the setting from the docs:

PUT _cluster/settings
{
  "transient": {
    "cluster.routing.allocation.disk.watermark.low": "100gb",
    "cluster.routing.allocation.disk.watermark.high": "50gb",
    "cluster.routing.allocation.disk.watermark.flood_stage": "10gb",
    "cluster.info.update.interval": "1m"
  }
}

Again, after doing this you'll have to use the curl command above to unlock the indices, but after that they should not go into read-only mode again.

How do I start Mongo DB from Windows?

I did below, it works for me in windows.

open cmd prompt in Administrator mode( right click command prompt and click "run as administrator")

then run below command

net start MongoDB

How to validate a file upload field using Javascript/jquery

I got this from some forum. I hope it will be useful for you.

<script type="text/javascript">
 function validateFileExtension(fld) {
    if(!/(\.bmp|\.gif|\.jpg|\.jpeg)$/i.test(fld.value)) {
        alert("Invalid image file type.");      
        fld.form.reset();
        fld.focus();        
        return false;   
    }   
    return true; 
 } </script> </head>
 <body> <form ...etc...  onsubmit="return
 validateFileExtension(this.fileField)"> <p> <input type="file"
 name="fileField"  onchange="return validateFileExtension(this)">
 <input type="submit" value="Submit"> </p> </form> </body>

How to find a value in an array and remove it by using PHP array functions?

You need to find the key of the array first, this can be done using array_search()

Once done, use the unset()

<?php
$array = array( 'apple', 'orange', 'pear' );

unset( $array[array_search( 'orange', $array )] );
?>

Java program to get the current date without timestamp

I was looking for the same solution and the following worked for me.

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.clear(Calendar.HOUR);
    calendar.clear(Calendar.MINUTE);
    calendar.clear(Calendar.SECOND);
    calendar.clear(Calendar.MILLISECOND);

    Date today = calendar.getTime();

Please note that I am using calendar.set(Calendar.HOUR_OF_DAY, 0) for HOUR_OF_DAY instead of using the clear method, because it is suggested in Calendar.clear method's javadocs as the following

The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.

With the above posted solution I get output as

Wed Sep 11 00:00:00 EDT 2013

Using clear method for HOUR_OF_DAY resets hour at 12 when executing after 12PM or 00 when executing before 12PM.

Can I mask an input text in a bat file?

This may be an older topic, but if you are using Windows Vista or 7, I have a solution that will work very well. I made a video of it here: http://www.youtube.com/watch?v=mk8uAa6PIFM

Pastebin for the batch file is here

How to step through Python code to help debug issues?

Let's take look at what breakpoint() can do for you in 3.7+.

I have installed ipdb and pdbpp, which are both enhanced debuggers, via

pip install pdbpp
pip install ipdb

My test script, really doesn't do much, just calls breakpoint().

#test_188_breakpoint.py
myvars=dict(foo="bar")
print("before breakpoint()")
breakpoint()   # 
print(f"after breakpoint myvars={myvars}")


breakpoint() is linked to the PYTHONBREAKPOINT environment variable.

CASE 1: disabling breakpoint()

You can set the variable via bash as usual

export PYTHONBREAKPOINT=0

This turns off breakpoint() where it does nothing (as long as you haven't modified sys.breakpointhook() which is outside of the scope of this answer).

This is what a run of the program looks like:

(venv38) myuser@explore$ export PYTHONBREAKPOINT=0
(venv38) myuser@explore$ python test_188_breakpoint.py
before breakpoint()
after breakpoint myvars={'foo': 'bar'}
(venv38) myuser@explore$

Didn't stop, because I disabled breakpoint. Something that pdb.set_trace() can't do !

CASE 2: using the default pdb behavior:

Now, let's unset PYTHONBREAKPOINT which puts us back to normal, enabled-breakpoint behavior (it's only disabled when 0 not when empty).

(venv38) myuser@explore$ unset PYTHONBREAKPOINT
(venv38) myuser@explore$ python test_188_breakpoint.py
before breakpoint()
[0] > /Users/myuser/kds2/wk/explore/test_188_breakpoint.py(6)<module>()
-> print(f"after breakpoint myvars={myvars}")
(Pdb++) print("pdbpp replaces pdb because it was installed")
pdbpp replaces pdb because it was installed
(Pdb++) c
after breakpoint myvars={'foo': 'bar'}

It stopped, but I actually got pdbpp because it replaces pdb entirely while installed. If I unistalled pdbpp, I'd be back to normal pdb.

Note: a standard pdb.set_trace() would still get me pdbpp

CASE 3: calling a custom debugger

But let's call ipdb instead. This time, instead of setting the environment variable, we can use bash to set it only for this one command.

(venv38) myuser@explore$ PYTHONBREAKPOINT=ipdb.set_trace py test_188_breakpoint.py
before breakpoint()
> /Users/myuser/kds2/wk/explore/test_188_breakpoint.py(6)<module>()
      5 breakpoint()
----> 6 print(f"after breakpoint myvars={myvars}")
      7

ipdb> print("and now I invoked ipdb instead")
and now I invoked ipdb instead
ipdb> c
after breakpoint myvars={'foo': 'bar'}

Essentially, what it does, when looking at $PYTHONBREAKPOINT:

from ipdb import set_trace  # function imported on the right-most `.`
set_trace()

Again, much cleverer than a plain old pdb.set_trace()

in practice? I'd probably settle on a debugger.

Say I want ipdb always, I would:

  • export it via .profile or similar.
  • disable on a command by command basis, without modifying the normal value

Example (pytest and debuggers often make for unhappy couples):

(venv38) myuser@explore$ export PYTHONBREAKPOINT=ipdb.set_trace
(venv38) myuser@explore$ echo $PYTHONBREAKPOINT
ipdb.set_trace
(venv38) myuser@explore$ PYTHONBREAKPOINT=0 pytest test_188_breakpoint.py
=================================== test session starts ====================================
platform darwin -- Python 3.8.6, pytest-5.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /Users/myuser/kds2/wk/explore
plugins: celery-4.4.7, cov-2.10.0
collected 0 items

================================== no tests ran in 0.03s ===================================
(venv38) myuser@explore$ echo $PYTHONBREAKPOINT
ipdb.set_trace

p.s.

I'm using bash under macos, any posix shell will behave substantially the same. Windows, either powershell or DOS, may have different capabilities, especially around PYTHONBREAKPOINT=<some value> <some command> to set a environment variable only for one command.

What is the difference between json.dump() and json.dumps() in python?

In memory usage and speed.

When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

I solved this problem by setting UseCookies in web.config.

  <system.web>
    <sessionState cookieless="UseCookies" />

and setting enableVersionHeader

  <system.web>
    <httpRuntime targetFramework="4.5.1" enableVersionHeader="false" executionTimeout="1200" shutdownTimeout="1200" maxRequestLength="103424" />

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
CASE
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 
END

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

Iterate over object in Angular

I have been tearing my hair out with trying to parse and use data returned form a JSON query/ api call. Im not sure exactly where i was going wrong, i feel like i have been circling the answer for days, chasing various error codes like:

"Cannot find 'iterableDiff' pipe supporting object"

"Generic TYpe Array requires one argument(s)"

JSON parsing Errors, and im sure others

Im assuming i just had the wrong combination of fixes.

So here's a bit of a summary of gotchas and things to look for.

Firstly check the result of your api calls, your results may be in the form of an object, an array, or an array of objects.

i wont go into it too much, suffice to say the OP's original Error of not being iterable is generally caused by you trying to iterate an object, not an Array.

Heres some of my debugging results showing variables of both arrays and objects

So as we generally would like to iterate over our JSON result we need to ensure it is in the form of an Array. I tried numerous examples, and perhaps knowing what i know now some of those would in fact work, but the approach i went with was indeed to implement a pipe and the code i used was that the posted by t.888

   transform(obj: {[key: string]: any}, arg: string) {
if (!obj)
        return undefined;

return arg === 'keyval' ?
    Object.keys(obj).map((key) => ({ 'key': key, 'value': obj[key] })) :
  arg === 'key' ?
    Object.keys(obj) :
  arg === 'value' ?
    Object.keys(obj).map(key => obj[key]) :
  null;

Honestly i think one of the things that was getting me was the lack of error handling, by adding the 'return undefined' call i believe we are now allowing for non expected data to be sent to the pipe, which obviously was occurring in my case.

if you don't want to deal with argument to the pipe (and look i don't think it's necessary in most cases) you can just return the following

       if (!obj)
          return undefined;
       return Object.keys(obj);

Some Notes on creating your pipe and page or component that uses that pipe

is i was receiving errors about ‘name_of_my_pipe’ not being found

Use the ‘ionic generate pipe’ command from the CLI to ensure the pipe modules.ts are created and referenced correctly. ensure you add the following to the mypage.module.ts page.

import { PipesModule } from ‘…/…/pipes/pipes.module’;

(not sure if this changes if you also have your own custom_module, you may also need to add it to the custommodule.module.ts)

if you used the 'ionic generate page' command to make your page, but decide to use that page as your main page, remember to remove the page reference from app.module.ts (here's another answer i posted dealing with that https://forum.ionicframework.com/t/solved-pipe-not-found-in-custom-component/95179/13?u=dreaser

In my searching for answers there where a number of ways to display the data in the html file, and i don't understand enough to explain the differences. You may find it better to use one over another in certain scenarios.

            <ion-item *ngFor="let myPost of posts">
                  <img src="https://somwhereOnTheInternet/{{myPost.ImageUrl}}"/>
                  <img src="https://somwhereOnTheInternet/{{posts[myPost].ImageUrl}}"/>
                  <img [src]="'https://somwhereOnTheInternet/' + myPost.ImageUrl" />
            </ion-item>

However what worked that allowed me to display both the value and the key was the following:

    <ion-list>  
      <ion-item *ngFor="let myPost of posts  | name_of_pip:'optional_Str_Varible'">

        <h2>Key Value = {{posts[myPost]}} 

        <h2>Key Name = {{myPost}} </h2>

      </ion-item>
   </ion-list>  

to make the API call it looks like you need to import HttpModule into app.module.ts

import { HttpModule } from '@angular/http';
 .
 .  
 imports: [
BrowserModule,
HttpModule,

and you need Http in the page you make the call from

import {Http} from '@angular/http';

When making the API call you seem to be able to get to the children data (the objects or arrays within the array) 2 different ways, either seem to work

either during the call

this.http.get('https://SomeWebsiteWithAPI').map(res => res.json().anyChildren.OrSubChildren).subscribe(
        myData => {

or when you assign the data to your local variable

posts: Array<String>;    
this.posts = myData['anyChildren'];

(not sure if that variable needs to be an Array String, but thats what i have it at now. It may work as a more generic variable)

And final note, it was not necessary to use the inbuilt JSON library however you may find these 2 calls handy for converting from an object to a string and vica versa

        var stringifiedData = JSON.stringify(this.movies);                  
        console.log("**mResults in Stringify");
        console.log(stringifiedData);

        var mResults = JSON.parse(<string>stringifiedData);
        console.log("**mResults in a JSON");
        console.log(mResults);

I hope this compilation of info helps someone out.

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

I'm going to expand your question a bit and also include the compile function.

  • compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link' attribute is ignored if the 'compile' attribute is defined.)

  • link function - normally use for registering listener callbacks (i.e., $watch expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>, the link function is executed after the <li> template (tElement) has been cloned (into an iElement) for that particular <li> element. A $watch allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.

  • controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.

    For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this (rather than on $scope), please see 'this' vs $scope in AngularJS controllers.

In general, you can put methods, $watches, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

  1. First of all, there is no difference between View.OnClickListener and OnClickListener. If you just use View.OnClickListener directly, then you don't need to write-

    import android.view.View.OnClickListener

  2. You set an OnClickListener instance (e.g. myListener named object)as the listener to a view via setOnclickListener(). When a click event is fired, that myListener gets notified and it's onClick(View view) method is called. Thats where we do our own task. Hope this helps you.

java howto ArrayList push, pop, shift, and unshift

Great Answer by Jon.

I'm lazy though and I hate typing, so I created a simple cut and paste example for all the other people who are like me. Enjoy!

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<String> animals = new ArrayList<>();

        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");

        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add() -> push(): Add items to the end of an array
        animals.add("Elephant");
        System.out.println(animals);  // [Lion, Tiger, Cat, Dog, Elephant]

        // remove() -> pop(): Remove an item from the end of an array
        animals.remove(animals.size() - 1);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add(0,"xyz") -> unshift(): Add items to the beginning of an array
        animals.add(0, "Penguin");
        System.out.println(animals); // [Penguin, Lion, Tiger, Cat, Dog]

        // remove(0) -> shift(): Remove an item from the beginning of an array
        animals.remove(0);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

    }

}

SQLite DateTime comparison

The following is working fine for me using SQLite:

SELECT * 
    FROM ingresosgastos 
    WHERE fecharegistro BETWEEN "2010-01-01" AND "2013-01-01"

Favicon not showing up in Google Chrome

Upload your favicon.ico to the root directory of your website and that should work with Chrome. Some browsers disregard the meta tag and just use /favicon.ico

Go figure?.....

undefined reference to boost::system::system_category() when compiling

I got the same Problem:

g++ -mconsole -Wl,--export-all-symbols -LC:/Programme/CPP-Entwicklung/MinGW-4.5.2/lib  -LD:/bfs_ENTW_deb/lib   -static-libgcc -static-libstdc++ -LC:/Programme/CPP-Entwicklung/boost_1_47_0/stage/lib   \
 D:/bfs_ENTW_deb/obj/test/main_filesystem.obj \
 -o D:/bfs_ENTW_deb/bin/filesystem.exe -lboost_system-mgw45-mt-1_47 -lboost_filesystem-mgw45-mt-1_47

D:/bfs_ENTW_deb/obj/test/main_filesystem.obj:main_filesystem.cpp:(.text+0x54): undefined reference to `boost::system::generic_category()

Solution was to use the debug-version of the system-lib:

g++ -mconsole -Wl,--export-all-symbols -LC:/Programme/CPP-Entwicklung/MinGW-4.5.2/lib  -LD:/bfs_ENTW_deb/lib   -static-libgcc -static-libstdc++ -LC:/Programme/CPP-Entwicklung/boost_1_47_0/stage/lib   \
 D:/bfs_ENTW_deb/obj/test/main_filesystem.obj \
 -o D:/bfs_ENTW_deb/bin/filesystem.exe -lboost_system-mgw45-mt-d-1_47 -lboost_filesystem-mgw45-mt-1_47

But why?

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

find filenames NOT ending in specific extensions on Unix?

Other solutions on this page aren't desirable if you have a long list of extensions -- maintaining a long sequence of -not -name 'this' -not -name 'that' -not -name 'other' would be tedious and error-prone -- or if the search is programmatic and the list of extensions is built at runtime.

For those situations, a solution that more clearly separates data (the list of extensions) and code (the parameters to find) may be desirable. Given a directory & file structure that looks like this:

.
+-- a
    +-- 1.txt
    +-- 15.xml
    +-- 8.dll
    +-- b
    ¦   +-- 16.xml
    ¦   +-- 2.txt
    ¦   +-- 9.dll
    ¦   +-- c
    ¦       +-- 10.dll
    ¦       +-- 17.xml
    ¦       +-- 3.txt
    +-- d
    ¦   +-- 11.dll
    ¦   +-- 18.xml
    ¦   +-- 4.txt
    ¦   +-- e
    ¦       +-- 12.dll
    ¦       +-- 19.xml
    ¦       +-- 5.txt
    +-- f
        +-- 13.dll
        +-- 20.xml
        +-- 6.txt
        +-- g
            +-- 14.dll
            +-- 21.xml
            +-- 7.txt

You can do something like this:

## data section, list undesired extensions here
declare -a _BADEXT=(xml dll)

## code section, this never changes
BADEXT="$( IFS="|" ; echo "${_BADEXT[*]}" | sed 's/|/\\|/g' )"
find . -type f ! -regex ".*\.\($BADEXT\)"

Which results in:

./a/1.txt
./a/b/2.txt
./a/b/c/3.txt
./a/d/4.txt
./a/d/e/5.txt
./a/f/6.txt
./a/f/g/7.txt

You can change the extensions list without changing the code block.

NOTE doesn't work with native OSX find - use gnu find instead.

exclude @Component from @ComponentScan

Another approach is to use new conditional annotations. Since plain Spring 4 you can use @Conditional annotation:

@Component("foo")
@Conditional(FooCondition.class)
class Foo {
    ...
}

and define conditional logic for registering Foo component:

public class FooCondition implements Condition{
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // return [your conditional logic]
    }     
}

Conditional logic can be based on context, because you have access to bean factory. For Example when "Bar" component is not registered as bean:

    return !context.getBeanFactory().containsBean(Bar.class.getSimpleName());

With Spring Boot (should be used for EVERY new Spring project), you can use these conditional annotations:

  • @ConditionalOnBean
  • @ConditionalOnClass
  • @ConditionalOnExpression
  • @ConditionalOnJava
  • @ConditionalOnMissingBean
  • @ConditionalOnMissingClass
  • @ConditionalOnNotWebApplication
  • @ConditionalOnProperty
  • @ConditionalOnResource
  • @ConditionalOnWebApplication

You can avoid Condition class creation this way. Refer to Spring Boot docs for more detail.

What is a vertical tab?

A vertical tab was the opposite of a line feed i.e. it went upwards by one line. It had nothing to do with tab positions. If you want to prove this, try it on an RS232 terminal.

How to easily resize/optimize an image size with iOS?

you can use this code to scale image in required size.

+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize
{
    CGSize actSize = image.size;
    float scale = actSize.width/actSize.height;

    if (scale < 1) {
        newSize.height = newSize.width/scale;
    } 
    else {
        newSize.width = newSize.height*scale;
    }

    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

unix sort descending order

The presence of the n option attached to the -k5 causes the global -r option to be ignored for that field. You have to specify both n and r at the same level (globally or locally).

sort -t $'\t' -k5,5rn

or

sort -rn -t $'\t' -k5,5

Are there any log file about Windows Services Status?

Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.

In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.

enter image description here

The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:

"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

Both Encrypt and Decrypt with AES and DES Algoritham ,This worked for me perfectly GithubLink: Java Code For Encryption and Decryption

package decrypt;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/* Decrypt encrypted string into plain string with aes and Des algoritham*/ 

public class Decrypt {

public String decrypt(String str,String k) throws Exception {
// Decode base64 to get bytes

 Cipher  dcipher = Cipher.getInstance("AES");
 Key aesKey = new SecretKeySpec(k.getBytes(), "AES");
 dcipher.init(dcipher.DECRYPT_MODE, aesKey);
//System.out.println(aesKey);
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
//System.out.println(utf8);
// Decode using utf-8
 return new String(utf8, "UTF8");
 }


  public String encrypt(String str,String k) throws Exception {
 Cipher ecipher = Cipher.getInstance("AES");
 Key aeskey = new SecretKeySpec(k.getBytes(),"AES");
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
 public String encrypt(String str,String k,String Algo) throws Exception {
 Cipher ecipher = Cipher.getInstance(Algo);
 Key aeskey = new SecretKeySpec(k.getBytes(),Algo);
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
public String decrypt(String str,String k,String Algo) throws Exception {
    // Decode base64 to get bytes

     Cipher  dcipher = Cipher.getInstance(Algo);
     Key aesKey = new SecretKeySpec(k.getBytes(), Algo);
     dcipher.init(dcipher.DECRYPT_MODE, aesKey);
    //System.out.println(aesKey);
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    byte[] utf8 = dcipher.doFinal(dec);
    //System.out.println(utf8);
 // Decode using utf-8
     return new String(utf8, "UTF8");
  }

public static void main(String args []) throws Exception
{
    String original = "rakesh";
    String data = "CfPcX0G+e7TLKKMyyvrvrQ==";
    String k = "qertyuiopasdfghw"; //AES key length must be 16
    String k1 = "qertyuio";  // DES key length must be 8 
    String data1 = "rakesh";
    String data2 = "nAtvNq7uHKE=";
    String Algo= "DES";
    String Algo1= "AES";
    Decrypt decrypter = new Decrypt();
     System.out.println("Original String: " + original);

     System.out.println("encrypted String in DES: " + decrypter.encrypt(data1, 
      k1,Algo));
     System.out.println("Decrypted String in DES: " + decrypter.decrypt(data2, 
       k1,Algo));
     System.out.println("encrypted String in AES: " + decrypter.encrypt(data1, 
      k,Algo1));
     System.out.println("Decrypted String in AES: " + decrypter.decrypt(data, 
      k,Algo1));
   }
}

How can I have a newline in a string in sh?

A $ right before single quotation marks '...\n...' as follows, however double quotation marks doesn't work.

$ echo $'Hello\nWorld'
Hello
World
$ echo $"Hello\nWorld"
Hello\nWorld

How add unique key to existing table (with non uniques rows)

I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:

ALTER TABLE `database_name`.`table_name` 
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);

This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).

Numpy: Checking if a value is NaT

Very simple and surprisingly fast: (without numpy or pandas)

    str( myDate ) == 'NaT'            # True if myDate is NaT

Ok, it's a little nasty, but given the ambiguity surrounding 'NaT' it does the job nicely.

It's also useful when comparing two dates either of which might be NaT as follows:

   str( date1 ) == str( date1 )       # True
   str( date1 ) == str( NaT )         # False
   str( NaT )   == str( date1 )       # False

wait for it...

   str( NaT )   == str( Nat )         # True    (hooray!)

How can I issue a single command from the command line through sql plus?

This is how I solved the problem:

<target name="executeSQLScript">
    <exec executable="sqlplus" failonerror="true" errorproperty="exit.status">
        <arg value="${dbUser}/${dbPass}@<DBHOST>:<DBPORT>/<SID>"/>
        <arg value="@${basedir}/db/scripttoexecute.sql"/>
    </exec>
</target>

How to remove border from specific PrimeFaces p:panelGrid?

Use below style modification to remove border for Primefaces radio button

.ui-selectoneradio td, .ui-selectoneradio tr
{
    border-style: none !important
}

Using (Ana)conda within PyCharm

Change the project interpreter to ~/anaconda2/python/bin by going to File -> Settings -> Project -> Project Interpreter. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations. This makes PyCharm use Anaconda instead of the default Python interpreter under usr/bin/python27.

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

var https = require('https');
https.globalAgent.options.secureProtocol = 'SSLv3_method';

Python's "in" set operator

That's right. You could try it in the interpreter like this:

>>> a_set = set(['a', 'b', 'c'])

>>> 'a' in a_set
True

>>>'d' in a_set
False

PHP array printing using a loop

I also find that using <pre></pre> tags around your var_dump or print_r results in a much more readable dump.

error: src refspec master does not match any

I had already committed the changes and added all the files, had the same origin as remote, still kept getting that error. My simple solution to this was just:

git push

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

Humm! did you try LOCK_TIMEOUT
Note down what it was orginally before running the query
set it for your query
after running your query set it back to original value

SET LOCK_TIMEOUT 1800;  
SELECT @@LOCK_TIMEOUT AS [Lock Timeout];  

How to comment out particular lines in a shell script

You can comment section of a script using a conditional.

For example, the following script:

DEBUG=false
if ${DEBUG}; then
echo 1
echo 2
echo 3
echo 4
echo 5
fi
echo 6
echo 7

would output:

6
7

In order to uncomment the section of the code, you simply need to comment the variable:

#DEBUG=false

(Doing so would print the numbers 1 through 7.)

How do I use the conditional operator (? :) in Ruby?

Easiest way:

param_a = 1
param_b = 2

result = param_a === param_b ? 'Same!' : 'Not same!'

since param_a is not equal to param_b then the result's value will be Not same!

How do you count the elements of an array in java

Isn't it just: System.out.println(Array.length);? Because this is what it seems like you are looking for.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Bind variable can be used in Oracle SQL query with "in" clause.

Works in 10g; I don't know about other versions.

Bind variable is varchar up to 4000 characters.

Example: Bind variable containing comma-separated list of values, e.g.

:bindvar = 1,2,3,4,5

select * from mytable
  where myfield in
    (
      SELECT regexp_substr(:bindvar,'[^,]+', 1, level) items
      FROM dual
      CONNECT BY regexp_substr(:bindvar, '[^,]+', 1, level) is not null
    );

(Same info as I posted here: How do you specify IN clause in a dynamic query using a variable? )

How do I get the value of a registry key and ONLY the value using powershell

NONE of these answers work for situations where the value name contains spaces, dots, or other characters that are reserved in PowerShell. In that case you have to wrap the name in double quotes as per http://blog.danskingdom.com/accessing-powershell-variables-with-periods-in-their-name/ - for example:

PS> Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7

14.0         : C:\Program Files (x86)\Microsoft Visual Studio 14.0\
12.0         : C:\Program Files (x86)\Microsoft Visual Studio 12.0\
11.0         : C:\Program Files (x86)\Microsoft Visual Studio 11.0\
15.0         : C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\V
               S7
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS
PSChildName  : VS7
PSProvider   : Microsoft.PowerShell.Core\Registry

If you want to access any of the 14.0, 12.0, 11.0, 15.0 values, the solution from the accepted answer will not work - you will get no output:

PS> (Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7 -Name 15.0).15.0
PS>

What does work is quoting the value name, which you should probably be doing anyway for safety:

PS> (Get-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7" -Name "15.0")."15.0"
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PS> 

Thus, the accepted answer should be modified as such:

PS> $key = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7"
PS> $value = "15.0"
PS> (Get-ItemProperty -Path $key -Name $value).$value
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PS> 

This works in PowerShell 2.0 through 5.0 (although you should probably be using Get-ItemPropertyValue in v5).

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

Strangely I had this occur with a single repository out of > 20 repositories on my MacBook Pro.

The solution was to upgrade git via homebrew, and everything strangely worked after it finished:

brew install git

Hope this helps someone!

Best way to convert text files between character sets?

Get-Content -Encoding UTF8 FILE-UTF8.TXT | Out-File -Encoding UTF7 FILE-UTF7.TXT

The shortest version, if you can assume that the input BOM is correct:

gc FILE.TXT | Out-File -en utf7 file-utf7.txt

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Add all files to a commit except a single file?

While Ben Jackson is correct, I thought I would add how I've been using that solution as well. Below is a very simple script I use (that I call gitadd) to add all changes except a select few that I keep listed in a file called .gittrackignore (very similar to how .gitignore works).

#!/bin/bash
set -e

git add -A
git reset `cat .gittrackignore`

And this is what my current .gittrackignore looks like.

project.properties

I'm working on an Android project that I compile from the command line when deploying. This project depends on SherlockActionBar, so it needs to be referenced in project.properties, but that messes with the compilation, so now I just type gitadd and add all of the changes to git without having to un-add project.properties every single time.

How to code a BAT file to always run as admin mode?

I think I have a solution to the password problem. This single argument is truly amazing. It asks for the password once, and than never asks for it again. Even if you put it onto another program, it will not ask for the password. Here it is:

runas /user:Administrator /savecred Example1Server.exe

How do I run Python code from Sublime Text 2?

In python v3.x you should go to : Tools->Build System->New Build System.

Then, it pop up the untitled.sublime-build window in sublime text editor.Enter setting as:

{

    "cmd": ["path_to_the_python.exe","-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

To see the path, Type following in terminal as:

python
>>> import sys
>>>print(sys.executable)

You can make more than one Build System but it should default save inside Packages of Sublime text with .sublime-build extension.

Then, select the new Build System and press cltr+b or other based on your os.

Converting Epoch time into the datetime

>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
'2012-09-13 14:22:50' # Local time

To get UTC:

>>> datetime.datetime.utcfromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
  '2012-09-13 06:22:50'

Get Request and Session Parameters and Attributes from JSF pages

You can like this:

#{requestScope["paramName"]} ,#{sessionScope["paramName"]}

Because requestScope or sessionScope is a Map object.

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

Parse JSON with R

The jsonlite package is easy to use and tries to convert json into data frames.

Example:

library(jsonlite)

# url with some information about project in Andalussia
url <- 'http://www.juntadeandalucia.es/export/drupaljda/ayudas.json'

# read url and convert to data.frame
document <- fromJSON(txt=url)

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

The issue here is that you just Added the reference to System.IO.Compression it is missing the reference to System.IO.Compression.Filesystem.dll

And you need to do it on .net 4.5 or later (because it doesn't exist on older versions).

I just posted a script on TechNet Maybe somebody would find it useful it requires .net 4.5 or 4.7

https://gallery.technet.microsoft.com/scriptcenter/Create-a-Zip-file-from-a-b23a7530

How to replace an entire line in a text file by line number

On mac I used

sed -i '' -e 's/text-on-line-to-be-changed.*/text-to-replace-the=whole-line/' file-name

"document.getElementByClass is not a function"

The getElementByClass does not exists, probably you want to use getElementsByClassName. However you can use alternative approach (used in angular/vue/react... templates)

_x000D_
_x000D_
function stop(ta) {_x000D_
  console.log(ta.value) // document['player'].stopMusicExt(ta.value);_x000D_
  ta.value='';_x000D_
}
_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
_x000D_
_x000D_
_x000D_

How to add many functions in ONE ng-click?

ng-click "$watch(edit($index), open())"

vi/vim editor, copy a block (not usual action)

You can do it as you do in vi, for example to yank lines from 3020 to the end, execute this command (write the block to a file):

:3020,$ w /tmp/yank

And to write this block in another line/file, go to the desired position and execute next command (insert file written before):

:r /tmp/yank

(Reminder: don't forget to remove file: /tmp/yank)

How do I change the data type for a column in MySQL?

alter table table_name modify column_name int(5)

Call and receive output from Python script in Java?

The best way to achieve would be to use Apache Commons Exec as I use it for production without problems even for Java 8 environment because of the fact that it lets you execute any external process (including python, bash etc) in synchronous and asynchronous way by using watchdogs.

 CommandLine cmdLine = new CommandLine("python");
 cmdLine.addArgument("/my/python/script/script.py");
 DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

 ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000);
 Executor executor = new DefaultExecutor();
 executor.setExitValue(1);
 executor.setWatchdog(watchdog);
 executor.execute(cmdLine, resultHandler);

 // some time later the result handler callback was invoked so we
 // can safely request the exit value
 resultHandler.waitFor();

Complete source code for a small but complete POC is shared here that addresses another concern in this post;

https://github.com/raohammad/externalprocessfromjava.git

How to store decimal values in SQL Server?

DECIMAL(18,0) will allow 0 digits after the decimal point.

Use something like DECIMAL(18,4) instead that should do just fine!

That gives you a total of 18 digits, 4 of which after the decimal point (and 14 before the decimal point).

Creating random colour in Java?

You can instantiate a color with three floats (r, g, b), each between 0.0 and 1.0: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html#Color(float,%20float,%20float).

Using Java's Random class you can easily instantiate a new random color as such:

Random r = new Random();
Color randomColor = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat());

I can't guarantee they'll all be pretty, but they'll be random =)

Deleting all records in a database table

BlogPost.find_each(&:destroy)

How to test if a string is JSON or not?

Well... It depends the way you are receiving your data. I think the server is responding with a JSON formated string (using json_encode() in PHP,e.g.). If you're using JQuery post and set response data to be a JSON format and it is a malformed JSON, this will produce an error:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        //Supposing x is a JSON property...
        alert(response.x);

  },
  dataType: 'json',
  //Invalid JSON
  error: function (){ alert("error!"); }
});

But, if you're using the type response as text, you need use $.parseJSON. According jquery site: "Passing in a malformed JSON string may result in an exception being thrown". Thus your code will be:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        try {
            parsedData = JSON.parse(response);
        } catch (e) {
            // is not a valid JSON string
        }

  },
  dataType: 'text',
});

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

Best place to insert the Google Analytics code

Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

This answer assumes you understand implementing the perfect algorithm for P1 and discusses how to achieve a win in conditions against ordinary human players, who will make some mistakes more commonly than others.

The game of course should end in a draw if both players play optimally. At a human level, P1 playing in a corner produces wins far more often. For whatever psychological reason, P2 is baited into thinking that playing in the center is not that important, which is unfortunate for them, since it's the only response that does not create a winning game for P1.

If P2 does correctly block in the center, P1 should play the opposite corner, because again, for whatever psychological reason, P2 will prefer the symmetry of playing a corner, which again produces a losing board for them.

For any move P1 may make for the starting move, there is a move P2 may make that will create a win for P1 if both players play optimally thereafter. In that sense P1 may play wherever. The edge moves are weakest in the sense that the largest fraction of possible responses to this move produce a draw, but there are still responses that will create a win for P1.

Empirically (more precisely, anecdotally) the best P1 starting moves seem to be first corner, second center, and last edge.

The next challenge you can add, in person or via a GUI, is not to display the board. A human can definitely remember all the state but the added challenge leads to a preference for symmetric boards, which take less effort to remember, leading to the mistake I outlined in the first branch.

I'm a lot of fun at parties, I know.

Gradient borders

I agree with szajmon. The only problem with his and Quentin's answers is cross-browser compatibility.

HTML:

<div class="g">
    <div>bla</div>
</div>

CSS:

.g {
background-image: -webkit-linear-gradient(300deg, white, black, white); /* webkit browsers (Chrome & Safari) */
background-image: -moz-linear-gradient(300deg, white, black, white); /* Mozilla browsers (Firefox) */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#000000', gradientType='1'); /* Internet Explorer */
background-image: -o-linear-gradient(300deg,rgb(255,255,255),rgb(0,0,0) 50%,rgb(255,255,255) 100%); /* Opera */
}

.g > div { background: #fff; }

How do you embed binary data in XML?

Any binary-to-text encoding will do the trick. I use something like that

<data encoding="yEnc>
<![CDATA[ encoded binary data ]]>
</data>

How to get the filename without the extension in Java?

public static String getFileExtension(String fileName) {
        if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static String getBaseFileName(String fileName) {
        if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
        return fileName.substring(0,fileName.lastIndexOf("."));
    }

How to put a symbol above another in LaTeX?

Use \overset{above}{main} in math mode. In your case, \overset{a}{\#}.

Efficient evaluation of a function at every cell of a NumPy array

I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.

One can write his own customised ufunc in C, which surely is more efficient, or by invoking np.frompyfunc, which is built-in factory method. After testing, this is more efficient than np.vectorize:

f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)

%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms

I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post

get current date with 'yyyy-MM-dd' format in Angular 4

Try this:

   import * as moment from 'moment';

     ngOnInit() {
     this.date = moment().format("YYYY Do MMM");
                }

using batch echo with special characters

You can escape shell metacharacters with ^:

echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

Note that since echo is a shell built-in it doesn't follow the usual conventions regarding quoting, so just quoting the argument will output the quotes instead of removing them.

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

For me it was just a matter of changing the path variable to: 'C:\Program Files\Mozilla Firefox' instead of 'C:\Program Files (x86)\Mozilla Firefox'

python-pandas and databases like mysql

For Sybase the following works (with http://python-sybase.sourceforge.net)

import pandas.io.sql as psql
import Sybase

df = psql.frame_query("<Query>", con=Sybase.connect("<dsn>", "<user>", "<pwd>"))

How do I use Ruby for shell scripting?

This might also be helpful: http://rush.heroku.com/

I haven't used it much, but looks pretty cool

From the site:

rush is a replacement for the unix shell (bash, zsh, etc) which uses pure Ruby syntax. Grep through files, find and kill processes, copy files - everything you do in the shell, now in Ruby

Get properties and values from unknown object

This example trims all the string properties of an object.

public static void TrimModelProperties(Type type, object obj)
{
    var propertyInfoArray = type.GetProperties(
                                    BindingFlags.Public | 
                                    BindingFlags.Instance);
    foreach (var propertyInfo in propertyInfoArray)
    {
        var propValue = propertyInfo.GetValue(obj, null);
        if (propValue == null) 
            continue;
        if (propValue.GetType().Name == "String")
            propertyInfo.SetValue(
                             obj, 
                             ((string)propValue).Trim(), 
                             null);
    }
}

Finding an element in an array in Java

With Java 8, you can do this:

int[] haystack = {1, 2, 3};
int needle = 3;

boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);

You'd need to do

boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));

if you're working with objects.

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

How can I get onclick event on webview in android?

I took a look at this and I found that a WebView doesn't seem to send click events to an OnClickListener. If anyone out there can prove me wrong or tell me why then I'd be interested to hear it.

What I did find is that a WebView will send touch events to an OnTouchListener. It does have its own onTouchEvent method but I only ever seemed to get MotionEvent.ACTION_MOVE using that method.

So given that we can get events on a registered touch event listener, the only problem that remains is how to circumvent whatever action you want to perform for a touch when the user clicks a URL.

This can be achieved with some fancy Handler footwork by sending a delayed message for the touch and then removing those touch messages if the touch was caused by the user clicking a URL.

Here's an example:

public class WebViewClicker extends Activity implements OnTouchListener, Handler.Callback {

private static final int CLICK_ON_WEBVIEW = 1;
private static final int CLICK_ON_URL = 2;

private final Handler handler = new Handler(this);

private WebView webView;
private WebViewClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.web_view_clicker);

    webView = (WebView)findViewById(R.id.web);
    webView.setOnTouchListener(this);

    client = new WebViewClient(){ 
        @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            handler.sendEmptyMessage(CLICK_ON_URL);
            return false;
        } 
    }; 

    webView.setWebViewClient(client);
    webView.setVerticalScrollBarEnabled(false);
    webView.loadUrl("http://www.example.com");
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (v.getId() == R.id.web && event.getAction() == MotionEvent.ACTION_DOWN){
        handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);
    }
    return false;
}

@Override
public boolean handleMessage(Message msg) {
    if (msg.what == CLICK_ON_URL){
        handler.removeMessages(CLICK_ON_WEBVIEW);
        return true;
    }
    if (msg.what == CLICK_ON_WEBVIEW){
        Toast.makeText(this, "WebView clicked", Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}
}


Hope this helps.

Does reading an entire file leave the file handle open?

Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:

with open('Path/to/file', 'r') as content_file:
    content_list = content_file.read().strip().split("\n")

As can be seen, one needs to add the concatenated methods .strip().split("\n") to the main answer in this thread.

Here, .strip() just removes whitespace and newline characters at the endings of the entire file string, and .split("\n") produces the actual list via splitting the entire file string at every newline character \n.

Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.

Java, How to implement a Shift Cipher (Caesar Cipher)

Java Shift Caesar Cipher by shift spaces.

Restrictions:

  1. Only works with a positive number in the shift parameter.
  2. Only works with shift less than 26.
  3. Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
  4. Does a cast number to character, so it will fail with anything but ascii letters.
  5. Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
  6. Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.

Pseudocode:

  1. Loop through each character in the string.
  2. Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
  3. If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
  4. Append the character onto a new string. Return the string.

Function:

String cipher(String msg, int shift){
    String s = "";
    int len = msg.length();
    for(int x = 0; x < len; x++){
        char c = (char)(msg.charAt(x) + shift);
        if (c > 'z')
            s += (char)(msg.charAt(x) - (26-shift));
        else
            s += (char)(msg.charAt(x) + shift);
    }
    return s;
}

How to invoke it:

System.out.println(cipher("abc", 3));  //prints def
System.out.println(cipher("xyz", 3));  //prints abc

Toggle visibility property of div

To clean this up a little bit and maintain a single line of code (like you would with a toggle()), you can use a ternary operator so your code winds up looking like this (also using jQuery):

$('#video-over').css('visibility', $('#video-over').css('visibility') == 'hidden' ? 'visible' : 'hidden');

Adding two Java 8 streams, or an extra element to a stream

If you add static imports for Stream.concat and Stream.of, the first example could be written as follows:

Stream<Foo> stream = concat(stream1, concat(stream2, of(element)));

Importing static methods with generic names can result in code that becomes difficult to read and maintain (namespace pollution). So, it might be better to create your own static methods with more meaningful names. However, for demonstration I will stick with this name.

public static <T> Stream<T> concat(Stream<? extends T> lhs, Stream<? extends T> rhs) {
    return Stream.concat(lhs, rhs);
}
public static <T> Stream<T> concat(Stream<? extends T> lhs, T rhs) {
    return Stream.concat(lhs, Stream.of(rhs));
}

With these two static methods (optionally in combination with static imports), the two examples could be written as follows:

Stream<Foo> stream = concat(stream1, concat(stream2, element));

Stream<Foo> stream = concat(
                         concat(stream1.filter(x -> x!=0), stream2).filter(x -> x!=1),
                         element)
                     .filter(x -> x!=2);

The code is now significantly shorter. However, I agree that the readability hasn't improved. So I have another solution.


In a lot of situations, Collectors can be used to extend the functionality of streams. With the two Collectors at the bottom, the two examples could be written as follows:

Stream<Foo> stream = stream1.collect(concat(stream2)).collect(concat(element));

Stream<Foo> stream = stream1
                     .filter(x -> x!=0)
                     .collect(concat(stream2))
                     .filter(x -> x!=1)
                     .collect(concat(element))
                     .filter(x -> x!=2);

The only difference between your desired syntax and the syntax above is, that you have to replace concat(...) with collect(concat(...)). The two static methods can be implemented as follows (optionally used in combination with static imports):

private static <T,A,R,S> Collector<T,?,S> combine(Collector<T,A,R> collector, Function<? super R, ? extends S> function) {
    return Collector.of(
        collector.supplier(),
        collector.accumulator(),
        collector.combiner(),
        collector.finisher().andThen(function));
}
public static <T> Collector<T,?,Stream<T>> concat(Stream<? extends T> other) {
    return combine(Collectors.toList(),
        list -> Stream.concat(list.stream(), other));
}
public static <T> Collector<T,?,Stream<T>> concat(T element) {
    return concat(Stream.of(element));
}

Of course there is a drawback with this solution that should be mentioned. collect is a final operation that consumes all elements of the stream. On top of that, the collector concat creates an intermediate ArrayList each time it is used in the chain. Both operations can have a significant impact on the behaviour of your program. However, if readability is more important than performance, it might still be a very helpful approach.

currently unable to handle this request HTTP ERROR 500

I found this was caused by adding a new scope variable to the login scope

Lookup City and State by Zip Google Geocode Api

I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.

Using the US Postal Service HTTP/XML API

According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.

According to their documentation, here's what you would send:

http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>

And here's what you would receive back:

<?xml version="1.0"?> 
<CityStateLookupResponse> 
    <ZipCode ID="0"> 
        <Zip5>90210</Zip5> 
        <City>BEVERLY HILLS</City> 
        <State>CA</State> 
    </ZipCode> 
</CityStateLookupResponse>

USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.

Using the Ziptastic HTTP/JSON API (no longer supported)

Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here

This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:

GET http://ziptasticapi.com/48867

And they will return a JSON object along the lines of:

{"country": "US", "state": "MI", "city": "OWOSSO"}

Indeed, it works. You can test this from a command line by doing something like:

curl http://ziptasticapi.com/48867 

Initialising a multidimensional array in Java

You can declare multi dimensional arrays like :

// 4 x 5 String arrays, all Strings are null
// [0] -> [null,null,null,null,null]
// [1] -> [null,null,null,null,null]
// [2] -> [null,null,null,null,null]
// [3] -> [null,null,null,null,null]

String[][] sa1 = new String[4][5];
for(int i = 0; i < sa1.length; i++) {           // sa1.length == 4
    for (int j = 0; j < sa1[i].length; j++) {     //sa1[i].length == 5
        sa1[i][j] = "new String value";
    }
}


// 5 x 0  All String arrays are null
// [null]
// [null]
// [null]
// [null]
// [null]
String[][] sa2 = new String[5][];
for(int i = 0; i < sa2.length; i++) {
    String[] anon = new String[ /* your number here */];
    // or String[] anon = new String[]{"I'm", "a", "new", "array"};
    sa2[i] = anon;
}

// [0] -> ["I'm","in","the", "0th", "array"]
// [1] -> ["I'm", "in", "another"]
String[][] sa3 = new String[][]{ {"I'm","in","the", "0th", "array"},{"I'm", "in", "another"}};

How to toggle font awesome icon on click?

There is another solution you can try by using only the css here is the answer i posted in another post: jQuery Accordion change font awesome icon class on click

Adding input elements dynamically to form

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.

Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.

_x000D_
_x000D_
<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>
_x000D_
_x000D_
_x000D_

See a working sample in this JSFiddle.

How do I get this javascript to run every second?

window.setTimeout(func,1000);

This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.

Reference

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.

How to POST JSON request using Apache HttpClient?

For Apache HttpClient 4.5 or newer version:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://targethost/login");
    String JSON_STRING="";
    HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

Note:

1 in order to make the code compile, both httpclient package and httpcore package should be imported.

2 try-catch block has been ommitted.

Reference: appache official guide

the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules

Check if a Class Object is subclass of another Class Object in Java

This is an improved version of @schuttek's answer. It is improved because it correctly return false for primitives (e.g. isSubclassOf(int.class, Object.class) => false) and also correctly handles interfaces (e.g. isSubclassOf(HashMap.class, Map.class) => true).

static public boolean isSubclassOf(final Class<?> clazz, final Class<?> possibleSuperClass)
{
    if (clazz == null || possibleSuperClass == null)
    {
        return false;
    }
    else if (clazz.equals(possibleSuperClass))
    {
        return true;
    }
    else
    {
        final boolean isSubclass = isSubclassOf(clazz.getSuperclass(), possibleSuperClass);

        if (!isSubclass && clazz.getInterfaces() != null)
        {
            for (final Class<?> inter : clazz.getInterfaces())
            {
                if (isSubclassOf(inter, possibleSuperClass))
                {
                    return true;
                }
            }
        }

        return isSubclass;
    }
}

Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

Wait until all jQuery Ajax requests are done?

I found a good answer by gnarf my self which is exactly what I was looking for :)

jQuery ajaxQueue

//This handles the queues    
(function($) {

  var ajaxQueue = $({});

  $.ajaxQueue = function(ajaxOpts) {

    var oldComplete = ajaxOpts.complete;

    ajaxQueue.queue(function(next) {

      ajaxOpts.complete = function() {
        if (oldComplete) oldComplete.apply(this, arguments);

        next();
      };

      $.ajax(ajaxOpts);
    });
  };

})(jQuery);

Then you can add a ajax request to the queue like this:

$.ajaxQueue({
        url: 'page.php',
        data: {id: 1},
        type: 'POST',
        success: function(data) {
            $('#status').html(data);
        }
    });

How to check if mod_rewrite is enabled in php?

Two lines of code:

$isEnabled = in_array('mod_rewrite', apache_get_modules());
echo ($isEnabled) ? 'Enabled' : 'Not enabled';

Understanding the ngRepeat 'track by' expression

If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

dynamically set iframe src

You should also consider that in some Opera versions onload is fired several times and add some hooks:

// fixing Opera 9.26, 10.00
if (doc.readyState && doc.readyState != 'complete') {
    // Opera fires load event multiple times
    // Even when the DOM is not ready yet
    // this fix should not affect other browsers
    return;
}

// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
    // In Opera 9.64 event was fired second time
    // when body.innerHTML changed from false
    // to server response approx. after 1 sec
    return;
}

Code borrowed from Ajax Upload

Angular2 dynamic change CSS property

1) Using inline styles

<div [style.color]="myDynamicColor">

2) Use multiple CSS classes mapping to what you want and switch classes like:

 /* CSS */
 .theme { /* any shared styles */ }
 .theme.blue { color: blue; }
 .theme.red { color: red; }

 /* Template */
 <div class="theme" [ngClass]="{blue: isBlue, red: isRed}">
 <div class="theme" [class.blue]="isBlue">

Code samples from: https://angular.io/cheatsheet

More info on ngClass directive : https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

IntelliJ shortcut to show a popup of methods in a class that can be searched

Use Navigate (View in older versions) | File Structure Popup (Ctrl+F12 on Windows, ?+F12 on OS X). Start typing method/symbol name to either narrow down the list or highlight the desired element. Press Enter to navigate to the selected element.

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.

Batch script to delete files

You need to escape the % with another...

del "D:\TEST\TEST 100%%\Archive*.TXT"

How to import or copy images to the "res" folder in Android Studio?

Goto Settings > Plugin > Browse Repository > Serach Android Drawable Import

This plugin consists of 4 main features.

  • AndroidIcons Drawable Import
  • Material Icons Drawable Import
  • Scaled Drawable
  • Multisource-Drawable

Edit : After Android Studios 1.5 android support Vector Asset Studio.


Follow this, which says:

To start Vector Asset Studio:

  1. In Android Studio, open an Android app project.
  2. In the Project window, select the Android view.
  3. Right-click the res folder and select New > Vector Asset.

enter image description here

Using the Web.Config to set up my SQL database connection string?

Your best bet, starting fresh like you are, is to go grab the enterprise library. They have a configuration tool you can use to wire everything up for you nicely.

They also have a data access application block which is very useful and documentation filled with good samples.

http://www.microsoft.com/downloads/details.aspx?FamilyId=90DE37E0-7B42-4044-99BE-F8ECFBBC5B65&displaylang=en

How to pass password automatically for rsync SSH command?

Though you've already implemented it by now,

you can also use any expect implementation (you'll find alternatives in Perl, Python: pexpect, paramiko, etc..)

How to fix "containing working copy admin area is missing" in SVN?

According to this: http://www.devcha.com/2008/03/svn-directory-svn-containing-working.html

Check-out the folder "blabla" to a different location and then copy its .svn folder back into the original "blabla".

Can't install any package with node npm

npm install <packagename> --registry http://registry.npmjs.org/

Try specifying the registry with the install command. Solved my problem.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

How to add image to canvas

You have to use .onload

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); 

const drawImage = (url) => {
    const image = new Image();
    image.src = url;
    image.onload = () => {
       ctx.drawImage(image, 0, 0)
    }
}

Here's Why

If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

Is Laravel really this slow?

Since nobody else has mentioned it, I found that the xdebug debugger dramatically increased the time. I served a basic "Hello World, the time is 2020-01-01T01:01:01.010101" dynamic page and used this in my httpd.conf to time the request:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" **%T/%D**" combined

%T is the serve time in seconds, %D is the time in microseconds. With this in my php.ini:

[XDebug]
xdebug.remote_autostart = 1
xdebug.remote_enable = 1

I was getting around 770ms response times, but with both of those set to 0 to disable them, it jumped to 160ms instantly. Running both of these brought it down to 120ms:

php artisan route:cache
php artisan config:cache

The downside being that if I made config or route changes, I would need to re-cache them, which is annoying.

As a sidenote, oddly, moving the site from my SSD to a spinning HDD provided no performance benefits, which is super odd to me, but I suppose it's maybe cached, I'm on Windows 10 with XAMPP.

Receiver not registered exception error?

Use this code everywhere for unregisterReceiver:

if (batteryNotifyReceiver != null) {
    unregisterReceiver(batteryNotifyReceiver);
    batteryNotifyReceiver = null;
}

Vim for Windows - What do I type to save and exit from a file?

Use:

:wq!

The exclamation mark is used for overriding read-only mode.

Android how to use Environment.getExternalStorageDirectory()

As described in Documentation Environment.getExternalStorageDirectory() :

Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.

This is an example of how to use it reading an image :

String fileName = "stored_image.jpg";
 String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
 String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";

 File f = new File(pathDir + File.separator + fileName);

        if(f.exists()){
          Log.d("Application", "The file " + file.getName() + " exists!";
         }else{
          Log.d("Application", "The file no longer exists!";
         }

jQuery ajax upload file in asp.net mvc

I have a sample like this on vuejs version: v2.5.2

<form action="url" method="post" enctype="multipart/form-data">
    <div class="col-md-6">
        <input type="file" class="image_0" name="FilesFront" ref="FilesFront" />
    </div>
    <div class="col-md-6">
        <input type="file" class="image_1" name="FilesBack" ref="FilesBack" />
    </div>
</form>
<script>
Vue.component('v-bl-document', {
    template: '#document-item-template',
    props: ['doc'],
    data: function () {
        return {
            document: this.doc
        };
    },
    methods: {
        submit: function () {
            event.preventDefault();

            var data = new FormData();
            var _doc = this.document;
            Object.keys(_doc).forEach(function (key) {
                data.append(key, _doc[key]);
            });
            var _refs = this.$refs;
            Object.keys(_refs).forEach(function (key) {
                data.append(key, _refs[key].files[0]);
            });

            debugger;
            $.ajax({
                type: "POST",
                data: data,
                url: url,
                cache: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    //do something
                },

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

Unmarshaling nested JSON objects

This is an example of how to unmarshall JSON responses from the Safebrowsing v4 API sbserver proxy server: https://play.golang.org/p/4rGB5da0Lt

// this example shows how to unmarshall JSON requests from the Safebrowsing v4 sbserver
package main

import (
    "fmt"
    "log"
    "encoding/json"
)

// response from sbserver POST request
type Results struct {
    Matches []Match     
}

// nested within sbserver response
type Match struct {
    ThreatType string 
    PlatformType string 
    ThreatEntryType string 
    Threat struct {
        URL string
    }
}

func main() {
    fmt.Println("Hello, playground")

    // sample POST request
    //   curl -X POST -H 'Content-Type: application/json' 
    // -d '{"threatInfo": {"threatEntries": [{"url": "http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}]}}' 
    // http://127.0.0.1:8080/v4/threatMatches:find

    // sample JSON response
    jsonResponse := `{"matches":[{"threatType":"MALWARE","platformType":"ANY_PLATFORM","threatEntryType":"URL","threat":{"url":"http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}}]}`

    res := &Results{}
    err := json.Unmarshal([]byte(jsonResponse), res)
        if(err!=nil) {
            log.Fatal(err)
        }

    fmt.Printf("%v\n",res)
    fmt.Printf("\tThreat Type: %s\n",res.Matches[0].ThreatType)
    fmt.Printf("\tPlatform Type: %s\n",res.Matches[0].PlatformType)
    fmt.Printf("\tThreat Entry Type: %s\n",res.Matches[0].ThreatEntryType)
    fmt.Printf("\tURL: %s\n",res.Matches[0].Threat.URL)
}

Does Visual Studio have code coverage for unit tests?

Toni's answer is very useful, but I thought a quick start for total beginners to test coverage assessment (like I am).

As already mentioned, Visual Studio Professional and Community Editions do not have built-in test coverage support. However, it can be obtained quite easily. I will write step-by-step configuration for use with NUnit tests within Visual Studion 2015 Professional.

  1. Install OpenCover NUGet component using NuGet interface

  2. Get OpenCoverUI extension. This can be installed directly from Visual Studio by using Tools -> Extensions and Updates

  3. Configure OpenCoverUI to use the appropriate executables, by accessing Tools -> Options -> OpenCover.UI Options -> General

NUnit Path: must point to the `nunit-console.exe file. This can be found only within NUnit 2.xx version, which can be downloaded from here.

OpenCover Path: this should point to the installed package, usually <solution path>\packages\OpenCover.4.6.519\tools\OpenCover.Console.exe

  1. Install ReportGenerator NUGet package

  2. Access OpenCover Test Explorer from OpenCover menu. Try discovering tests from there. If it fails, check Output windows for more details.

  3. Check OpenCover Results (within OpenCover menu) for more details. It will output details such as Code Coverage in a tree based view. You can also highlight code that is or is not covered (small icon in the top-left).

NOTE: as mentioned, OpenCoverUI does not support latest major version of NUnit (3.xx). However, if nothing specific to this version is used within tests, it will work with no problems, regardless of having installed NUnit 3.xx version.

This covers the quick start. As already mentioned in the comments, for more advanced configuration and automation check this article.

How merge two objects array in angularjs?

Simple

var a=[{a:4}], b=[{b:5}]

angular.merge(a,b) // [{a:4, b:5}]

Tested on angular 1.4.1

Node.js - Maximum call stack size exceeded

Please check that the function you are importing and the one that you have declared in the same file do not have the same name.

I will give you an example for this error. In express JS (using ES6), consider the following scenario:

import {getAllCall} from '../../services/calls';

let getAllCall = () => {
   return getAllCall().then(res => {
      //do something here
   })
}
module.exports = {
getAllCall
}

The above scenario will cause infamous RangeError: Maximum call stack size exceeded error because the function keeps calling itself so many times that it runs out of maximum call stack.

Most of the times the error is in code (like the one above). Other way of resolving is manually increasing the call stack. Well, this works for certain extreme cases, but it is not recommended.

Hope my answer helped you.

How to get to Model or Viewbag Variables in a Script Tag

When you're doing this

var model = @Html.Raw(Json.Encode(Model));

You're probably getting a JSON string, and not a JavaScript object.

You need to parse it in to an object:

var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);

How to take the first N items from a generator or list?

In my taste, it's also very concise to combine zip() with xrange(n) (or range(n) in Python3), which works nice on generators as well and seems to be more flexible for changes in general.

# Option #1: taking the first n elements as a list
[x for _, x in zip(xrange(n), generator)]

# Option #2, using 'next()' and taking care for 'StopIteration'
[next(generator) for _ in xrange(n)]

# Option #3: taking the first n elements as a new generator
(x for _, x in zip(xrange(n), generator))

# Option #4: yielding them by simply preparing a function
# (but take care for 'StopIteration')
def top_n(n, generator):
    for _ in xrange(n): yield next(generator)

100% width background image with an 'auto' height

Instead of using background-image you can use img directly and to get the image to spread all the width of the viewport try using max-width:100%; and please remember don't apply any padding or margin to your main container div as they will increase the total width of the container. Using this rule you can have a image width equal to the width of the browser and the height will also change according to the aspect ratio. Thanks.

Edit: Changing the image on different size of the window

_x000D_
_x000D_
$(window).resize(function(){_x000D_
  var windowWidth = $(window).width();_x000D_
  var imgSrc = $('#image');_x000D_
  if(windowWidth <= 400){   _x000D_
    imgSrc.attr('src','http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a');_x000D_
  }_x000D_
  else if(windowWidth > 400){_x000D_
    imgSrc.attr('src','http://i.stack.imgur.com/oURrw.png');_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="image-container">_x000D_
  <img id="image" src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a" alt=""/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In this way you change your image in different size of the browser.

Why is enum class preferred over plain enum?

C++ has two kinds of enum:

  1. enum classes
  2. Plain enums

Here are a couple of examples on how to declare them:

 enum class Color { red, green, blue }; // enum class
 enum Animal { dog, cat, bird, human }; // plain enum 

What is the difference between the two?

  • enum classes - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum or int)

  • Plain enums - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types

Example:

enum Color { red, green, blue };                    // plain enum 
enum Card { red_card, green_card, yellow_card };    // another plain enum 
enum class Animal { dog, deer, cat, bird, human };  // enum class
enum class Mammal { kangaroo, deer, human };        // another enum class

void fun() {

    // examples of bad use of plain enums:
    Color color = Color::red;
    Card card = Card::green_card;

    int num = color;    // no problem

    if (color == Card::red_card) // no problem (bad)
        cout << "bad" << endl;

    if (card == Color::green)   // no problem (bad)
        cout << "bad" << endl;

    // examples of good use of enum classes (safe)
    Animal a = Animal::deer;
    Mammal m = Mammal::deer;

    int num2 = a;   // error
    if (m == a)         // error (good)
        cout << "bad" << endl;

    if (a == Mammal::deer) // error (good)
        cout << "bad" << endl;

}

Conclusion:

enum classes should be preferred because they cause fewer surprises that could potentially lead to bugs.

sequelize findAll sort order in nodejs

I don't think this is possible in Sequelize's order clause, because as far as I can tell, those clauses are meant to be binary operations applicable to every element in your list. (This makes sense, too, as it's generally how sorting a list works.)

So, an order clause can do something like order a list by recursing over it asking "which of these 2 elements is older?" Whereas your ordering is not reducible to a binary operation (compare_bigger(1,2) => 2) but is just an arbitrary sequence (2,4,11,2,9,0).

When I hit this issue with findAll, here was my solution (sub in your returned results for numbers):

var numbers = [2, 20, 23, 9, 53];
var orderIWant = [2, 23, 20, 53, 9];
orderIWant.map(x => { return numbers.find(y => { return y === x })});

Which returns [2, 23, 20, 53, 9]. I don't think there's a better tradeoff we can make. You could iterate in place over your ordered ids with findOne, but then you're doing n queries when 1 will do.

How do I link to Google Maps with a particular longitude and latitude?

This works too:

https://www.google.pl/maps/@<lat>,<lon>,<zoom>z

Example.

With pointer:

https://www.google.com/maps/place/<lat>,<lon>/@<lat>,<lon>,<zoom>z

Example.

Simple insecure two-way data "obfuscation"?

[EDIT] Years later, I've come back to say: don't do this! See What's wrong with XOR encryption? for details.

A very simple, easy two-way encrytpion is XOR encryption.

  1. Come up with a password. Let's have it be mypass.
  2. Convert the password into binary (according to ASCII). The password becomes 01101101 01111001 01110000 01100001 01110011 01110011.
  3. Take the message you want to encode. Convert that into binary, also.
  4. Look at the length of the message. If the message length is 400 bytes, turn the password into a 400 byte string by repeating it over and over again. It would become 01101101 01111001 01110000 01100001 01110011 01110011 01101101 01111001 01110000 01100001 01110011 01110011 01101101 01111001 01110000 01100001 01110011 01110011... (or mypassmypassmypass...)
  5. XOR the message with the long password.
  6. Send the result.
  7. Another time, XOR the encrypted message with the same password (mypassmypassmypass...).
  8. There's your message!

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

My issue was Mysql connector net 6.4.4, Nuget, xamarin, VSPackage, EditorPackage and etc.. package did not load correctly.

My solution is below for vs2015

  1. Open AppData location // all the configurations are updating on it.
  2. Backup and Remove the folder in which configuration error is thrown in the visual studio.

forex. If you have Nuget package did not load correctly error - Remove Nuget folder in Local and Roaming directories.

  1. And also clear the data on AppData/Microsoft/visual Studio/14.0 for vs2015

that's it and it worked for me!...

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

In our case it was an empty AndroidManifest.xml.

While upgrading Eclispe we ran into the usual trouble, and AndroidManifest.xml must have been checked into SVN by the build script after being clobbered.

Found it by compiling from inside Eclipse, instead of from the command line.

How can I parse a string with a comma thousand separator to a number?

All of these answers fail if you have a number in the millions.

3,456,789 would simply return 3456 with the replace method.

The most correct answer for simply removing the commas would have to be.

var number = '3,456,789.12';
number.split(',').join('');
/* number now equips 3456789.12 */
parseFloat(number);

Or simply written.

number = parseFloat(number.split(',').join(''));

Open a new tab in the background?

As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.

For example in firefox preferences:

Firefox setup example

Notice the last option.

Open Redis port for remote connections

  1. Open the file at location /etc/redis.conf

  2. Comment out bind 127.0.0.1

  3. Restart Redis:

     sudo systemctl start redis.service
    
  4. Disable Firewalld:

     systemctl disable firewalld
    
  5. Stop Firewalld:

     systemctl stop firewalld
    

Then try:

redis-cli -h 192.168.0.2(ip) -a redis(username)

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

If you are running on a 64 bit system and trying to load a 32 bit dll you need to compile your application as 32 bit instead of any cpu. If you are not doing this it behaves exactly as you describe.

If that isn't the case use Dependency Walker to verify that the dll has its required dependencies.

How do I catch an Ajax query post error?

In case you want to utilize .then() which has a subtle difference in comparison with .done() :

return $.post(url, payload)
.then(
    function (result, textStatus, jqXHR) {
        return result;
    },
    function (jqXHR, textStatus, errorThrown) {
        return console.error(errorThrown);
    });

jQuery append() vs appendChild()

append is a jQuery method to append some content or HTML to an element.

$('#example').append('Some text or HTML');

appendChild is a pure DOM method for adding a child element.

document.getElementById('example').appendChild(newElement);

How to show Bootstrap table with sort icon

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

To do so, you would

  1. need to include fontawesome:

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

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

Hope that helps.

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

form serialize javascript (no framework)

function serialize (form) {
    if (!form || form.nodeName !== "FORM") {
            return;
    }
    var i, j, q = [];
    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
        if (form.elements[i].name === "") {
            continue;
        }
        switch (form.elements[i].nodeName) {
            case 'INPUT':
                switch (form.elements[i].type) {
                    case 'text':
                    case 'tel':
                    case 'email':
                    case 'hidden':
                    case 'password':
                    case 'button':
                    case 'reset':
                    case 'submit':
                        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                        break;
                    case 'checkbox':
                    case 'radio':
                        if (form.elements[i].checked) {
                                q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                        }                                               
                        break;
                }
                break;
                case 'file':
                break; 
            case 'TEXTAREA':
                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                    break;
            case 'SELECT':
                switch (form.elements[i].type) {
                    case 'select-one':
                        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                        break;
                    case 'select-multiple':
                        for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
                            if (form.elements[i].options[j].selected) {
                                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
                            }
                        }
                        break;
                }
                break;
            case 'BUTTON':
                switch (form.elements[i].type) {
                    case 'reset':
                    case 'submit':
                    case 'button':
                        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                        break;
                }
                break;
            }
        }
    return q.join("&");
}

Source: http://code.google.com/p/form-serialize/source/browse/trunk/serialize-0.1.js

What does the Java assert keyword do, and when should it be used?

Let's assume that you are supposed to write a program to control a nuclear power-plant. It is pretty obvious that even the most minor mistake could have catastrophic results, therefore your code has to be bug-free (assuming that the JVM is bug-free for the sake of the argument).

Java is not a verifiable language, which means: you cannot calculate that the result of your operation will be perfect. The main reason for this are pointers: they can point anywhere or nowhere, therefore they cannot be calculated to be of this exact value, at least not within a reasonable span of code. Given this problem, there is no way to prove that your code is correct at a whole. But what you can do is to prove that you at least find every bug when it happens.

This idea is based on the Design-by-Contract (DbC) paradigm: you first define (with mathematical precision) what your method is supposed to do, and then verify this by testing it during actual execution. Example:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
  return a + b;
}

While this is pretty obvious to work fine, most programmers will not see the hidden bug inside this one (hint: the Ariane V crashed because of a similar bug). Now DbC defines that you must always check the input and output of a function to verify that it worked correctly. Java can do this through assertions:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
    assert (Integer.MAX_VALUE - a >= b) : "Value of " + a + " + " + b + " is too large to add.";
  final int result = a + b;
    assert (result - a == b) : "Sum of " + a + " + " + b + " returned wrong sum " + result;
  return result;
}

Should this function now ever fail, you will notice it. You will know that there is a problem in your code, you know where it is and you know what caused it (similar to Exceptions). And what is even more important: you stop executing right when it happens to prevent any further code to work with wrong values and potentially cause damage to whatever it controls.

Java Exceptions are a similar concept, but they fail to verify everything. If you want even more checks (at the cost of execution speed) you need to use assertions. Doing so will bloat your code, but you can in the end deliver a product at a surprisingly short development time (the earlier you fix a bug, the lower the cost). And in addition: if there is any bug inside your code, you will detect it. There is no way of a bug slipping-through and cause issues later.

This still is not a guarantee for bug-free code, but it is much closer to that, than usual programs.

How do I get the App version and build number using Swift?

For Swift 2.0

//First get the nsObject by defining as an optional anyObject

let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
let version = nsObject as! String

How to find length of digits in an integer?

Let the number be n then the number of digits in n is given by:

math.floor(math.log10(n))+1

Note that this will give correct answers for +ve integers < 10e15. Beyond that the precision limits of the return type of math.log10 kicks in and the answer may be off by 1. I would simply use len(str(n)) beyond that; this requires O(log(n)) time which is same as iterating over powers of 10.

Thanks to @SetiVolkylany for bringing my attenstion to this limitation. Its amazing how seemingly correct solutions have caveats in implementation details.

Install / upgrade gradle on Mac OS X

As mentioned in this tutorial, it's as simple as:

To install

brew install gradle

To upgrade

brew upgrade gradle

(using Homebrew of course)

Also see (finally) updated docs.

Cheers :)!

Use awk to find average of a column

Try this:

ls -l  | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'

NR is an AWK builtin variable to count the no. of records

Java switch statement: Constant expression required, but it IS constant

I recommend you to use enums :)

Check this out:

public enum Foo 
{
    BAR("bar"),
    BAZ("baz"),
    BAM("bam");

    private final String description;

    private Foo(String description)
    {
        this.description = description;
    }

    public String getDescription()
    {
        return description;
    }
}

Then you can use it like this:

System.out.println(Foo.BAR.getDescription());

Apache redirect to another port

This is working in ISPConfig too. In website list get inside a domain, click to Options tab, add these lines: ;

ProxyPass / http://localhost:8181/
ProxyPassReverse / http://localhost:8181/

Then go to website and wolaa :) This is working HTTPS protocol too.

Difference between <span> and <div> with text-align:center;?

It might be, because your span element sets is side as width as its content. if you have a div with 500px width and text-align center, and you enter a span tag it should be aligned in the center. So your problem might be a CSS one. Install Firebug at Firefox and check the style attributes your span or div object has.

How to stop asynctask thread in android?

u can check onCancelled() once then :

protected Object doInBackground(Object... x) {

while (/* condition */) {
  if (isCancelled()) break;
}
return null;

}

Target a css class inside another css class

Not certain what the HTML looks like (that would help with answers). If it's

<div class="testimonials content">stuff</div>

then simply remove the space in your css. A la...

.testimonials.content { css here }

UPDATE:

Okay, after seeing HTML see if this works...

.testimonials .wrapper .content { css here }

or just

.testimonials .wrapper { css here }

or

.desc-container .wrapper { css here }

all 3 should work.

PHP Fatal Error Failed opening required File

Hey I just had this problem and found that I wasn't looking at the folder location closely enough:

I had

require_once /vagrant/public/liberate/**APP**/vendor/autoload.php

What worked was:

require_once /vagrant/public/liberate/vendor/autoload.php

It was very easy (as a beginner) to overlook this very unnoticeable issue. Yes I do realize that the require issue being logged points directly to the issue at hand, but if you are a beginner, like me, these things can be easily overlooked.

FIX:

Have a good look at the debug of ( __ Dir __ '/etc/etc/etc/file.php') then have your file system open in a different window, and map the two directly. If there is even the slightest difference this require will not work and the above error will be spat out.

How do I finish the merge after resolving my merge conflicts?

Whenever You merge two branches using command git merge brancha branchb , There are two possibilities:

  1. One branch (lets say brancha) can be reached by the other branch (lets say branchb) by following its commits history.In this case git simply fast-forward the head to point to the recent branch (in this case branchb).

    2.But if the two branches have diverged at some older point then git creates a new snapshot and add a new commit that points to it. So in case there is no conflict between the branches you are merging, git smoothly creates a new commit.

Run git log to see the commit after you have merged two non-conflicting branches.

Now coming back to the interesting case when there are merge conflicts between the merging branches. I quote this from the page https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

Git hasn’t automatically created a new merge commit. It has paused the process while you resolve the conflict. If you want to see which files are unmerged at any point after a merge conflict, you can run git status


So in case there are merge conflicts, you need to resolve the conflict then add the changes you have made to the staging area using git add filename and then commit the changes by using the command git commit which was paused by git because of the conflict.I hope this explains your query. Also do visit the link above for a detailed understanding. In case of any query please comment below , I'll be happy to help.

How can I remove an entry in global configuration with git config?

Try these commands to remove all users' usernames and emails.

git config --global --unset-all user.name
git config --global --unset-all user.email

How do I create test and train samples from one dataframe with pandas?

Pandas random sample will also work

train=df.sample(frac=0.8,random_state=200) #random state is a seed value
test=df.drop(train.index)

Creating an abstract class in Objective-C

The solution I came up with is:

  1. Create a protocol for everything you want in your "abstract" class
  2. Create a base class (or maybe call it abstract) that implements the protocol. For all the methods you want "abstract" implement them in the .m file, but not the .h file.
  3. Have your child class inherit from the base class AND implement the protocol.

This way the compiler will give you a warning for any method in the protocol that isn't implemented by your child class.

It's not as succinct as in Java, but you do get the desired compiler warning.

Programmatically find the number of cores on a machine

More on OS X: sysconf(_SC_NPROCESSORS_ONLN) is available only versions >= 10.5, not 10.4.

An alternative is the HW_AVAILCPU/sysctl() BSD code which is available on versions >= 10.2.

character count using jquery

Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";
   console.log(str.length); 
   console.log($.trim(str).length); 
   console.log(str.replace(/ /g,'').length); 

Output:

20
7
5

Source: How to count number of characters in a string with JQuery

Git Pull While Ignoring Local Changes?

If you are on Linux:

git fetch
for file in `git diff origin/master..HEAD --name-only`; do rm -f "$file"; done
git pull

The for loop will delete all tracked files which are changed in the local repo, so git pull will work without any problems.
The nicest thing about this is that only the tracked files will be overwritten by the files in the repo, all other files will be left untouched.

Center the nav in Twitter Bootstrap

Possible duplicate of Modify twitter bootstrap navbar. I guess this is what you are looking for (copied):

.navbar .nav,
.navbar .nav > li {
  float:none;
  display:inline-block;
  *display:inline; /* ie7 fix */
  *zoom:1; /* hasLayout ie7 trigger */
  vertical-align: top;
}

.navbar-inner {
  text-align:center;
}

As stated in the linked answer, you should make a new class with these properties and add it to the nav div.

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

Test if a string contains any of the strings from an array

You can use String#matches method like this:

System.out.printf("Matches - [%s]%n", string.matches("^.*?(item1|item2|item3).*$"));

How to change Bootstrap's global default font size?

There are several ways but since you are using just the CSS version and not the SASS or LESS versions, your best bet to use Bootstraps own customization tool:

http://getbootstrap.com/customize/

Customize whatever you want on this page and then you can download a custom build with your own font sizes and anything else you want to change.

Altering the CSS file directly (or simply adding new CSS styles that override the Bootstrap CSS) is not recommended because other Bootstrap styles' values are derived from the base font size. For example:

https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_variables.scss#L52

You can see that the base font size is used to calculate the sizes of the h1, h2, h3 etc. If you just changed the font size in the CSS (or added your own overriding font-size) all the other values that used the font size in calculations would no longer be proportionally accurate according to Bootstrap's design.

As I said, your best bet is to just use their own Customize tool. That is exactly what it's for.

If you are using SASS or LESS, you would change the font size in the variables file before compiling.

Select top 2 rows in Hive

Here I think it's worth mentioning SORT BY and ORDER BY both clauses and why they different,

SELECT * FROM <table_name> SORT BY <column_name> DESC LIMIT 2

If you are using SORT BY clause it sort data per reducer which means if you have more than one MapReduce task it will result partially ordered data. On the other hand, the ORDER BY clause will result in ordered data for the final Reduce task. To understand more please refer to this link.

SELECT * FROM <table_name> ORDER BY <column_name> DESC LIMIT 2

Note: Finally, Even though the accepted answer contains SORT BY clause, I mostly prefer to use ORDER BY clause for the general use case to avoid any data loss.

Decorators with parameters?

In my instance, I decided to solve this via a one-line lambda to create a new decorator function:

def finished_message(function, message="Finished!"):

    def wrapper(*args, **kwargs):
        output = function(*args,**kwargs)
        print(message)
        return output

    return wrapper

@finished_message
def func():
    pass

my_finished_message = lambda f: finished_message(f, "All Done!")

@my_finished_message
def my_func():
    pass

if __name__ == '__main__':
    func()
    my_func()

When executed, this prints:

Finished!
All Done!

Perhaps not as extensible as other solutions, but worked for me.

Why aren't variable-length arrays part of the C++ standard?

(Background: I have some experience implementing C and C++ compilers.)

Variable-length arrays in C99 were basically a misstep. In order to support VLAs, C99 had to make the following concessions to common sense:

  • sizeof x is no longer always a compile-time constant; the compiler must sometimes generate code to evaluate a sizeof-expression at runtime.

  • Allowing two-dimensional VLAs (int A[x][y]) required a new syntax for declaring functions that take 2D VLAs as parameters: void foo(int n, int A[][*]).

  • Less importantly in the C++ world, but extremely important for C's target audience of embedded-systems programmers, declaring a VLA means chomping an arbitrarily large chunk of your stack. This is a guaranteed stack-overflow and crash. (Anytime you declare int A[n], you're implicitly asserting that you have 2GB of stack to spare. After all, if you know "n is definitely less than 1000 here", then you would just declare int A[1000]. Substituting the 32-bit integer n for 1000 is an admission that you have no idea what the behavior of your program ought to be.)

Okay, so let's move to talking about C++ now. In C++, we have the same strong distinction between "type system" and "value system" that C89 does… but we've really started to rely on it in ways that C has not. For example:

template<typename T> struct S { ... };
int A[n];
S<decltype(A)> s;  // equivalently, S<int[n]> s;

If n weren't a compile-time constant (i.e., if A were of variably modified type), then what on earth would be the type of S? Would S's type also be determined only at runtime?

What about this:

template<typename T> bool myfunc(T& t1, T& t2) { ... };
int A1[n1], A2[n2];
myfunc(A1, A2);

The compiler must generate code for some instantiation of myfunc. What should that code look like? How can we statically generate that code, if we don't know the type of A1 at compile time?

Worse, what if it turns out at runtime that n1 != n2, so that !std::is_same<decltype(A1), decltype(A2)>()? In that case, the call to myfunc shouldn't even compile, because template type deduction should fail! How could we possibly emulate that behavior at runtime?

Basically, C++ is moving in the direction of pushing more and more decisions into compile-time: template code generation, constexpr function evaluation, and so on. Meanwhile, C99 was busy pushing traditionally compile-time decisions (e.g. sizeof) into the runtime. With this in mind, does it really even make sense to expend any effort trying to integrate C99-style VLAs into C++?

As every other answerer has already pointed out, C++ provides lots of heap-allocation mechanisms (std::unique_ptr<int[]> A = new int[n]; or std::vector<int> A(n); being the obvious ones) when you really want to convey the idea "I have no idea how much RAM I might need." And C++ provides a nifty exception-handling model for dealing with the inevitable situation that the amount of RAM you need is greater than the amount of RAM you have. But hopefully this answer gives you a good idea of why C99-style VLAs were not a good fit for C++ — and not really even a good fit for C99. ;)


For more on the topic, see N3810 "Alternatives for Array Extensions", Bjarne Stroustrup's October 2013 paper on VLAs. Bjarne's POV is very different from mine; N3810 focuses more on finding a good C++ish syntax for the things, and on discouraging the use of raw arrays in C++, whereas I focused more on the implications for metaprogramming and the typesystem. I don't know if he considers the metaprogramming/typesystem implications solved, solvable, or merely uninteresting.


A good blog post that hits many of these same points is "Legitimate Use of Variable Length Arrays" (Chris Wellons, 2019-10-27).

How do I get the scroll position of a document?

It uses HTML DOM Elements, but not jQuery selector. It can be used like:

var height = document.body.scrollHeight;

What does '?' do in C++?

You can just rewrite it as:

int qempty(){ return(f==r);}

Which does the same thing as said in the other answers.

Adding a tooltip to an input box

It seems to be a bug, it work for all input type that aren't textbox (checkboxes, radio,...)

There is a quick workaround that will work.

<div data-tip="This is the text of the tooltip2">
    <input type="text" name="test" value="44"/>
</div>

JsFiddle

Background color of text in SVG

No, you can not add background color to SVG elements. You can do it programmatically with d3.

var text = d3.select("text");
var bbox = text.node().getBBox();
var padding = 2;
var rect = self.svg.insert("rect", "text")
    .attr("x", bbox.x - padding)
    .attr("y", bbox.y - padding)
    .attr("width", bbox.width + (padding*2))
    .attr("height", bbox.height + (padding*2))
    .style("fill", "red");

Put search icon near textbox using bootstrap

<input type="text" name="whatever" id="funkystyling" />

Here's the CSS for the image on the left:

#funkystyling {
    background: white url(/path/to/icon.png) left no-repeat;
    padding-left: 17px;
}

And here's the CSS for the image on the right:

#funkystyling {
    background: white url(/path/to/icon.png) right no-repeat;
    padding-right: 17px;
}

How to enable native resolution for apps on iPhone 6 and 6 Plus?

You can add a launch screen file that appears to work for multiple screen sizes. I just added the MainStoryboard as a launch screen file and that stopped the app from scaling. I think I will need to add a permanent launch screen later, but that got the native resolution up and working quickly. In Xcode, go to your target, general and add the launch screen file there.

Launch Screen File

Is there a way to check which CSS styles are being used or not used on a web page?

Without any third-party tools and any app, you can find unused CSS and javascript by using chrome dev tools in the coverage tab. read the post below from google developers. chrome coverage tab

ReactJS: setTimeout() not working?

Try to use ES6 syntax of set timeout. Normal javascript setTimeout() won't work in react js

setTimeout(
      () => this.setState({ position: 100 }), 
      5000
    );

What is the difference between <html lang="en"> and <html lang="en-US">?

You can use any country code, yes, but that doesn't mean a browser or other software will recognize it or do anything differently because of it. For example, a screen reader might deal with "en-US" and "en-GB" the same if they only support an American accent in English. Another piece of software that has two distinct voices, though, could adjust according to the country code.

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?

How can I print using JQuery

There is a jquery print area. I've been using it for some time now.

$(".printMe").click(function(){
   $("#outprint").printArea({ mode: 'popup', popClose: true });
});

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Just my two sends here

I was facing this issue with datetimes so what I did is this:

const moment = require('moment-timezone')

const date = moment.tz('America/Bogota').format()

Then save date to db to be able to compare it from some query.


To install moment-timezone

npm i moment-timezone

The network path was not found

There may be some reasons like:

  1. Wrong SQL connection string.
  2. SQL Server in services is not running.
  3. Distributed Transaction Coordinator service is not running.

First try to connect from SQL Server Management Studio to your Remote database. If it connects it means problem is at the code side or at Visual Studio side if you are using the one.

Check the connectionstring, if the problem persists, check these two services:

  1. Distributed Transaction Coordinator service
  2. SQL Server services.

Go in services.msc and search and start these two services.

The above answer works for the Exception: [Win32Exception (0x80004005): The network path was not found]

Count textarea characters

They say IE has issues with the input event but other than that, the solution is rather straightforward.

_x000D_
_x000D_
ta = document.querySelector("textarea");_x000D_
count = document.querySelector("label");_x000D_
_x000D_
ta.addEventListener("input", function (e) {_x000D_
  count.innerHTML = this.value.length;_x000D_
});
_x000D_
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">_x000D_
</textarea>_x000D_
<label for="my-textarea"></label>
_x000D_
_x000D_
_x000D_

Python read-only property

Notice that instance methods are also attributes (of the class) and that you could set them at the class or instance level if you really wanted to be a badass. Or that you may set a class variable (which is also an attribute of the class), where handy readonly properties won't work neatly out of the box. What I'm trying to say is that the "readonly attribute" problem is in fact more general than it's usually perceived to be. Fortunately there are conventional expectations at work that are so strong as to blind us wrt these other cases (after all, almost everything is an attribute of some sort in python).

Building upon these expectations I think the most general and lightweight approach is to adopt the convention that "public" (no leading underscore) attributes are readonly except when explicitly documented as writeable. This subsumes the usual expectation that methods won't be patched and class variables indicating instance defaults are better let alone. If you feel really paranoid about some special attribute, use a readonly descriptor as a last resource measure.

Generating statistics from Git repository

commits per author

git shortlog -s -n 

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

CSS Cell Margin

You can use both of them:

padding-right:10px;

padding-right:10%;

But it's better to use with %.

View a file in a different Git branch without changing branches

A simple, newbie friendly way for looking into a file: git gui browser <branch> which lets you explore the contents of any file.

It's also there in the File menu of git gui. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.

Change navbar color in Twitter Bootstrap

Try this too. This worked for me.

.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
  background-color: #00a950;
  color: #000000;
}

Store output of sed into a variable

line=`sed -n 2p myfile`
echo $line

What does numpy.random.seed(0) do?

As noted, numpy.random.seed(0) sets the random seed to 0, so the pseudo random numbers you get from random will start from the same point. This can be good for debuging in some cases. HOWEVER, after some reading, this seems to be the wrong way to go at it, if you have threads because it is not thread safe.

from differences-between-numpy-random-and-random-random-in-python:

For numpy.random.seed(), the main difficulty is that it is not thread-safe - that is, it's not safe to use if you have many different threads of execution, because it's not guaranteed to work if two different threads are executing the function at the same time. If you're not using threads, and if you can reasonably expect that you won't need to rewrite your program this way in the future, numpy.random.seed() should be fine for testing purposes. If there's any reason to suspect that you may need threads in the future, it's much safer in the long run to do as suggested, and to make a local instance of the numpy.random.Random class. As far as I can tell, random.random.seed() is thread-safe (or at least, I haven't found any evidence to the contrary).

example of how to go about this:

from numpy.random import RandomState
prng = RandomState()
print prng.permutation(10)
prng = RandomState()
print prng.permutation(10)
prng = RandomState(42)
print prng.permutation(10)
prng = RandomState(42)
print prng.permutation(10)

may give:

[3 0 4 6 8 2 1 9 7 5]

[1 6 9 0 2 7 8 3 5 4]

[8 1 5 0 7 2 9 4 3 6]

[8 1 5 0 7 2 9 4 3 6]

Lastly, note that there might be cases where initializing to 0 (as opposed to a seed that has not all bits 0) may result to non-uniform distributions for some few first iterations because of the way xor works, but this depends on the algorithm, and is beyond my current worries and the scope of this question.

Put byte array to JSON and vice versa

what about simply this:

byte[] args2 = getByteArry();
String byteStr = new String(args2);

How to kill a process running on particular port in Linux?

This is the solution for Windows:

C:\Users\Niroshan>netstat -ano|findstr "PID :8080"

Proto Local Address Foreign Address State PID
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 18264

taskkill /pid 18264 /f

How to create unique keys for React elements?

There are many ways in which you can create unique keys, the simplest method is to use the index when iterating arrays.

Example

    var lists = this.state.lists.map(function(list, index) {
        return(
            <div key={index}>
                <div key={list.name} id={list.name}>
                    <h2 key={"header"+list.name}>{list.name}</h2>
                    <ListForm update={lst.updateSaved} name={list.name}/>
                </div>
            </div>
        )
    });

Wherever you're lopping over data, here this.state.lists.map, you can pass second parameter function(list, index) to the callback as well and that will be its index value and it will be unique for all the items in the array.

And then you can use it like

<div key={index}>

You can do the same here as well

    var savedLists = this.state.savedLists.map(function(list, index) {
        var list_data = list.data;
        list_data.map(function(data, index) {
            return (
                <li key={index}>{data}</li>
            )
        });
        return(
            <div key={index}>
                <h2>{list.name}</h2>
                <ul>
                    {list_data}
                </ul>
            </div>
        )
    });

Edit

However, As pointed by the user Martin Dawson in the comment below, This is not always ideal.

So whats the solution then?

Many

  • You can create a function to generate unique keys/ids/numbers/strings and use that
  • You can make use of existing npm packages like uuid, uniqid, etc
  • You can also generate random number like new Date().getTime(); and prefix it with something from the item you're iterating to guarantee its uniqueness
  • Lastly, I recommend using the unique ID you get from the database, If you get it.

Example:

const generateKey = (pre) => {
    return `${ pre }_${ new Date().getTime() }`;
}

const savedLists = this.state.savedLists.map( list => {
    const list_data = list.data.map( data => <li key={ generateKey(data) }>{ data }</li> );
    return(
        <div key={ generateKey(list.name) }>
            <h2>{ list.name }</h2>
            <ul>
                { list_data }
            </ul>
        </div>
    )
});

How to create separate AngularJS controller files?

For brevity, here's an ES2015 sample that doesn't rely on global variables

// controllers/example-controller.js

export const ExampleControllerName = "ExampleController"
export const ExampleController = ($scope) => {
  // something... 
}

// controllers/another-controller.js

export const AnotherControllerName = "AnotherController"
export const AnotherController = ($scope) => {
  // functionality... 
}

// app.js

import angular from "angular";

import {
  ExampleControllerName,
  ExampleController
} = "./controllers/example-controller";

import {
  AnotherControllerName,
  AnotherController
} = "./controllers/another-controller";

angular.module("myApp", [/* deps */])
  .controller(ExampleControllerName, ExampleController)
  .controller(AnotherControllerName, AnotherController)