Programs & Examples On #Extended procedures

Extended stored procedures let you create your own external routines in a programming language such as C

No route matches "/users/sign_out" devise rails 3

Add:

  <%= csrf_meta_tag %>  and 
  <%= javascript_include_tag :defaults %>  to layouts

Use these link_to tags

 link_to 'Sign out', destroy_user_session_path, :method => :delete

  or

 link_to 'Sign out', '/users/sign_out', :method => :delete

In routes add:

  devise_for :users do
    get '/users/sign_out' => 'devise/sessions#destroy'
  end

java: Class.isInstance vs Class.isAssignableFrom

For brevity, we can understand these two APIs like below:

  1. X.class.isAssignableFrom(Y.class)

If X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

  1. X.class.isInstance(y)

Say y is an instance of class Y, if X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

d3 add text to circle

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:

enter image description here

The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header.

The main code is:

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)

d3.json("data.json", function(json) {
    /* Define the data for the circles */
    var elem = svg.selectAll("g")
        .data(json.nodes)

    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .attr("transform", function(d){return "translate("+d.x+",80)"})

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", function(d){return d.r} )
        .attr("stroke","black")
        .attr("fill", "white")

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})
        .text(function(d){return d.label})
})

and the json file is:

{"nodes":[
  {"x":80, "r":40, "label":"Node 1"}, 
  {"x":200, "r":60, "label":"Node 2"}, 
  {"x":380, "r":80, "label":"Node 3"}
]}

The resulting html code shows the encapsulation you want:

<svg width="960" height="500">
    <g transform="translate(80,80)">
        <circle r="40" stroke="black" fill="white"></circle>
        <text dx="-20">Node 1</text>
    </g>
    <g transform="translate(200,80)">
        <circle r="60" stroke="black" fill="white"></circle>
        <text dx="-20">Node 2</text>
    </g>
    <g transform="translate(380,80)">
        <circle r="80" stroke="black" fill="white"></circle>
        <text dx="-20">Node 3</text>
    </g>
</svg>

Getting an attribute value in xml element

Below is the code to do it in vtd-xml. It basically queries the XML with the XPath of "/xml/item/@name."

import com.ximpleware.*;

public class getAttrs{

   public static void main(String[] s) throws VTDException{
         VTDGen vg = new VTDGen();
         if (!vg.parseFile("input.xml",false)) // turn off namespace
              return;
         VTDNav vn = vg.getNav();
         AutoPilot ap =  new AutoPilot(vn);
         ap.selectXPath("/xml/item/@name");
         int i=0;
         while( (i=ap.evalXPath())!=-1){
              System.out.println(" item name is ===>"+vn.toString(i+1)); 
         }
   }
}

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

Pre Java 6 the DriverManager class wouldn't have known which JDBC driver you wanted to use. Class.forName("...") was a way on pre-loading the driver classes.

If you are using Java 6 you no longer need to do this.

Add rows to CSV File in powershell

Simple to me is like this:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"

"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables

If you have a lot of columns, then create a variable like $NewRow like:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).

$NewRow | Add-Content -Path $File # Keep no space between content variables

Please note the difference between Set-Content (overwrites the existing contents) and Add-Content (appends to the existing contents) of the file.

How do I get unique elements in this array?

You can just use the method uniq. Assuming your array is ary, call:

ary.uniq{|x| x.user_id}

and this will return a set with unique user_ids.

Moment Js UTC to Local Time

To convert UTC time to Local you have to use moment.local().

For more info see docs

Example:

var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');

console.log(date); // 2015-09-13 03:39:27

var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');

console.log(local); // 2015-09-13 09:39:27

Demo:

_x000D_
_x000D_
var date = moment.utc().format();_x000D_
console.log(date, "- now in UTC"); _x000D_
_x000D_
var local = moment.utc(date).local().format();_x000D_
console.log(local, "- UTC now to local"); 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Is there a way to make Firefox ignore invalid ssl-certificates?

Go to Tools > Options > Advanced "Tab"(?) > Encryption Tab

Click the "Validation" button, and uncheck the checkbox for checking validity

Be advised though that this is pretty unsecure as it leaves you wide open to accept any invalid certificate. I'd only do this if using the browser on an Intranet where the validity of the cert isn't a concern to you, or you aren't concerned in general.

Passing 'this' to an onclick event

You can always call funciton differently: foo.call(this); in this way you will be able to use this context inside the function.

Example:

<button onclick="foo.call(this)" id="bar">Button</button>?

var foo = function()
{
    this.innerHTML = "Not a button";
};

Get visible items in RecyclerView

Addendum:

The proposed functions findLast...Position() do not work correctly in a scenario with a collapsing toolbar while the toolbar is expanded.

It seems that the recycler view has a fixed height, and while the toolbar is expanded, the recycler is moved down, partially out of the screen. As a consequence the results of the proposed functions are too high. Example: The last visible item is told to be #9, but in fact item #7 is the last one that is on screen.

This behaviour is also the reason why my view often failed to scroll to the correct position, i.e. scrollToPosition() did not work correctly (I finally collapsed the toolbar programmatically).

How to enter ssh password using bash?

Create a new keypair: (go with the defaults)

ssh-keygen

Copy the public key to the server: (password for the last time)

ssh-copy-id [email protected]

From now on the server should recognize your key and not ask you for the password anymore:

ssh [email protected]

How do I interpret precision and scale of a number in a database?

Precision, Scale, and Length in the SQL Server 2000 documentation reads:

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.

Chart creating dynamically. in .net, c#

Try to include these lines on your code, after mych.Visible = true;:

ChartArea chA = new ChartArea();
mych.ChartAreas.Add(chA);

Get a CSS value with JavaScript

Use the following. It helped me.

document.getElementById('image_1').offsetTop

See also Get Styles.

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

Remove the Newtonsoft.Json assembly from the project reference and add it again. You probably deleted or replaced the dll by accident.

How to scroll to specific item using jQuery?

For what it's worth, this is how I managed to achieve such behavior for a general element which can be inside a DIV with scrolling (without knowing the container)

It creates a fake input of the height of the target element, and then puts a focus to it, and the browser will take care about the rest no matter how deep within the scrollable hierarchy you are. Works like a charm.

var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');

$scrollTo.prepend(inputElem);
inputElem.css({
  position: 'absolute',
  width: '1px',
  height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();

Using NSLog for debugging

The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:

Instead of:

NSString *digit = [[sender titlelabel] text];
NSLog(digit);

Use:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);

It will still work doing that first way, but doing it this way will get rid of the warning.

Node.js: How to read a stream into a buffer?

You can convert your readable stream to a buffer and integrate it in your code in an asynchronous way like this.

async streamToBuffer (stream) {
    return new Promise((resolve, reject) => {
      const data = [];

      stream.on('data', (chunk) => {
        data.push(chunk);
      });

      stream.on('end', () => {
        resolve(Buffer.concat(data))
      })

      stream.on('error', (err) => {
        reject(err)
      })
   
    })
  }

the usage would be as simple as:

 // usage
  const myStream // your stream
  const buffer = await streamToBuffer(myStream) // this is a buffer

jQuery Selector: Id Ends With?

In order to find an iframe id ending with "iFrame" within a page containing many iframes.

jQuery(document).ready(function (){     
                  jQuery("iframe").each(function(){                     
                    if( jQuery(this).attr('id').match(/_iFrame/) ) {
                            alert(jQuery(this).attr('id'));

                     }                   
                  });     
         });

How to format a floating number to fixed width in Python

In python3 the following works:

>>> v=10.4
>>> print('% 6.2f' % v)
  10.40
>>> print('% 12.1f' % v)
        10.4
>>> print('%012.1f' % v)
0000000010.4

How to program a delay in Swift 3

After a lot of research, I finally figured this one out.

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
   // Code you want to be delayed
}

This creates the desired "wait" effect in Swift 3 and Swift 4.

Inspired by a part of this answer.

Lotus Notes email as an attachment to another email

Tested vith Notes versions 6.5.x and 7.0.x From your Lotus Notes inbox

  1. Open the message
  2. Click View > Show > Page Source
  3. Copy all the data into a text file and save the file with .eml extension.
  4. Create a new message
  5. Attach the .eml file(s) and send the new message

Hop this helps. I have no client on my current machine but will test from home on 8.5.1

Representing Directory & File Structure in Markdown Syntax

