Programs & Examples On #Subsonic select

MongoDB query with an 'or' condition

Query objects in Mongo by default AND expressions together. Mongo currently does not include an OR operator for such queries, however there are ways to express such queries.

Use "in" or "where".

Its gonna be something like this:

db.mycollection.find( { $where : function() { 
return ( this.startTime < Now() && this.expireTime > Now() || this.expireTime == null ); } } );

How do you format an unsigned long long int using printf?

In addition to what people wrote years ago:

  • you might get this error on gcc/mingw:

main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]

printf("%llu\n", k);

Then your version of mingw does not default to c99. Add this compiler flag: -std=c99.

Writing string to a file on a new line every time

You can do this in two ways:

f.write("text to write\n")

or, depending on your Python version (2 or 3):

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x

Failed to resolve version for org.apache.maven.archetypes

Create New User Environment Variables:

MAVEN_HOME=D:\apache-maven-3.5.3

MAVEN=D:\apache-maven-3.5.3\bin

MAVEN_OPTS=-Xms256m -Xmx512m

Appened below in Path variable (System Variable):

;D:\apache-maven-3.5.3\bin;

Serializing to JSON in jQuery

I did find this somewhere. Can't remember where though... probably on StackOverflow :)

$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

MySQL FULL JOIN?

SELECT  p.LastName, p.FirstName, o.OrderNo
FROM    persons AS p
LEFT JOIN
        orders AS o
ON      o.orderNo = p.p_id
UNION ALL
SELECT  NULL, NULL, orderNo
FROM    orders
WHERE   orderNo NOT IN
        (
        SELECT  p_id
        FROM    persons
        )

Dynamically updating css in Angular 2

You can also use hostbinding:

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

export class HomeComponent {
    @HostBinding('style.width') width: Number;
    @HostBinding('style.height') height: Number;
} 

Now when you change the width or height property from within the HomeComponent, this should affect the style attributes.

batch file to copy files to another location?

@echo off cls echo press any key to continue backup ! pause xcopy c:\users\file*.* e:\backup*.* /s /e echo backup complete pause


file = name of file your wanting to copy

backup = where u want the file to be moved to

Hope this helps

Can I run Keras model on gpu?

Sure. I suppose that you have already installed TensorFlow for GPU.

You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.

import keras
import tensorflow as tf


config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} ) 
sess = tf.Session(config=config) 
keras.backend.set_session(sess)

Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.

forward declaration of a struct in C?

Try this

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(struct context *ctx);
  void (*func1)(void);
};

struct context{
    struct funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }

void getContext(struct context *con){
    con->fps.func0 = func0;  
    con->fps.func1 = func1;  
}

int main(int argc, char *argv[]){
 struct context c;
   c.fps.func0 = func0;
   c.fps.func1 = func1;
   getContext(&c);
   c.fps.func0(&c);
   getchar();
   return 0;
}

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

I am assuming that you need the JDK itself. If so you can accomplish this with:

sudo add-apt-repository ppa:sun-java-community-team/sun-java6

sudo apt-get update

sudo apt-get install sun-java6-jdk

You don't really need to go around editing sources or anything along those lines.

How do you do block comments in YAML?

One way to block commenting in YAML is by using a text editor like Notepad++ to add a # (comment) tag to multiple lines at once.

In Notepad++ you can do that using the "Block Comment" right-click option for selected text.

Woo Images!

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

How to Return partial view of another controller by controller?

Simply you could use:

PartialView("../ABC/XXX")

How to getElementByClass instead of GetElementById with JavaScript?

Use it to access class in Javascript.

<script type="text/javascript">
var var_name = document.getElementsByClassName("class_name")[0];
</script>

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

If you don't mind mutating x,

x.update(y) or x

Simple, readable, performant. You know update() always returns None, which is a false value. So the above expression will always evaluate to x, after updating it.

Most mutating methods in the standard library (like .update()) return None by convention, so this kind of pattern will work on those too. However, if you're using a dict subclass or some other method that doesn't follow this convention, then or may return its left operand, which may not be what you want. Instead, you can use a tuple display and index, which works regardless of what the first element evaluates to (although it's not quite as pretty):

(x.update(y), x)[-1]

If you don't have x in a variable yet, you can use lambda to make a local without using an assignment statement. This amounts to using lambda as a let expression, which is a common technique in functional languages, but maybe unpythonic.

(lambda x: x.update(y) or x)({'a': 1, 'b': 2})

Although it's not that different from the following use of the new walrus operator (Python 3.8+ only):

(x := {'a': 1, 'b': 2}).update(y) or x

If you do want a copy, PEP 584 style x | y is the most Pythonic on 3.9+. If you must support older versions, PEP 448 style {**x, **y} is easiest for 3.5+. But if that's not available in your (even older) Python version, the let pattern works here too.

(lambda z: z.update(y) or z)(x.copy())

(That is, of course, nearly equivalent to (z := x.copy()).update(y) or z, but if your Python version is new enough for that, then the PEP 448 style will be available.)

JQuery show and hide div on mouse click (animate)

Use slideToggle(500) function with a duration in milliseconds for getting a better effect.

Sample Html

<body>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">2.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details ">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">3.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
</body>

In your js file, if you need child propagation for the animation then remove the second click event function and its codes.

$(document).ready(function(){
    $(".js--growth-step").click(function(event){
       $(this).children(".step-details").slideToggle(500);
         return false;
    });
//for stoping child to manipulate the animation
    $(".js--growth-step .step-details").click(function(event) {
        event.stopPropagation();
   });
});

remote: repository not found fatal: not found

Also, be sure, that two-factor authentication is off, otherwise use personal access tokens

Details here : Can I use GitHub's 2-Factor Authentication with TortoiseGit?

How to remove item from list in C#?

Short answer:
Remove (from list results)

results.RemoveAll(r => r.ID == 2); will remove the item with ID 2 in results (in place).

Filter (without removing from original list results):

var filtered = result.Where(f => f.ID != 2); returns all items except the one with ID 2

Detailed answer:

I think .RemoveAll() is very flexible, because you can have a list of item IDs which you want to remove - please regard the following example.

If you have:

class myClass {
    public int ID; public string FirstName; public string LastName;
}

and assigned some values to results as follows:

var results = new List<myClass> {
    new myClass { ID=1, FirstName="Bill", LastName="Smith" },   // results[0]
    new myClass { ID=2, FirstName="John", LastName="Wilson" },  // results[1]
    new myClass { ID=3, FirstName="Doug", LastName="Berg" },    // results[2]
    new myClass { ID=4, FirstName="Bill", LastName="Wilson" }   // results[3]
};

Then you can define a list of IDs to remove:

var removeList = new List<int>() { 2, 3 };

And simply use this to remove them:

results.RemoveAll(r => removeList.Any(a => a==r.ID));

It will remove the items 2 and 3 and keep the items 1 and 4 - as specified by the removeList. Note that this happens in place, so there is no additional assigment required.

Of course, you can also use it on single items like:

results.RemoveAll(r => r.ID==4);

where it will remove Bill with ID 4 in our example.

A last thing to mention is that lists have an indexer, that is, they can also be accessed like a dynamic array, i.e. results[3] will give you the 4th element in the results list (because the first element has the index 0, the 2nd has index 1 etc).

So if you want to remove all entries where the first name is the same as in the 4th element of the results list, you can simply do it this way:

results.RemoveAll(r => results[3].FirstName == r.FirstName);

Note that afterwards, only John and Doug will remain in the list, Bill is removed (the first and last element in the example). Important is that the list will shrink automatically, so it has only 2 elements left - and hence the largest allowed index after executing RemoveAll in this example is 1
(which is results.Count() - 1).

Some Trivia: You can use this knowledge and create a local function

void myRemove()  { var last = results.Count() - 1; 
                   results.RemoveAll(r => results[last].FirstName == r.FirstName); }

What do you think will happen, if you call this function twice? Like

myRemove(); myRemove(); 

The first call will remove Bill at the first and last position, the second call will remove Doug and only John Wilson remains in the list.


DotNetFiddle: Run the demo

Note: Since C# Version 8, you can as well write results[^1] instead of var last = results.Count() - 1; and results[last]:

void myRemove() { results.RemoveAll(r => results[^1].FirstName == r.FirstName); }

So you would not need the local variable last anymore (see indices and ranges. For a list of all the new features in C#, look here).

How to create a localhost server to run an AngularJS project

cd <your project folder> (where your angularjs's deployable code is there)

sudo npm install serve -g

serve

You can hit your page at

localhost:3000 or IPaddress:3000

How can I combine two commits into one commit?

  1. Checkout your branch and count quantity of all your commits.
  2. Open git bash and write: git rebase -i HEAD~<quantity of your commits> (i.e. git rebase -i HEAD~5)
  3. In opened txt file change pick keyword to squash for all commits, except first commit (which is on the top). For top one change it to reword (which means you will provide a new comment for this commit in the next step) and click SAVE! If in vim, press esc then save by entering wq! and press enter.
  4. Provide Comment.
  5. Open Git and make "Fetch all" to see new changes.

Done

How to install SQL Server 2005 Express in Windows 8

I had the same problem. But I also had to perform additional steps. Here is what I did.

Perform the following steps (Only 64bit version of SQL Server 2005 Developer Edition tested on Windows 8 Pro 64bit)

  1. Extract sqlncli.msi / sqlncli_x64.msi from SP3 or SP4. I did it from SP4
  2. Install sqlncli
  3. Start SQL Server 2005 Setup
  4. During setup I received an error The SQL Server service failed to start. For more information, see the SQL Server Books Online topics, "How to: View SQL Server 2005 Setup Log Files" and "Starting SQL Server Manually."
  5. Don't click cancel yet. From an installation of SQL Server 2005 SP3 or SP4 copy SQLSERVR.EXE and SQLOS.DLL files and put them in your SQL install folder.
  6. Click RETRY

For STEP 5 above: Although I didn't try looking into SP4 / SP3 setup for SQLSERVR.EXE and SQLOS.DLL but if you don't have an existing installation of SQL Server 2005 SP3/SP4 then maybe try looking into the SP3/SP4 EXE (Compressed file). I am not sure if this may help. In any case you can create a VM and install SQL Server 2005 with SP3/Sp4 to copy the files for Windows 8

What's the best way to set a single pixel in an HTML5 canvas?

Fast and handy

Following class implements fast method described in this article and contains all you need: readPixel, putPixel, get width/height. Class update canvas after calling refresh() method. Example solve simple case of 2d wave equation

_x000D_
_x000D_
class Screen{
  constructor(canvasSelector) {
    this.canvas = document.querySelector(canvasSelector);
    this.width  = this.canvas.width;
    this.height = this.canvas.height;
    this.ctx = this.canvas.getContext('2d');
    this.imageData = this.ctx.getImageData(0, 0, this.width, this.height);
    this.buf = new ArrayBuffer(this.imageData.data.length);
    this.buf8 = new Uint8ClampedArray(this.buf);
    this.data = new Uint32Array(this.buf);  
  }
  
  // r,g,b,a - red, gren, blue, alpha components in range 0-255
  putPixel(x,y,r,g,b,a=255) {
    this.data[y * this.width + x] = (a<<24) | (b<<16) | (g<<8) | r;
  }
  
  readPixel(x,y) {
    let p= this.data[y * this.width + x]
    return [p&0xff, p>>8&0xff, p>>16&0xff, p>>>24];
  }

  refresh() {
    this.imageData.data.set(this.buf8);
    this.ctx.putImageData(this.imageData, 0, 0);
  }
}




// --------
// TEST
// --------

let s= new Screen('#canvas');                // initialise

function draw() {

  for (var y = 1; y < s.height-1; ++y) {
    for (var x = 1; x < s.width-1; ++x) {      
      let a = [[1,0],[-1,0],[0,1],[0,-1]].reduce((a,[xp,yp])=> 
        a+= s.readPixel(x+xp,y+yp)[0]        // read pixel
      ,0);
      let v= a/1.99446-tmp[x][y];
      tmp[x][y]=v<0 ? 0:v;
    }
  }

  for (var y = 1; y < s.height-1; ++y) {
    for (var x = 1; x < s.width-1; ++x) {  
      let v=tmp[x][y];
      tmp[x][y]= s.readPixel(x,y)[0];        // read pixel
      s.putPixel(x,y, v,0,0);                // put pixel
    }
  }

  s.refresh(); 
  frame++;
  window.requestAnimationFrame(draw)
}

// temporary 2d buffer ()for solving wave equation)
let tmp = [...Array(s.width)].map(x => Array(s.height).fill(0));

function move(e) { s.putPixel(e.x-10, e.y-10, 255,255,255);}

draw();
_x000D_
<canvas id="canvas" height="150" width="512" onmousemove="move(event)"></canvas>
<div>Move mouse on black square</div>
_x000D_
_x000D_
_x000D_

Can git undo a checkout of unstaged files

Dude,

lets say you're a very lucky guy just like I've been, go back to your editor and do an undo(command + Z for mac), you should see your lost content in the file. Hope it helped you. Of course, this will work only for existing files.

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

const vs constexpr on variables

No difference here, but it matters when you have a type that has a constructor.

struct S {
    constexpr S(int);
};

const S s0(0);
constexpr S s1(1);

s0 is a constant, but it does not promise to be initialized at compile-time. s1 is marked constexpr, so it is a constant and, because S's constructor is also marked constexpr, it will be initialized at compile-time.

Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program

Error: Could not find or load main class in intelliJ IDE

I inherited a bunch of .JAVA files from elsewhere and couldn't figure out how to get them to work in any IDE. Ultimately I had to go to the command line where the Main.JAVA file was and run javac Main.java. This created a bunch of .CLASS files. The IDE's were then able to figure out what to do.

How to detect DataGridView CheckBox event change?

This also handles the keyboard activation.

    private void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if(dgvApps.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
        {
            if (dgvApps.CurrentCell.IsInEditMode)
            {
                if (dgvApps.IsCurrentCellDirty)
                {
                    dgvApps.EndEdit();
                }
            }
        }
    }


    private void dgvApps_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
          // handle value changed.....
    }

TypeError: 'str' does not support the buffer interface

There is an easier solution to this problem.

You just need to add a t to the mode so it becomes wt. This causes Python to open the file as a text file and not binary. Then everything will just work.

The complete program becomes this:

plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
    outfile.write(plaintext)

Setting background images in JFrame

Try this :

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        try {
            f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        f.pack();
        f.setVisible(true);
    }

}

By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.

Get total number of items on Json object?

That's an Object and you want to count the properties of it.

Object.keys(jsonArray).length

References:

How do I get logs/details of ansible-playbook module executions?

Offical plugins

You can use the output callback plugins. For example, starting in Ansible 2.4, you can use the debug output callback plugin:

# In ansible.cfg:
[defaults]
stdout_callback = debug

(Altervatively, run export ANSIBLE_STDOUT_CALLBACK=debug before running your playbook)

Important: you must run ansible-playbook with the -v (--verbose) option to see the effect. With stdout_callback = debug set, the output should now look something like this:

TASK [Say Hello] ********************************
changed: [192.168.1.2] => {
    "changed": true,
    "rc": 0
}

STDOUT:


Hello!



STDERR:

Shared connection to 192.168.1.2 closed.

There are other modules besides the debug module if you want the output to be formatted differently. There's json, yaml, unixy, dense, minimal, etc. (full list).

For example, with stdout_callback = yaml, the output will look something like this:

TASK [Say Hello] **********************************
changed: [192.168.1.2] => changed=true 
  rc: 0
  stderr: |-
    Shared connection to 192.168.1.2 closed.
  stderr_lines:
  - Shared connection to 192.168.1.2 closed.
  stdout: |2-

    Hello!
  stdout_lines: <omitted>

Third-party plugins

If none of the official plugins are satisfactory, you can try the human_log plugin. There are a few versions:

How to allow only a number (digits and decimal point) to be typed in an input?

HTML

 <input type="text" name="number" only-digits>

// Just type 123

  .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9]/g, '');

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseInt(digits,10);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };

