Programs & Examples On #Coldbox

ColdBox is an object-oriented, event-driven framework for ColdFusion that includes tools to help developers with bug reporting, logging, enterprise caching, debugging, i18n, URL rewriting, ORM integration, testing, and mocking.

ASP.NET Background image

1) Use a CSS stylesheet - add <link rel="stylesheet" type="text/css" href="styles.css" /> to include it.

2) Apply the background to the body:

body {
    background-image:url('images/background.png');
    background-repeat:no-repeat;
    background-attachment:fixed;
}

See:

http://www.w3schools.com/css/css_howto.asp

http://www.w3schools.com/cssref/pr_background-position.asp

How to create a directory using Ansible

to create directory

ansible host_name -m file -a "dest=/home/ansible/vndir state=directory"

sql try/catch rollback/commit - preventing erroneous commit after rollback

Transaction counter

--@@TRANCOUNT = 0
begin try
--@@TRANCOUNT = 0
BEGIN TRANSACTION tran1
 --@@TRANCOUNT = 1

        --your code
        -- if failed  @@TRANCOUNT = 1
        -- if success @@TRANCOUNT = 0

COMMIT TRANSACTION tran1

end try

begin catch
    print 'FAILED'
end catch

Deserialize a json string to an object in python

There are different methods to deserialize json string to an object. All above methods are acceptable but I suggest using a library to prevent duplicate key issues or serializing/deserializing of nested objects.

Pykson, is a JSON Serializer and Deserializer for Python which can help you achieve. Simply define Payload class model as JsonObject then use Pykson to convert json string to object.

from pykson import Pykson, JsonObject, StringField

class Payload(pykson.JsonObject):
    action = StringField()
    method = StringField()
    data = StringField()

json_text = '{"action":"print","method":"onData","data":"Madan Mohan"}'
payload = Pykson.from_json(json_text, Payload)

How can I get the class name from a C++ object?

To get class name without mangling stuff you can use func macro in constructor:

class MyClass {
    const char* name;
    MyClass() {
        name = __func__;
    }
}

How to generate XML from an Excel VBA macro?

You might like to consider ADO - a worksheet or range can be used as a table.

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adPersistXML = 1

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

''It wuld probably be better to use the proper name, but this is
''convenient for notes
strFile = Workbooks(1).FullName

''Note HDR=Yes, so you can use the names in the first row of the set
''to refer to columns, note also that you will need a different connection
''string for >=2007
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
        & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"


cn.Open strCon
rs.Open "Select * from [Sheet1$]", cn, adOpenStatic, adLockOptimistic

If Not rs.EOF Then
    rs.MoveFirst
    rs.Save "C:\Docs\Table1.xml", adPersistXML
End If

rs.Close
cn.Close

Python handling socket.error: [Errno 104] Connection reset by peer

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)

So you can't do anything about it, it is the issue of the server.

But you could use try .. except block to handle that exception:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        raise # Not error we are looking for
    pass # Handle error here.

Get data from JSON file with PHP

Get the content of the JSON file using file_get_contents():

$str = file_get_contents('http://example.com/example.json/');

Now decode the JSON using json_decode():

$json = json_decode($str, true); // decode the JSON into an associative array

You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:

echo '<pre>' . print_r($json, true) . '</pre>';

This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:

$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];

Or loop through the array however you wish:

foreach ($json['daily']['data'] as $field => $value) {
    // Use $field and $value here
}

Demo!

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

You can implement this way

$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
        UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
        ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
    })

RealMen.query() //GET  /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1

//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1

//query string
RealMen.query({name:'john'}) //GET /realmen?name=john

Documentation: https://docs.angularjs.org/api/ngResource/service/$resource

Hope it helps

Integrity constraint violation: 1452 Cannot add or update a child row:

I hope my decision will help. I had a similar error in Laravel. I added a foreign key to the wrong table.
Wrong code:

Schema::create('comments', function (Blueprint $table) {
$table->unsignedBigInteger('post_id')->index()->nullable();
...
$table->foreign('post_id')->references('id')->on('comments')->onDelete('cascade');
    });


Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    ...
    });

Please note to the function on('comments') above. Correct code

 $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

Override standard close (X) button in a Windows Form

The accepted answer works quite well. An alternative method that I have used is to create a FormClosing method for the main Form. This is very similar to the override. My example is for an application that minimizes to the system tray when clicking the close button on the Form.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.ApplicationExitCall)
        {
            return;
        }
        else
        {
            e.Cancel = true;
            WindowState = FormWindowState.Minimized;
        }            
    }

This will allow ALT+F4 or anything in the Application calling Application.Exit(); to act as normal while clicking the (X) will minimize the Application.

How to split a string literal across multiple lines in C / Objective-C?

There are two ways to split strings over multiple lines:

Using \

All lines in C can be split into multiple lines using \.

Plain C:

char *my_string = "Line 1 \
                   Line 2";

Objective-C:

NSString *my_string = @"Line1 \
                        Line2";

Better approach

There's a better approach that works just for strings.

Plain C:

char *my_string = "Line 1 "
                  "Line 2";

Objective-C:

NSString *my_string = @"Line1 "
                       "Line2";    // the second @ is optional

The second approach is better, because there isn't a lot of whitespace included. For a SQL query however, both are possible.

NOTE: With a #define, you have to add an extra '\' to concatenate the two strings:

Plain C:

#define kMyString "Line 1"\
                  "Line 2"

How to open local file on Jupyter?

I do not know if it's what you were looking for, but it sounds to me something like this.

This is for linux (ubuntu) but maybe it also works on mac:

If the file is a pdf called 'book.pdf' and is located in your downloads, then

import subprocess

path='/home/user/Downloads/book.pdf'
subprocess.call(['evince', path])

where evince is the program that open pdfs in ubuntu

How to disable Google Chrome auto update?

For Ubuntu:

  1. go to 'Software & Updates'.
  2. click 'Other Software' tab.
  3. Uncheck the next checkbox 'http://dl.google.com/linux/chrome/deb/ stable main'

enter image description here

Regex to replace everything except numbers and a decimal point

Removing only decimal part can be done as follows:

number.replace(/(\.\d+)+/,'');

This would convert 13.6667px into 13px (leaving units px untouched).

Force div element to stay in same place, when page is scrolled

Use position: fixed instead of position: absolute.

See here.

Java split string to array

Consider this example:

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|")));
    // output : [Real, How, To]
  }
}

The result does not include the empty strings between the "|" separator. To keep the empty strings :

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|", -1)));
    // output : [Real, How, To, , , ]
  }
}

For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html

Find the IP address of the client in an SSH session

Try the following to get just the IP address:

who am i|awk '{ print $5}'

How to run a .awk file?

If you put #!/bin/awk -f on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)

#!/bin/awk -f
BEGIN {}  # Begin section
{}        # Loop section
END{}     # End section

Change the file to be executable by running:

chmod ugo+x ./awk-script

and you can then call your AWK script like this:

`$ echo "something" | ./awk-script`

How do I remove the title bar from my app?

I have faced the same problem as you, and solve this problem just by changing the class which I extended.

//you will get the app that does not have a title bar at the top.
import android.app.Activity;
public class MainActivity extends Activity
{}

//you will get the app that has title bar at top
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
{}

I hope this will solve your problem.

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

For .NET < 4.0 (e.x: Unity) you can write an extension method to have the TimeSpan.ToString(string format) behavior like .NET > 4.0

public static class TimeSpanExtensions
{
    public static string ToString(this TimeSpan time, string format)
    {
        DateTime dateTime = DateTime.Today.Add(time);
        return dateTime.ToString(format);
    }
}

And from anywhere in your code you can use it like:

var time = TimeSpan.FromSeconds(timeElapsed);

string formattedDate = time.ToString("hh:mm:ss:fff");

This way you can format any TimeSpanobject by simply calling ToString from anywhere of your code.

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I had this issue and i fixed with the code below.

@Configuration
open class JacksonMapper {

    @Bean
    open fun mapper(): ObjectMapper {
        val mapper = ObjectMapper()
        ...

        mapper.registerModule(KotlinModule())
        return mapper
    }
}

Efficiently finding the last line in a text file

Here's a slightly different solution. Instead of multi-line, I focused on just the last line, and instead of a constant block size, I have a dynamic (doubling) block size. See comments for more info.

# Get last line of a text file using seek method.  Works with non-constant block size.  
# IDK if that speed things up, but it's good enough for us, 
# especially with constant line lengths in the file (provided by len_guess), 
# in which case the block size doubling is not performed much if at all.  Currently,
# we're using this on a textfile format with constant line lengths.
# Requires that the file is opened up in binary mode.  No nonzero end-rel seeks in text mode.
REL_FILE_END = 2
def lastTextFileLine(file, len_guess=1):
    file.seek(-1, REL_FILE_END)      # 1 => go back to position 0;  -1 => 1 char back from end of file
    text = file.read(1)
    tot_sz = 1              # store total size so we know where to seek to next rel file end
    if text != b'\n':        # if newline is the last character, we want the text right before it
        file.seek(0, REL_FILE_END)    # else, consider the text all the way at the end (after last newline)
        tot_sz = 0
    blocks = []           # For storing succesive search blocks, so that we don't end up searching in the already searched
    j = file.tell()          # j = end pos
    not_done = True
    block_sz = len_guess
    while not_done:
        if j < block_sz:   # in case our block doubling takes us past the start of the file (here j also = length of file remainder)
            block_sz = j
            not_done = False
        tot_sz += block_sz
        file.seek(-tot_sz, REL_FILE_END)         # Yes, seek() works with negative numbers for seeking backward from file end
        text = file.read(block_sz)
        i = text.rfind(b'\n')
        if i != -1:
            text = text[i+1:].join(reversed(blocks))
            return str(text)
        else:
            blocks.append(text)
            block_sz <<= 1    # double block size (converge with open ended binary search-like strategy)
            j = j - block_sz      # if this doesn't work, try using tmp j1 = file.tell() above
    return str(b''.join(reversed(blocks)))      # if newline was never found, return everything read

Ideally, you'd wrap this in a class LastTextFileLine and keep track of a moving average of line lengths. This would give you a good len_guess maybe.

Android : How to read file in bytes?

Since the accepted BufferedInputStream#read isn't guaranteed to read everything, rather than keeping track of the buffer sizes myself, I used this approach:

    byte bytes[] = new byte[(int) file.length()];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    DataInputStream dis = new DataInputStream(bis);
    dis.readFully(bytes);

Blocks until a full read is complete, and doesn't require extra imports.

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

If you are providing mappings like this:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ClassificationMap());
        modelBuilder.Configurations.Add(new CompanyMap());
        modelBuilder.Configurations.Add(new GroupMap());
        ....  
    }

Remember to add the map for BaseCs.

You won't get a compile error if it is missing. But you will get a runtime error when you use the entity.

How do I alias commands in git?

You can set custom git aliases using git's config. Here's the syntax:

git config --global alias.<aliasName> "<git command>"

For example, if you need an alias to display a list of files which have merge conflicts, run:

git config --global alias.conflicts "diff --name-only --diff-filter=U"

Now you can use the above command only using "conflicts":

git conflicts
# same as running: git diff --name-only --diff-filter=U