I followed an example in another repository and wrapped the directory structure within a pair of triple backticks (```):

```
project
¦   README.md
¦   file001.txt    
¦
+---folder1
¦   ¦   file011.txt
¦   ¦   file012.txt
¦   ¦
¦   +---subfolder1
¦       ¦   file111.txt
¦       ¦   file112.txt
¦       ¦   ...
¦   
+---folder2
    ¦   file021.txt
    ¦   file022.txt
```

Printing Even and Odd using two Threads in Java

public class Multi extends Thread{  
    public static int a;
    static{a=1;}
    public void run(){  
        for(int i=1;i<5;i++){  
        System.out.println("Thread Id  "+this.getId()+"  Value "+a++);
        try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  

        }  
    }  
public static void main(String args[]){  
       Multi t1=new Multi();  
       Multi t2=new Multi();  

      t1.start();  
      t2.start();  
    }  
}  

Android Percentage Layout Height

With introduction of ContraintLayout, it's possible to implement with Guidelines:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.eugene.test1.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#AAA"
        android:text="TextView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/guideline" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

</android.support.constraint.ConstraintLayout>

Result View

You can read more in this article Building interfaces with ConstraintLayout.

React - uncaught TypeError: Cannot read property 'setState' of undefined

  1. Check state check state whether you create particular property or not

_x000D_
_x000D_
this.state = {_x000D_
            name: "",_x000D_
            email: ""_x000D_
            }_x000D_
            _x000D_
           _x000D_
            _x000D_
this.setState(() => ({ _x000D_
             comments: comments          //comments not available in state_x000D_
             })) 
_x000D_
_x000D_
_x000D_

2.Check the (this) if you doing setState inside any function (i.e handleChange) check whether the function bind to this or the function should be arrow function .

## 3 ways for binding this to the below function##

_x000D_
_x000D_
//3 ways for binding this to the below function_x000D_
_x000D_
handleNameChange(e) {  _x000D_
     this.setState(() => ({ name }))_x000D_
    }_x000D_
    _x000D_
// 1.Bind while callling function_x000D_
      onChange={this.handleNameChange.bind(this)}_x000D_
      _x000D_
      _x000D_
//2.make it as arrow function_x000D_
     handleNameChange((e)=> {  _x000D_
     this.setState(() => ({ name }))_x000D_
     })_x000D_
    _x000D_
//3.Bind in constuctor _x000D_
_x000D_
constructor(props) {_x000D_
        super(props)_x000D_
        this.state = {_x000D_
            name: "",_x000D_
            email: ""_x000D_
        }_x000D_
        this.handleNameChange = this.handleNameChange.bind(this)_x000D_
        }
_x000D_
_x000D_
_x000D_

Using TortoiseSVN via the command line

After selecting "SVN command line tools" it will become like this:

Enter image description here

Use jquery click to handle anchor onClick()

Lets take an anchor tag with an onclick event, that calls a Javascript function.

<a href="#" onClick="showDiv(1);">1</a>

Now in javascript write the below code

function showDiv(pageid)
{
   alert(pageid);
}

This will show you an alert of "1"....

Disable elastic scrolling in Safari

I made an extension to disable it on all sites. In doing so I used three techniques: pure CSS, pure JS and hybrid.

The CSS version is similar to the above solutions. The JS one goes a bit like this:

var scroll = function(e) {
    // compute state
    if (stopScrollX || stopScrollY) {
        e.preventDefault();              // this one is the key
        e.stopPropagation();
        window.scroll(scrollToX, scrollToY);
    }
}

document.addEventListener('mousewheel', scroll, false);

The CSS one works when one is using position: fixed elements and let the browser do the scrolling. The JS one is needed when some other JS depends on window (e.g events), which would get blocked by the previous CSS (since it makes the body scroll instead of the window), and works by stopping event propagation at the edges, but needs to synthesize the scrolling of the non-edge component; the downside is that it prevents some types of scrolling to happen (those do work with the CSS one). The hybrid one tries to take a mixed approach by selectively disabling directional overflow (CSS) when scrolling reaches an edge (JS), and in theory could work in both cases, but doesn't quite currently as it has some leeway at the limit.

So depending on the implementations of one's website, one needs to either take one approach or the other.

See here if one wants more details: https://github.com/lloeki/unelastic

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had similar problem. I r?n npm cache clear, closed android SDK manager(which was open before) and re-ran npm install -g cordova and that was enough to solve the problem.

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

None of the above answers worked for me but I finally found what my issue was. Hopefully this will help someone down the line.

First run IIS Express from command prompt to validate that the site can or cannot be run

https://docs.microsoft.com/en-us/iis/extensions/using-iis-express/running-iis-express-from-the-command-line

Im my case, i got an error saying that C:\Windows\Microsoft.NET\Framework64\v4.0.30319\CONFIG\web.config had malformed xml on line 14. Looking at that line in the file it just said null null null null null etc.

The fix for me was to replace the web.config file with one from my coworkers. IMPORTANT you must get the file from someone running the same version ie if you are VS2015 get a copy from someone running VS2015. If you get it from someone running a different version you will see an error saying it could not load an assembly from the manifest.

Hopefully this helps someone that has tried all the suggestions above. I think the cause of this for me was updating from trial mode and adding a product key within VS2017

How can I tell if a VARCHAR variable contains a substring?

The standard SQL way is to use like:

where @stringVar like '%thisstring%'

That is in a query statement. You can also do this in TSQL:

if @stringVar like '%thisstring%'

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

Read whole ASCII file into C++ std::string

Try one of these two methods:

string get_file_string(){
    std::ifstream ifs("path_to_file");
    return string((std::istreambuf_iterator<char>(ifs)),
                  (std::istreambuf_iterator<char>()));
}

string get_file_string2(){
    ifstream inFile;
    inFile.open("path_to_file");//open the input file

    stringstream strStream;
    strStream << inFile.rdbuf();//read the file
    return strStream.str();//str holds the content of the file
}

What does bundle exec rake mean?

bundle exec is a Bundler command to execute a script in the context of the current bundle (the one from your directory's Gemfile). rake db:migrate is the script where db is the namespace and migrate is the task name defined.

So bundle exec rake db:migrate executes the rake script with the command db:migrate in the context of the current bundle.

As to the "why?" I'll quote from the bundler page:

In some cases, running executables without bundle exec may work, if the executable happens to be installed in your system and does not pull in any gems that conflict with your bundle.

However, this is unreliable and is the source of considerable pain. Even if it looks like it works, it may not work in the future or on another machine.

Initializing IEnumerable<string> In C#

Ok, adding to the answers stated you might be also looking for

IEnumerable<string> m_oEnum = Enumerable.Empty<string>();

or

IEnumerable<string> m_oEnum = new string[]{};

Git merge two local branches

The answer from the Abiraman was absolutely correct. However, for newbies to git, they might forget to pull the repository. Whenever you want to do a merge from branchB into branchA. First checkout and take pull from branchB (Make sure that, your branch is updated with remote branch)

git checkout branchB
git pull

Now you local branchB is updated with remote branchB Now you can checkout to branchA

git checkout branchA

Now you are in branchA, then you can merge with branchB using following command

git merge branchB

Install .ipa to iPad with or without iTunes

You can also checkout ios-deploy.

It is as simple as running ios-deploy -b path/to/ipa/file.

It even works with path/to/project.app, which should be in the same location if you are doing cordova/phonegap builds locally.

Cheers!

What is the quickest way to HTTP GET in Python?

If you are working with HTTP APIs specifically, there are also more convenient choices such as Nap.

For example, here's how to get gists from Github since May 1st 2014:

from nap.url import Url
api = Url('https://api.github.com')

gists = api.join('gists')
response = gists.get(params={'since': '2014-05-01T00:00:00Z'})
print(response.json())

More examples: https://github.com/kimmobrunfeldt/nap#examples

How can I check that two objects have the same set of property names?

2 Here a short ES6 variadic version:

function objectsHaveSameKeys(...objects) {
   const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
   const union = new Set(allKeys);
   return objects.every(object => union.size === Object.keys(object).length);
}

A little performance test (MacBook Pro - 2,8 GHz Intel Core i7, Node 5.5.0):

var x = {};
var y = {};

for (var i = 0; i < 5000000; ++i) {
    x[i] = i;
    y[i] = i;
}

Results:

objectsHaveSameKeys(x, y) // took  4996 milliseconds
compareKeys(x, y)               // took 14880 milliseconds
hasSameProps(x,y)               // after 10 minutes I stopped execution

Why I got " cannot be resolved to a type" error?

I had this problem while the other class (CarService) was still empty, no methods, nothing. When it had methods and variables, the error was gone.

How do I access nested HashMaps in Java?

I prefer creating a custom map that extends HashMap. Then just override get() to add extra logic so that if the map doesnt contain your key. It will a create a new instance of the nested map, add it, then return it.

public class KMap<K, V> extends HashMap<K, V> {

    public KMap() {
        super();
    }

    @Override
    public V get(Object key) {
        if (this.containsKey(key)) {
            return super.get(key);
        } else {
            Map<K, V> value = new KMap<K, V>();
            super.put((K)key, (V)value);
            return (V)value;
        }
    }
}

Now you can use it like so:

Map<Integer, Map<Integer, Map<String, Object>>> nestedMap = new KMap<Integer, Map<Integer, Map<String, Object>>>();

Map<String, Object> map = (Map<String, Object>) nestedMap.get(1).get(2);
Object obj= new Object();
map.put(someKey, obj);

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

Swift extract regex matches

This is how I did it, I hope it brings a new perspective how this works on Swift.

In this example below I will get the any string between []

var sample = "this is an [hello] amazing [world]"

var regex = NSRegularExpression(pattern: "\\[.+?\\]"
, options: NSRegularExpressionOptions.CaseInsensitive 
, error: nil)

var matches = regex?.matchesInString(sample, options: nil
, range: NSMakeRange(0, countElements(sample))) as Array<NSTextCheckingResult>

for match in matches {
   let r = (sample as NSString).substringWithRange(match.range)//cast to NSString is required to match range format.
    println("found= \(r)")
}

How to run two jQuery animations simultaneously?

While it's true that consecutive calls to animate will give the appearance they are running at the same time, the underlying truth is they're distinct animations running very close to parallel.

To insure the animations are indeed running at the same time use:

$(function() {
    $('#first').animate({..., queue: 'my-animation'});
    $('#second').animate({..., queue: 'my-animation'}).dequeue('my-animation');
});

Further animations can be added to the 'my-animation' queue and all can be initiated provided the last animation dequeue's them.

Cheers, Anthony

How to get the last characters in a String in Java, regardless of String size

This question is the top Google result for "Java String Right".

Surprisingly, no-one has yet mentioned Apache Commons StringUtils.right():

String numbers = org.apache.commons.lang.StringUtils.right( text, 7 );

This also handles the case where text is null, where many of the other answers would throw a NullPointerException.

Modifying list while iterating

The general rule of thumb is that you don't modify a collection/array/list while iterating over it.

Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.

How to check for empty array in vba macro

This code doesn't do what you expect:

If Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

If you pass an empty string ("") or vbNullString to Dir, it will return the name of the first file in the current directory path (the path returned by CurDir$). So, if SigString is empty, your If condition will evaluate to True because Dir will return a non-empty string (the name of the first file in the current directory), and GetBoiler will be called. And if SigString is empty, the call to fso.GetFile will fail.

You should either change your condition to check that SigString isn't empty, or use the FileSystemObject.FileExists method instead of Dir for checking if the file exists. Dir is tricky to use precisely because it does things you might not expect it to do. Personally, I would use Scripting.FileSystemObject over Dir because there's no funny business (FileExists returns True if the file exists, and, well, False if it doesn't). What's more, FileExists expresses the intent of your code much clearly than Dir.

Method 1: Check that SigString is non-empty first

If SigString <> "" And Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

Method 2: Use the FileSystemObject.FileExists method

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")

If fso.FileExists(SigString) Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

Find Locked Table in SQL Server

You can use sp_lock (and sp_lock2), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks:

select  
    object_name(p.object_id) as TableName, 
    resource_type, resource_description
from
    sys.dm_tran_locks l
    join sys.partitions p on l.resource_associated_entity_id = p.hobt_id

How to push a docker image to a private repository

Ref: dock.docker.com

This topic provides basic information about deploying and configuring a registry

Run a local registry

Before you can deploy a registry, you need to install Docker on the host.

Use a command like the following to start the registry container:

start_registry.sh

#!/bin/bash

docker run -d \
  -p 5000:5000 \
  --restart=always \
  --name registry \
  -v /data/registry:/var/lib/registry \
  registry:2

Copy an image from Docker Hub to your registry

  1. Pull the ubuntu:16.04 image from Docker Hub.

    $ docker pull ubuntu:16.04
    
  2. Tag the image as localhost:5000/my-ubuntu. This creates an additional tag for the existing image. When the first part of the tag is a hostname and port, Docker interprets this as the location of a registry, when pushing.

    $ docker tag ubuntu:16.04 localhost:5000/my-ubuntu
    
  3. Push the image to the local registry running at localhost:5000:

    $ docker push localhost:5000/my-ubuntu
    
  4. Remove the locally-cached images. This does not remove the localhost:5000/my-ubuntu image from your registry.

    $ docker image remove ubuntu:16.04
    $ docker image remove localhost:5000/my-ubuntu
    
  5. Pull the localhost:5000/my-ubuntu image from your local registry.

    $ docker pull localhost:5000/my-ubuntu
    
Deploy a plain HTTP registry

According to docs.docker.com, this is very insecure and is not recommended.

  1. Edit the daemon.json file, whose default location is /etc/docker/daemon.json on Linux or C:\ProgramData\docker\config\daemon.json on Windows Server. If you use Docker for Mac or Docker for Windows, click Docker icon -> Preferences -> Daemon, add in the insecure registry.

    If the daemon.json file does not exist, create it. Assuming there are no other settings in the file, it should have the following contents:

    {
      "insecure-registries" : ["myregistrydomain.com:5000"]
    }
    

    With insecure registries enabled, Docker goes through the following steps:

    • First, try using HTTPS.
      • If HTTPS is available but the certificate is invalid, ignore the error about the certificate.
      • If HTTPS is not available, fall back to HTTP.
  2. Restart Docker for the changes to take effect.

Vue component event after render

updated might be what you're looking for. https://vuejs.org/v2/api/#updated

Upload Progress Bar in PHP

A php/ajax progress bar can be done. (Checkout the Html_Ajax library in pear). However this requires installing a custom module into php.

Other methods require using an iframe, through which php looks to see how much of the file has been uploaded. However this hidden iframe, may be blocked by some browsers addons because hidden iframes are often used to send malicious data to a users computer.

Your best bet is to use some form of flash progress bar if you do not have control over your server.

What do .c and .h file extensions mean to C?

They're not really library files. They're just source files. Like Stefano said, the .c file is the C source file which actually uses/defines the actual source of what it merely outlined in the .h file, the header file. The header file usually outlines all of the function prototypes and structures that will be used in the actual source file. Think of it like a reference/appendix. This is evident upon looking at the header file, as you will see :) So then when you want to use something that was written in these source files, you #include the header file, which contains the information that the compiler will need to know.

Parsing JSON in Spring MVC using Jackson JSON

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

Define a Java class that resembles the JSON you will be expecting.

e.g. this JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}

could be mapped to this class:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

For a full working example see this previous answer of mine.

POST: sending a post request in a url itself

Based on what you provided, it is pretty simple for what you need to do and you even have a number of ways to go about doing it. You'll need something that'll let you post a body with your request. Almost any programming language can do this as well as command line tools like cURL.

One you have your tool decided, you'll need to create your JSON body and submit it to the server.

An example using cURL would be (all in one line, minus the \ at the end of the first line):

curl -v -H "Content-Type: application/json" -X POST \
     -d '{"name":"your name","phonenumber":"111-111"}' http://www.abc.com/details

The above command will create a request that should look like the following:

POST /details HTTP/1.1
Host: www.abc.com
Content-Type: application/json
Content-Length: 44

{"name":"your name","phonenumber":"111-111"}

How to delete mysql database through shell command

Another suitable way:

$ mysql -u you -p
<enter password>

>>> DROP DATABASE foo;

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

JUST copy and paste tnsnames and sqlnet files from Oracle home in PLSQL Developer Main folder. Use below Query to get oracle home

select substr(file_spec, 1, instr(file_spec, '\', -1, 2) -1) ORACLE_HOME from dba_libraries where library_name = 'DBMS_SUMADV_LIB';

How to install Ruby 2.1.4 on Ubuntu 14.04

update ubuntu:

 sudo apt-get update
 sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Install rvm, which manages the ruby versions:

to install rvm use the following command.

 \curl -sSL https://get.rvm.io | bash -s stable
 source ~/.bash_profile
 rvm install ruby-2.1.4

Check ruby versions installed and in use:

rvm list
rvm use --default ruby-2.1.4

Find elements inside forms and iframe using Java and Selenium WebDriver

On Selenium >= 3.41 (C#) the rigth syntax is:

webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));

How do I compare two strings in Perl?

print "Matched!\n" if ($str1 eq $str2)

Perl has seperate string comparison and numeric comparison operators to help with the loose typing in the language. You should read perlop for all the different operators.

How to find/identify large commits in git history?

I stumbled across this for the same reason as anyone else. But the quoted scripts didn't quite work for me. I've made one that is more a hybrid of those I've seen and it now lives here - https://gitlab.com/inorton/git-size-calc

PHP's array_map including keys

This is probably the shortest and easiest to reason about:

$states = array('az' => 'Arizona', 'al' => 'Alabama');

array_map(function ($short, $long) {
    return array(
        'short' => $short,
        'long'  => $long
    );
}, array_keys($states), $states);

// produces:
array(
     array('short' => 'az', 'long' => 'Arizona'), 
     array('short' => 'al', 'long' => 'Alabama')
)

$(document).on("click"... not working?

Your code should work, but I'm aware that answer doesn't help you. You can see a working example here (jsfiddle).

Jquery:

$(document).on('click','#test-element',function(){
    alert("You clicked the element with and ID of 'test-element'");
});

As someone already pointed out, you are using an ID instead of a class. If you have more that one element on the page with an ID, then jquery will return only the first element with that ID. There won't be any errors because that's how it works. If this is the problem, then you'll notice that the click event works for the first test-element but not for any that follow.

If this does not accurately describe the symptoms of the problem, then perhaps your selector is wrong. Your update leads me to believe this is the case because of inspecting an element then clicking the page again and triggering the click. What could be causing this is if you put the event listener on the actual document instead of test-element. If so, when you click off the document and back on (like from the developer window back to the document) the event will trigger. If this is the case, you'll also notice the click event is triggered if you click between two different tabs (because they are two different documents and therefore you are clicking the document.

If neither of these are the answer, posting HTML will go a long way toward figuring it out.

How do I push a local Git branch to master branch in the remote?

You can also do it this way to reference the previous branch implicitly:

git checkout mainline
git pull
git merge -
git push

Set QLineEdit to accept only numbers

QLineEdit::setValidator(), for example:

myLineEdit->setValidator( new QIntValidator(0, 100, this) );

or

myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );

See: QIntValidator, QDoubleValidator, QLineEdit::setValidator

MySQL - Make an existing Field Unique

This code is to solve our problem to set unique key for existing table

alter ignore table ioni_groups add unique (group_name);

Using the passwd command from within a shell script

from "man 1 passwd":

   --stdin
          This option is used to indicate that passwd should read the new
          password from standard input, which can be a pipe.

So in your case

adduser "$1"
echo "$2" | passwd "$1" --stdin

[Update] a few issues were brought up in the comments:

Your passwd command may not have a --stdin option: use the chpasswd utility instead, as suggested by ashawley.

If you use a shell other than bash, "echo" might not be a builtin command, and the shell will call /bin/echo. This is insecure because the password will show up in the process table and can be seen with tools like ps.

In this case, you should use another scripting language. Here is an example in Perl:

#!/usr/bin/perl -w
open my $pipe, '|chpasswd' or die "can't open pipe: $!";
print {$pipe} "$username:$password";
close $pipe

Error "The connection to adb is down, and a severe error has occurred."

The killing of the mysteriously running abd.exe worked. This sudden roadblock stopped me for a long time. I was doing all sorts of command line stuff and removed the lock icon from my user folder, but nothing worked until your simple suggestion of looking for the abd in the running processes of the task manager and killing it.

Another newbie roadblock I discovered an answer to: don't run Eclipse when any file other than the main .java file is active. If you run it when, for example, the main.xml file is active, you will get unhelpful error messages, an odd file created like main.xml.out, and it wont run.

Git - how delete file from remote repository

  1. If you want to push a deleted file to remote

git add 'deleted file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote and locally

git rm 'file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote only

git rm --cached 'file name'

git commit -m'message'

git push -u origin branch

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

In general, the key to avoiding an explicit loop would be to join (merge) 2 instances of the dataframe on rowindex-1==rowindex.

Then you would have a big dataframe containing rows of r and r-1, from where you could do a df.apply() function.

However the overhead of creating the large dataset may offset the benefits of parallel processing...

When to use Common Table Expression (CTE)

One of the scenarios I found useful to use CTE is when you want to get DISTINCT rows of data based on one or more columns but return all columns in the table. With a standard query you might first have to dump the distinct values into a temp table and then try to join them back to the original table to retrieve the rest of the columns or you might write an extremely complex partition query that can return the results in one run but in most likelihood, it will be unreadable and cause performance issue.

But by using CTE (as answered by Tim Schmelter on Select the first instance of a record)

WITH CTE AS(
    SELECT myTable.*
    , RN = ROW_NUMBER()OVER(PARTITION BY patientID ORDER BY ID)
    FROM myTable 
)
SELECT * FROM CTE
WHERE RN = 1

As you can see, this is much easier to read and maintain. And in comparison to other queries, is much better at performance.

Set Google Maps Container DIV width and height 100%

You have to set all parent containers to a 100% width if you want to cover the whole page with it. You have to set an absolute value at width and height for the #content div at the very least.

body, html {
  height: 100%;
  width: 100%;
}

div#content {
  width: 100%; height: 100%;
}

Difference between a View's Padding and Margin

Sometimes you can achieve the same result by playing only with padding OR margin. Example :

Say View X contains view Y (aka : View Y is inside View X).

-View Y with Margin=30 OR View X with Padding=30 will achieve the same result: View Y will have an offset of 30.

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 
});

Using jQuery bind() and specififying your desired eventTypes .

making a paragraph in html contain a text from a file

Here is a javascript code I have tested successfully :

    var txtFile = new XMLHttpRequest();
    var allText = "file not found";
    txtFile.onreadystatechange = function () {
        if (txtFile.readyState === XMLHttpRequest.DONE && txtFile.status == 200) {
            allText = txtFile.responseText;
            allText = allText.split("\n").join("<br>");
        }

        document.getElementById('txt').innerHTML = allText;
    }
    txtFile.open("GET", '/result/client.txt', true);
    txtFile.send(null);

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions:

require("util").inspect.defaultOptions.depth = null;
console.log(myObject);

Primitive type 'short' - casting in Java

What language are you using?

Many C based languages have a rule that any mathematical expression is performed in size int or larger. Because of this, once you add two shorts the result is of type int. This causes the need for a cast.

Server.UrlEncode vs. HttpUtility.UrlEncode

Keep in mind that you probably shouldn't be using either one of those methods. Microsoft's Anti-Cross Site Scripting Library includes replacements for HttpUtility.UrlEncode and HttpUtility.HtmlEncode that are both more standards-compliant, and more secure. As a bonus, you get a JavaScriptEncode method as well.

How to make "if not true condition"?

Here is an answer by way of example:

In order to make sure data loggers are online a cron script runs every 15 minutes that looks like this:

#!/bin/bash
#
if ! ping -c 1 SOLAR &>/dev/null
then
  echo "SUBJECT:  SOLAR is not responding to ping" | ssmtp [email protected]
  echo "SOLAR is not responding to ping" | ssmtp [email protected]
else
  echo "SOLAR is up"
fi
#
if ! ping -c 1 OUTSIDE &>/dev/null
then
  echo "SUBJECT:  OUTSIDE is not responding to ping" | ssmtp [email protected]
  echo "OUTSIDE is not responding to ping" | ssmtp [email protected]
else
  echo "OUTSIDE is up"
fi
#

...and so on for each data logger that you can see in the montage at http://www.SDsolarBlog.com/montage


FYI, using &>/dev/null redirects all output from the command, including errors, to /dev/null

(The conditional only requires the exit status of the ping command)

Also FYI, note that since cron jobs run as root there is no need to use sudo ping in a cron script.

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Here are my 2 cents = 5 methods ;)

I like encapsulate these details and have AppCode tell me how to finish my sentences.

void dispatch_after_delay(float delayInSeconds, dispatch_queue_t queue, dispatch_block_t block) {
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, queue, block);
}

void dispatch_after_delay_on_main_queue(float delayInSeconds, dispatch_block_t block) {
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_after_delay(delayInSeconds, queue, block);
}

void dispatch_async_on_high_priority_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), block);
}

void dispatch_async_on_background_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block);
}

void dispatch_async_on_main_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_main_queue(), block);
}

How to store token in Local or Session Storage in Angular 2?

That totally depends of what do you need exactly. If you just need to store and retrieve a token in order to use it in your http requests, i suggest you to simply create a service and use it in your whole project.

example of basic integration:

import {Injectable} from 'angular@core'

@Injectable()
export class TokenManager {

    private tokenKey:string = 'app_token';

    private store(content:Object) {
        localStorage.setItem(this.tokenKey, JSON.stringify(content));
    }

    private retrieve() {
        let storedToken:string = localStorage.getItem(this.tokenKey);
        if(!storedToken) throw 'no token found';
        return storedToken;
    }

    public generateNewToken() {
        let token:string = '...';//custom token generation;
        let currentTime:number = (new Date()).getTime() + ttl;
        this.store({ttl: currentTime, token});
    }

    public retrieveToken() {

        let currentTime:number = (new Date()).getTime(), token = null;
        try {
            let storedToken = JSON.parse(this.retrieve());
            if(storedToken.ttl < currentTime) throw 'invalid token found';
            token = storedToken.token;
        }
        catch(err) {
            console.error(err);
        }
        return token;

    }

}

However if you need to use the local storage more often, by using the stored values in your app views for example. You can use one of the libraries that provides a wrapper of the webstorages like you did with angular2-localstorage.

I created some months ago ng2-webstorage that should respond to your needs. It provides two ng2 services and two decorators to sync the webstorage's values and the service/component's attributes.

import {Component} from '@angular/core';
import {LocalStorageService, LocalStorage} from 'ng2-webstorage';

@Component({
    selector: 'foo',
    template: `
        <section>{{boundValue}}</section>
        <section><input type="text" [(ngModel)]="attribute"/></section>
        <section><button (click)="saveValue()">Save</button></section>
    `,
})
export class FooComponent {

    @LocalStorage()
    boundValue; // attribute bound to the localStorage
    value;

    constructor(private storage:LocalStorageService) {
        this.localSt.observe('boundValue')// triggers the callback each time a new value is set
            .subscribe((newValue) => console.log('new value', newValue));
    }

    saveValue() {
      this.storage.store('boundValue', this.value); // store the given value
    }

}

How can I get the DateTime for the start of the week?

try with this in c#.With this code you can get both first date and last date of a given week.Here Sunday is the first day and Saturday is the last day but you can set both day's according to your culture

DateTime firstDate = GetFirstDateOfWeek(DateTime.Parse("05/09/2012").Date,DayOfWeek.Sunday);
DateTime lastDate = GetLastDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Saturday);

public static DateTime GetFirstDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
{
    DateTime firstDayInWeek = dayInWeek.Date;
    while (firstDayInWeek.DayOfWeek != firstDay)
        firstDayInWeek = firstDayInWeek.AddDays(-1);

    return firstDayInWeek;
}
public static DateTime GetLastDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
{
    DateTime lastDayInWeek = dayInWeek.Date;
    while (lastDayInWeek.DayOfWeek != firstDay)
        lastDayInWeek = lastDayInWeek.AddDays(1);

    return lastDayInWeek;
}

How to continue a Docker container which has exited

by name

sudo docker start bob_the_container

or by Id

sudo docker start aa3f365f0f4e

this restarts stopped container, use -i to attach container's STDIN or instead of -i you can attach to container session (if you run with -it)

sudo docker attach bob_the_container

Renew Provisioning Profile

To renew the development profile before it expired, I finally found a way that works for me. I boldfaced the steps I had been missing before.

Go to the Apple provisioning portal, select "Provisioning". You'll get a list "Development Provisioning Profiles" where you'll see your soon to expire profile with the label "Managed by XCode". Click the "New Profile" button on top, select the type of profile you want and create it. Wait half a minute, refresh the home screen and when it shows the new profile as "Active", switch back to XCode, go to the Organizer, select "Provisioning profiles" under "Library" in left top column. Click "Refresh" at the bottom, log in (if it asks) and the new profile appears in the list after a short while.

Now, crucially, connect your device and drag your new profile to the "Provisioning Profiles" row under the connected device in the left column.

Finally, you can clean up the old profiles from your device if you feel like it.

Note: interestingly, it seems that simply marking and deleting your provisioning profile on the iOS Provisioning Portal site causes a new fresh Team Provisioning Profile to be created. So maybe that is all that is needed. I will try that next time to see if that is enough, if so you don't need to create a profile as I described above.

How do I list all the files in a directory and subdirectories in reverse chronological order?

The command in wfg5475's answer is working properly, just need to add one thing to show only files in a directory & sub directory:

ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total|^d' |sed '/^$/d'

Added one thing: ^d to ignore the all directories from the listing outputs

WARNING: sanitizing unsafe style value url

I got the same issue while adding dynamic url in Image tag in Angular 7. I searched a lot and found this solution.

First, write below code in the component file.

constructor(private sanitizer: DomSanitizer) {}
public getSantizeUrl(url : string) {
    return this.sanitizer.bypassSecurityTrustUrl(url);
}

Now in your html image tag, you can write like this.

<img class="image-holder" [src]=getSantizeUrl(item.imageUrl) />

You can write as per your requirement instead of item.imageUrl

I got a reference from this site.dynamic urls. Hope this solution will help you :)

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

C++ initial value of reference to non-const must be an lvalue

When you call test with &nKByte, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.

Either do not use a reference for the argument, or better yet don't use a pointer.

IIS Config Error - This configuration section cannot be used at this path

Most IIS sections are locked by default but you can "unlock" them by setting the attribute overrideModeDefault from "Deny" to "Allow" for the relevant section group by modifying the ApplicationHost.config file located in %windir%\system32\inetsrv\config in Administrator mode

enter image description here

Postgresql SQL: How check boolean field with null and True,False Value?

There are 3 states for boolean in PG: true, false and unknown (null). Explained here: Postgres boolean datatype

Therefore you need only query for NOT TRUE:

SELECT * from table_name WHERE boolean_column IS NOT TRUE;

Origin null is not allowed by Access-Control-Allow-Origin

I was looking for an solution to make an XHR request to a server from a local html file and found a solution using Chrome and PHP. (no Jquery)

Javascripts:

var x = new XMLHttpRequest(); 
if(x) x.onreadystatechange=function(){ 
    if (x.readyState === 4 && x.status===200){
        console.log(x.responseText); //Success
    }else{ 
        console.log(x); //Failed
    }
};
x.open(GET, 'http://example.com/', true);
x.withCredentials = true;
x.send();

My Chrome's request header Origin: null

My PHP response header (Note that 'null' is a string). HTTP_REFERER allow cross-origin from a remote server to another.

header('Access-Control-Allow-Origin: '.(trim($_SERVER['HTTP_REFERER'],'/')?:'null'),true);
header('Access-Control-Allow-Credentials:true',true);

I was able to successfully connect to my server. You can disregards the Credentials headers, but this works for me with Apache's AuthType Basic enabled

I tested compatibility with FF and Opera, It works in many cases such as:

From a VM LAN IP (192.168.0.x) back to the VM'S WAN (public) IP:port
From a VM LAN IP back to a remote server domain name.
From a local .HTML file to the VM LAN IP and/or VM WAN IP:port,
From a local .HTML file to a remote server domain name.
And so on.

PHP PDO with foreach and fetch

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Here $users is a PDOStatement object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach is essentially shorthand for:

while ($row = $users->fetch()) ...

Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
    echo $key . "-" . $value . "<br/>";
}

Here all results are being output by the first loop. The call to fetch will return false, since you have already exhausted the result set (see above), so you get an error trying to loop over false.

In the last example you are simply fetching the first result row and are looping over it.

Eclipse error "Could not find or load main class"

I too faced same problem.

Simple solution is : delete project( not source files please). close eclipse--> go to project folder-- > remove classpath and project file .

then open Eclipse and create project in same location

How do I capture the output of a script if it is being ran by the task scheduler?

Try this as the command string in Task Scheduler:

cmd /c yourscript.cmd > logall.txt

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

Unable to process Jar entry [module-info.class] from Jar [jar:file:/xxxxxxxx/lombok-1.18.4.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19

1.update and append below argument in <root or instance tomcat folder>/conf/catalina.properties

org.apache.catalina.startup.ContextConfig.jarsToSkip=...,lombok-1.18.4.jar

2.clean and deploy the to-be-pulish project.

How to generate random positive and negative numbers in Java

Generate numbers between 0 and 65535 then just subtract 32768

Can an int be null in Java?

An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.

Data Type / Default Value (for fields)

int ------------------ 0

long ---------------- 0L

float ---------------- 0.0f

double ------------- 0.0d

char --------------- '\u0000'

String --------------- null

boolean ------------ false

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

Another solution:

public class CountryInfoResponse {
  private List<Object> geonames;
}

Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.

How does delete[] know it's an array?

It's up to the runtime which is responsible for the memory allocation, in the same way that you can delete an array created with malloc in standard C using free. I think each compiler implements it differently. One common way is to allocate an extra cell for the array size.

However, the runtime is not smart enough to detect whether or not it is an array or a pointer, you have to inform it, and if you are mistaken, you either don't delete correctly (E.g., ptr instead of array), or you end up taking an unrelated value for the size and cause significant damage.

How do format a phone number as a String in Java?

I'd have thought you need to use a MessageFormat rather than DecimalFormat. That should be more flexible.

How to get a Char from an ASCII Character Code in c#

Two options:

char c1 = '\u0001';
char c1 = (char) 1;

get current date from [NSDate date] but set the time to 10:00 am

I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.

let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!

XmlSerializer: remove unnecessary xsi and xsd namespaces

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)

Apply function to all elements of collection through LINQ

You can try something like

var foo = (from fooItems in context.footable select fooItems.fooID + 1);

Returns a list of id's +1, you can do the same with using a function to whatever you have in the select clause.

Update: As suggested from Jon Skeet this is a better version of the snippet of code I just posted:

var foo = context.footable.Select(foo => foo.fooID + 1);

HTML table sort

Check if you could go with any of the below mentioned JQuery plugins. Simply awesome and provide wide range of options to work through, and less pains to integrate. :)

https://github.com/paulopmx/Flexigrid - Flexgrid
http://datatables.net/index - Data tables.
https://github.com/tonytomov/jqGrid

If not, you need to have a link to those table headers that calls a server-side script to invoke the sort.

How to compare pointers?

It depends on the types of the values, and the way that operators happen to have been defined. For example, string comparison is by value, not by address. But char * is by address normally (I think).

A big trap for the unwary. There is no guaranteed pointer comparison operator, but

  (void *)a == (void *)b 

is probably fairly safe.

How to render an ASP.NET MVC view as a string?

Here's what I came up with, and it's working for me. I added the following method(s) to my controller base class. (You can always make these static methods somewhere else that accept a controller as a parameter I suppose)

MVC2 .ascx style

protected string RenderViewToString<T>(string viewPath, T model) {
  ViewData.Model = model;
  using (var writer = new StringWriter()) {
    var view = new WebFormView(ControllerContext, viewPath);
    var vdd = new ViewDataDictionary<T>(model);
    var viewCxt = new ViewContext(ControllerContext, view, vdd,
                                new TempDataDictionary(), writer);
    viewCxt.View.Render(viewCxt, writer);
    return writer.ToString();
  }
}

Razor .cshtml style

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                             viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                 ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

Edit: added Razor code.

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

SQL: How to properly check if a record exists

You can use:

SELECT 1 FROM MyTable WHERE <MyCondition>

If there is no record matching the condition, the resulted recordset is empty.

Django: How can I call a view function from template?

For deleting all data:

HTML FILE

  class="btn btn-primary" href="{% url 'delete_product'%}">Delete

Put the above code in an anchor tag. (the a tag!)

url.py

path('delete_product', views.delete_product, name='delete_product')]

views.py

def delete_product(request):
    if request.method == "GET":
        dest = Racket.objects.all()
        dest.delete()
        return render(request, "admin_page.html")

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

from datetime import datetime
from calendar import timegm

# Note: if you pass in a naive dttm object it's assumed to already be in UTC
def unix_time(dttm=None):
    if dttm is None:
       dttm = datetime.utcnow()

    return timegm(dttm.utctimetuple())

print "Unix time now: %d" % unix_time()
print "Unix timestamp from an existing dttm: %d" % unix_time(datetime(2014, 12, 30, 12, 0))

How to pass a single object[] to a params object[]

A simple typecast will ensure the compiler knows what you mean in this case.

Foo((object)new object[]{ (object)"1", (object)"2" }));

As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree.

React-Native Button style not work

I had an issue with margin and padding with a Button. I added Button inside a View component and apply your properties to the View.

<View style={{margin:10}}>
<Button
  title="Decrypt Data"
  color="orange"
  accessibilityLabel="Tap to Decrypt Data"
  onPress={() => {
    Alert.alert('You tapped the Decrypt button!');
  }}
  />  
</View>

Inline CSS styles in React: how to implement a:hover?

This can be a nice hack for having inline style inside a react component (and also using :hover CSS function):

...

<style>
  {`.galleryThumbnail.selected:hover{outline:2px solid #00c6af}`}
</style>

...

Coarse-grained vs fine-grained

One more way to understand would be to think in terms of communication between processes and threads. Processes communicate with the help of coarse grained communication mechanisms like sockets, signal handlers, shared memory, semaphores and files. Threads, on the other hand, have access to shared memory space that belongs to a process, which allows them to apply finer grain communication mechanisms.

Source: Java concurrency in practice

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

Easy way to convert a unicode list to a list containing python strings?

[str(x) for x in EmployeeList] would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.

>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']


>>> EmployeeList = [u'1001', u'????', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

How to develop or migrate apps for iPhone 5 screen resolution?

I guess, it is not going to work in all cases, but in my particular project it avoided me from duplication of NIB-files:

Somewhere in common.h you can make these defines based off of screen height:

#define HEIGHT_IPHONE_5 568
#define IS_IPHONE   ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
#define IS_IPHONE_5 ([[UIScreen mainScreen] bounds ].size.height == HEIGHT_IPHONE_5)

In your base controller:

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IS_IPHONE_5) {
        CGRect r = self.view.frame;
        r.size.height = HEIGHT_IPHONE_5 - 20;
        self.view.frame = r;
    }
    // now the view is stretched properly and not pushed to the bottom
    // it is pushed to the top instead...

    // other code goes here...
}

C# get string from textbox

I show you this with an example:

string userName= textBox1.text;

and then use it as you wish

What's the difference between a method and a function?

Function is a set of logic that can be used to manipulate data.

While, Method is function that is used to manipulate the data of the object where it belongs. So technically, if you have a function that is not completely related to your class but was declared in the class, its not a method; It's called a bad design.

Store text file content line by line into array

When you do str = in.readLine()) != null you read one line into str variable and if it's not null execute the while block. You do not need to read the line one more time in arr[i] = in.readLine();. Also use lists instead of arrays when you do not know the exact size of the input file (number of lines).

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;