// type: 123 or 123.45

 .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9.]/g, '');

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseFloat(digits);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };

Get visible items in RecyclerView

You can use recyclerView.getChildAt() to get each visible child, and setting some tag convertview.setTag(index) on these view in adapter code will help you to relate it with adapter data.

Callback functions in Java

You also can do theCallback using the Delegate pattern:

Callback.java

public interface Callback {
    void onItemSelected(int position);
}

PagerActivity.java

public class PagerActivity implements Callback {

    CustomPagerAdapter mPagerAdapter;

    public PagerActivity() {
        mPagerAdapter = new CustomPagerAdapter(this);
    }

    @Override
    public void onItemSelected(int position) {
        // Do something
        System.out.println("Item " + postion + " selected")
    }
}

CustomPagerAdapter.java

public class CustomPagerAdapter {
    private static final int DEFAULT_POSITION = 1;
    public CustomPagerAdapter(Callback callback) {
        callback.onItemSelected(DEFAULT_POSITION);
    }
}

Failed to Connect to MySQL at localhost:3306 with user root

Steps:

1 - Right click on your task bar -->Start Task Manager

2 - Click on Services button (at bottom).

3 - Search for MYSQL57

4 - Right Click on MYSQL57 --> Start

Now again start your mysql-cmd-prompt or MYSQL WorkBench

Invoking Java main method with parameters from Eclipse

This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.

When selecting Run As..., go into the run configurations.

On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).

Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.

Extract every nth element of a vector

Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:

foo[ c( rep(FALSE, 5), TRUE ) ]

Cannot ping AWS EC2 instance

By default EC2 is secured by AWS Security Group (A service found in EC2 and VPC). Security Group by default are disallowing Any ICMP request which includes the ping. To allow it:

Goto: AWS EC2 Instance Locate: The Security Group bind to that instance (It's possible to have multiple security group) Check: Inbound Rules for Protocol (ICMP) Port (0 - 65535) if it's not present you can add it and allow it on your specified source IP or Another Security Group.

Use .htaccess to redirect HTTP to HTTPs

Just add this code, And it will work like charm:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST}#%{HTTPS}s ^www\.([^#]+)#(?:off|on(s)) [NC]
    RewriteRule ^ http%2://%1%{REQUEST_URI} [R=301,L]
</IfModule>

.htaccess not working on localhost with XAMPP

Just had a similar issue

Resolved it by checking in httpd.conf

     # AllowOverride controls what directives may be placed in .htaccess files.
     # It can be "All", "None", or any combination of the keywords:
     #   Options FileInfo AuthConfig Limit
     #
     AllowOverride All   <--- make sure this is not set to "None"