How to divide flask app into multiple py files?

This task can be accomplished without blueprints and tricky imports using Centralized URL Map

app.py

import views
from flask import Flask

app = Flask(__name__)

app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

views.py

from flask import render_template

def index():
    return render_template('index.html')

def other():
    return render_template('other.html')

CSS3 Spin Animation

The only answer which gives the correct 359deg:

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(359deg); }
}

&.active {
  animation: spin 1s linear infinite;
}

Here's a useful gradient so you can prove it is spinning (if its a circle):

background: linear-gradient(to bottom, #000000 0%,#ffffff 100%);

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

how to convert from int to char*?

You also can use casting.

example:

string s;
int value = 3;
s.push_back((char)('0' + value));

How to install popper.js with Bootstrap 4?

It's simple you can Visit this, And save the file as popper.min.js

then import it.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.css';
import './index.css';
import 'bootstrap/dist/js/popper.min.js';
global.jQuery = require('jquery');
require('bootstrap');

Parsing JSON array into java.util.List with Gson

Definitely the easiest way to do that is using Gson's default parsing function fromJson().

There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).

In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();

List<String> yourList = new Gson().fromJson(yourJson, listType);

In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.

You may want to take a look at Gson API documentation.

file_get_contents() Breaks Up UTF-8 Characters

Try this too

 $url = 'http://www.domain.com/';
    $html = file_get_contents($url);

    //Change encoding to UTF-8 from ISO-8859-1
    $html = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $html);

Regular expression to get a string between two strings in Javascript

  • You need capture the .*
  • You can (but don't have to) make the .* nongreedy
  • There's really no need for the lookahead.

    > /cow(.*?)milk/i.exec('My cow always gives milk');
    ["cow always gives milk", " always gives "]
    

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

If you're running on a Mac you could just search for Install Certificates.command on the spotlight and hit enter.

CSS body background image fixed to full screen even when zooming in/out

Here is the simple code for full page background image when zooming you just apply the width:100% in style/css thats it

position:absolute; width:100%;

C#: calling a button event handler method without actually clicking the button

All above methods are not good because you might change event function name. The easiest is:

btnTest.PerfromClick();

Show a PDF files in users browser via PHP/Perl

You could modify a PDF renderer such as xpdf or evince to render into a graphics image on your server, and then deliver the image to the user. This is how Google's quick view of PDF files works, they render it locally, then deliver images to the user. No downloaded PDF file, and the source is pretty well obscured. :)

Initializing C dynamic arrays

I think the more tedious way is the only way to do it. I tried the first one and it doesn't compile (After commenting the '...')

No many shortcuts in 'C' I guess.ac

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

try it.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Problems installing the devtools package

Best solution to solve this. I was searching the same problem. I spent 1 day and then I got solution. Now, It is well.

Check your R version in bash terminal if you are on Ubuntu or Linux.

R --version

then use these commands

sudo apt-get update 
sudo apt-get upgrade              

Now check the new version of R. Use this command

sudo apt-cache showpkg r-base

Now update the R only.

sudo apt-get install r-base

Now R will be updated and the error will be removed. Make sure to cd the library path where you want to install the new package. This way in bash terminal. Try to create the R directory at home folder or it will be at the default. Locate this location for package ~/R/lib/ .

R
.libPaths("~/R/lib")
install.packages("devtools")

OR

install.packages("devtools", lib="~/R/lib")

Updating a java map entry

Use

table.put(key, val);

to add a new key/value pair or overwrite an existing key's value.

From the Javadocs:

V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Convert String to int array in java

try this one, it might be helpful for you

String arr= "[1,2]";
int[] arr=Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();

SQLite add Primary Key

I tried to add the primary key afterwards by changing the sqlite_master table directly. This trick seems to work. It is a hack solution of course.

In short: create a regular (unique) index on the table, then make the schema writable and change the name of the index to the form reserved by sqlite to identify a primary key index, (i.e. sqlite_autoindex_XXX_1, where XXX is the table name) and set the sql string to NULL. At last change the table definition itself. One pittfal: sqlite does not see the index name change until the database is reopened. This seems like a bug, but not a severe one (even without reopening the database, you can still use it).

Suppose the table looks like:

CREATE TABLE tab1(i INTEGER, j INTEGER, t TEXT);

Then I did the following:

BEGIN;
CREATE INDEX pk_tab1 ON tab1(i,j);
pragma writable_schema=1;
UPDATE sqlite_master SET name='sqlite_autoindex_tab1_1',sql=null WHERE name='pk_tab1';
UPDATE sqlite_master SET sql='CREATE TABLE tab1(i integer,j integer,t text,primary key(i,j))' WHERE name='tab1';
COMMIT;

Some tests (in sqlite shell):

sqlite> explain query plan select * from tab1 order by i,j;
0|0|0|SCAN TABLE tab1 USING INDEX sqlite_autoindex_tab1_1
sqlite> drop index sqlite_autoindex_tab1_1;
Error: index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped    

PHP import Excel into database (xls & xlsx)

I wrote an inherited class:

_x000D_
_x000D_
<?php_x000D_
class ExcelReader extends Spreadsheet_Excel_Reader { _x000D_
 _x000D_
 function GetInArray($sheet=0) {_x000D_
_x000D_
  $result = array();_x000D_
_x000D_
   for($row=1; $row<=$this->rowcount($sheet); $row++) {_x000D_
    for($col=1;$col<=$this->colcount($sheet);$col++) {_x000D_
     if(!$this->sheets[$sheet]['cellsInfo'][$row][$col]['dontprint']) {_x000D_
      $val = $this->val($row,$col,$sheet);_x000D_
      $result[$row][$col] = $val;_x000D_
     }_x000D_
    }_x000D_
   }_x000D_
  return $result;_x000D_
 }_x000D_
_x000D_
}_x000D_
?>
_x000D_
_x000D_
_x000D_

So I can do this:

_x000D_
_x000D_
<?php_x000D_
_x000D_
 $data = new ExcelReader("any_excel_file.xls");_x000D_
 print_r($data->GetInArray());_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

Clear listview content?

You need to call both clear() from ArrayAdapter and notifyDataSetChanged() both.

Below is link click

How to log cron jobs?

Here is my code:

* * * * * your_script_fullpath >> your_log_path 2>&1

How can I create a self-signed cert for localhost?

I would recomment Pluralsight's tool for creating self-signed-certs: http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net

Make your cert as a .pfx and import it into IIS. And add it as a trusted root cert authority.

How to make Bitmap compress without change the bitmap size?

Are you sure it is smaller?

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

Gives

12-07 17:43:36.333: E/Original   dimensions(278): 1024 768
12-07 17:43:36.333: E/Compressed dimensions(278): 1024 768

Maybe you get your bitmap from a resource, in which case the bitmap dimension will depend on the phone screen density

Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());

12-07 17:43:38.733: E/Dimensions(278): 768 576

'module' object has no attribute 'DataFrame'

For me he problem was that my script was called pandas.py in the folder pandas which obviously messed up my imports.

How to count number of unique values of a field in a tab-delimited text file?

This script outputs the number of unique values in each column of a given file. It assumes that first line of given file is header line. There is no need for defining number of fields. Simply save the script in a bash file (.sh) and provide the tab delimited file as a parameter to this script.

Code

#!/bin/bash

awk '
(NR==1){
    for(fi=1; fi<=NF; fi++)
        fname[fi]=$fi;
} 
(NR!=1){
    for(fi=1; fi<=NF; fi++) 
        arr[fname[fi]][$fi]++;
} 
END{
    for(fi=1; fi<=NF; fi++){
        out=fname[fi];
        for (item in arr[fname[fi]])
            out=out"\t"item"_"arr[fname[fi]][item];
        print(out);
    }
}
' $1

Execution Example:

bash> ./script.sh <path to tab-delimited file>

Output Example

isRef    A_15      C_42     G_24     T_18
isCar    YEA_10    NO_40    NA_50
isTv     FALSE_33  TRUE_66

Youtube autoplay not working on mobile devices with embedded HTML5 player

As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.

See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512

How can I call a shell command in my Perl script?

As you become more experienced with using Perl, you'll find that there are fewer and fewer occasions when you need to run shell commands. For example, one way to get a list of files is to use Perl's built-in glob function. If you want the list in sorted order you could combine it with the built-in sort function. If you want details about each file, you can use the stat function. Here's an example:

#!/usr/bin/perl

use strict;
use warnings;

foreach my $file ( sort glob('/home/grant/*') ) {
    my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
        = stat($file);
    printf("%-40s %8u bytes\n", $file, $size);
}

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

jQuery: Performing synchronous AJAX requests

how remote is that url ? is it from the same domain ? the code looks okay

try this

$.ajaxSetup({async:false});
$.get(remote_url, function(data) { remote = data; });
// or
remote = $.get(remote_url).responseText;

Import existing Gradle Git project into Eclipse

Go to the GitHub page where they are maintain the official repository: https://github.com/spring-projects/eclipse-integration-gradle/blob/master/README.md

Copy the latest release link: http://dist.springsource.com/release/TOOLS/gradle (latest release)

Use this in Eclipse->Help->Install New Software..->Paste the link in "Work With"->press enter->select the names of the extension->click next and agree the license and follow the prompts.

After you have installed just import the project as a grade project and eclipse will take of the rest.

Unlink of file Failed. Should I try again?

As mentioned in the above answers, yes file must be used maybe by other java processes, simple way to get rid-off this is, just kill all java processes then execute git pull I did this, it works for me.

For windows kill all java processes:

taskkill /F /IM java.exe

For Linux kill all java processes:

kill -9 `pidof java`

What are best practices for multi-language database design?

Martin's solution is very similar to mine, however how would you handle a default descriptions when the desired translation isn't found ?

Would that require an IFNULL() and another SELECT statement for each field ?

The default translation would be stored in the same table, where a flag like "isDefault" indicates wether that description is the default description in case none has been found for the current language.

How to POST JSON Data With PHP cURL?

Try like this:

$url = 'url_to_post';
// this is only part of the data you need to sen
$customer_data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
// As per your API, the customer data should be structured this way
$data = array("customer" => $customer_data);
// And then encoded as a json string
$data_string = json_encode($data);
$ch=curl_init($url);

curl_setopt_array($ch, array(
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data_string,
    CURLOPT_HEADER => true,
    CURLOPT_HTTPHEADER => array('Content-Type:application/json', 'Content-Length: ' . strlen($data_string)))
));

$result = curl_exec($ch);
curl_close($ch);

The key thing you've forgotten was to json_encode your data. But you also may find it convenient to use curl_setopt_array to set all curl options at once by passing an array.

Get random integer in range (x, y]?

Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

PHP, getting variable from another php-file