List<String> output = new LinkedList<String>();

while((str = in.readLine()) != null){
    output.add(str);
}

String[] arr = output.toArray(new String[output.size()]);

Converting between datetime and Pandas Timestamp objects

Pandas Timestamp to datetime.datetime:

pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()

datetime.datetime to Timestamp

pd.Timestamp(datetime(2014, 1, 23))

How to generate a GUID in Oracle?

It is not clear what you mean by auto-generate a guid into an insert statement but at a guess, I think you are trying to do something like the following:

INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Adams');
INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Baker');

In that case I believe the ID column should be declared as RAW(16);

I am doing this off the top of my head. I don't have an Oracle instance handy to test against, but I think that is what you want.

Convert IEnumerable to DataTable

Look at this one: Convert List/IEnumerable to DataTable/DataView

In my code I changed it into a extension method:

public static DataTable ToDataTable<T>(this List<T> items)
{
    var tb = new DataTable(typeof(T).Name);

    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach(var prop in props)
    {
        tb.Columns.Add(prop.Name, prop.PropertyType);
    }

     foreach (var item in items)
    {
       var values = new object[props.Length];
        for (var i=0; i<props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }

        tb.Rows.Add(values);
    }

    return tb;
}

Get the contents of a table row with a button click

The selector ".nr:first" is specifically looking for the first, and only the first, element having class "nr" within the selected table element. If you instead call .find(".nr") you will get all of the elements within the table having class "nr". Once you have all of those elements, you could use the .each method to iterate over them. For example:

$(".use-address").click(function() {
    $("#choose-address-table").find(".nr").each(function(i, nrElt) {
        var id = nrElt.text();
        $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
    });
});

However, that would get you all of the td.nr elements in the table, not just the one in the row that was clicked. To further limit your selection to the row containing the clicked button, use the .closest method, like so:

$(".use-address").click(function() {
    $(this).closest("tr").find(".nr").each(function(i, nrElt) {
        var id = nrElt.text();
        $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
    });
});

How to make a PHP SOAP call using the SoapClient class

You can use SOAP services this way too:

<?php 
//Create the client object
$soapclient = new SoapClient('http://www.webservicex.net/globalweather.asmx?WSDL');

//Use the functions of the client, the params of the function are in 
//the associative array
$params = array('CountryName' => 'Spain', 'CityName' => 'Alicante');
$response = $soapclient->getWeather($params);

var_dump($response);

// Get the Cities By Country
$param = array('CountryName' => 'Spain');
$response = $soapclient->getCitiesByCountry($param);

var_dump($response);

This is an example with a real service, and it works when the url is up.

Just in case the http://www.webservicex.net is down.

Here is another example using the example web service from W3C XML Web Services example, you can find more information on the link.

<?php
//Create the client object
$soapclient = new SoapClient('https://www.w3schools.com/xml/tempconvert.asmx?WSDL');