It is worth bearing in mind I tried (from Mark's answer) the "put garbage in the .htaccess" which did give a server error - but even though it was being read, it wasn't being acted on due to no overrides allowed.

Failed to open/create the internal network Vagrant on Windows10

The two answers did not solve my issue but combining them, I was able to solve the problem. My situation was I was trying to install and run Docker on a Windows 7 pc and kept getting an error: "Looks like something went wrong... Press any key to continue..."

After much digging, I was able to relate the issue to the host network adapter that was created by Docker. I had the NDIS6 driver installed but it was enabled. I tried to uncheck, disable, recheck, enable etc but it did not help.

I then uninstalled VB and reinstalled as per the first answer to get the NDIS5 driver. This was unchecked, so checking it I was able to move past this issue.

Bootstrap trying to load map file. How to disable it? Do I need to do it?

.map files allow a browser to download a full version of the minified JS. It is really for debugging purposes.

In effect, the .map missing isn't a problem. You only know it is missing, as the browser has had its Developer tools opened, detected a minified file and is just informing you that the JS debugging won't be as good as it could be.

This is why libraries like jQuery have the full, the minified and the map file too.

See this article for a full explanation of .map files:

Any way to Invoke a private method?

You can invoke private method with reflection. Modifying the last bit of the posted code:

Method method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object r = method.invoke(object);

There are a couple of caveats. First, getDeclaredMethod will only find method declared in the current Class, not inherited from supertypes. So, traverse up the concrete class hierarchy if necessary. Second, a SecurityManager can prevent use of the setAccessible method. So, it may need to run as a PrivilegedAction (using AccessController or Subject).

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

I have to point that out as a lot of people can struggle into that without knowing the problem.

If you want the kb to hide when clicking Done, and you set android:imeOptions="actionDone" & android:maxLines="1" without setting your EditText inputType it will NOT work as the default inputType for the EditText is not "text" as a lot of people think.

so, setting only inputType will give you the results you desire whatever what you are setting it to like "text", "number", ...etc.

What is the difference between Cloud, Grid and Cluster?

Cloud: the hardware running the application scales to meet the demand (potentially crossing multiple machines, networks, etc).

Grid: the application scales to take as much hardware as possible (for example in the hope of finding extra-terrestrial intelligence).

Cluster: this is an old term referring to one OS instance or one DB instance installed across multiple machines. It was done with special OS handling, proprietary drivers, low latency network cards with fat cables, and various hardware bedfellows.

(We love you SGI, but notice that "Cloud" and "Grid" are available to the little guy and your NUMAlink never has been...)

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

Just Check your webconfig file and remove this code :-

<dependentAssembly>
    <assemblyIdentity name="itextsharp" publicKeyToken="8354ae6d2174ddca" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.5.13.0" newVersion="5.5.13.0" />
  </dependentAssembly>

How to edit Docker container files from the host?

docker run -it -name YOUR_NAME IMAGE_ID /bin/bash

$>vi path_to_file

Download and open PDF file using Ajax

If you have to work with file-stream (so no physically saved PDF) like we do and you want to download the PDF without page-reload, the following function works for us:

HTML

<div id="download-helper-hidden-container" style="display:none">
     <form id="download-helper-form" target="pdf-download-output" method="post">
            <input type="hidden" name="downloadHelperTransferData" id="downloadHelperTransferData" />
     </form>
     <iframe id="pdf-helper-output" name="pdf-download-output"></iframe>
</div>

Javascript

var form = document.getElementById('download-helper-form');
$("#downloadHelperTransferData").val(transferData);
form.action = "ServerSideFunctionWhichWritesPdfBytesToResponse";
form.submit();

Due to the target="pdf-download-output", the response is written into the iframe and therefore no page reload is executed, but the pdf-response-stream is output in the browser as a download.

Add leading zeroes/0's to existing Excel values to certain length

=TEXT(A1,"0000")

However the TEXT function is able to do other fancy stuff like date formating, aswell.

Make div stay at bottom of page's content all the time even when there are scrollbars

if you have a fixed height footer (for example 712px) you can do this with js like so:

var bgTop = 0;
window.addEventListener("resize",theResize);
function theResize(){
    bgTop = winHeight - 712;
    document.getElementById("bg").style.marginTop = bgTop+"px";
}

Adding a default value in dropdownlist after binding with database

After data-binding, do this:

ddlColor.Items.Insert(0, new ListItem("Select","NA")); //updated code

Or follow Brian's second suggestion if you want to do it in markup.

You should probably add a RequiredFieldValidator control and set its InitialValue to "NA".

<asp:RequiredFieldValidator .. ControlToValidate="ddlColor" InitialValue="NA" />

c# foreach (property in object)... Is there a simple way of doing this?

A small word of caution, if "do some stuff" means updating the value of the actual property that you visit AND if there is a struct type property along the path from root object to the visited property, the change you made on the property will not be reflected on the root object.

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Robert Love's book LINUX System Programming 2nd Edition, specifically addresses your question at the beginning of Chapter 11, pg 363:

The important aspect of a monotonic time source is NOT the current value, but the guarantee that the time source is strictly linearly increasing, and thus useful for calculating the difference in time between two samplings

That said, I believe he is assuming the processes are running on the same instance of an OS, so you might want to have a periodic calibration running to be able to estimate drift.

What does bundle exec rake mean?

When you directly run the rake task or execute any binary file of a gem, there is no guarantee that the command will behave as expected. Because it might happen that you already have the same gem installed on your system which have a version say 1.0 but in your project you have higher version say 2.0. In this case you can not predict which one will be used.

To enforce the desired gem version you take the help of bundle exec command which would execute the binary in context of current bundle. That means when you use bundle exec, bundler checks the gem version configured for the current project and use that to perform the task.

I have also written a post about it which also shows how we can avoid using it using bin stubs.

jQuery "blinking highlight" effect on div?

just give elem.fadeOut(10).fadeIn(10);

Highlight all occurrence of a selected word?

I know than it's a really old question, but if someone is interested in this feature, can check this code http://vim.wikia.com/wiki/Auto_highlight_current_word_when_idle

" Highlight all instances of word under cursor, when idle.
" Useful when studying strange source code.
" Type z/ to toggle highlighting on/off.
nnoremap z/ :if AutoHighlightToggle()<Bar>set hls<Bar>endif<CR>
function! AutoHighlightToggle()
   let @/ = ''
   if exists('#auto_highlight')
     au! auto_highlight
     augroup! auto_highlight
     setl updatetime=4000
     echo 'Highlight current word: off'
     return 0
  else
    augroup auto_highlight
    au!
    au CursorHold * let @/ = '\V\<'.escape(expand('<cword>'), '\').'\>'
    augroup end
    setl updatetime=500
    echo 'Highlight current word: ON'
  return 1
 endif
endfunction

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

In my case it was a duplicate Swift Flag entry inside my Target's Build Settings > Other Swift Flags. I had two -Xfrontend entries in it.

Slide a layout up from bottom of screen

Use these animations:

bottom_up.xml

<?xml version="1.0" encoding="utf-8"?>
 <set xmlns:android="http://schemas.android.com/apk/res/android">
   <translate android:fromYDelta="75%p" android:toYDelta="0%p" 
    android:fillAfter="true"
 android:duration="500"/>
</set>

bottom_down.xml

 <?xml version="1.0" encoding="utf-8"?>
 <set xmlns:android="http://schemas.android.com/apk/res/android">

<translate android:fromYDelta="0%p" android:toYDelta="100%p" android:fillAfter="true"
            android:interpolator="@android:anim/linear_interpolator"
    android:duration="500" />

</set>

Use this code in your activity for hiding/animating your view:

Animation bottomUp = AnimationUtils.loadAnimation(getContext(),
            R.anim.bottom_up);
ViewGroup hiddenPanel = (ViewGroup)findViewById(R.id.hidden_panel);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);

Using RegEX To Prefix And Append In Notepad++

Assuming alphanumeric words, you can use:

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

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

Search = ^(.+)$

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

\1 will be the source match within the parentheses.

How to handle-escape both single and double quotes in an SQL-Update statement

You can escape the quotes with a backslash:

"I asked my son's teacher, \"How is my son doing now?\""

Semi-transparent color layer over background-image?

Here it is:

.background {
    background:url('../img/bg/diagonalnoise.png');
    position: relative;
}

.layer {
    background-color: rgba(248, 247, 216, 0.7);
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

HTML for this:

<div class="background">
    <div class="layer">
    </div>
</div>

Of course you need to define a width and height to the .background class, if there are no other elements inside of it

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

One minor thing, which wasted my time.

Put the conditions(if comparing using " = ", " != ") in parenthesis, failing to do so also raises this exception. This will work

df[(some condition) conditional operator (some conditions)]

This will not

df[some condition conditional-operator some condition]

How to check if JavaScript object is JSON

I wrote an npm module to solve this problem. It's available here:

object-types: a module for finding what literal types underly objects

Install

  npm install --save object-types


Usage

const objectTypes = require('object-types');

objectTypes({});
//=> 'object'

objectTypes([]);
//=> 'array'

objectTypes(new Object(true));
//=> 'boolean'

Take a look, it should solve your exact problem. Let me know if you have any questions! https://github.com/dawsonbotsford/object-types

Git - Ignore files during merge

I got over this issue by using git merge command with the --no-commit option and then explicitly removed the staged file and ignore the changes to the file. E.g.: say I want to ignore any changes to myfile.txt I proceed as follows:

git merge --no-ff --no-commit <merge-branch>
git reset HEAD myfile.txt
git checkout -- myfile.txt
git commit -m "merged <merge-branch>"

You can put statements 2 & 3 in a for loop, if you have a list of files to skip.

Converting String Array to an Integer Array

For Java 8 and higher:

    String[] test = {"1", "2", "3", "4", "5"};
    int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

After insuring that the string "strOutput" has a correct XML structure, you can do this:

Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");

Check if the number is integer

Here's a solution using simpler functions and no hacks:

all.equal(a, as.integer(a))

What's more, you can test a whole vector at once, if you wish. Here's a function:

testInteger <- function(x){
  test <- all.equal(x, as.integer(x), check.attributes = FALSE)
  if(test == TRUE){ return(TRUE) }
  else { return(FALSE) }
}

You can change it to use *apply in the case of vectors, matrices, etc.

How can I find whitespace in a String?

I purpose to you a very simple method who use String.contains:

public static boolean containWhitespace(String value) {
    return value.contains(" ");
}

A little usage example:

public static void main(String[] args) {
    System.out.println(containWhitespace("i love potatoes"));
    System.out.println(containWhitespace("butihatewhitespaces"));
}

Output:

true
false

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

Using Tyler Dodge's excellent answer kept lagging on my iPad, so I added some throttling code, now it's quite smooth. There is some minimal skipping sometimes while scrolling.

// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
  e.preventDefault();
});

var scrolling = false;

// Uses body because jquery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart','.scrollable',function(e) {

    // Only execute the below code once at a time
    if (!scrolling) {
        scrolling = true;   
        if (e.currentTarget.scrollTop === 0) {
          e.currentTarget.scrollTop = 1;
        } else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
          e.currentTarget.scrollTop -= 1;
        }
        scrolling = false;
    }
});

// Prevents preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove','.scrollable',function(e) {
  e.stopPropagation();
});

Also, adding the following CSS fixes some rendering glitches (source):

.scrollable {
    overflow: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
}
.scrollable * {
    -webkit-transform: translate3d(0,0,0);
}

Format date to MM/dd/yyyy in JavaScript

Try this; bear in mind that JavaScript months are 0-indexed, whilst days are 1-indexed.

_x000D_
_x000D_
var date = new Date('2010-10-11T00:00:00+05:30');_x000D_
    alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
_x000D_
_x000D_
_x000D_

C++ Erase vector element by value rather than by position?

You can use std::find to get an iterator to a value:

#include <algorithm>
std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
if (position != myVector.end()) // == myVector.end() means the element was not found
    myVector.erase(position);

WCF error: The caller was not authenticated by the service

I was able to resolve the shared issue by following below steps:

  1. Go to IIS-->Sites-->Your Site-->
  2. Features View Pane-->Authentication
  3. Set Anonymous Authentication to Disabled
  4. Set Windows Authentication to Enabled

enter image description here

How to uninstall a package installed with pip install --user

I strongly recommend you to use virtual environments for python package installation. With virtualenv, you prevent any package conflict and total isolation from your python related userland commands.

To delete all your package follow this;

It's possible to uninstall packages installed with --user flag. This one worked for me;

pip freeze --user | xargs pip uninstall -y

For python 3;

pip3 freeze --user | xargs pip3 uninstall -y

But somehow these commands don't uninstall setuptools and pip. After those commands (if you really want clean python) you may delete them with;

pip uninstall setuptools && pip uninstall pip

How to open a page in a new window or tab from code-behind

This code works for me:

Dim script As String = "<script type=""text/javascript"">window.open('" & URL.ToString & "');</script>"
ClientScript.RegisterStartupScript(Me.GetType, "openWindow", script)

NotificationCompat.Builder deprecated in Android O

enter image description here

Here is working code for all android versions as of API LEVEL 26+ with backward compatibility.

 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");

        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker("Hearty365")
                .setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
                .setContentTitle("Default notification")
                .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
                .setContentInfo("Info");

NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());

UPDATE for API 26 to set Max priority

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);

        // Configure the notification channel.
        notificationChannel.setDescription("Channel description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }


    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("Hearty365")
       //     .setPriority(Notification.PRIORITY_MAX)
            .setContentTitle("Default notification")
            .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            .setContentInfo("Info");

    notificationManager.notify(/*notification id*/1, notificationBuilder.build());

Multiplication on command line terminal

I have a simple script I use for this:

me@mycomputer:~$ cat /usr/local/bin/c

#!/bin/sh

echo "$*" | sed 's/x/\*/g' | bc -l

It changes x to * since * is a special character in the shell. Use it as follows:

  • c 5x5
  • c 5-4.2 + 1
  • c '(5 + 5) * 30' (you still have to use quotes if the expression contains any parentheses).

How can you determine a point is between two other points on a line segment?

C# version of Jules' answer:

public static double CalcDistanceBetween2Points(double x1, double y1, double x2, double y2)
{
    return Math.Sqrt(Math.Pow (x1-x2, 2) + Math.Pow (y1-y2, 2));
}

public static bool PointLinesOnLine (double x, double y, double x1, double y1, double x2, double y2, double allowedDistanceDifference)
{
    double dist1 = CalcDistanceBetween2Points(x, y, x1, y1);
    double dist2 = CalcDistanceBetween2Points(x, y, x2, y2);
    double dist3 = CalcDistanceBetween2Points(x1, y1, x2, y2);
    return Math.Abs(dist3 - (dist1 + dist2)) <= allowedDistanceDifference;
}

What exactly is OAuth (Open Authorization)?

Oauth is definitely gaining momentum and becoming popular among enterprise APIs as well. In the app and data driven world, Enterprises are exposing APIs more and more to the outer world in line with Google, Facebook, twitter. With this development a 3 way triangle of authentication gets formed

1) API provider- Any enterprise which exposes their assets by API, say Amazon,Target etc 2) Developer - The one who build mobile/other apps over this APIs 3) The end user- The end user of the service provided by the - say registered/guest users of Amazon

Now this develops a situation related to security - (I am listing few of these complexities) 1) You as an end user wants to allow the developer to access APIs on behalf of you. 2) The API provider has to authenticate the developer and the end user 3) The end user should be able to grant and revoke the permissions for the consent they have given 4) The developer can have varying level of trust with the API provider, in which the level of permissions given to her is different

The Oauth is an authorization framework which tries to solve the above mentioned problem in a standard way. With the prominence of APIs and Apps this problem will become more and more relevant and any standard which tries to solve it - be it ouath or any other - will be something to care about as an API provider/developer and even end user!

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

Getting the ID of the element that fired an event

this works with most types of elements:

$('selector').on('click',function(e){
    log(e.currentTarget.id);
    });

How to use onSavedInstanceState example please

A good information: you don't need to check whether the Bundle object is null into the onCreate() method. Use the onRestoreInstanceState() method, which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null

How to join multiple lines of file names into one with custom delimiter?

If Python3 is your cup of tea, you can do this (but please explain why you would?):

ls -1 | python -c "import sys; print(','.join(sys.stdin.read().splitlines()))"

Generate random array of floats between a range

This is the simplest way

np.random.uniform(start,stop,(rows,columns))

How often does python flush to a file?

You can also force flush the buffer to a file programmatically with the flush() method.

with open('out.log', 'w+') as f:
    f.write('output is ')
    # some work
    s = 'OK.'
    f.write(s)
    f.write('\n')
    f.flush()
    # some other work
    f.write('done\n')
    f.flush()

I have found this useful when tailing an output file with tail -f.

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

XMLHttpRequest is a standard object in the JavaScript Object model.

According to Wikipedia, XMLHttpRequest first appeared in Internet Explorer 5 as an ActiveX object, but has since been made into a standard and has been included for use in JavaScript in the Mozilla family since 1.0, Apple Safari 1.2, Opera 7.60-p1, and IE 7.0.

The open() method on the object takes the HTTP Method as an argument - and is specified as taking any valid HTTP method (see the item number 5 of the link) - including GET, POST, HEAD, PUT and DELETE, as specified by RFC 2616.

As a side note IE 7–8 only permit the following HTTP methods: "GET", "POST", "HEAD", "PUT", "DELETE", "MOVE", "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "LOCK", "UNLOCK", and "OPTIONS".

Using the Underscore module with Node.js

Note: The following only works for the next line of code, and only due to a coincidence.

With Lodash,

require('lodash');
_.isArray([]); // true

No var _ = require('lodash') since Lodash mysteriously sets this value globally when required.

I can't find my git.exe file in my Github folder

I faced the same issue and was not able to find it out where git.exe is located. After spending so much time I fount that in my windows 8, it is located at

C:\Program Files (x86)\Git\bin

And for command line :

C:\Program Files (x86)\Git\cmd

Hope this helps someone facing the same issue.

Mysql database sync between two databases

three different approaches:

  1. Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.

  2. replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.

  3. offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.

Add space between HTML elements only using CSS

<span> is an inline element so you cant make spacing on them without making it block level. Try this

Horizontal

span{
    margin-right: 10px;
    float: left;
}

Vertical

span{
    margin-bottom: 10px;
}

Compatible with all browsers.

2D character array initialization in C

char **options[2][100];

declares a size-2 array of size-100 arrays of pointers to pointers to char. You'll want to remove one *. You'll also want to put your string literals in double quotes.

How do I install jmeter on a Mac?

The easiest way to install it is using Homebrew:

brew install jmeter

Or if you need plugins also:

brew install jmeter --with-plugins

And to open it, use the following command (since it doesn't appear in your Applications):

open /usr/local/bin/jmeter

Detect if string contains any spaces

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {
    // It has any kind of whitespace
}

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {
    // It has only spaces, or is empty
}

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {
    // It has only whitespace
}

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

In Python, how do I iterate over a dictionary in sorted key order?

sorted returns a list, hence your error when you try to iterate over it, but because you can't order a dict you will have to deal with a list.

I have no idea what the larger context of your code is, but you could try adding an iterator to the resulting list. like this maybe?:

return iter(sorted(dict.iteritems()))

of course you will be getting back tuples now because sorted turned your dict into a list of tuples

ex: say your dict was: {'a':1,'c':3,'b':2} sorted turns it into a list:

[('a',1),('b',2),('c',3)]

so when you actually iterate over the list you get back (in this example) a tuple composed of a string and an integer, but at least you will be able to iterate over it.

How to open mail app from Swift

Here how it looks for Swift 4:

import MessageUI

if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self
    mail.setToRecipients(["[email protected]"])
    mail.setSubject("Bla")
    mail.setMessageBody("<b>Blabla</b>", isHTML: true)
    present(mail, animated: true, completion: nil)
} else {
    print("Cannot send mail")
    // give feedback to the user
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        switch result.rawValue {
        case MFMailComposeResult.cancelled.rawValue:
            print("Cancelled")
        case MFMailComposeResult.saved.rawValue:
            print("Saved")
        case MFMailComposeResult.sent.rawValue:
            print("Sent")
        case MFMailComposeResult.failed.rawValue:
            print("Error: \(String(describing: error?.localizedDescription))")
        default:
            break
        }
        controller.dismiss(animated: true, completion: nil)
    }

Finding the average of a list

If you wanted to get more than just the mean (aka average) you might check out scipy stats

from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))

# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111, 
# variance=572.3611111111111, skewness=1.7791785448425341, 
# kurtosis=1.9422716419666397)

Oracle PL/SQL : remove "space characters" from a string

select regexp_replace('This is a test   ' || chr(9) || ' foo ', '[[:space:]]', '') from dual;

REGEXP_REPLACE
--------------
Thisisatestfoo