using include 'page1.php' in second page is one option but it can generate warnings and errors of undefined variables.
Three methods by which you can use variables of one php file in another php file:

  • use session to pass variable from one page to another
    method:
    first you have to start the session in both the files using php command

    sesssion_start();
    then in first file consider you have one variable
    $x='var1';

    now assign value of $x to a session variable using this:
    $_SESSION['var']=$x;
    now getting value in any another php file:
    $y=$_SESSION['var'];//$y is any declared variable

  • using get method and getting variables on clicking a link
    method

    <a href="page2.php?variable1=value1&variable2=value2">clickme</a>
    getting values in page2.php file by $_GET function:
    $x=$_GET['variable1'];//value1 be stored in $x
    $y=$_GET['variable2'];//vale2 be stored in $y

  • if you want to pass variable value using button then u can use it by following method:

    $x='value1'
    <input type="submit" name='btn1' value='.$x.'/>
    in second php
    $var=$_POST['btn1'];

Swift - Integer conversion to Hours/Minutes/Seconds

Swift 4 I'm using this extension

 extension Double {

    func stringFromInterval() -> String {

        let timeInterval = Int(self)

        let millisecondsInt = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
        let secondsInt = timeInterval % 60
        let minutesInt = (timeInterval / 60) % 60
        let hoursInt = (timeInterval / 3600) % 24
        let daysInt = timeInterval / 86400

        let milliseconds = "\(millisecondsInt)ms"
        let seconds = "\(secondsInt)s" + " " + milliseconds
        let minutes = "\(minutesInt)m" + " " + seconds
        let hours = "\(hoursInt)h" + " " + minutes
        let days = "\(daysInt)d" + " " + hours

        if daysInt          > 0 { return days }
        if hoursInt         > 0 { return hours }
        if minutesInt       > 0 { return minutes }
        if secondsInt       > 0 { return seconds }
        if millisecondsInt  > 0 { return milliseconds }
        return ""
    }
}

useage

// assume myTimeInterval = 96460.397    
myTimeInteval.stringFromInterval() // 1d 2h 47m 40s 397ms

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

Ifelse statement in R with multiple conditions

There is a simpler solution to this. What you describe is the natural behavior of the & operator and can thus be done primatively:

> c(1,1,NA) & c(1,0,NA) & c(1,NA,NA)
[1]  TRUE FALSE    NA

If all are 1, then 1 is returned. If any are 0, then 0. If all are NA, then NA.

In your case, the code would be:

DF$Den<-DF$Denial1 & DF$Denial2 & DF$Denial3

In order for this to work, you will need to stop working in character and use numeric or logical types.

insert/delete/update trigger in SQL server

Not possible, per MSDN:

You can have the same code execute for multiple trigger types, but the syntax does not allow for multiple code blocks in one trigger:

Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger)

CREATE TRIGGER [ schema_name . ]trigger_name 
ON { table | view } 
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER | INSTEAD OF } 
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } 
[ NOT FOR REPLICATION ] 
AS { sql_statement  [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }

jQuery on window resize

Use this:

window.onresize = function(event) {
    ...
}

Run script on mac prompt "Permission denied"

Check the permissions on your Ruby script (may not have execute permission), your theme file and directory (in case it can't read the theme or tries to create other themes in there), and the directory you're in when you run the script (in case it makes temporary files in the current directory rather then /tmp).

Any one of them could be causing you grief.

How to add a new line in textarea element?

You might want to use \n instead of /n.

PYTHONPATH on Linux

  1. PYTHONPATH is an environment variable
  2. Yes (see https://unix.stackexchange.com/questions/24802/on-which-unix-distributions-is-python-installed-as-part-of-the-default-install)
  3. /usr/lib/python2.7 on Ubuntu
  4. you shouldn't install packages manually. Instead, use pip. When a package isn't in pip, it usually has a setuptools setup script which will install the package into the proper location (see point 3).
  5. if you use pip or setuptools, then you don't need to set PYTHONPATH explicitly

If you look at the instructions for pyopengl, you'll see that they are consistent with points 4 and 5.

How to make FileFilter in java?

Another simple example:

public static void listFilesInDirectory(String pathString) {
  // A local class (a class defined inside a block, here a method).
  class MyFilter implements FileFilter {
    @Override
    public boolean accept(File file) {
      return !file.isHidden() && file.getName().endsWith(".txt");
    }
  }

  File directory = new File(pathString);
  File[] files = directory.listFiles(new MyFilter());

  for (File fileLoop : files) {
    System.out.println(fileLoop.getName());
  }
}

// Call it
listFilesInDirectory("C:\\Users\\John\\Documents\\zTemp");

// Output
Cool.txt
RedditKinsey.txt
...

Setting the Vim background colors

Try adding

set background=dark

to your .gvimrc too. This work well for me.

How to get a dependency tree for an artifact?

If you use a current version of m2eclipse (which you should if you use eclipse and maven):

Select the menu entry

Navigate -> Open Maven POM

and enter the artifact you are looking for.

The pom will open in the pom editor, from which you can select the tab Dependency Hierarchy to view the dependency hierarchy (as the name suggests :-) )

How to use npm with node.exe?

Search all .npmrc file in your system.

Please verify that the path you have given is correct. If not please remove the incorrect path.

Best way to do a PHP switch with multiple values per case?

You are simply looking for common patterns in strings. I would have thought a regular expression would be a more efficient way of doing this as PHP implements this with preg_match so little code to write and probably massively quicker. For example:

case preg_match('/^users./'):
// do something here
break;

Store output of subprocess.Popen call in a string

This worked for me for redirecting stdout (stderr can be handled similarly):

from subprocess import Popen, PIPE
pipe = Popen(path, stdout=PIPE)
text = pipe.communicate()[0]

If it doesn't work for you, please specify exactly the problem you're having.

HTML to PDF with Node.js

Extending upon Mustafa's answer.

A) Install http://phantomjs.org/ and then

B) install the phantom node module https://github.com/amir20/phantomjs-node

enter image description here

C) Here is an example of rendering a pdf

var phantom = require('phantom');   

phantom.create().then(function(ph) {
    ph.createPage().then(function(page) {
        page.open("http://www.google.com").then(function(status) {
            page.render('google.pdf').then(function() {
                console.log('Page Rendered');
                ph.exit();
            });
        });
    });
});

Output of the PDF:

enter image description here

EDIT: Silent printing that PDF

java -jar pdfbox-app-2.0.2.jar PrintPDF -silentPrint C:\print_mypdf.pdf

ASP.NET MVC 404 Error Handling

Yet another solution.

Add ErrorControllers or static page to with 404 error information.

Modify your web.config (in case of controller).

<system.web>
    <customErrors mode="On" >
       <error statusCode="404" redirect="~/Errors/Error404" />
    </customErrors>
</system.web>

Or in case of static page

<system.web>
    <customErrors mode="On" >
        <error statusCode="404" redirect="~/Static404.html" />
    </customErrors>
</system.web>

This will handle both missed routes and missed actions.

SELECT query with CASE condition and SUM()

Select SUM(CASE When CPayment='Cash' Then CAmount Else 0 End ) as CashPaymentAmount,
       SUM(CASE When CPayment='Check' Then CAmount Else 0 End ) as CheckPaymentAmount
from TableOrderPayment
Where ( CPayment='Cash' Or CPayment='Check' ) AND CDate<=SYSDATETIME() and CStatus='Active';

How to create a bash script to check the SSH connection?

Just in case someone only wishes to check if port 22 is open on a remote machine, this simple netcat command is useful. I used it because nmap and telnet were not available for me. Moreover, my ssh configuration uses keyboard password auth.

It is a variant of the solution proposed by GUESSWHOz.

nc -q 0 -w 1 "${remote_ip}" 22 < /dev/null &> /dev/null && echo "Port is reachable" || echo "Port is unreachable"

How to copy static files to build directory with Webpack?

Above suggestions are good. But to try to answer your question directly I'd suggest using cpy-cli in a script defined in your package.json.

This example expects node to somewhere on your path. Install cpy-cli as a development dependency:

npm install --save-dev cpy-cli

Then create a couple of nodejs files. One to do the copy and the other to display a checkmark and message.

copy.js

#!/usr/bin/env node

var shelljs = require('shelljs');
var addCheckMark = require('./helpers/checkmark');
var path = require('path');

var cpy = path.join(__dirname, '../node_modules/cpy-cli/cli.js');

shelljs.exec(cpy + ' /static/* /build/', addCheckMark.bind(null, callback));

function callback() {
  process.stdout.write(' Copied /static/* to the /build/ directory\n\n');
}

checkmark.js

var chalk = require('chalk');

/**
 * Adds mark check symbol
 */
function addCheckMark(callback) {
  process.stdout.write(chalk.green(' ?'));
  callback();
}

module.exports = addCheckMark;

Add the script in package.json. Assuming scripts are in <project-root>/scripts/