//Use the functions of the client, the params of the function are in
//the associative array
$params = array('Celsius' => '25');
$response = $soapclient->CelsiusToFahrenheit($params);

var_dump($response);

// Get the Celsius degrees from the Farenheit
$param = array('Fahrenheit' => '25');
$response = $soapclient->FahrenheitToCelsius($param);

var_dump($response);

This is working and returning the converted temperature values.

Hope this helps.

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

I thought Activity was deprecated

No.

So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?

Activity is the baseline. Every activity inherits from Activity, directly or indirectly.

FragmentActivity is for use with the backport of fragments found in the support-v4 and support-v13 libraries. The native implementation of fragments was added in API Level 11, which is lower than your proposed minSdkVersion values. The only reason why you would need to consider FragmentActivity specifically is if you want to use nested fragments (a fragment holding another fragment), as that was not supported in native fragments until API Level 17.

AppCompatActivity is from the appcompat-v7 library. Principally, this offers a backport of the action bar. Since the native action bar was added in API Level 11, you do not need AppCompatActivity for that. However, current versions of appcompat-v7 also add a limited backport of the Material Design aesthetic, in terms of the action bar and various widgets. There are pros and cons of using appcompat-v7, well beyond the scope of this specific Stack Overflow answer.

ActionBarActivity is the old name of the base activity from appcompat-v7. For various reasons, they wanted to change the name. Unless some third-party library you are using insists upon an ActionBarActivity, you should prefer AppCompatActivity over ActionBarActivity.

So, given your minSdkVersion in the 15-16 range:

  • If you want the backported Material Design look, use AppCompatActivity

  • If not, but you want nested fragments, use FragmentActivity

  • If not, use Activity

Just adding from comment as note: AppCompatActivity extends FragmentActivity, so anyone who needs to use features of FragmentActivity can use AppCompatActivity.

PHP Try and Catch for SQL Insert

This can do the trick,

function createLog($data){ 
    $file = "Your path/incompletejobs.txt";
    $fh = fopen($file, 'a') or die("can't open file");
    fwrite($fh,$data);
    fclose($fh);
}
$qry="INSERT INTO redirects SET ua_string = '$ua_string'"   
$result=mysql_query($qry);
if(!$result){
    createLog(mysql_error());
}

Makefile, header dependencies

Most answers are surprisingly complicated or erroneous. However simple and robust examples have been posted elsewhere [codereview]. Admittedly the options provided by the gnu preprocessor are a bit confusing. However, the removal of all directories from the build target with -MM is documented and not a bug [gpp]:

By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as ‘.c’, and appends the platform's usual object suffix.

The (somewhat newer) -MMD option is probably what you want. For completeness an example of a makefile that supports multiple src dirs and build dirs with some comments. For a simple version without build dirs see [codereview].

CXX = clang++
CXX_FLAGS = -Wfatal-errors -Wall -Wextra -Wpedantic -Wconversion -Wshadow

# Final binary
BIN = mybin
# Put all auto generated stuff to this build dir.
BUILD_DIR = ./build