How do I rename a Git repository?

  1. Go to the remote host (e.g., https://github.com/<User>/<Project>/ ).
  2. Click tab Settings.
  3. Rename under Repository name (and press button Rename).

javascript : sending custom parameters with window.open() but its not working

if you want to pass POST variables, you have to use a HTML Form:

<form action="http://localhost:8080/login" method="POST" target="_blank">
    <input type="text" name="cid" />
    <input type="password" name="pwd" />
    <input type="submit" value="open" />
</form>

or:

if you want to pass GET variables in an URL, write them without single-quotes:

http://yourdomain.com/login?cid=username&pwd=password

here's how to create the string above with javascrpt variables:

myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");

in the document with that url, you have to read the GET parameters. if it's in php, use:

$_GET['username']

be aware: to transmit passwords that way is a big security leak!

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

For Windows you can try below solution

Copy your gradle-->bin path and add it to system environment variable path.

In my case gradle path is

C:\Users\username\.gradle\wrapper\dists\gradle-3.3-all\55gk2rcmfc6p2dg9u9ohc3hw9\gradle-3.3\bin

This solution worked for me.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

I may be quite late to the party, but we can create custom foldr using simple lambda calculus and curried function. Here is my implementation of foldr in python.

def foldr(func):
    def accumulator(acc):
        def listFunc(l):
            if l:
                x = l[0]
                xs = l[1:]
                return func(x)(foldr(func)(acc)(xs))
            else:
                return acc
        return listFunc
    return accumulator  


def curried_add(x):
    def inner(y):
        return x + y
    return inner

def curried_mult(x):
    def inner(y):
        return x * y
    return inner

print foldr(curried_add)(0)(range(1, 6))
print foldr(curried_mult)(1)(range(1, 6))

Even though the implementation is recursive (might be slow), it will print the values 15 and 120 respectively

Create a Date with a set timezone without using a string representation

any mileage in

var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();

Change directory command in Docker?

RUN git clone http://username:password@url/example.git
WORKDIR /folder
RUN make

Traversing text in Insert mode

If you are a vim purist, skip reading this answer. OTOH, if you are new to vim and are looking for a few helpful tips you wont find in the many hundred of vim tutorials and blogs, read on... :-)

A few un-orthodox (vim) ways

It's 2014, and as someone who's recently gone back to vim I can offer a few, potentially contrarian, points of view and tips.

Use shift+left or shift+right to traverse words

While repetition is a powerful concept in vim, I (personally) find it strange that using it either forces me to count (lines, characters, words, etc.) or make guesses. My brain usually works like "I want the cursor there" and not like "I want the cursor _5_words_to_the_left_". Quickly being able to move the cursor, and visually observe where the insertion point this way allows me to keep my mind on what I'm editing instead of having to count how many hops I need to make to get to where I need to edit.

Turn on mouse mode, and use the mouse wheel and clicking

...to navigate large bodies of text.

Most (all) modern computers have a touchpad that is closely integrated with the keyboard (e.g. MacBooks). Industrial designers have spent many man years optimizing these designs so that the old problem of having to move the hand away from the keyboard is no longer a real issue. Okay, it is if you are used to a mouse and don't like to switch, but for anyone new to vim (like those that might find this post via a search), this should not be much of an issue.

As a bonus, click + drag puts you in visual mode

With mouse enabled, clicking and dragging has the effect of switching to visual mode and marking a region for yanking.

And use the scroll wheel

Using the mouse (wheel) to scroll around, and clicking to position the cursor (duh) just works. See http://usevim.com/2012/05/16/mouse/ for more on this.

And so...

These are what I'd call more modern (using mouse, scroll wheel, etc.) ways of navigating in vim, equally effective depending on your preference of input.

HTH

Fastest way to count exact number of rows in a very large table?

Well, late by 5 years and unsure if it helps :

I was trying to count the no. of rows in a SQL Server table using MS SQL Server Management Studio and ran into some overflow error, then I used the below :

select count_big(1) FROM [dbname].[dbo].[FactSampleValue];

The result :

24296650578 rows

html5 input for money/currency

More easy and beautiful if you has vue.js v-money-spinner :)

enter image description here

Java 8 Distinct by property

The Most simple code you can write:

    persons.stream().map(x-> x.getName()).distinct().collect(Collectors.toList());

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

For my case, I deleted the mappedBy and joined tables like this:

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_group", joinColumns = {
        @JoinColumn(name = "user", referencedColumnName = "user_id")
}, inverseJoinColumns = {
        @JoinColumn(name = "group", referencedColumnName = "group_id")
})
private List<User> users;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonIgnore
private List<Group> groups;

Regular expression for a hexadecimal number?

If you are looking for an specific hex character in the middle of the string, you can use "\xhh" where hh is the character in hexadecimal. I've tried and it works. I use framework for C++ Qt but it can solve problems in other cases, depends on the flavor you need to use (php, javascript, python , golang, etc.).

This answer was taken from:http://ult-tex.net/info/perl/

ERROR: Sonar server 'http://localhost:9000' can not be reached

In sonar.properties file in conf folder I had hardcoaded ip of my machine where sobarqube was installed in property sonar.web.host=10.9 235.22 I commented this and it started working for me.

How do I pass environment variables to Docker containers?

Use -e or --env value to set environment variables (default []).

An example from a startup script:

 docker run  -e myhost='localhost' -it busybox sh

If you want to use multiple environments from the command line then before every environment variable use the -e flag.

Example:

 sudo docker run -d -t -i -e NAMESPACE='staging' -e PASSWORD='foo' busybox sh

Note: Make sure put the container name after the environment variable, not before that.

If you need to set up many variables, use the --env-file flag

For example,

 $ docker run --env-file ./my_env ubuntu bash

For any other help, look into the Docker help:

 $ docker run --help

Official documentation: https://docs.docker.com/compose/environment-variables/

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

WPF Databinding: How do I access the "parent" data context?

This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"

Can I escape html special chars in javascript?

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

Show a popup/message box from a Windows batch file

A better option

set my_message=Hello world&& start cmd /c "@echo off & mode con cols=15 lines=2 & echo %my_message% & pause>nul"


Description:
lines= amount of lines,plus 1
cols= amount of characters in the message, plus 3 (However, minimum must be 15)

Auto-calculated cols version:

set my_message=Hello world&& (echo %my_message%>EMPTY_FILE123 && FOR %? IN (EMPTY_FILE123 ) DO SET strlength=%~z? && del EMPTY_FILE123 ) && start cmd /c "@echo off && mode con lines=2 cols=%strlength% && echo %my_message% && pause>nul"

Oracle database: How to read a BLOB?

You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2()).

SELECT b FROM foo;
-- (BLOB)

SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000

This is handy because you this is the same format used for inserting into BLOB columns:

CREATE GLOBAL TEMPORARY TABLE foo (
    b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');

DESC foo;
-- Name Null Type 
-- ---- ---- ---- 
-- B        BLOB 

However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR for a more complicated approach that will allow you to see substrings of the BLOB.

How to hide command output in Bash

A process normally has two outputs to screen: stdout (standard out), and stderr (standard error).

Normally informational messages go to sdout, and errors and alerts go to stderr.

You can turn off stdout for a command by doing

MyCommand >/dev/null

and turn off stderr by doing:

MyCommand 2>/dev/null

If you want both off, you can do:

MyCommand 2>&1 >/dev/null

The 2>&1 says send stderr to the same place as stdout.

How to generate a random number between 0 and 1?

In your version rand() % 10000 will yield an integer between 0 and 9999. Since RAND_MAX may be as little as 32767, and since this is not exactly divisible by 10000 and not large relative to 10000, there will be significant bias in the 'randomness' of the result, moreover, the maximum value will be 0.9999, not 1.0, and you have unnecessarily restricted your values to four decimal places.

It is simple arithmetic, a random number divided by the maximum possible random number will yield a number from 0 to 1 inclusive, while utilising the full resolution and distribution of the RNG

double r2()
{
    return (double)rand() / (double)RAND_MAX ;
}

Use (double)rand() / (double)((unsigned)RAND_MAX + 1) if exclusion of 1.0 was intentional.

text box input height

I came here looking for making an input that's actually multiple lines. Turns out I didn't want an input, I wanted a textarea. You can set height or line-height as other answers specify, but it'll still just be one line of a textbox. If you want actual multiple lines, use a textarea instead. The following is an example of a 3-row textarea with a width of 500px (should be a good part of the page, not necessary to set this and will have to change it based on your requirements).

<textarea name="roleExplanation" style="width: 500px" rows="3">This role is for facility managers and holds the highest permissions in the application.</textarea>

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

Example that works for me on OSX / MacOS (replace name of device)

~/Library/Android/sdk/emulator/emulator @Pixel_2_API_28 -no-snapshot -wipe-data

Maven: Failed to retrieve plugin descriptor error

I had a similar issue with Eclipse and the same steps as Sanders did solve it. It happens because the proxy restricts call to maven repository

  1. Go to D:\Maven\apache-maven-3.0.4-bin\apache-maven-3.0.4\conf (ie your maven installation folder)
  2. Copy settings.xml and paste it in .m2 folder, which is in the users folder of your windows machine.
  3. Add the proxy setting

Something like this:

 <proxies>
    <!-- proxy
      Specification for one proxy, to be used in connecting to the network.
     -->
    <proxy>      
      <active>true</active>
      <protocol>http</protocol>
      <username>your username</username>
      <password>password</password>    
      <host>proxy.host.net</host>
      <port>80</port>  
    </proxy>

  </proxies>

Refreshing page on click of a button

I'd suggest <a href='page1.jsp'>Refresh</a>.

How to add additional fields to form before submit?

May be useful for some:

(a function that allow you to add the data to the form using an object, with override for existing inputs, if there is) [pure js]

(form is a dom el, and not a jquery object [jqryobj.get(0) if you need])

function addDataToForm(form, data) {
    if(typeof form === 'string') {
        if(form[0] === '#') form = form.slice(1);
        form = document.getElementById(form);
    }

    var keys = Object.keys(data);
    var name;
    var value;
    var input;

    for (var i = 0; i < keys.length; i++) {
        name = keys[i];
        // removing the inputs with the name if already exists [overide]
        // console.log(form);
        Array.prototype.forEach.call(form.elements, function (inpt) {
             if(inpt.name === name) {
                 inpt.parentNode.removeChild(inpt);
             }
        });

        value = data[name];
        input = document.createElement('input');
        input.setAttribute('name', name);
        input.setAttribute('value', value);
        input.setAttribute('type', 'hidden');

        form.appendChild(input);
    }

    return form;
}

Use :

addDataToForm(form, {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can use it like that too

var form = addDataToForm('myFormId', {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can add # if you like too ("#myformid").

Get the current date and time

DateTimePicker1.value = Format(Date.Now)

How do I change a PictureBox's image?

You can use the ImageLocation property of pictureBox1:

pictureBox1.ImageLocation = @"C:\Users\MSI\Desktop\MYAPP\Slider\Slider\bt1.jpg";

Composer: Command Not Found

This problem arises when you have composer installed locally. To make it globally executable,run the below command in terminal

sudo mv composer.phar /usr/local/bin/composer

For CentOS 7 the command is

sudo mv composer.phar /usr/bin/composer

Is there a way to make a DIV unselectable?

I wrote a simple jQuery extension to disable selection some time back: Disabling Selection in jQuery. You can invoke it through $('.button').disableSelection();

Alternately, using CSS (cross-browser):

.button {
        user-select: none;
        -moz-user-select: none;
        -khtml-user-select: none;
        -webkit-user-select: none;
        -o-user-select: none;
} 

What is the default database path for MongoDB?

The Windows x64 installer shows the a path in the installer UI/wizard.

You can confirm which path it used later, by opening your mongod.cfg file. My mongod.cfg was located here C:\Program Files\MongoDB\Server\4.0\bin\mongod.cfg (change for your version of MongoDB!

When I opened my mongd.cfg I found this line, showing the default db path:

dbPath: C:\Program Files\MongoDB\Server\4.0\data

However, this caused an error when trying to run mongod, which was still expecting to find C:\data\db:

2019-05-05T09:32:36.084-0700 I STORAGE [initandlisten] exception in initAndListen: NonExistentPath: Data directory C:\data\db\ not found., terminating

You could pass mongod a --dbpath=... parameter. In my case:

mongod --dbpath="C:\Program Files\MongoDB\Server\4.0\data"

ORA-00979 not a group by expression

You should do the following:

SELECT cr.review_sk, 
       cr.cs_sk, 
       cr.full_name,
       tolist(to_char(cf.fact_date, 'mm/dd/yyyy')) "appt",
       cs.cs_id, 
       cr.tracking_number
from review cr, cs, fact cf
where cr.cs_sk = cs.cs_sk
       and UPPER(cs.cs_id) like '%' || UPPER(i_cs_id) || '%'
       and row_delete_date_time is null
       and cr.review_sk = cf.review_wk (+)
       and cr.fact_type_code (+) = 183050
GROUP BY cr.review_sk, cr.cs_sk, cf.fact_date, cr.tracking_number, cs.cs_id, cr.full_name
ORDER BY cs.cs_id, cr.full_name;

How to use filter, map, and reduce in Python 3

As an addendum to the other answers, this sounds like a fine use-case for a context manager that will re-map the names of these functions to ones which return a list and introduce reduce in the global namespace.

A quick implementation might look like this:

from contextlib import contextmanager    

@contextmanager
def noiters(*funcs):
    if not funcs: 
        funcs = [map, filter, zip] # etc
    from functools import reduce
    globals()[reduce.__name__] = reduce
    for func in funcs:
        globals()[func.__name__] = lambda *ar, func = func, **kwar: list(func(*ar, **kwar))
    try:
        yield
    finally:
        del globals()[reduce.__name__]
        for func in funcs: globals()[func.__name__] = func

With a usage that looks like this:

with noiters(map):
    from operator import add
    print(reduce(add, range(1, 20)))
    print(map(int, ['1', '2']))

Which prints:

190
[1, 2]

Just my 2 cents :-)

What can be the reasons of connection refused errors?

1.Check your server status.

2.Check the port status.

For example 3306 netstat -nupl|grep 3306.

3.Check your firewalls. For example add 3306

vim /etc/sysconfig/iptables
# add
-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT

How do I create a new branch?

My solution if you work with the Trunk/ and Release/ workflow:

Right click on Trunk/ which you will be creating your Branch from:

Trunk

Select Branch/Tag:

Branch/Tag

Type in location of your new branch, commit message, and any externals (if your repository has them):

enter image description here

How do I copy the contents of one ArrayList into another?

There are no implicit copies made in java via the assignment operator. Variables contain a reference value (pointer) and when you use = you're only coping that value.

In order to preserve the contents of myTempObject you would need to make a copy of it.

This can be done by creating a new ArrayList using the constructor that takes another ArrayList:

ArrayList<Object> myObject = new ArrayList<Object>(myTempObject);

Edit: As Bohemian points out in the comments below, is this what you're asking? By doing the above, both ArrayLists (myTempObject and myObject) would contain references to the same objects. If you actually want a new list that contains new copies of the objects contained in myTempObject then you would need to make a copy of each individual object in the original ArrayList

How to get last N records with activerecord?

Add an :order parameter to the query

When to use a View instead of a Table?

You should design your table WITHOUT considering the views.
Apart from saving joins and conditions, Views do have a performance advantage: SQL Server may calculate and save its execution plan in the view, and therefore make it faster than "on the fly" SQL statements.
View may also ease your work regarding user access at field level.

Node.js Best Practice Exception Handling

Update: Joyent now has their own guide. The following information is more of a summary:

Safely "throwing" errors

Ideally we'd like to avoid uncaught errors as much as possible, as such, instead of literally throwing the error, we can instead safely "throw" the error using one of the following methods depending on our code architecture:

  • For synchronous code, if an error happens, return the error:

    // Define divider as a syncrhonous function
    var divideSync = function(x,y) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by returning it
            return new Error("Can't divide by zero")
        }
        else {
            // no error occured, continue on
            return x/y
        }
    }
    
    // Divide 4/2
    var result = divideSync(4,2)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/2=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/2='+result)
    }
    
    // Divide 4/0
    result = divideSync(4,0)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/0=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/0='+result)
    }
    
  • For callback-based (ie. asynchronous) code, the first argument of the callback is err, if an error happens err is the error, if an error doesn't happen then err is null. Any other arguments follow the err argument:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    divide(4,2,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/2=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/2='+result)
        }
    })
    
    divide(4,0,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/0=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/0='+result)
        }
    })
    
  • For eventful code, where the error may happen anywhere, instead of throwing the error, fire the error event instead:

    // Definite our Divider Event Emitter
    var events = require('events')
    var Divider = function(){
        events.EventEmitter.call(this)
    }
    require('util').inherits(Divider, events.EventEmitter)
    
    // Add the divide function
    Divider.prototype.divide = function(x,y){
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by emitting it
            var err = new Error("Can't divide by zero")
            this.emit('error', err)
        }
        else {
            // no error occured, continue on
            this.emit('divided', x, y, x/y)
        }
    
        // Chain
        return this;
    }
    
    // Create our divider and listen for errors
    var divider = new Divider()
    divider.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    divider.on('divided', function(x,y,result){
        console.log(x+'/'+y+'='+result)
    })
    
    // Divide
    divider.divide(4,2).divide(4,0)
    

Safely "catching" errors

Sometimes though, there may still be code that throws an error somewhere which can lead to an uncaught exception and a potential crash of our application if we don't catch it safely. Depending on our code architecture we can use one of the following methods to catch it:

  • When we know where the error is occurring, we can wrap that section in a node.js domain

    var d = require('domain').create()
    d.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    
    // catch the uncaught errors in this asynchronous or synchronous code block
    d.run(function(){
        // the asynchronous or synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    })
    
  • If we know where the error is occurring is synchronous code, and for whatever reason can't use domains (perhaps old version of node), we can use the try catch statement:

    // catch the uncaught errors in this synchronous code block
    // try catch statements only work on synchronous code
    try {
        // the synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    } catch (err) {
        // handle the error safely
        console.log(err)
    }
    

    However, be careful not to use try...catch in asynchronous code, as an asynchronously thrown error will not be caught:

    try {
        setTimeout(function(){
            var err = new Error('example')
            throw err
        }, 1000)
    }
    catch (err) {
        // Example error won't be caught here... crashing our app
        // hence the need for domains
    }
    

    If you do want to work with try..catch in conjunction with asynchronous code, when running Node 7.4 or higher you can use async/await natively to write your asynchronous functions.

    Another thing to be careful about with try...catch is the risk of wrapping your completion callback inside the try statement like so:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    var continueElsewhere = function(err, result){
            throw new Error('elsewhere has failed')
    }
    
    try {
            divide(4, 2, continueElsewhere)
            // ^ the execution of divide, and the execution of 
            //   continueElsewhere will be inside the try statement
    }
    catch (err) {
            console.log(err.stack)
            // ^ will output the "unexpected" result of: elsewhere has failed
    }
    

    This gotcha is very easy to do as your code becomes more complex. As such, it is best to either use domains or to return errors to avoid (1) uncaught exceptions in asynchronous code (2) the try catch catching execution that you don't want it to. In languages that allow for proper threading instead of JavaScript's asynchronous event-machine style, this is less of an issue.

  • Finally, in the case where an uncaught error happens in a place that wasn't wrapped in a domain or a try catch statement, we can make our application not crash by using the uncaughtException listener (however doing so can put the application in an unknown state):

    // catch the uncaught errors that weren't wrapped in a domain or try catch statement
    // do not use this in modules, but only in applications, as otherwise we could have multiple of these bound
    process.on('uncaughtException', function(err) {
        // handle the error safely
        console.log(err)
    })
    
    // the asynchronous or synchronous code that emits the otherwise uncaught error
    var err = new Error('example')
    throw err
    

range() for floats

You can either use:

[x / 10.0 for x in range(5, 50, 15)]

or use lambda / map:

map(lambda x: x/10.0, range(5, 50, 15))

Android: adb pull file on desktop

Note need root than:

  • adb root
  • adb pull /data/data/com.google.android.apps.nexuslauncher/databases/launcher.db launcher.db

Bash script to run php script

If you have PHP installed as a command line tool (try issuing php to the terminal and see if it works), your shebang (#!) line needs to look like this:

#!/usr/bin/php

Put that at the top of your script, make it executable (chmod +x myscript.php), and make a Cron job to execute that script (same way you'd execute a bash script).

You can also use php myscript.php.

Oracle - What TNS Names file am I using?

Not direct answer to your question, but I've been quite frustrated myself trying find and update all of the tnsnames files, as I had several oracle installs: Client, BI tools, OWB, etc, each of which had its own oracle home. I ended up creating a utility called TNSNamesSync that will update all of the tnsnames in all of the oracle homes. It's under the MIT license, free to use here https://github.com/artybug/TNSNamesSync/releases

The docs are here: https://github.com/artchik/TNSNamesSync/blob/master/README.md

This is for Windows only, though.

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

Easiest way is to do this from your accounts with Xcode:

Head over Xcode -> Preferences -> Choose Accounts Tab -> View Details -> Hit refresh button on the bottom left -> Done.

Build again and it should work.

Scroll to the top of the page using JavaScript?

Pure JavaScript solution:

function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
});

I write an animated solution on Codepen

Also, you can try another solution with CSS scroll-behavior: smooth property.

html {
    scroll-behavior: smooth;
}

@media (prefers-reduced-motion: reduce) {
    html {
        scroll-behavior: auto;
    }
}

Order discrete x scale by frequency/value

The best way for me was using vector with categories in order I need as limits parameter to scale_x_discrete. I think it is pretty simple and straightforward solution.

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar() + 
  scale_x_discrete(limits=c(8,4,6))

enter image description here

Pass Javascript Array -> PHP

You can transfer array from javascript to PHP...

Javascript... ArraySender.html

<script language="javascript">

//its your javascript, your array can be multidimensional or associative

plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info'; 
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3'; 
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4'; 
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5'; 

function convertJsArr2Php(JsArr){
    var Php = '';
    if (Array.isArray(JsArr)){  
        Php += 'array(';
        for (var i in JsArr){
            Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
            if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
                Php += ', ';
            }
        }
        Php += ')';
        return Php;
    }
    else{
        return '\'' + JsArr + '\'';
    }
}


function ajaxPost(str, plArrayC){
    var xmlhttp;
    if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
    else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
    xmlhttp.open("POST",str,true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send('Array=' + plArrayC);
}

ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>

and PHP Code... ArrayReader.php

<?php 

eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);

?>

Task<> does not contain a definition for 'GetAwaiter'

I had the same issue, I had to remove the async keyword from the method and also remove the await keyword from the calling method to use getawaiter() without any error.

View array in Visual Studio debugger?

If you have a large array and only want to see a subsection of the array you can type this into the watch window;

ptr+100,10

to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.

How can I get the list of files in a directory using C or C++?

System call it!

system( "dir /b /s /a-d * > file_names.txt" );

Then just read the file.

EDIT: This answer should be considered a hack, but it really does work (albeit in a platform specific way) if you don't have access to more elegant solutions.

How to add multiple jar files in classpath in linux

Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do

$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java

To run do

$java -cp .:a.jar:b.jar:c.jar HelloWorld

Handling identity columns in an "Insert Into TABLE Values()" statement?

By default, if you have an identity column, you do not need to specify it in the VALUES section. If your table is:

ID    NAME    ADDRESS

Then you can do:

INSERT INTO MyTbl VALUES ('Joe', '123 State Street, Boston, MA')

This will auto-generate the ID for you, and you don't have to think about it at all. If you SET IDENTITY_INSERT MyTbl ON, you can assign a value to the ID column.

Get url parameters from a string in .NET

This is probably what you want

var uri = new Uri("http://domain.test/Default.aspx?var1=true&var2=test&var3=3");
var query = HttpUtility.ParseQueryString(uri.Query);

var var2 = query.Get("var2");

How to format a QString?

You can use QString.arg like this

QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"

This method is preferred over sprintf because:

Changing the position of the string without having to change the ordering of substitution, e.g.

// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");

Or, changing the type of the arguments doesn't require changing the format string, e.g.

// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));

As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.

One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.

UPDATE: Examples are updated thanks to Frank Osterfeld.

UPDATE: Examples are updated thanks to alexisdm.

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

The method tf.shape is a TensorFlow static method. However, there is also the method get_shape for the Tensor class. See

https://www.tensorflow.org/api_docs/python/tf/Tensor#get_shape

What is the right way to populate a DropDownList from a database?

I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.

You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.

<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
    <Columns>
        <asp:TemplateField HeaderText="Subjects">
            <ItemTemplate>
                <asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
                </asp:DropDownList>
                <asp:SqlDataSource ID="sdsSubjects" runat="server"
                    SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

GROUP_CONCAT ORDER BY

You can use SEPARATOR and ORDER BY inside the GROUP_CONCAT function in this way:

SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC SEPARATOR ',') 
AS views, group_concat(li.percentage ORDER BY li.percentage ASC SEPARATOR ',') FROM li
GROUP BY client_id;