...
"scripts": {
  "copy": "node scripts/copy.js",
...

To run the sript:

npm run copy

C# LINQ find duplicates in List

there is an answer but i did not understand why is not working;

var anyDuplicate = enumerable.GroupBy(x => x.Key).Any(g => g.Count() > 1);

my solution is like that in this situation;

var duplicates = model.list
                    .GroupBy(s => s.SAME_ID)
                    .Where(g => g.Count() > 1).Count() > 0;
if(duplicates) {
    doSomething();
}

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

jQuery Call to WebService returns "No Transport" error

I solved it simply by removing the domain from the request url.

Before: https://some.domain.com/_vti_bin/service.svc

After: /_vti_bin/service.svc

How to request Location Permission at runtime

This code work for me. I also handled case "Never Ask Me"

In AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

In build.gradle (Module: app)

dependencies {
    ....
    implementation "com.google.android.gms:play-services-location:16.0.0"
}

This is CurrentLocationManager.kt

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.CommonStatusCodes
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.LocationSettingsRequest
import com.google.android.gms.location.LocationSettingsStatusCodes
import java.lang.ref.WeakReference


object CurrentLocationManager : LocationListener {

    const val REQUEST_CODE_ACCESS_LOCATION = 123

    fun checkLocationPermission(activity: Activity) {
        if (ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                activity,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                REQUEST_CODE_ACCESS_LOCATION
            )
        } else {
            Thread(Runnable {
                // Moves the current Thread into the background
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
                //
                requestLocationUpdates(activity)
            }).start()
        }
    }

    /**
     * be used in HomeActivity.
     */
    const val REQUEST_CHECK_SETTINGS = 55
    /**
     * The number of millis in the future from the call to start().
     * until the countdown is done and onFinish() is called.
     *
     *
     * It is also the interval along the way to receive onTick(long) callbacks.
     */
    private const val TWENTY_SECS: Long = 20000
    /**
     * Timer to get location from history when requestLocationUpdates don't return result.
     */
    private var mCountDownTimer: CountDownTimer? = null
    /**
     * WeakReference of current activity.
     */
    private var mWeakReferenceActivity: WeakReference<Activity>? = null
    /**
     * user's location.
     */
    var currentLocation: Location? = null

    @Synchronized
    fun requestLocationUpdates(activity: Activity) {
        if (mWeakReferenceActivity == null) {
            mWeakReferenceActivity = WeakReference(activity)
        } else {
            mWeakReferenceActivity?.clear()
            mWeakReferenceActivity = WeakReference(activity)
        }
        //create location request: https://developer.android.com/training/location/change-location-settings.html#prompt
        val mLocationRequest = LocationRequest()
        // Which your app prefers to receive location updates. Note that the location updates may be
        // faster than this rate, or slower than this rate, or there may be no updates at all
        // (if the device has no connectivity)
        mLocationRequest.interval = 20000
        //This method sets the fastest rate in milliseconds at which your app can handle location updates.
        // You need to set this rate because other apps also affect the rate at which updates are sent
        mLocationRequest.fastestInterval = 10000
        mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        //Get Current Location Settings
        val builder = LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest)
        //Next check whether the current location settings are satisfied
        val client = LocationServices.getSettingsClient(activity)
        val task = client.checkLocationSettings(builder.build())
        //Prompt the User to Change Location Settings
        task.addOnSuccessListener(activity) {
            Log.d("CurrentLocationManager", "OnSuccessListener")
            // All location settings are satisfied. The client can initialize location requests here.
            // If it's failed, the result after user updated setting is sent to onActivityResult of HomeActivity.
            val activity1 = mWeakReferenceActivity?.get()
            if (activity1 != null) {
                startRequestLocationUpdate(activity1.applicationContext)
            }
        }

        task.addOnFailureListener(activity) { e ->
            Log.d("CurrentLocationManager", "addOnFailureListener")
            val statusCode = (e as ApiException).statusCode
            when (statusCode) {
                CommonStatusCodes.RESOLUTION_REQUIRED ->
                    // Location settings are not satisfied, but this can be fixed
                    // by showing the user a dialog.
                    try {
                        val activity1 = mWeakReferenceActivity?.get()
                        if (activity1 != null) {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            val resolvable = e as ResolvableApiException
                            resolvable.startResolutionForResult(
                                activity1, REQUEST_CHECK_SETTINGS
                            )
                        }
                    } catch (sendEx: IntentSender.SendIntentException) {
                        // Ignore the error.
                        sendEx.printStackTrace()
                    }

                LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
                    // Location settings are not satisfied. However, we have no way
                    // to fix the settings so we won't show the dialog.
                }
            }
        }
    }

    fun startRequestLocationUpdate(appContext: Context) {
        val mLocationManager = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (ActivityCompat.checkSelfPermission(
                appContext.applicationContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            //Utilities.showProgressDialog(mWeakReferenceActivity.get());
            if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 10000, 0f, this
                )
            } else {
                mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 10000, 0f, this
                )
            }
        }

        /*Timer to call getLastKnownLocation() when requestLocationUpdates don 't return result*/
        countDownUpdateLocation()
    }

    override fun onLocationChanged(location: Location?) {
        if (location != null) {
            stopRequestLocationUpdates()
            currentLocation = location
        }
    }

    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {

    }

    override fun onProviderEnabled(provider: String) {

    }

    override fun onProviderDisabled(provider: String) {

    }

    /**
     * Init CountDownTimer to to get location from history when requestLocationUpdates don't return result.
     */
    @Synchronized
    private fun countDownUpdateLocation() {
        mCountDownTimer?.cancel()
        mCountDownTimer = object : CountDownTimer(TWENTY_SECS, TWENTY_SECS) {
            override fun onTick(millisUntilFinished: Long) {}

            override fun onFinish() {
                if (mWeakReferenceActivity != null) {
                    val activity = mWeakReferenceActivity?.get()
                    if (activity != null && ActivityCompat.checkSelfPermission(
                            activity,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {
                        val location = (activity.applicationContext
                            .getSystemService(Context.LOCATION_SERVICE) as LocationManager)
                            .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)
                        stopRequestLocationUpdates()
                        onLocationChanged(location)
                    } else {
                        stopRequestLocationUpdates()
                    }
                } else {
                    mCountDownTimer?.cancel()
                    mCountDownTimer = null
                }
            }
        }.start()
    }

    /**
     * The method must be called in onDestroy() of activity to
     * removeUpdateLocation and cancel CountDownTimer.
     */
    fun stopRequestLocationUpdates() {
        val activity = mWeakReferenceActivity?.get()
        if (activity != null) {
            /*if (ActivityCompat.checkSelfPermission(activity,
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {*/
            (activity.applicationContext
                .getSystemService(Context.LOCATION_SERVICE) as LocationManager).removeUpdates(this)
            /*}*/
        }
        mCountDownTimer?.cancel()
        mCountDownTimer = null
    }
}

In MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
...
CurrentLocationManager.checkLocationPermission(this@LoginActivity)
}

override fun onDestroy() {
        CurrentLocationManager.stopRequestLocationUpdates()
        super.onDestroy()
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CurrentLocationManager.REQUEST_CODE_ACCESS_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                //denied
                val builder = AlertDialog.Builder(this)
                builder.setMessage("We need permission to use your location for the purpose of finding friends near you.")
                    .setTitle("Device Location Required")
                    .setIcon(com.eswapp.R.drawable.ic_info)
                    .setPositiveButton("OK") { _, _ ->
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                Manifest.permission.ACCESS_FINE_LOCATION
                            )
                        ) {
                            //only deny
                            CurrentLocationManager.checkLocationPermission(this@LoginActivity)
                        } else {
                            //never ask again
                            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                            val uri = Uri.fromParts("package", packageName, null)
                            intent.data = uri
                            startActivityForResult(intent, CurrentLocationManager.REQUEST_CHECK_SETTINGS)
                        }
                    }
                    .setNegativeButton("Ask Me Later") { _, _ ->

                    }
                // Create the AlertDialog object and return it
                val dialog = builder.create()
                dialog.show()
            } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                CurrentLocationManager.requestLocationUpdates(this)
            }
        }
    }

    //Forward Login result to the CallBackManager in OnActivityResult()
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            //case 1. After you allow the app access device location, Another dialog will be displayed to request you to turn on device location
            //case 2. Or You chosen Never Ask Again, you open device Setting and enable location permission
            CurrentLocationManager.REQUEST_CHECK_SETTINGS -> when (resultCode) {
                RESULT_OK -> {
                    Log.d("REQUEST_CHECK_SETTINGS", "RESULT_OK")
                    //case 1. You choose OK
                    CurrentLocationManager.startRequestLocationUpdate(applicationContext)
                }
                RESULT_CANCELED -> {
                    Log.d("REQUEST_CHECK_SETTINGS", "RESULT_CANCELED")
                    //case 1. You choose NO THANKS
                    //CurrentLocationManager.requestLocationUpdates(this)

                    //case 2. In device Setting screen: user can enable or not enable location permission,
                    // so when user back to this activity, we should re-call checkLocationPermission()
                    CurrentLocationManager.checkLocationPermission(this@LoginActivity)
                }
                else -> {
                    //do nothing
                }
            }
            else -> {
                super.onActivityResult(requestCode, resultCode, data)
            }
        }
    }

Check If array is null or not in php

if array is look like this [null] or [null, null] or [null, null, null, ...]

you can use implode:

implode is use for convert array to string.

if(implode(null,$arr)==null){
     //$arr is empty
}else{
     //$arr has some value rather than null
}

How to have a default option in Angular.js select box

You can simply use ng-init like this

<select ng-init="somethingHere = options[0]" 
        ng-model="somethingHere" 
        ng-options="option.name for option in options">
</select>

How to modify list entries during for loop?

It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:

my_strings = ['a','b','c','d','e']
undesirable_strings = ['b','d']
for undesirable_string in undesirable_strings:
    for i in range(my_strings.count(undesirable_string)):
        my_strings.remove(undesirable_string)

which changes my_strings to ['a', 'c', 'e']

How to make EditText not editable through XML in Android?

As mentioned in other answers, you can do a setEnabled(false) but since you are asking how to set it via XML, here is how to do it.

Add the following attribute to your EditText:

android:enabled="false"

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

Replace multiple characters in one replace call

For replacing with nothing, tckmn's answer is the best.

If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:

const replacements = {
  '’': "'",
  '“': '"',
  '”': '"',
  '—': '---',
  '–': '--',
};
const replacement_regex = new RegExp(Object
  .keys(replacements)
  // escape any regex literals found in the replacement keys:
  .map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
  .join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);

Delete certain lines in a txt file via a batch file

You can accomplish the same solution as @paxdiablo's using just findstr by itself. There's no need to pipe multiple commands together:

findstr /V "ERROR REFERENCE" infile.txt > outfile.txt

Details of how this works:

  • /v finds lines that don't match the search string (same switch @paxdiablo uses)
  • if the search string is in quotes, it performs an OR search, using each word (separator is a space)
  • findstr can take an input file, you don't need to feed it the text using the "type" command
  • "> outfile.txt" will send the results to the file outfile.txt instead printing them to your console. (Note that it will overwrite the file if it exists. Use ">> outfile.txt" instead if you want to append.)
  • You might also consider adding the /i switch to do a case-insensitive match.

How to send image to PHP file using Ajax?

Post both multiple text inputs plus multiple files via Ajax in one Ajax request

HTML

<form class="form-horizontal" id="myform" enctype="multipart/form-data">
<input type="text" name="name" class="form-control">
<input type="text" name="email" class="form-control">
<input type="file" name="image" class="form-control">
<input type="file" name="anotherFile" class="form-control">

Jquery Code

$(document).on('click','#btnSendData',function (event) {
    event.preventDefault();
    var form = $('#myform')[0];
    var formData = new FormData(form);
    // Set header if need any otherwise remove setup part
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
        }
    });
    $.ajax({
        url: "{{route('sendFormWithImage')}}",// your request url
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (data) {
            console.log(data);
        },
        error: function () {

        }
    });

});

Java "user.dir" property - what exactly does it mean?

Typically this is the directory where your app (java) was started (working dir). "Typically" because it can be changed, eg when you run an app with Runtime.exec(String[] cmdarray, String[] envp, File dir)

Date format in the json output using spring boot

If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

For Example :

public class Subject {

     private String uid;
     private String number;
     private String initials;

     @JsonFormat(pattern="yyyy-MM-dd")
     private Date dateOfBirth;  

     //Other Code  

}  

From Docs :

annotation used for configuring details of how values of properties are to be serialized.

More Reference Doc

Hope this helps.

java.net.SocketException: Connection reset

Whenever I have had odd issues like this, I usually sit down with a tool like WireShark and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being notified when you try and read.

Missing .map resource?

I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!

How do I get bit-by-bit data from an integer value in C?

@prateek thank you for your help. I rewrote the function with comments for use in a program. Increase 8 for more bits (up to 32 for an integer).

std::vector <bool> bits_from_int (int integer)    // discern which bits of PLC codes are true
{
    std::vector <bool> bool_bits;

    // continously divide the integer by 2, if there is no remainder, the bit is 1, else it's 0
    for (int i = 0; i < 8; i++)
    {
        bool_bits.push_back (integer%2);    // remainder of dividing by 2
        integer /= 2;    // integer equals itself divided by 2
    }

    return bool_bits;
}

CSS/HTML: Create a glowing border around an Input Field

This will create glowing input fields and textareas:

textarea,textarea:focus,input,input:focus{
    transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
    border: 1px solid #c4c4c4;
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    box-shadow: 0px 0px 8px #d9d9d9;
    -moz-box-shadow: 0px 0px 8px #d9d9d9;
    -webkit-box-shadow: 0px 0px 8px #d9d9d9;
}