# List of all .cpp source files.
CPP = main.cpp $(wildcard dir1/*.cpp) $(wildcard dir2/*.cpp)

# All .o files go to build dir.
OBJ = $(CPP:%.cpp=$(BUILD_DIR)/%.o)
# Gcc/Clang will create these .d files containing dependencies.
DEP = $(OBJ:%.o=%.d)

# Default target named after the binary.
$(BIN) : $(BUILD_DIR)/$(BIN)

# Actual target of the binary - depends on all .o files.
$(BUILD_DIR)/$(BIN) : $(OBJ)
    # Create build directories - same structure as sources.
    mkdir -p $(@D)
    # Just link all the object files.
    $(CXX) $(CXX_FLAGS) $^ -o $@

# Include all .d files
-include $(DEP)

# Build target for every single object file.
# The potential dependency on header files is covered
# by calling `-include $(DEP)`.
$(BUILD_DIR)/%.o : %.cpp
    mkdir -p $(@D)
    # The -MMD flags additionaly creates a .d file with
    # the same name as the .o file.
    $(CXX) $(CXX_FLAGS) -MMD -c $< -o $@

.PHONY : clean
clean :
    # This should remove all generated files.
    -rm $(BUILD_DIR)/$(BIN) $(OBJ) $(DEP)

This method works because if there are multiple dependency lines for a single target, the dependencies are simply joined, e.g.:

a.o: a.h
a.o: a.c
    ./cmd

is equivalent to:

a.o: a.c a.h
    ./cmd

as mentioned at: Makefile multiple dependency lines for a single target?

Radio/checkbox alignment in HTML/CSS

This is a simple solution which solved the problem for me:

label 
{

/* for firefox */
vertical-align:middle; 

/*for internet explorer */
*bottom:3px;
*position:relative; 

padding-bottom:7px; 

}

Search for value in DataGridView in a column

"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView;

How about the relation to the database connections and the Datatable? And how should i set the DefaultView correct?

I use this code to get the data out:

con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();

DataTable dt = new DataTable();

adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);        
adapt.Fill(dt);        
dataGridView1.DataSource = dt;
con.Close();

Hibernate Error: a different object with the same identifier value was already associated with the session

Transfer the task of assigning the object ID from Hibernate to the database by using:

<generator class="native"/>

This solved the problem for me.

What is com.sun.proxy.$Proxy

  1. Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler, which defines a method that is invoked when a proxy method is invoked.

  2. You create them by using the call

    Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
    

    The arguments are:

    1. classLoader. Once the class is generated, it is loaded with this class loader.
    2. interfaces. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
    3. invocationHandler. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler. When a method from any of the supported interfaces, or hashCode, equals, or toString, is invoked, the method invoke is invoked on the handler, passing the Method object for the method to be invoked and the arguments passed.

    For more on this, see the documentation for the Proxy class.

  3. Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.

Java 8 Lambda function that throws exception?

public void frankTest() {
    int pageId= -1;

    List<Book> users= null;
    try {
        //Does Not Compile:  Object page=DatabaseConnection.getSpringConnection().queryForObject("SELECT * FROM bookmark_page", (rw, n) -> new Portal(rw.getInt("id"), "", users.parallelStream().filter(uu -> uu.getVbid() == rw.getString("user_id")).findFirst().get(), rw.getString("name")));

        //Compiles:
        Object page= DatabaseConnection.getSpringConnection().queryForObject("SELECT * FROM bookmark_page", (rw, n) -> { 
            try {
                final Book bk= users.stream().filter(bp -> { 
                    String name= null;
                    try {
                        name = rw.getString("name");
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return bp.getTitle().equals(name); 
                }).limit(1).collect(Collectors.toList()).get(0);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return new Portal(rw.getInt("id"), "", users.get(0), rw.getString("name")); 
        } );
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

How to center the text in a JLabel?

The following constructor, JLabel(String, int), allow you to specify the horizontal alignment of the label.

JLabel label = new JLabel("The Label", SwingConstants.CENTER);

Create Directory When Writing To File In Node.js

If you don't want to use any additional package, you can call the following function before creating your file:

var path = require('path'),
    fs = require('fs');

function ensureDirectoryExistence(filePath) {
  var dirname = path.dirname(filePath);
  if (fs.existsSync(dirname)) {
    return true;
  }
  ensureDirectoryExistence(dirname);
  fs.mkdirSync(dirname);
}

how to get selected row value in the KendoUI

If you want to select particular element use below code

var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Followed this.

I have solved it with adding some key in info.plist. The steps I followed are:

  1. Opened my Projects info.plist file

  2. Added a Key called NSAppTransportSecurity as a Dictionary.

  3. Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES as like following image. enter image description here

Clean the Project and Now Everything is Running fine as like before.

Ref Link.

How can I get the intersection, union, and subset of arrays in Ruby?

Utilizing the fact that you can do set operations on arrays by doing &(intersection), -(difference), and |(union).

Obviously I didn't implement the MultiSet to spec, but this should get you started:

class MultiSet
  attr_accessor :set
  def initialize(set)
    @set = set
  end
  # intersection
  def &(other)
    @set & other.set
  end
  # difference
  def -(other)
    @set - other.set
  end
  # union
  def |(other)
    @set | other.set
  end
end

x = MultiSet.new([1,1,2,2,3,4,5,6])
y = MultiSet.new([1,3,5,6])

p x - y # [2,2,4]
p x & y # [1,3,5,6]
p x | y # [1,2,3,4,5,6]

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date -j -f "%Y-%m-%d" "2010-10-02" "+%s"

How to know if docker is already logged in to a docker registry server

As pointed out by @Christian, best to try operation first then login only if necessary. Problem is that "if necessary" is not that obvious to do robustly. One approach is to compare the stderr of the docker operation with some strings that are known (by trial and error). For example,

try "docker OPERATION"
if it failed: 
    capture the stderr of "docker OPERATION"
    if it ends with "no basic auth credentials": 
        try docker login
    else if it ends with "not found":
        fatal error: image name/tag probably incorrect
    else if it ends with <other stuff you care to trap>:
        ...
    else:
        fatal error: unknown cause

try docker OPERATION again
if this fails: you're SOL!

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Python: Is there an equivalent of mid, right, and left from BASIC?

There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.

str = "this_is_a_test"
left = str.startswith("this")
print(left)
> True

right = str.endswith("test")
print(right)
> True

How to hash some string with sha256 in Java?

In Java, MessageDigest class is used to calculate cryptographic hashing value. This class provides cryptographic hash function ( MD5, SHA-1 and SHA-256) to find hash value of text.

Code example for using SHA-256 algorithm.

public void printHash(String str) throws NoSuchAlgorithmException {

MessageDigest md=MessageDigest.getInstance("SHA-256");

byte[] sha256=md.digest(str.getBytes(StandardCharsets.UTF_8));

   for(byte b : sha256){

      System.out.printf("%02x",b);

  }
}

python selenium click on button

open a website https://adviserinfo.sec.gov/compilation and click on button to download the file and even i want to close the pop up if it comes using python selenium

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.chrome.options import Options 

#For Mac - If you use windows change the chromedriver location
chrome_path = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(chrome_path)

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-popup-blocking")

driver.maximize_window()
driver.get("https://adviserinfo.sec.gov/compilation")

# driver.get("https://adviserinfo.sec.gov/")
# tabName = driver.find_element_by_link_text("Investment Adviser Data")
# tabName.click()

time.sleep(3)

# report1 = driver.find_element_by_xpath("//div[@class='compilation-container ng-scope layout-column flex']//div[1]//div[1]//div[1]//div[2]//button[1]")

report1 = driver.find_element_by_xpath("//button[@analytics-label='IAPD - SEC Investment Adviser Report (GZIP)']")

# print(report1)
report1.click()

time.sleep(5)

driver.close()

How best to read a File into List<string>

A little update to Evan Mulawski answer to make it shorter

List<string> allLinesText = File.ReadAllLines(fileName).ToList()

Java Strings: "String s = new String("silly");"

The best way to answer your question would be to make you familiar with the "String constant pool". In java string objects are immutable (i.e their values cannot be changed once they are initialized), so when editing a string object you end up creating a new edited string object wherease the old object just floats around in a special memory ares called the "string constant pool". creating a new string object by

String s = "Hello";

will only create a string object in the pool and the reference s will refer to it, but by using

String s = new String("Hello");

you create two string objects: one in the pool and the other in the heap. the reference will refer to the object in the heap.

How to get ERD diagram for an existing database?

We used DBVisualizer for that.

Description: The references graph is a great feature as it automatically renders all primary/foreign key mappings (also called referential integrity constraints) in a graph style. The table nodes and relations are layed out automatically, with a number of layout modes available. The resulting graph is unique as it displays all information in an optimal and readable layout. from its site

Enable Hibernate logging

Hibernate logging has to be also enabled in hibernate configuration.

Add lines

hibernate.show_sql=true
hibernate.format_sql=true

either to

server\default\deployers\ejb3.deployer\META-INF\jpa-deployers-jboss-beans.xml

or to application's persistence.xml in <persistence-unit><properties> tag.

Anyway hibernate logging won't include (in useful form) info on actual prepared statements' parameters.

There is an alternative way of using log4jdbc for any kind of sql logging.

The above answer assumes that you run the code that uses hibernate on JBoss, not in IDE. In this case you should configure logging also on JBoss in server\default\deploy\jboss-logging.xml, not in local IDE classpath.

Note that JBoss 6 doesn't use log4j by default. So adding log4j.properties to ear won't help. Just try to add to jboss-logging.xml:

   <logger category="org.hibernate">
     <level name="DEBUG"/>
   </logger>

Then change threshold for root logger. See SLF4J logger.debug() does not get logged in JBoss 6.

If you manage to debug hibernate queries right from IDE (without deployment), then you should have log4j.properties, log4j, slf4j-api and slf4j-log4j12 jars on classpath. See http://www.mkyong.com/hibernate/how-to-configure-log4j-in-hibernate-project/.

How to bind bootstrap popover on dynamic elements

Try this HTML

<a href="#" data-toggle="popover" data-popover-target="#popover-content-1">Do Popover 1</a>
<a href="#" data-toggle="popover" data-popover-target="#popover-content-2">Do Popover</a>

<div id="popover-content-1" style="display: none">Content 1</div>
<div id="popover-content-2" style="display: none">Content 2</div>

jQuery:

$(function() {
  $('[data-toggle="popover"]').each(function(i, obj) {
    var popover_target = $(this).data('popover-target');
    $(this).popover({
        html: true,
        trigger: 'focus',
        placement: 'right',
        content: function(obj) {
            return $(popover_target).html();
        }
    });
  });
});

mysql - move rows from one table to another

A simple INSERT INTO SELECT statement:

INSERT INTO persons_table SELECT * FROM customer_table WHERE person_name = 'tom';

DELETE FROM customer_table WHERE person_name = 'tom';

Javascript: set label text

you are doing several things wrong. The explanation follows the corrected code:

<label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, 'LblTextCount')">
</textarea>

Note the quotes around the id.

function checkLength(object, maxlength, label) {
    charsleft = (maxlength - object.value.length);

    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        object.value = object.value.substring(0, maxlength-1);
    }

    // set the value of charsleft into the label
    document.getElementById(label).innerHTML = charsleft;
}

First, on your key press event you need to send the label id as a string for it to read correctly. Second, InnerHTML has a lowercase i. Lastly, because you sent the function the string id you can get the element by that id.

Let me know how that works out for you

EDIT Not that by not declaring charsleft as a var, you are implicitly creating a global variable. a better way would be to do the following when declaring it in the function:

var charsleft = ....

What is the optimal way to compare dates in Microsoft SQL server?

Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand

From that article:

DECLARE @dateVar datetime = '19700204';

-- Quickest when there is an index on t.[DateColumn], 
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);

-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn] 
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND 
      t.[DateColumn] < @dateEnd;