ESRI : Failed to parse source map

Source code of CSS/JS we usually minified/compress. Now if we want to debug those minified files then we have to add following line at the end of minified file

/*# sourceMappingURL=bootstrap.min.css.map */

This tells compiler where is source file actually mapped.

In the case of JS its make sense
but in the case of CSS, its actually debugging of SCSS.

To Remove Warning: remove /*# sourceMappingURL=bootstrap.min.css.map */ from the end of minified file, .

if (select count(column) from table) > 0 then

not so elegant but you dont need to declare any variable:

for k in (select max(1) from table where 1 = 1) loop
    update x where column = value;
end loop;

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Raise an error manually in T-SQL to jump to BEGIN CATCH block

SQL has an error raising mechanism

RAISERROR ( { msg_id | msg_str | @local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n ] ]

Just look up Raiserror in the Books Online. But.. you have to generate an error of the appropriate severity, an error at severity 0 thru 10 do not cause you to jump to the catch block.

error C2039: 'string' : is not a member of 'std', header file problem

Take care not to include

#include <string.h> 

but only

#include <string>

It took me 1 hour to find this in my code.

Hope this can help

how to set length of an column in hibernate with maximum length

Use @Column annotation and define its length attribute. Check Hibernate's documentation for references (section 2.2.2.3).

How to download PDF automatically using js?

It is also possible to open the pdf link in a new window and let the browser handle the rest:

window.open(pdfUrl, '_blank');

or:

window.open(pdfUrl);

Passing Javascript variable to <a href >

put id attribute on anchor element

<a id="link2">

set href attribute on page load event:

(function() {
    var scrt_var = 10;
    var strLink = "2.html&Key=" + scrt_var;
    document.getElementById("link2").setAttribute("href",strLink);
})();

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

This isn't a direct answer, but I think it is a pretty sweet alternative.

http://www.s3auth.com/

It allows you to host your pages behind basic auth. Great for things like api docs in your private github repo. just ad a s3 put as part of your api build.

Run bash command on jenkins pipeline

For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash), and simply run it with sh from Jenkinsfile:

sh 'chmod +x ./script.sh'
sh './script.sh'

Setting max-height for table cell contents

Possibly not cross browser but I managed get this: http://jsfiddle.net/QexkH/

basically it requires a fixed height header and footer. and it absolute positions the table.

    table {
        width: 50%;
        height: 50%;
        border-spacing: 0;
        position:absolute;
    }
    td {
        border: 1px solid black;
    }
    #content {
        position:absolute;
        width:100%;
        left:0px;
        top:20px;
        bottom:20px;
        overflow: hidden;
    }

Change the borderColor of the TextBox

You can handle WM_NCPAINT message of TextBox and draw a border on the non-client area of control if the control has focus. You can use any color to draw border:

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ExTextBox : TextBox
{
    [DllImport("user32")]
    private static extern IntPtr GetWindowDC(IntPtr hwnd);
    private const int WM_NCPAINT = 0x85;
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_NCPAINT && this.Focused)
        {
            var dc = GetWindowDC(Handle);
            using (Graphics g = Graphics.FromHdc(dc))
            {
                g.DrawRectangle(Pens.Red, 0, 0, Width - 1, Height - 1);
            }
        }
    }
}

Result

The painting of borders while the control is focused is completely flicker-free:

Change TextBox border color on focus

BorderColor property for TextBox

In the current post I just change the border color on focus. You can also add a BorderColor property to the control. Then you can change border-color based on your requirement at design-time or run-time. I've posted a more completed version of TextBox which has BorderColor property: in the following post:

Change Textbox border color

How do I move a file (or folder) from one folder to another in TortoiseSVN?

Subversion does not yet have a first-class rename operations.

There's a 6-year-old bug on the problem: http://subversion.tigris.org/issues/show_bug.cgi?id=898

It's being considered for 1.6, now that merge tracking (a higher priority) has been added (in 1.5).

Duplicate Entire MySQL Database

Once upon a time in MySQL you could just copy all the table files to another directory in the mysql tree

mysql cli - create database db2

linux cli - cp db1 db2

How to remove the last element added into the List?

The direct answer to this question is:

if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
    rows.RemoveAt(rows.Count - 1);
}

However... in the specific case of this question, it makes more sense not to add the row in the first place:

Row row = new Row();
//...      

if (!row.cell[0].Equals("Something"))
{
    rows.Add(row);
}

TBH, I'd go a step further by testing "Something" against user."", and not even instantiating a Row unless the condition is satisfied, but seeing as user."" won't compile, I'll leave that as an exercise for the reader.

Get all child elements

Another veneration of find_elements_by_xpath(".//*") is:

from selenium.webdriver.common.by import By


find_elements(By.XPATH, ".//*")

What is the correct way of reading from a TCP socket in C/C++?

Several pointers:

You need to handle a return value of 0, which tells you that the remote host closed the socket.

For nonblocking sockets, you also need to check an error return value (-1) and make sure that errno isn't EINPROGRESS, which is expected.

You definitely need better error handling - you're potentially leaking the buffer pointed to by 'buffer'. Which, I noticed, you don't allocate anywhere in this code snippet.

Someone else made a good point about how your buffer isn't a null terminated C string if your read() fills the entire buffer. That is indeed a problem, and a serious one.

Your buffer size is a bit small, but should work as long as you don't try to read more than 256 bytes, or whatever you allocate for it.

If you're worried about getting into an infinite loop when the remote host sends you a malformed message (a potential denial of service attack) then you should use select() with a timeout on the socket to check for readability, and only read if data is available, and bail out if select() times out.

Something like this might work for you:

fd_set read_set;
struct timeval timeout;

timeout.tv_sec = 60; // Time out after a minute
timeout.tv_usec = 0;

FD_ZERO(&read_set);
FD_SET(socketFileDescriptor, &read_set);

int r=select(socketFileDescriptor+1, &read_set, NULL, NULL, &timeout);

if( r<0 ) {
    // Handle the error
}

if( r==0 ) {
    // Timeout - handle that. You could try waiting again, close the socket...
}

if( r>0 ) {
    // The socket is ready for reading - call read() on it.
}

Depending on the volume of data you expect to receive, the way you scan the entire message repeatedly for the "end;" token is very inefficient. This is better done with a state machine (the states being 'e'->'n'->'d'->';') so that you only look at each incoming character once.

And seriously, you should consider finding a library to do all this for you. It's not easy getting it right.