input:focus,textarea:focus { 
    outline: none;
    border: 1px solid #7bc1f7;
    box-shadow: 0px 0px 8px #7bc1f7;
    -moz-box-shadow: 0px 0px 8px #7bc1f7;
    -webkit-box-shadow: 0px 0px 8px #7bc1f7;
}

What are access specifiers? Should I inherit with private, protected or public?

The explanation from Scott Meyers in Effective C++ might help understand when to use them:

Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.

How to get 30 days prior to current date?

I will prefer moment js

startDate = moment().subtract(30, 'days').format('LL')  // January 29, 2015

endDate = moment().format('LL'); // February 28, 2015

Use multiple custom fonts using @font-face?

You can use multiple font faces quite easily. Below is an example of how I used it in the past:

<!--[if (IE)]><!-->
    <style type="text/css" media="screen">
        @font-face {
            font-family: "Century Schoolbook";
            src: url(/fonts/century-schoolbook.eot);
        }
        @font-face {
            font-family: "Chalkduster";
            src: url(/fonts/chalkduster.eot);
        }
    </style>
<!--<![endif]-->
<!--[if !(IE)]><!-->
    <style type="text/css" media="screen">
        @font-face {
            font-family: "Century Schoolbook";
            src: url(/fonts/century-schoolbook.ttf);
        }
        @font-face {
            font-family: "Chalkduster";
            src: url(/fonts/chalkduster.ttf);
        }
    </style>
<!--<![endif]-->

It is worth noting that fonts can be funny across different Browsers. Font face on earlier browsers works, but you need to use eot files instead of ttf.

That is why I include my fonts in the head of the html file as I can then use conditional IE tags to use eot or ttf files accordingly.

If you need to convert ttf to eot for this purpose there is a brilliant website you can do this for free online, which can be found at http://ttf2eot.sebastiankippe.com/.

Hope that helps.

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

With synchronized blocks, you can have multiple synchronizers, so that multiple simultaneous but non-conflicting things can go on at the same time.

How can I remove all files in my git repo and update/push from my local git repo?

Do a git add -A from the top of the working copy, take a look at git status and/or git diff --cached to review what you're about to do, then git commit the result.

SQL Server SELECT into existing table

It would work as given below :

insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration 
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""

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

I think df['word'].value_counts() should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count should be much slower than max. Both take some time to avoid missing values. (Compare with size.)

In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.

Formatting MM/DD/YYYY dates in textbox in VBA

Private Sub txtBoxBDayHim_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 48 And KeyAscii <= 57 Or KeyAscii = 8 Then 'only numbers and backspace
    If KeyAscii = 8 Then 'if backspace, ignores + "/"
    Else
        If txtBoxBDayHim.TextLength = 10 Then 'limit textbox to 10 characters
        KeyAscii = 0
        Else
            If txtBoxBDayHim.TextLength = 2 Or txtBoxBDayHim.TextLength = 5 Then 'adds / automatically
            txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
            End If
        End If
    End If
Else
KeyAscii = 0
End If
End Sub

This works for me. :)

Your code helped me a lot. Thanks!

I'm brazilian and my english is poor, sorry for any mistake.

Changing ImageView source

Or try this one. For me it's working fine:

imageView.setImageDrawable(ContextCompat.getDrawable(this, image));

php refresh current page?

header('Location: '.$_SERVER['REQUEST_URI']);

Getting the absolute path of the executable, using C#?

On my side, I used, with a form application:

String Directory = System.Windows.Forms.Application.StartupPath;

it takes the application startup path.

FromBody string parameter is giving null

You are on the right track.

On your header set

Content-Type: application/x-www-form-urlencoded

The body of the POST request should be =test and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.


See also POST string to ASP.NET Web Api application - returns null

Expanding tuples into arguments

myfun(*some_tuple) does exactly what you request. The * operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.

How to remove an element from the flow?

There's display: none, but I think that might be a bit more than what you're looking for.

Making an iframe responsive

For Example :

<div class="intrinsic-container">
  <iframe src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>
</div>

CSS 

.intrinsic-container {
  position: relative;
  height: 0;
  overflow: hidden;
}

/* 16x9 Aspect Ratio */
.intrinsic-container-16x9 {
  padding-bottom: 56.25%;
}

/* 4x3 Aspect Ratio */
.intrinsic-container-4x3 {
  padding-bottom: 75%;
}

.intrinsic-container iframe {
  position: absolute;
  top:0;
  left: 0;
  width: 100%;
  height: 100%;
}

How do I generate a random integer between min and max in Java?

You can use Random.nextInt(n). This returns a random int in [0,n). Just using max-min+1 in place of n and adding min to the answer will give a value in the desired range.

Epoch vs Iteration when training neural networks

To my understanding, when you need to train a NN, you need a large dataset involves many data items. when NN is being trained, data items go in to NN one by one, that is called an iteration; When the whole dataset goes through, it is called an epoch.

Return 0 if field is null in MySQL

Yes IFNULL function will be working to achieve your desired result.

SELECT uo.order_id, uo.order_total, uo.order_status,
        (SELECT IFNULL(SUM(uop.price * uop.qty),0) 
         FROM uc_order_products uop 
         WHERE uo.order_id = uop.order_id
        ) AS products_subtotal,
        (SELECT IFNULL(SUM(upr.amount),0) 
         FROM uc_payment_receipts upr 
         WHERE uo.order_id = upr.order_id
        ) AS payment_received,
        (SELECT IFNULL(SUM(uoli.amount),0) 
         FROM uc_order_line_items uoli 
         WHERE uo.order_id = uoli.order_id
        ) AS line_item_subtotal
        FROM uc_orders uo
        WHERE uo.order_status NOT IN ("future", "canceled")
        AND uo.uid = 4172;

Why does DEBUG=False setting make my django Static Files Access fail?

You can debug this in many different ways. Here's my approach.

localsettings.py:

DEBUG = False
DEBUG404 = True

urls.py:

from django.conf import settings
import os

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
         {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
    )

Be sure to read the docs ;)

https://docs.djangoproject.com/en/2.0/howto/static-files/#limiting-use-to-debug-true

How to display (print) vector in Matlab?

You can use

x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))

This results in

Answer: (1, 2, 3)

For vectors of arbitrary size, you can use

disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))

An alternative way would be

disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))

How do I get the current absolute URL in Ruby on Rails?

I needed the application URL but with the subdirectory. I used:

root_url(:only_path => false)

Flatten list of lists

I would use itertools.chain - this will also cater for > 1 element in each sublist:

from itertools import chain
list(chain.from_iterable([[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]))

bundle install returns "Could not locate Gemfile"

I had this problem as well on an OSX machine. I discovered that rails was not installed... which surprised me as I thought OSX always came with Rails. To install rails

  • sudo gem install rails
  • to install jekyll I also needed sudo
  • sudo gem install jekyll bundler
  • cd ~/Sites
  • jekyll new <foldername>
  • cd <foldername> OR cd !$ (that is magic ;)
  • bundle install
  • bundle exec jekyll serve
  • Then in your browser just go to http://127.0.0.1:4000/ and it really should be running

Why the switch statement cannot be applied on strings?

To add a variation using the simplest container possible (no need for an ordered map)... I wouldn't bother with an enum--just put the container definition immediately before the switch so it'll be easy to see which number represents which case.

This does a hashed lookup in the unordered_map and uses the associated int to drive the switch statement. Should be quite fast. Note that at is used instead of [], as I've made that container const. Using [] can be dangerous--if the string isn't in the map, you'll create a new mapping and may end up with undefined results or a continuously growing map.

Note that the at() function will throw an exception if the string isn't in the map. So you may want to test first using count().

const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
switch(string_to_case.at("raj")) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;


}

The version with a test for an undefined string follows:

const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
// in C++20, you can replace .count with .contains
switch(string_to_case.count("raj") ? string_to_case.at("raj") : 0) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;
  case 0: //this is for the undefined case

}

Auto height of div

div's will naturally resize in accordance with their content.

If you set no height on your div, it will expand to contain its conent.

An exception to this rule is when the div contains floating elements. If this is the case you'll need to do a bit extra to ensure that the containing div (wrapper) clears the floats.

Here's some ways to do this:

#wrapper{
overflow:hidden;
}

Or

#wrapper:after
{
content:".";
display:block;
clear:both;
visibility:hidden;
}

Using number_format method in Laravel

This should work :

<td>{{ number_format($Expense->price, 2) }}</td>

How to encode the filename parameter of Content-Disposition header in HTTP?

I use the following code snippets for encoding (assuming fileName contains the filename and extension of the file, i.e.: test.txt):


PHP:

if ( strpos ( $_SERVER [ 'HTTP_USER_AGENT' ], "MSIE" ) > 0 )
{
     header ( 'Content-Disposition: attachment; filename="' . rawurlencode ( $fileName ) . '"' );
}
else
{
     header( 'Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode ( $fileName ) );
}

Java:

fileName = request.getHeader ( "user-agent" ).contains ( "MSIE" ) ? URLEncoder.encode ( fileName, "utf-8") : MimeUtility.encodeWord ( fileName );
response.setHeader ( "Content-disposition", "attachment; filename=\"" + fileName + "\"");

In PHP, how do you change the key of an array element?

if your array is built from a database query, you can change the key directly from the mysql statement:

instead of

"select ´id´ from ´tablename´..."

use something like:

"select ´id´ **as NEWNAME** from ´tablename´..."

How do I set the default font size in Vim?

Try a \<Space> before 12, like so:

:set guifont=Monospace\ 12

Disable Tensorflow debugging information

As TF_CPP_MIN_LOG_LEVEL didn't work for me you can try:

tf.logging.set_verbosity(tf.logging.WARN)

Worked for me in tensorflow v1.6.0

What is the string concatenation operator in Oracle?

Using CONCAT(CONCAT(,),) worked for me when concatenating more than two strings.

My problem required working with date strings (only) and creating YYYYMMDD from YYYY-MM-DD as follows (i.e. without converting to date format):

CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD

Load image with jQuery and append it to the DOM

I imagine that you define your image something like this:

<img id="image_portrait" src="" alt="chef etat"  width="120" height="135"  />

You can simply load/update image for this tag and chage/set atts (width,height):

var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

SQL Server: Best way to concatenate multiple columns?

Blockquote

Using concatenation in Oracle SQL is very easy and interesting. But don't know much about MS-SQL.

Blockquote

Here we go for Oracle : Syntax: SQL> select First_name||Last_Name as Employee from employees;

Result: EMPLOYEE

EllenAbel SundarAnde MozheAtkinson

Here AS: keyword used as alias. We can concatenate with NULL values. e.g. : columnm1||Null

Suppose any of your columns contains a NULL value then the result will show only the value of that column which has value.

You can also use literal character string in concatenation.

e.g. select column1||' is a '||column2 from tableName; Result: column1 is a column2. in between literal should be encolsed in single quotation. you cna exclude numbers.

NOTE: This is only for oracle server//SQL.

Serialize an object to string

In some rare cases you might want to implement your own String serialization.

But that probably is a bad idea unless you know what you are doing. (e.g. serializing for I/O with a batch file)

Something like that would do the trick (and it would be easy to edit by hand/batch), but be careful that some more checks should be done, like that name doesn't contain a newline.

public string name {get;set;}
public int age {get;set;}

Person(string serializedPerson) 
{
    string[] tmpArray = serializedPerson.Split('\n');
    if(tmpArray.Length>2 && tmpArray[0].Equals("#")){
        this.name=tmpArray[1];
        this.age=int.TryParse(tmpArray[2]);
    }else{
        throw new ArgumentException("Not a valid serialization of a person");
    }
}

public string SerializeToString()
{
    return "#\n" +
           name + "\n" + 
           age;
}

When to use Spring Security`s antMatcher()?

Basically http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

numbers not allowed (0-9) - Regex Expression in javascript

It is better to rely on regexps like ^[^0-9]+$ rather than on regexps like [a-zA-Z]+ as your app may one day accept user inputs from users speaking language like Polish, where many more characters should be accepted rather than only [a-zA-Z]+. Using ^[^0-9]+$ easily rules out any such undesired side effects.

Declare and Initialize String Array in VBA

Try this:

Dim myarray As Variant
myarray = Array("Cat", "Dog", "Rabbit")

How can I make a CSS table fit the screen width?

Set font-size in viewport-width-related units, e.g.:

table { font-size: 0.9vw; }

This will make font unreadable when page is too narrow, but sometimes this is acceptable.

Dynamically Add Variable Name Value Pairs to JSON Object

You can achieve this using Lodash _.assign function.

_x000D_
_x000D_
var ipID = {};_x000D_
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});_x000D_
console.log(ipID);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Mocking member variables of a class using Mockito

I had the same issue where a private value was not set because Mockito does not call super constructors. Here is how I augment mocking with reflection.

First, I created a TestUtils class that contains many helpful utils including these reflection methods. Reflection access is a bit wonky to implement each time. I created these methods to test code on projects that, for one reason or another, had no mocking package and I was not invited to include it.

public class TestUtils {
    // get a static class value
    public static Object reflectValue(Class<?> classToReflect, String fieldNameValueToFetch) {
        try {
            Field reflectField  = reflectField(classToReflect, fieldNameValueToFetch);
            reflectField.setAccessible(true);
            Object reflectValue = reflectField.get(classToReflect);
            return reflectValue;
        } catch (Exception e) {
            fail("Failed to reflect "+fieldNameValueToFetch);
        }
        return null;
    }
    // get an instance value
    public static Object reflectValue(Object objToReflect, String fieldNameValueToFetch) {
        try {
            Field reflectField  = reflectField(objToReflect.getClass(), fieldNameValueToFetch);
            Object reflectValue = reflectField.get(objToReflect);
            return reflectValue;
        } catch (Exception e) {
            fail("Failed to reflect "+fieldNameValueToFetch);
        }
        return null;
    }
    // find a field in the class tree
    public static Field reflectField(Class<?> classToReflect, String fieldNameValueToFetch) {
        try {
            Field reflectField = null;
            Class<?> classForReflect = classToReflect;
            do {
                try {
                    reflectField = classForReflect.getDeclaredField(fieldNameValueToFetch);
                } catch (NoSuchFieldException e) {
                    classForReflect = classForReflect.getSuperclass();
                }
            } while (reflectField==null || classForReflect==null);
            reflectField.setAccessible(true);
            return reflectField;
        } catch (Exception e) {
            fail("Failed to reflect "+fieldNameValueToFetch +" from "+ classToReflect);
        }
        return null;
    }
    // set a value with no setter
    public static void refectSetValue(Object objToReflect, String fieldNameToSet, Object valueToSet) {
        try {
            Field reflectField  = reflectField(objToReflect.getClass(), fieldNameToSet);
            reflectField.set(objToReflect, valueToSet);
        } catch (Exception e) {
            fail("Failed to reflectively set "+ fieldNameToSet +"="+ valueToSet);
        }
    }

}

Then I can test the class with a private variable like this. This is useful for mocking deep in class trees that you have no control as well.

@Test
public void testWithRectiveMock() throws Exception {
    // mock the base class using Mockito
    ClassToMock mock = Mockito.mock(ClassToMock.class);
    TestUtils.refectSetValue(mock, "privateVariable", "newValue");
    // and this does not prevent normal mocking
    Mockito.when(mock.somthingElse()).thenReturn("anotherThing");
    // ... then do your asserts
}

I modified my code from my actual project here, in page. There could be a compile issue or two. I think you get the general idea. Feel free to grab the code and use it if you find it useful.

Mocking python function based on input arguments

You can also use partial from functools if you want to use a function that takes parameters but the function you are mocking does not. E.g. like this:

def mock_year(year):
    return datetime.datetime(year, 11, 28, tzinfo=timezone.utc)
@patch('django.utils.timezone.now', side_effect=partial(mock_year, year=2020))

This will return a callable that doesn't accept parameters (like Django's timezone.now()), but my mock_year function does.

What's a standard way to do a no-op in python?

If you need a function that behaves as a nop, try

nop = lambda *a, **k: None
nop()

Sometimes I do stuff like this when I'm making dependencies optional:

try:
    import foo
    bar=foo.bar
    baz=foo.baz
except:
    bar=nop
    baz=nop

# Doesn't break when foo is missing:
bar()
baz()

How to fit Windows Form to any screen resolution?

int h = Screen.PrimaryScreen.WorkingArea.Height;
int w = Screen.PrimaryScreen.WorkingArea.Width;
this.ClientSize = new Size(w , h);

How to resize JLabel ImageIcon?

Resizing the icon is not straightforward. You need to use Java's graphics 2D to scale the image. The first parameter is a Image class which you can easily get from ImageIcon class. You can use ImageIcon class to load your image file and then simply call getter method to get the image.

private Image getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = resizedImg.createGraphics();

    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();

    return resizedImg;
}

break statement in "if else" - java

The "break" command does not work within an "if" statement.

If you remove the "break" command from your code and then test the code, you should find that the code works exactly the same without a "break" command as with one.

"Break" is designed for use inside loops (for, while, do-while, enhanced for and switch).

Have bash script answer interactive prompts

There is a special build-in util for this - 'yes'.

To answer all questions with the same answer, you can run

yes [answer] |./your_script

Or you can put it inside your script have specific answer to each question

Cross-platform way of getting temp directory in Python

This should do what you want:

print tempfile.gettempdir()

For me on my Windows box, I get:

c:\temp

and on my Linux box I get:

/tmp

How to get input field value using PHP

You can get the value $value as :

$value =  $_POST['subject'];

or:

$value = $_GET['subject']; ,depending upon the form method used.

session_start();
$_SESSION['subject'] =  $value;

the value is assigned to session variable subject.

Excel column number from column name

I think you want this?

Column Name to Column Number

Sub Sample()
    ColName = "C"
    Debug.Print Range(ColName & 1).Column
End Sub

Edit: Also including the reverse of what you want

Column Number to Column Name

Sub Sample()
    ColNo = 3
    Debug.Print Split(Cells(, ColNo).Address, "$")(1)
End Sub

FOLLOW UP

Like if i have salary field at the very top lets say at cell C(1,1) now if i alter the file and shift salary column to some other place say F(1,1) then i will have to modify the code so i want the code to check for Salary and find the column number and then do rest of the operations according to that column number.

In such a case I would recommend using .FIND See this example below

Option Explicit

Sub Sample()
    Dim strSearch As String
    Dim aCell As Range

    strSearch = "Salary"

    Set aCell = Sheet1.Rows(1).Find(What:=strSearch, LookIn:=xlValues, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    If Not aCell Is Nothing Then
        MsgBox "Value Found in Cell " & aCell.Address & _
        " and the Cell Column Number is " & aCell.Column
    End If
End Sub

SNAPSHOT

enter image description here

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

I would always recomend that you use NSMutableArray as the object to pass on. This is because you can then pass several objects, like the button pressed and other values. NSNumber, NSInteger and NSString are just containers of some value. Make sure that when you get the object from the array that you refer to to a correct container type. You need to pass on NS containers. There you may test the value. Remember that containers use isEqual when values are compared.

#define DELAY_TIME 5

-(void)changePlayerGameOnes:(UIButton*)sender{
    NSNumber *nextPlayer = [NSNumber numberWithInt:[gdata.currentPlayer intValue]+1 ];
    NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:sender, nil];
    [array addObject:nextPlayer];
    [self performSelector:@selector(next:) withObject:array afterDelay:DELAY_TIME];
}
-(void)next:(NSMutableArray*)nextPlayer{
    if(gdata != nil){ //if game choose next player
       [self nextPlayer:[nextPlayer objectAtIndex:1] button:[nextPlayer objectAtIndex:0]];
    }
}

How do I replace a character in a string in Java?

String taskLatLng = task.getTask_latlng().replaceAll( "\\(","").replaceAll("\\)","").replaceAll("lat/lng:", "").trim();

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

With Nodejs, if you are using routers, make sure to add cors before the routers. Otherwise, you'll still get the cors error. Like below:

const cors = require('cors');

const userRouter = require('./routers/user');

expressApp = express();
expressApp.use(cors());
expressApp.use(express.json());
expressApp.use(userRouter);

How to convert enum value to int?

If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.

If you want a unique number that represent the enum value, you can use ordinal().

How do I get rid of the b-prefix in a string in python?

You need to decode it to convert it to a string. Check the answer here about bytes literal in python3.

In [1]: b'I posted a new photo to Facebook'.decode('utf-8')
Out[1]: 'I posted a new photo to Facebook'

How to compare two date values with jQuery

just use the jQuery datepicker UI library and convert both your strings into date format, then you can easily compare. following link might be useful

https://stackoverflow.com/questions/2974496/jquery-javascript-convert-date-string-to-date

cheers..!!

how to define variable in jquery

Here's are some examples:

var name = 'india';
alert(name);  


var name = $("#txtname").val();
alert(name);

Taken from http://way2finder.blogspot.in/2013/09/how-to-create-variable-in-jquery.html

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

MySQL Where DateTime is greater than today

I guess you looking for CURDATE() or NOW() .

  SELECT name, datum 
  FROM tasks 
  WHERE datum >= CURDATE()

LooK the rsult of NOW and CURDATE

   NOW()                    CURDATE()        
   2008-11-11 12:45:34      2008-11-11       

WCF gives an unsecured or incorrectly secured fault error

Although your problem was solved with one of the above solutions, for the benefit of others, here's another option.

You also can get this exception when incorrect credentials are passed to a basic endpoint (SOAP 1.1) that uses username message credentials as you are. For example, if you are calling the service from code and do something like this:

var service = new TestService();

service.ClientCredentials.UserName.UserName = "InvalidUser";
service.ClientCredentials.UserName.Password = "InvalidPass";

This is different from a WSHTTP endpoint (SOAP 1.2) that throws an AccessDeniedException when invalid credentials are passed through. I personally find the message contained herein a little misleading (it certainly cost me a few minutes the first time I encountered it for this reason) but the underlying cause was clear once I consulted the WCF Diagnostic Trace Logs.

"ssl module in Python is not available" when installing package with pip3

I was having the same issue and was able to resolve with the following steps:

sudo yum install -y libffi-devel
sudo yum install openssl-devel
cd /usr/src
sudo wget https://www.python.org/ftp/python/3.7.1/Python-3.7.1.tar.xz
sudo tar xf Python-3.7.1.tar.xz
cd Python-3.7.1
sudo ./configure --enable-optimizations
# Install into /usr/local/bin/python3.7, don't overwrite global python bin
sudo make altinstall

depending on perms, you may not need sudo.

Results:
Collecting setuptools
Collecting pip
Installing collected packages: setuptools, pip
Successfully installed pip-10.0.1 setuptools-39.0.1

should now be able to run

python3.7 -V 

and

pip3.7 -V

When installing packages:

pip3.7 install pandas

or depending on perms, you can also add the --user flag like so:

pip3.7 install pandas --user

git: fatal: Could not read from remote repository

I solved this problem by switching to root with sudo su.

How to set "style=display:none;" using jQuery's attr method?

$(document).ready(function(){
var display =  $("#msform").css("display");
    if(display!="none")
    {
        $("#msform").attr("style", "display:none");
    }
});

How to access model hasMany Relation with where condition?

//lower for v4 some version

public function videos() {
    $instance =$this->hasMany('Video');
    $instance->getQuery()->where('available','=', 1);
    return $instance
}

//v5

public function videos() {
    return $this->hasMany('Video')->where('available','=', 1);
}

sql query to return differences between two tables

Simple variation on @erikkallen answer that shows which table the row is present in:

(   SELECT 'table1' as source, * FROM table1
    EXCEPT
    SELECT * FROM table2)  
UNION ALL
(   SELECT 'table2' as source, * FROM table2
    EXCEPT
    SELECT * FROM table1) 

If you get an error

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

then it may help to add

(   SELECT 'table1' as source, * FROM table1
    EXCEPT
    SELECT 'table1' as source, * FROM table2)  
UNION ALL
(   SELECT 'table2' as source, * FROM table2
    EXCEPT
    SELECT 'table2' as source, * FROM table1) 

Neither BindingResult nor plain target object for bean name available as request attr

Try adding a BindingResult parameter to methods annotated with @RequestMapping which have a @ModelAttribute annotated parameters. After each @ModelAttribute parameter, Spring looks for a BindingResult in the next parameter position (order is important).

So try changing:

@RequestMapping(method = RequestMethod.POST)
public String loadCharts(HttpServletRequest request, ModelMap model, @ModelAttribute("sideForm") Chart chart) 
...

To:

@RequestMapping(method = RequestMethod.POST)
public String loadCharts(@ModelAttribute("sideForm") Chart chart, BindingResult bindingResult, HttpServletRequest request, ModelMap model) 
...

HTML checkbox onclick called in Javascript

jQuery has a function that can do this:

  1. include the following script in your head:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
    

    (or just download the jQuery.js file online and include it locally)

  2. use this script to toggle the check box when the input is clicked:

    var toggle = false;
    $("#INPUTNAMEHERE").click(function() {
            $("input[type=checkbox]").attr("checked",!toggle);
            toggle = !toggle;
    }); 
    

That should do what you want if I understood what you were trying to do.

How to vertically align an image inside a div

http://jsfiddle.net/MBs64/

.frame {
    height: 35px;      /* Equals maximum image height */
    width: 160px;
    border: 1px solid red;
    text-align: center;
    margin: 1em 0;
    display: table-cell;
    vertical-align: middle;
}
img {
    background: #3A6F9A;
    display: block;
    max-height: 35px;
    max-width: 160px;
}

The key property is display: table-cell; for .frame. Div.frame is displayed as inline with this, so you need to wrap it in a block element.

This works in Firefox, Opera, Chrome, Safari and Internet Explorer 8 (and later).

UPDATE

For Internet Explorer 7 we need to add a CSS expression:

*:first-child+html img {
    position: relative;
    top: expression((this.parentNode.clientHeight-this.clientHeight)/2+"px");
}

Generate list of all possible permutations of a string

Some working Java code based on Sarp's answer:

public class permute {

    static void permute(int level, String permuted,
                    boolean used[], String original) {
        int length = original.length();
        if (level == length) {
            System.out.println(permuted);
        } else {
            for (int i = 0; i < length; i++) {
                if (!used[i]) {
                    used[i] = true;
                    permute(level + 1, permuted + original.charAt(i),
                       used, original);
                    used[i] = false;
                }
            }
        }
    }

    public static void main(String[] args) {
        String s = "hello";
        boolean used[] = {false, false, false, false, false};
        permute(0, "", used, s);
    }
}

How to hide a mobile browser's address bar?

This should be the code you need to hide the address bar:

window.addEventListener("load",function() {
    setTimeout(function(){
        // This hides the address bar:
        window.scrollTo(0, 1);
    }, 0);
});

Also nice looking Pokedex by the way! Hope this helps!

OSX -bash: composer: command not found

The path /usr/local/bin/composer is not in your PATH, executables in that folder won't be found.

Delete the folder /usr/local/bin/composer, then run

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

This moves composer.phar into /usr/local/bin/ and renames it into composer (which is still an executable, not a folder).

Then just use it like:

$ composer ...

How to prevent line-break in a column of a table cell (not a single cell)?

There are a few ways to do this; none of them are the easy, obvious way.

Applying white-space:nowrap to a <col> won't work; only four CSS properties work on <col> elements - background-color, width, border, and visibility. IE7 and earlier used to support all properties, but that's because they used a strange table model. IE8 now matches everyone else.

So, how do you solve this?

Well, if you can ignore IE (including IE8), you can use the :nth-child() pseudoclass to select particular <td>s from each row. You'd use td:nth-child(2) { white-space:nowrap; }. (This works for this example, but would break if you had any rowspans or colspans involved.)

If you have to support IE, then you've got to go the long way around and apply a class to every <td> that you want to affect. It sucks, but them's the breaks.

In the long run, there are proposals to fix this lack in CSS, so that you can more easily apply styles to all the cells in a column. You'll be able to do something like td:nth-col(2) { white-space:nowrap; } and it would do what you want.

Tomcat 7: How to set initial heap size correctly?

Just came across this and I've implemented Nathan's solution:

add the line (changing the values as required):

export JAVA_OPTS="-Xms512M -Xmx1024M"

to /usr/share/tomcat7/bin/setenv.sh

If that file doesn't exists then create it and

chown root:root it
chmod 755 it

And then restart tomcat and check it with

ps aux | grep logging

Which should just pick up the instance and show the java parms

Extract column values of Dataframe as List in Apache Spark

List<String> whatever_list = df.toJavaRDD().map(new Function<Row, String>() {
    public String call(Row row) {
        return row.getAs("column_name").toString();
    }
}).collect();

logger.info(String.format("list is %s",whatever_list)); //verification

Since no one has given any solution in java(Real Programming Language) Can thank me later

Override valueof() and toString() in Java enum

Try this, but i don't sure that will work every where :)

public enum MyEnum {
    A("Start There"),
    B("Start Here");

    MyEnum(String name) {
        try {
            Field fieldName = getClass().getSuperclass().getDeclaredField("name");
            fieldName.setAccessible(true);
            fieldName.set(this, name);
            fieldName.setAccessible(false);
        } catch (Exception e) {}
    }
}

How can I pass a list as a command-line argument with argparse?

I think the most elegant solution is to pass a lambda function to "type", as mentioned by Chepner. In addition to this, if you do not know beforehand what the delimiter of your list will be, you can also pass multiple delimiters to re.split:

# python3 test.py -l "abc xyz, 123"

import re
import argparse

parser = argparse.ArgumentParser(description='Process a list.')
parser.add_argument('-l', '--list',
                    type=lambda s: re.split(' |, ', s),
                    required=True,
                    help='comma or space delimited list of characters')

args = parser.parse_args()
print(args.list)


# Output: ['abc', 'xyz', '123']

Notepad++ Setting for Disabling Auto-open Previous Files

Use the menu item Settings>Preferences.

On the MISC tab of the resulting dialog, uncheck "Remember current session for next launch."

Git workflow and rebase vs merge questions

"Conflicts" mean "parallel evolutions of a same content". So if it goes "all to hell" during a merge, it means you have massive evolutions on the same set of files.

The reason why a rebase is then better than a merge is that:

  • you rewrite your local commit history with the one of the master (and then reapply your work, resolving any conflict then)
  • the final merge will certainly be a "fast forward" one, because it will have all the commit history of the master, plus only your changes to reapply.

I confirm that the correct workflow in that case (evolutions on common set of files) is rebase first, then merge.

However, that means that, if you push your local branch (for backup reason), that branch should not be pulled (or at least used) by anyone else (since the commit history will be rewritten by the successive rebase).


On that topic (rebase then merge workflow), barraponto mentions in the comments two interesting posts, both from randyfay.com:

Using this technique, your work always goes on top of the public branch like a patch that is up-to-date with current HEAD.

(a similar technique exists for bazaar)

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:

IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END 

Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.


If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.

IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE clockDate = '08/10/2012' AND userName = 'test'
END 

As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.

Git: Merge a Remote branch locally

Whenever I do a merge, I get into the branch I want to merge into (e.g. "git checkout branch-i-am-working-in") and then do the following:

git merge origin/branch-i-want-to-merge-from

CodeIgniter: 404 Page Not Found on Live Server

I had the same problem. Changing controlers first letter to uppercase helped.

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

Determining the version of Java SDK on the Mac

The simplest solution would be open terminal

$ java -version

it shows the following

java version "1.6.0_65"
  1. Stefan's solution also works for me. Here's the exact input:

$ cd /System/Library/Frameworks/JavaVM.framework/Versions

$ ls -l

Below is the last line of output:

lrwxr-xr-x   1 root  wheel   59 Feb 12 14:57 CurrentJDK -> /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents

1.6.0.jdk would be the answer

Reducing the gap between a bullet and text in a list item

To achieve the look I wanted, I made a div containing a basic UL and several LIs. I couldn't easily adjust the indent between the bullet and text with any of the suggested ideas above (technically possible, but not simple.) I just left the UL and LI without any listing feature (list-style-type: none) then adding a &bull; to the beginning of each line. It did give me a bit of trouble at first, it only displayed the first bullet, so I added a bullet character to the end of the first line, refreshed, then removed it and they all popped up. Just manually add a bullet HTML entity if you don't want a huge indent, add space HTML entities if you want more space :o I know it isn't the best method, but it worked for me.

Windows batch script to unhide files hidden by virus

this will unhide all files and folders on your computer

attrib -r -s -h /S /D

Detect rotation of Android phone in the browser with JavaScript

The actual behavior across different devices is inconsistent. The resize and orientationChange events can fire in a different sequence with varying frequency. Also, some values (e.g. screen.width and window.orientation) don't always change when you expect. Avoid screen.width -- it doesn't change when rotating in iOS.

The reliable approach is to listen to both resize and orientationChange events (with some polling as a safety catch), and you'll eventually get a valid value for the orientation. In my testing, Android devices occasionally fail to fire events when rotating a full 180 degrees, so I've also included a setInterval to poll the orientation.

var previousOrientation = window.orientation;
var checkOrientation = function(){
    if(window.orientation !== previousOrientation){
        previousOrientation = window.orientation;
        // orientation changed, do your magic here
    }
};

window.addEventListener("resize", checkOrientation, false);
window.addEventListener("orientationchange", checkOrientation, false);

// (optional) Android doesn't always fire orientationChange on 180 degree turns
setInterval(checkOrientation, 2000);

Here are the results from the four devices that I've tested (sorry for the ASCII table, but it seemed like the easiest way to present the results). Aside from the consistency between the iOS devices, there is a lot of variety across devices. NOTE: The events are listed in the order that they fired.

|==============================================================================|
|     Device     | Events Fired      | orientation | innerWidth | screen.width |
|==============================================================================|
| iPad 2         | resize            | 0           | 1024       | 768          |
| (to landscape) | orientationchange | 90          | 1024       | 768          |
|----------------+-------------------+-------------+------------+--------------|
| iPad 2         | resize            | 90          | 768        | 768          |
| (to portrait)  | orientationchange | 0           | 768        | 768          |
|----------------+-------------------+-------------+------------+--------------|
| iPhone 4       | resize            | 0           | 480        | 320          |
| (to landscape) | orientationchange | 90          | 480        | 320          |
|----------------+-------------------+-------------+------------+--------------|
| iPhone 4       | resize            | 90          | 320        | 320          |
| (to portrait)  | orientationchange | 0           | 320        | 320          |
|----------------+-------------------+-------------+------------+--------------|
| Droid phone    | orientationchange | 90          | 320        | 320          |
| (to landscape) | resize            | 90          | 569        | 569          |
|----------------+-------------------+-------------+------------+--------------|
| Droid phone    | orientationchange | 0           | 569        | 569          |
| (to portrait)  | resize            | 0           | 320        | 320          |
|----------------+-------------------+-------------+------------+--------------|
| Samsung Galaxy | orientationchange | 0           | 400        | 400          |
| Tablet         | orientationchange | 90          | 400        | 400          |
| (to landscape) | orientationchange | 90          | 400        | 400          |
|                | resize            | 90          | 683        | 683          |
|                | orientationchange | 90          | 683        | 683          |
|----------------+-------------------+-------------+------------+--------------|
| Samsung Galaxy | orientationchange | 90          | 683        | 683          |
| Tablet         | orientationchange | 0           | 683        | 683          |
| (to portrait)  | orientationchange | 0           | 683        | 683          |
|                | resize            | 0           | 400        | 400          |
|                | orientationchange | 0           | 400        | 400          |
|----------------+-------------------+-------------+------------+--------------|

jQuery table sort

I ended up using Nick's answer (the most popular but not accepted) https://stackoverflow.com/a/19947532/5271220

and combined it with the https://stackoverflow.com/a/16819442/5271220 but didn't want to add icons or fontawesome to the project. The CSS styles for sort-column-asc/desc I did color, padding, rounded border.

I also modified it to go by class rather than by any so we could control which ones are sortable. This could also come in handy later if there are two tables although more modifications would need to be done for that.

body:

 html += "<thead>\n";
    html += "<th></th>\n";
    html += "<th class=\"sort-header\">Name <span></span></i></th>\n";
    html += "<th class=\"sort-header\">Status <span></span></th>\n";
    html += "<th class=\"sort-header\">Comments <span></span></th>\n";
    html += "<th class=\"sort-header\">Location <span></span></th>\n";
    html += "<th nowrap class=\"sort-header\">Est. return <span></span></th>\n";
    html += "</thead>\n";
    html += "<tbody>\n"; ...

... further down the body

$("body").on("click", ".sort-header", function (e) {
    var table = $(this).parents('table').eq(0)
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
    this.asc = !this.asc
    if (!this.asc) { rows = rows.reverse() }
    for (var i = 0; i < rows.length; i++) { table.append(rows[i]) }

    setIcon(e.target, this.asc);
});

functions:

function comparer(index) {
        return function (a, b) {
            var valA = getCellValue(a, index), valB = getCellValue(b, index)
            return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
        }
    }

    function getCellValue(row, index) {
        return $(row).children('td').eq(index).text()
    }

    function setIcon(element, inverse) {

        var iconSpan = $(element).find('span');

        if (inverse == true) {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('sort-column-asc');
            $(iconSpan)[0].innerHTML = " &#8593 " // arrow up
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('sort-column-desc');
            $(iconSpan)[0].innerHTML = " &#8595 " // arrow down 
        }

        $(element).siblings().find('span').each(function (i, obj) {
            $(obj).removeClass();
            obj.innerHTML = "";
        });
    }

How can I hide a checkbox in html?

Elements that are not being rendered (be it through visibility: hidden, display: none, opacity: 0.0, whatever) will not indicate focus. The browser will not draw a focus border around nothing.

If you want the text to be focusable, that's completely doable. You can wrap the whole thing in an element that can receive focus (for example, a hyperlink), or allow another tag to have focus using the tabindex property:

<label tabindex="0" class="checkbox">
  <input type="checkbox" value="valueofcheckbox" style="display:none" checked="checked" />Option Text
</label>

Fiddle

In this case, the <label> tag above is actually receiving focus and everything within it will have a focus border when it's in focus.

I do question what your goal is. If you're using a hidden checkbox to internally track some sort of state, you might be better off using a <input type="hidden" /> tag instead.

How to reload .bashrc settings without logging out and back in again?

For me what works when I change the PATH is: exec "$BASH" --login

How to turn off Wifi via ADB?

All these input keyevent combinations are SO android/hardware dependent, it's a pain.

However, I finally found the combination for my old android 4.1 device :

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell "input keyevent KEYCODE_DPAD_LEFT;input keyevent KEYCODE_DPAD_RIGHT;input keyevent KEYCODE_DPAD_CENTER"

Print Html template in Angular 2 (ng-print in Angular 2)

EDIT: updated the snippets for a more generic approach

Just as an extension to the accepted answer,

For getting the existing styles to preserve the look 'n feel of the targeted component, you can:

  1. make a query to pull the <style> and <link> elements from the top-level document

  2. inject it into the HTML string.

To grab a HTML tag:

private getTagsHtml(tagName: keyof HTMLElementTagNameMap): string
{
    const htmlStr: string[] = [];
    const elements = document.getElementsByTagName(tagName);
    for (let idx = 0; idx < elements.length; idx++)
    {
        htmlStr.push(elements[idx].outerHTML);
    }

    return htmlStr.join('\r\n');
}

Then in the existing snippet:

const printContents = document.getElementById('print-section').innerHTML;
const stylesHtml = this.getTagsHtml('style');
const linksHtml = this.getTagsHtml('link');

const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
    <html>
        <head>
            <title>Print tab</title>
            ${linksHtml}
            ${stylesHtml}
            ^^^^^^^^^^^^^ add them as usual to the head
        </head>
        <body onload="window.print(); window.close()">
            ${printContents}
        </body>
    </html>
    `
);
popupWin.document.close();