Also from that article: using BETWEEN, DATEDIFF or CONVERT(CHAR(8)... are all slower.

Save image from url with curl PHP

Improved version of Komang answer (add referer and user agent, check if you can write the file), return true if it's ok, false if there is an error :

public function downloadImage($url,$filename){
    if(file_exists($filename)){
        @unlink($filename);
    }
    $fp = fopen($filename,'w');
    if($fp){
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $result = parse_url($url);
        curl_setopt($ch, CURLOPT_REFERER, $result['scheme'].'://'.$result['host']);
        curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0');
        $raw=curl_exec($ch);
        curl_close ($ch);
        if($raw){
            fwrite($fp, $raw);
        }
        fclose($fp);
        if(!$raw){
            @unlink($filename);
            return false;
        }
        return true;
    }
    return false;
}

.bashrc: Permission denied

.bashrc is not meant to be executed but sourced. Try this instead:

. ~/.bashrc

Cheers!

How to Query an NTP Server using C#?

I know the topic is quite old, but such tools are always handy. I've used the resources above and created a version of NtpClient which allows asynchronously to acquire accurate time, instead of event based.

 /// <summary>
/// Represents a client which can obtain accurate time via NTP protocol.
/// </summary>
public class NtpClient
{
    private readonly TaskCompletionSource<DateTime> _resultCompletionSource;

    /// <summary>
    /// Creates a new instance of <see cref="NtpClient"/> class.
    /// </summary>
    public NtpClient()
    {
        _resultCompletionSource = new TaskCompletionSource<DateTime>();
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync()
    {
        return await GetNetworkTimeAsync(TimeSpan.FromSeconds(45));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeoutMs">Operation timeout in milliseconds.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(int timeoutMs)
    {
        return await GetNetworkTimeAsync(TimeSpan.FromMilliseconds(timeoutMs));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeout">Operation timeout.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
    {
        using (var socket = new DatagramSocket())
        using (var ct = new CancellationTokenSource(timeout))
        {
            ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());

            socket.MessageReceived += OnSocketMessageReceived;
            //The UDP port number assigned to NTP is 123
            await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
            using (var writer = new DataWriter(socket.OutputStream))
            {
                // NTP message size is 16 bytes of the digest (RFC 2030)
                var ntpBuffer = new byte[48];

                // Setting the Leap Indicator, 
                // Version Number and Mode values
                // LI = 0 (no warning)
                // VN = 3 (IPv4 only)
                // Mode = 3 (Client Mode)
                ntpBuffer[0] = 0x1B;

                writer.WriteBytes(ntpBuffer);
                await writer.StoreAsync();
                var result = await _resultCompletionSource.Task;
                return result;
            }
        }
    }

    private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
    {
        try
        {
            using (var reader = args.GetDataReader())
            {
                byte[] response = new byte[48];
                reader.ReadBytes(response);
                _resultCompletionSource.TrySetResult(ParseNetworkTime(response));
            }
        }
        catch (Exception ex)
        {
            _resultCompletionSource.TrySetException(ex);
        }
    }

    private static DateTime ParseNetworkTime(byte[] rawData)
    {
        //Offset to get to the "Transmit Timestamp" field (time at which the reply 
        //departed the server for the client, in 64-bit timestamp format."
        const byte serverReplyTime = 40;

        //Get the seconds part
        ulong intPart = BitConverter.ToUInt32(rawData, serverReplyTime);

        //Get the seconds fraction
        ulong fractPart = BitConverter.ToUInt32(rawData, serverReplyTime + 4);

        //Convert From big-endian to little-endian
        intPart = SwapEndianness(intPart);
        fractPart = SwapEndianness(fractPart);

        var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

        //**UTC** time
        DateTime networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
        return networkDateTime;
    }

    // stackoverflow.com/a/3294698/162671
    private static uint SwapEndianness(ulong x)
    {
        return (uint)(((x & 0x000000ff) << 24) +
                       ((x & 0x0000ff00) << 8) +
                       ((x & 0x00ff0000) >> 8) +
                       ((x & 0xff000000) >> 24));
    }
}

Usage:

var ntp = new NtpClient();
var accurateTime = await ntp.GetNetworkTimeAsync(TimeSpan.FromSeconds(10));

Check if an element is present in an array

In lodash you can use _.includes (which also aliases to _.contains)

You can search the whole array:

_.includes([1, 2, 3], 1); // true

You can search the array from a starting index:

_.includes([1, 2, 3], 1, 1);  // false (begins search at index 1)

Search a string:

_.includes('pebbles', 'eb');  // true (string contains eb)

Also works for checking simple arrays of objects:

_.includes({ 'user': 'fred', 'age': 40 }, 'fred');    // true
_.includes({ 'user': 'fred', 'age': false }, false);  // true

One thing to note about the last case is it works for primitives like strings, numbers and booleans but cannot search through arrays or objects

_.includes({ 'user': 'fred', 'age': {} }, {});   // false
_.includes({ 'user': [1,2,3], 'age': {} }, 3);   // false

How to check if a "lateinit" variable has been initialized?

There is a lateinit improvement in Kotlin 1.2 that allows to check the initialization state of lateinit variable directly:

lateinit var file: File    

if (this::file.isInitialized) { ... }

See the annoucement on JetBrains blog or the KEEP proposal.

UPDATE: Kotlin 1.2 has been released. You can find lateinit enhancements here:

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

AllowOverride AuthConfig

try this. Authentication may be the problem. I was working with a CGI script written in C++, and faced some authentication issues when passed DELETE. The above solution helped me. It may help in your case too.


Also even if you don't get the solution for your problem of PUT and DELETE, do not stop working rather use "CORS". It is a google chrome app, which will help you bypass the problem, but remember it is a temporary solution, so that your work or experiments doesn't remain freeze for long. Obviously, you cannot ask your client to have "CORS" enabled to run your solution, as it may compromise systems security.

Looking for a 'cmake clean' command to clear up CMake output

It's funny to see this question gets so many attentions and complicated solutions, which indeed shows a pain to not have a clean method with cmake.

Well, you can definitely cd build to do you work, then do a rm -rf * when you need to clean. However, rm -rf * is a dangerous command given that many people are often not aware which dir they are in.

If you cd .., rm -rf build and then mkdir build and then cd build, that's just too much typing.

So a good solution is to just stay out of the build folder and tell cmake the path:
to configure: cmake -B build
to build: cmake --build build
to clean: rm -rf build
to recreate build folder: you don't even need mkdir build, just configure it with cmake -B build and cmake will create it

Vertical alignment of text and icon in button

Alternativly if your using bootstrap then you can just add align-middle to vertical align the element.

<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">Continue
    <i class="icon-ok align-middle" style="font-size:40px;"></i>
</button>

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

How to measure time taken between lines of code in python?

I was looking for a way how to output a formatted time with minimal code, so here is my solution. Many people use Pandas anyway, so in some cases this can save from additional library imports.

import pandas as pd
start = pd.Timestamp.now()
# code
print(pd.Timestamp.now()-start)

Output:

0 days 00:05:32.541600

I would recommend using this if time precision is not the most important, otherwise use time library:

%timeit pd.Timestamp.now() outputs 3.29 µs ± 214 ns per loop

%timeit time.time() outputs 154 ns ± 13.3 ns per loop

Where does gcc look for C and C++ header files?

You can create a file that attempts to include a bogus system header. If you run gcc in verbose mode on such a source, it will list all the system include locations as it looks for the bogus header.

$ echo "#include <bogus.h>" > t.c; gcc -v t.c; rm t.c

[..]

#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.

[..]

t.c:1:32: error: bogus.h: No such file or directory

Fixing a systemd service 203/EXEC failure (no such file or directory)

I actually used the answer from How do I run a node.js app as a background service? combined with what dwrz said above. In my case, I was creating a Discord bot that needed to be able to run when I was not around.

With this service in place, I initially got the same error that the initial poster did, which brought me here. I was missing the #!/usr/bin/env node at the top of my executed node.js script.

Since then, no problems, although I intend to see what else can be extended to the service itself.

setOnItemClickListener on custom ListView

Sorry for coding with Kotlin. But I faced the same problem. I solved with the code below.

list.setOnItemClickListener{ _, view, _, _ ->
        val text1 = view.find<TextView>(R.id.~~).text

        }

You can put an id which shows a TextView that you want in "~~".

Hope it'll help someone!

what is the most efficient way of counting occurrences in pandas?

When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()

-Source.

Unzipping files in Python

If you want to do it in shell, instead of writing code.

 python3 -m zipfile -e myfiles.zip myfiles/

myfiles.zip is the zip archive and myfiles is the path to extract the files.

CSS checkbox input styling

I create my own solution without label

_x000D_
_x000D_
input[type=checkbox] {_x000D_
         position: relative;_x000D_
        cursor: pointer;_x000D_
    }_x000D_
    input[type=checkbox]:before {_x000D_
         content: "";_x000D_
         display: block;_x000D_
         position: absolute;_x000D_
         width: 16px;_x000D_
         height: 16px;_x000D_
         top: 0;_x000D_
         left: 0;_x000D_
         border: 2px solid #555555;_x000D_
         border-radius: 3px;_x000D_
         background-color: white;_x000D_
}_x000D_
    input[type=checkbox]:checked:after {_x000D_
         content: "";_x000D_
         display: block;_x000D_
         width: 5px;_x000D_
         height: 10px;_x000D_
         border: solid black;_x000D_
         border-width: 0 2px 2px 0;_x000D_
         -webkit-transform: rotate(45deg);_x000D_
         -ms-transform: rotate(45deg);_x000D_
         transform: rotate(45deg);_x000D_
         position: absolute;_x000D_
         top: 2px;_x000D_
         left: 6px;_x000D_
}
_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
input[type=checkbox] {_x000D_
         position: relative;_x000D_
        cursor: pointer;_x000D_
    }_x000D_
    input[type=checkbox]:before {_x000D_
         content: "";_x000D_
         display: block;_x000D_
         position: absolute;_x000D_
         width: 20px;_x000D_
         height: 20px;_x000D_
         top: 0;_x000D_
         left: 0;_x000D_
         background-color:#e9e9e9;_x000D_
}_x000D_
input[type=checkbox]:checked:before {_x000D_
         content: "";_x000D_
         display: block;_x000D_
         position: absolute;_x000D_
         width: 20px;_x000D_
         height: 20px;_x000D_
         top: 0;_x000D_
         left: 0;_x000D_
         background-color:#1E80EF;_x000D_
}_x000D_
    input[type=checkbox]:checked:after {_x000D_
         content: "";_x000D_
         display: block;_x000D_
         width: 5px;_x000D_
         height: 10px;_x000D_
         border: solid white;_x000D_
         border-width: 0 2px 2px 0;_x000D_
         -webkit-transform: rotate(45deg);_x000D_
         -ms-transform: rotate(45deg);_x000D_
         transform: rotate(45deg);_x000D_
         position: absolute;_x000D_
         top: 2px;_x000D_
         left: 6px;_x000D_
}
_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">
_x000D_
_x000D_
_x000D_

Adjust width of input field to its input

A bullet-proof, generic way has to:

  1. Take into account all possible styles of the measured input element
  2. Be able to apply the measurement on any input without modifying the HTML or

Codepen demo

_x000D_
_x000D_
var getInputValueWidth = (function(){
  // https://stackoverflow.com/a/49982135/104380
  function copyNodeStyle(sourceNode, targetNode) {
    var computedStyle = window.getComputedStyle(sourceNode);
    Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
  }
  
  function createInputMeassureElm( inputelm ){
    // create a dummy input element for measurements
    var meassureElm = document.createElement('span');
    // copy the read input's styles to the dummy input
    copyNodeStyle(inputelm, meassureElm);
    
    // set hard-coded styles needed for propper meassuring 
    meassureElm.style.width = 'auto';
    meassureElm.style.position = 'absolute';
    meassureElm.style.left = '-9999px';
    meassureElm.style.top = '-9999px';
    meassureElm.style.whiteSpace = 'pre';
    
    meassureElm.textContent = inputelm.value || '';
    
    // add the meassure element to the body
    document.body.appendChild(meassureElm);
    
    return meassureElm;
  }
  
  return function(){
    return createInputMeassureElm(this).offsetWidth;
  }
})();


// delegated event binding
document.body.addEventListener('input', onInputDelegate)

function onInputDelegate(e){
  if( e.target.classList.contains('autoSize') )
    e.target.style.width = getInputValueWidth.call(e.target) + 'px';
}
_x000D_
input{ 
  font-size:1.3em; 
  padding:5px; 
  margin-bottom: 1em;
}

input.type2{
  font-size: 2.5em;
  letter-spacing: 4px;
  font-style: italic;
}
_x000D_
<input class='autoSize' value="type something">
<br>
<input class='autoSize type2' value="here too">
_x000D_
_x000D_
_x000D_

How to drop all tables in a SQL Server database?

The accepted answer doesn't support Azure. It uses an undocumented stored procedure "sp_MSforeachtable". If you get an "azure could not find stored procedure 'sp_msforeachtable" error when running or simply want to avoid relying on undocumented features (which can be removed or have their functionality changed at any point) then try the below.

This version ignores the entity framework migration history table "__MigrationHistory" and the "database_firewall_rules" which is an Azure table you will not have permission to delete.

Lightly tested on Azure. Do check to make this this has no undesired effects on your environment.

DECLARE @sql NVARCHAR(2000)

WHILE(EXISTS(SELECT 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY'))
BEGIN
    SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
    EXEC(@sql)
    PRINT @sql
END

WHILE(EXISTS(SELECT * from INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'))
BEGIN
    SELECT TOP 1 @sql=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'
    EXEC(@sql)
    PRINT @sql
END

Taken from:

https://edspencer.me.uk/2013/02/25/drop-all-tables-in-a-sql-server-database-azure-friendly/

http://www.sqlservercentral.com/blogs/sqlservertips/2011/10/11/remove-all-foreign-keys/

Python 2.7 getting user input and manipulating as string without quotations

This is my work around to fail safe in case if i will need to move to python 3 in future.

def _input(msg):
  return raw_input(msg)

Javascript - sort array based on another array

let a = ['A', 'B', 'C' ]

let b = [3, 2, 1]

let c = [1.0, 5.0, 2.0]

// these array can be sorted by sorting order of b

const zip = rows => rows[0].map((_, c) => rows.map(row => row[c]))

const sortBy = (a, b, c) => {
  const zippedArray = zip([a, b, c])
  const sortedZipped = zippedArray.sort((x, y) => x[1] - y[1])

  return zip(sortedZipped)
}

sortBy(a, b, c)

Custom sort function in ng-repeat

The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat. http://toddmotto.com/everything-about-custom-filters-in-angular-js

For sorting object with properties, this is the code I have used: (Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.

self.myArray.sort(function(itemA, itemB) {
    if (self.sortOrder === "ASC") {
        return itemA[columnName] > itemB[columnName];
    } else {
        return itemA[columnName] < itemB[columnName];
    }
});

no module named zlib

For the case I met, I found there are missing modules after make. So I did the following:

  1. install zlib-devel
  2. make and install python again.

Why should I use var instead of a type?

In this case it is just coding style.

Use of var is only necessary when dealing with anonymous types.
In other situations it's a matter of taste.

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

what does numpy ndarray shape do?

Unlike it's most popular commercial competitor, numpy pretty much from the outset is about "arbitrary-dimensional" arrays, that's why the core class is called ndarray. You can check the dimensionality of a numpy array using the .ndim property. The .shape property is a tuple of length .ndim containing the length of each dimensions. Currently, numpy can handle up to 32 dimensions:

a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32

If a numpy array happens to be 2d like your second example, then it's appropriate to think about it in terms of rows and columns. But a 1d array in numpy is truly 1d, no rows or columns.

If you want something like a row or column vector you can achieve this by creating a 2d array with one of its dimensions equal to 1.

a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T

What is the best project structure for a Python application?

According to Jean-Paul Calderone's Filesystem structure of a Python project:

Project/
|-- bin/
|   |-- project
|
|-- project/
|   |-- test/
|   |   |-- __init__.py
|   |   |-- test_main.py
|   |   
|   |-- __init__.py
|   |-- main.py
|
|-- setup.py
|-- README

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

This can happen if you accidentally are not dragging the element that does have an id assigned (for example you are dragging the surrounding element). In that case the ID is empty and the function drag() is assigning an empty value which is then passed to drop() and fails there.

Try assigning the ids to all of your elements, including the tds, divs, or whatever is around your draggable element.

how to download image from any web page in java

   // Do you want to download an image?
   // But are u denied access?
   // well here is the solution.

    public static void DownloadImage(String search, String path) {

    // This will get input data from the server
    InputStream inputStream = null;

    // This will read the data from the server;
    OutputStream outputStream = null;

    try {
        // This will open a socket from client to server
        URL url = new URL(search);

       // This user agent is for if the server wants real humans to visit
        String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";

       // This socket type will allow to set user_agent
        URLConnection con = url.openConnection();

        // Setting the user agent
        con.setRequestProperty("User-Agent", USER_AGENT);

        // Requesting input data from server
        inputStream = con.getInputStream();

        // Open local file writer
        outputStream = new FileOutputStream(path);

        // Limiting byte written to file per loop
        byte[] buffer = new byte[2048];

        // Increments file size
        int length;

        // Looping until server finishes
        while ((length = inputStream.read(buffer)) != -1) {
            // Writing data
            outputStream.write(buffer, 0, length);
        }
    } catch (Exception ex) {
        Logger.getLogger(WebCrawler.class.getName()).log(Level.SEVERE, null, ex);
     }

     // closing used resources
     // The computer will not be able to use the image
     // This is a must

     outputStream.close();
     inputStream.close();
}

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

go to the directory of .Net framework and register their the respective dll with Regsvr32.exe white space dll path.

MongoDB and "joins"

The database does not do joins -- or automatic "linking" between documents. However you can do it yourself client side. If you need to do 2, that is ok, but if you had to do 2000, the number of client/server turnarounds would make the operation slow.

In MongoDB a common pattern is embedding. In relational when normalizing things get broken into parts. Often in mongo these pieces end up being a single document, so no join is needed anyway. But when one is needed, one does it client-side.

Consider the classic ORDER, ORDER-LINEITEM example. One order and 8 line items are 9 rows in relational; in MongoDB we would typically just model this as a single BSON document which is an order with an array of embedded line items. So in that case, the join issue does not arise. However the order would have a CUSTOMER which probably is a separate collection - the client could read the cust_id from the order document, and then go fetch it as needed separately.

There are some videos and slides for schema design talks on the mongodb.org web site I belive.

onclick="location.href='link.html'" does not load page in Safari

try

_x000D_
_x000D_
<select onchange="location=this.value">_x000D_
    <option value="unit_01.htm">Unit 1</option>_x000D_
    <option value="#5.2" selected >Bookmark 2</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to Convert UTC Date To Local time Zone in MySql Select Query

 select convert_tz(now(),@@session.time_zone,'+05:30')

replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994

to format into desired time format, eg:

 select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p') 

you will get similar to this -> Dec 17 2014 10:39:56 AM

How to unpackage and repackage a WAR file

you can update your war from the command line using java commands as mentioned here:

jar -uvf test.war yourclassesdir 

Other useful commands:

Command to unzip/explode the war file

jar -xvf test.war

Command to create the war file

jar -cvf test.war yourclassesdir 

Eg:

jar -cvf test.war *
jar -cvf test.war WEB-INF META-INF

How do I create a new branch?

In the Repository Browser of TortoiseSVN, find the branch that you want to create the new branch from. Right-click, Copy To.... and enter the new branch path. Now you can "switch" your local WC to that branch.

How to send parameters from a notification-click to an activity?

If you use

android:taskAffinity="myApp.widget.notify.activity"
android:excludeFromRecents="true"

in your AndroidManifest.xml file for the Activity to launch, you have to use the following in your intent:

Intent notificationClick = new Intent(context, NotifyActivity.class);
    Bundle bdl = new Bundle();
    bdl.putSerializable(NotifyActivity.Bundle_myItem, myItem);
    notificationClick.putExtras(bdl);
    notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
    notificationClick.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);  // schließt tasks der app und startet einen seperaten neuen

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(NotifyActivity.class);
    stackBuilder.addNextIntent(notificationClick);

    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(notificationPendingIntent);

Important is to set unique data e.g. using an unique id like:

notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));

How to convert a normal Git repository to a bare one?

In short: replace the contents of repo with the contents of repo/.git, then tell the repository that it is now a bare repository.

To do this, execute the following commands:

cd repo
mv .git ../repo.git # renaming just for clarity
cd ..
rm -fr repo
cd repo.git
git config --bool core.bare true

Note that this is different from doing a git clone --bare to a new location (see below).

How to pass data to all views in Laravel 5?

I think that the best way is with View Composers. If someone came here and want to find how can do it with View Composers way, read my answer => How to share a variable across all views?

How do I point Crystal Reports at a new database

Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.

You will need to do this for the 'Subreports' nodes as well.

FYI, you can also do individual tables by selecting each individually, then choosing Update.

How to extract closed caption transcript from YouTube video?

You can download the streaming subtitles from YouTube with KeepSubs DownSub and SaveSubs.

You can choose from the Automatic Transcript or author supplied close captions. It also offers the possibility to automatically translate the English subtitles into other languages using Google Translate.