Extract code country from phone number [libphonenumber]

Use a try catch block like below:

try { 

const phoneNumber = this.phoneUtil.parseAndKeepRawInput(value, this.countryCode);

}catch(e){}

Excel: Use a cell value as a parameter for a SQL query

queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value

Debug vs Release in CMake

// CMakeLists.txt : release

set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)

// CMakeLists.txt : debug

set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)

What's the strangest corner case you've seen in C# or .NET?

Few years ago, when working on loyality program, we had an issue with the amount of points given to customers. The issue was related to casting/converting double to int.

In code below:

double d = 13.6;

int i1 = Convert.ToInt32(d);
int i2 = (int)d;

does i1 == i2 ?

It turns out that i1 != i2. Because of different rounding policies in Convert and cast operator the actual values are:

i1 == 14
i2 == 13

It's always better to call Math.Ceiling() or Math.Floor() (or Math.Round with MidpointRounding that meets our requirements)

int i1 = Convert.ToInt32( Math.Ceiling(d) );
int i2 = (int) Math.Ceiling(d);

Is it possible to break a long line to multiple lines in Python?

There is more than one way to do it.

1). A long statement:

>>> def print_something():
         print 'This is a really long line,', \
               'but we can make it across multiple lines.'

2). Using parenthesis:

>>> def print_something():
        print ('Wow, this also works?',
               'I never knew!')

3). Using \ again:

>>> x = 10
>>> if x == 10 or x > 0 or \
       x < 100:
       print 'True'

Quoting PEP8:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

Cast Double to Integer in Java

Indeed, the simplest way is to use intValue(). However, this merely returns the integer part; it does not do any rounding. If you want the Integer nearest to the Double value, you'll need to do this:

Integer integer = Integer.valueOf((int) Math.round(myDouble)));

And don't forget the null case:

Integer integer = myDouble == null ? null : Integer.valueOf((int) Math.round(myDouble)));

Math.round() handles odd duck cases, like infinity and NaN, with relative grace.

Serializing and submitting a form with jQuery and PHP

Have you looked in firebug if POST or GET?.

check the console display.

Put in the test script:

console.log(data);

You can see the response from the server, if it shows something.

Angular 2 Routing run in new tab

Try this please, <a target="_blank" routerLink="/Page2">


Update1: Custom directives to the rescue! Full code is here: https://github.com/pokearound/angular2-olnw

import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';

@Directive({ selector: '[olinw007]' })
export class OpenLinkInNewWindowDirective {
    //@Input('olinwLink') link: string; //intro a new attribute, if independent from routerLink
    @Input('routerLink') link: string;
    constructor(private el: ElementRef, @Inject(Window) private win:Window) {
    }
    @HostListener('mousedown') onMouseEnter() {
        this.win.open(this.link || 'main/default');
    }
}

Notice, Window is provided and OpenLinkInNewWindowDirective declared below:

import { AppAboutComponent } from './app.about.component';
import { AppDefaultComponent } from './app.default.component';
import { PageNotFoundComponent } from './app.pnf.component';
import { OpenLinkInNewWindowDirective } from './olinw.directive';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';


const appRoutes: Routes = [
  { path: '', pathMatch: 'full', component: AppDefaultComponent },
  { path: 'home', component: AppComponent },
  { path: 'about', component: AppAboutComponent },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  declarations: [
    AppComponent, AppAboutComponent, AppDefaultComponent, PageNotFoundComponent, OpenLinkInNewWindowDirective
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [{ provide: Window, useValue: window }],
  bootstrap: [AppComponent]
})
export class AppModule { }

First link opens in new Window, second one will not:

<h1>
    {{title}}
    <ul>
        <li><a routerLink="/main/home" routerLinkActive="active" olinw007> OLNW</a></li>
        <li><a routerLink="/main/home" routerLinkActive="active"> OLNW - NOT</a></li>
    </ul>
    <div style="background-color:#eee;">
        <router-outlet></router-outlet>
    </div>
</h1>

Tada! ..and you are welcome =)

Update2: As of v2.4.10 <a target="_blank" routerLink="/Page2"> works

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

How do you find the first key in a dictionary?

Update: as of Python 3.7, insertion order is maintained, so you don't need an OrderedDict here. You can use the below approaches with a normal dict

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

source


Python 3.6 and earlier*

If you are talking about a regular dict, then the "first key" doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your dict you will likely not get "banana" as the first thing you see.

If you need to keep things in order, then you have to use an OrderedDict and not just a plain dictionary.

import collections
prices  = collections.OrderedDict([
        ("banana", 4),
        ("apple", 2),
        ("orange", 1.5),
        ("pear", 3),
])

If you then wanted to see all the keys in order you could do so by iterating through it

for k in prices:
    print(k)

You could, alternatively put all of the keys into a list and then work with that

ks = list(prices)
print(ks[0]) # will print "banana"

A faster way to get the first element without creating a list would be to call next on the iterator. This doesn't generalize nicely when trying to get the nth element though

>>> next(iter(prices))
'banana'

* CPython had guaranteed insertion order as an implementation detail in 3.6.

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

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

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

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

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

ALTER TABLE ReferencingTable DROP 
   CONSTRAINT fk__ReferencingTable__MainTable;

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

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

Change icons of checked and unchecked for Checkbox for Android

I realize this is an old question, and the OP is talking about using custom gx that aren't necessary 'checkbox'-looking, but there is a fantastic resource for generating custom colored assets here: http://kobroor.pl/

Just give it the relevant details and it spits out graphics, complete with xml resources, that you can just drop right in.

Java HashMap: How to get a key and value by index?

If you don't care about the actual key, a concise way to iterate over all the Map's values would be to use its values() method

Map<String, List<String>> myMap;

for ( List<String> stringList : myMap.values() ) {
    for ( String myString : stringList ) {
        // process the string here
    }
}

The values() method is part of the Map interface and returns a Collection view of the values in the map.

Download image with JavaScript

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo

How do I make a text input non-editable?

Add readonly:

<input type="text" value="3" class="field left" readonly>

If you want the value to be not submitted in a form, instead add the disabled attribute.

<input type="text" value="3" class="field left" disabled>

There is no way to use CSS that always works to do this.

Why? CSS can't "disable" anything. You can still turn off display or visibility and use pointer-events: none but pointer-events doesn't work on versions of IE that came out earlier than IE 11.

How to open local files in Swagger-UI

Use the spec parameter.

Instructions below.

Create spec.js file containing Swagger JSON

Create a new javascript file in the same directory as index.html (/dist/)

Then insert spec variable declaration:

var spec = 

Then paste in the swagger.json file contents after. It does not have to be on the same line as the = sign.

Example:

var spec =

{
    "swagger": "2.0",
    "info": {
        "title": "I love Tex-Mex API",
        "description": "You can barbecue it, boil it, broil it, bake it, sauté it. Dey's uh, Tex-Mex-kabobs, Tex-Mex creole, Tex-Mex gumbo. Pan fried, deep fried, stir-fried. There's pineapple Tex-Mex, lemon Tex-Mex, coconut Tex-Mex, pepper Tex-Mex, Tex-Mex soup, Tex-Mex stew, Tex-Mex salad, Tex-Mex and potatoes, Tex-Mex burger, Tex-Mex sandwich..",
        "version": "1.0.0"
    },
    ...
    }
}

Modify Swagger UI index.html

This is a two-step like Ciara.

Include spec.js

Modify the /dist/index.html file to include the external spec.js file.

 <script src='spec.js' type="text/javascript"></script>

Example:

  <!-- Some basic translations -->
  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
  <!-- <script src='lang/en.js' type='text/javascript'></script> -->

  <!-- Original file pauses -->
  <!-- Insert external modified swagger.json -->
  <script src='spec.js' type="text/javascript"></script>
  <!-- Original file resumes -->

  <script type="text/javascript">

    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "http://petstore.swagger.io/v2/swagger.json";
      }

Add spec parameter

Modify the SwaggerUi instance to include the spec parameter:

  window.swaggerUi = new SwaggerUi({
    url: url,
    spec: spec,
    dom_id: "swagger-ui-container",

How to strip HTML tags from a string in SQL Server?

While Arvin Amir's answer comes close to a full one-line solution you can drop in anywhere; he's got a slight bug in his select statement (missing the end of the line), and I wanted to handle the most common character references.

What I ended up doing was this:

SELECT replace(replace(replace(CAST(CAST(replace([columnNameHere], '&', '&amp;') as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max)), '&amp;', '&'), '&nbsp;', ' '), '&#x20;', ' ')
FROM [tableName]

Without the character reference code it can be simplified to this:

SELECT CAST(CAST([columnNameHere] as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max))
FROM [tableName]

Google Apps Script to open a URL

There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.

window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)

openUrl.html

<!DOCTYPE html>
<html>
  <head>
   <base target="_blank">
    <script>
     var url1 ='https://stackoverflow.com/a/54675103';
     var winRef = window.open(url1);
     winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
     window.onload=function(){document.getElementById('url').href = url1;}
    </script>
  </head>
  <body>
    Kindly allow pop ups</br>
    Or <a id='url'>Click here </a>to continue!!!
  </body>
</html>

code.gs:

function modalUrl(){
  SpreadsheetApp.getUi()
   .showModalDialog(
     HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
     'Opening StackOverflow'
   )
}    

@Scope("prototype") bean scope not creating new bean

Scope prototype means that every time you ask spring (getBean or dependency injection) for an instance it will create a new instance and give a reference to that.

In your example a new instance of LoginAction is created and injected into your HomeController . If you have another controller into which you inject LoginAction you will get a different instance.

If you want a different instance for each call - then you need to call getBean each time - injecting into a singleton bean will not achieve that.

Given URL is not permitted by the application configuration

  1. From the menu item of your app name which is located on the top left corner, create a test app.
  2. In the settings section of the new test app: add 'http://localhost:3000' to the Website url and add 'localhost' to App domains.
  3. Update your app with the new Facebook APP Id
  4. Use Facebook sdk v2.2 or whatever the latest in your app.

What should I do when 'svn cleanup' fails?

Subclipse gets confused by Windows' truly diabolical locking behaviour. Unlocker is your friend. This can find locked files and forcibly release the locks.