Now using existing styles (Angular components create a minted style for itself), as well as existing style frameworks (e.g. Bootstrap, MaterialDesign, Bulma) it should look like a snippet of the existing screen

The application may be doing too much work on its main thread

taken from : Android UI : Fixing skipped frames

Anyone who begins developing android application sees this message on logcat “Choreographer(abc): Skipped xx frames! The application may be doing too much work on its main thread.” So what does it actually means, why should you be concerned and how to solve it.

What this means is that your code is taking long to process and frames are being skipped because of it, It maybe because of some heavy processing that you are doing at the heart of your application or DB access or any other thing which causes the thread to stop for a while.

Here is a more detailed explanation:

Choreographer lets apps to connect themselves to the vsync, and properly time things to improve performance.

Android view animations internally uses Choreographer for the same purpose: to properly time the animations and possibly improve performance.

Since Choreographer is told about every vsync events, I can tell if one of the Runnables passed along by the Choreographer.post* apis doesnt finish in one frame’s time, causing frames to be skipped.

In my understanding Choreographer can only detect the frame skipping. It has no way of telling why this happens.

The message “The application may be doing too much work on its main thread.” could be misleading.

source : Meaning of Choreographer messages in Logcat

Why you should be concerned

When this message pops up on android emulator and the number of frames skipped are fairly small (<100) then you can take a safe bet of the emulator being slow – which happens almost all the times. But if the number of frames skipped and large and in the order of 300+ then there can be some serious trouble with your code. Android devices come in a vast array of hardware unlike ios and windows devices. The RAM and CPU varies and if you want a reasonable performance and user experience on all the devices then you need to fix this thing. When frames are skipped the UI is slow and laggy, which is not a desirable user experience.

How to fix it

Fixing this requires identifying nodes where there is or possibly can happen long duration of processing. The best way is to do all the processing no matter how small or big in a thread separate from main UI thread. So be it accessing data form SQLite Database or doing some hardcore maths or simply sorting an array – Do it in a different thread

Now there is a catch here, You will create a new Thread for doing these operations and when you run your application, it will crash saying “Only the original thread that created a view hierarchy can touch its views“. You need to know this fact that UI in android can be changed by the main thread or the UI thread only. Any other thread which attempts to do so, fails and crashes with this error. What you need to do is create a new Runnable inside runOnUiThread and inside this runnable you should do all the operations involving the UI. Find an example here.

So we have Thread and Runnable for processing data out of main Thread, what else? There is AsyncTask in android which enables doing long time processes on the UI thread. This is the most useful when you applications are data driven or web api driven or use complex UI’s like those build using Canvas. The power of AsyncTask is that is allows doing things in background and once you are done doing the processing, you can simply do the required actions on UI without causing any lagging effect. This is possible because the AsyncTask derives itself from Activity’s UI thread – all the operations you do on UI via AsyncTask are done is a different thread from the main UI thread, No hindrance to user interaction.

So this is what you need to know for making smooth android applications and as far I know every beginner gets this message on his console.

How to create a QR code reader in a HTML5 website?

There aren't many JavaScript decoders.

There is one at http://www.webqr.com/index.html

The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.

Center div on the middle of screen

The best way to align a div in center both horizontally and vertically will be

HTML

<div></div>

CSS:

div {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background-color: blue;
}

FIDDLE

How to use cookies in Python Requests

From the documentation:

  1. get cookie from response

    url = 'http://example.com/some/cookie/setting/url'
    r = requests.get(url)
    r.cookies
    

    {'example_cookie_name': 'example_cookie_value'}

  2. give cookie back to server on subsequent request

    url = 'http://httpbin.org/cookies'
    cookies = dict(cookies_are='working')
    r = requests.get(url, cookies=cookies)`
    

Altering a column to be nullable

for Oracle Database 10g users:

alter table mytable modify(mycolumn null);

You get "ORA-01735: invalid ALTER TABLE option" when you try otherwise

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

This is a bit late but I know it will help someone:

If you are using datetimepicker make sure you include the right CSS and JS files. datetimepicker uses(Take note of their names);

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css

and

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js

On the above question asked by @mindfreak,The main problem is due to the imported files.

Check if a string contains a number

I'll make the @zyxue answer a bit more explicit:

RE_D = re.compile('\d')

def has_digits(string):
    res = RE_D.search(string)
    return res is not None

has_digits('asdf1')
Out: True

has_digits('asdf')
Out: False

which is the solution with the fastest benchmark from the solutions that @zyxue proposed on the answer.