Programs & Examples On #Eval

eval is a function that allows a programmer to execute arbitrary code written in the same language, from a string variable within a code.

Executing <script> elements inserted with .innerHTML

function insertHtml(id, html)  
{  
   var ele = document.getElementById(id);  
   ele.innerHTML = html;  
   var codes = ele.getElementsByTagName("script");   
   for(var i=0;i<codes.length;i++)  
   {  
       eval(codes[i].text);  
   }  
}  

It works in Chrome in my project

Why is using the JavaScript eval function a bad idea?

It greatly reduces your level of confidence about security.

Using python's eval() vs. ast.literal_eval()?

ast.literal_eval() only considers a small subset of Python's syntax to be valid:

The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

Passing __import__('os').system('rm -rf /a-path-you-really-care-about') into ast.literal_eval() will raise an error, but eval() will happily delete your files.

Since it looks like you're only letting the user input a plain dictionary, use ast.literal_eval(). It safely does what you want and nothing more.

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

Why is `input` in Python 3 throwing NameError: name... is not defined

I got the same error. In the terminal when I typed "python filename.py", with this command, python2 was tring to run python3 code, because the is written python3. It runs correctly when I type "python3 filename.py" in the terminal. I hope this works for you too.

Is there an eval() function in Java?

As there are many answers, I'm adding my implementation on top of eval() method with some additional features like support for factorial, evaluating complex expressions etc.

package evaluation;

import java.math.BigInteger;
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class EvalPlus {
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("This Evaluation is based on BODMAS rule\n");
        evaluate();
    }

    private static void evaluate() {
        StringBuilder finalStr = new StringBuilder();
        System.out.println("Enter an expression to evaluate:");
        String expr = scanner.nextLine(); 
        if(isProperExpression(expr)) {
            expr = replaceBefore(expr);
            char[] temp = expr.toCharArray();
            String operators = "(+-*/%)";
            for(int i = 0; i < temp.length; i++) {
                if((i == 0 && temp[i] != '*') || (i == temp.length-1 && temp[i] != '*' && temp[i] != '!')) {
                    finalStr.append(temp[i]);
                } else if((i > 0 && i < temp.length -1) || (i==temp.length-1 && temp[i] == '!')) {
                    if(temp[i] == '!') {
                        StringBuilder str = new StringBuilder();
                        for(int k = i-1; k >= 0; k--) {
                            if(Character.isDigit(temp[k])) {
                                str.insert(0, temp[k] );
                            } else {
                                break;
                            }
                        }
                        Long prev = Long.valueOf(str.toString());
                        BigInteger val = new BigInteger("1");
                        for(Long j = prev; j > 1; j--) {
                            val = val.multiply(BigInteger.valueOf(j));
                        }
                        finalStr.setLength(finalStr.length() - str.length());
                        finalStr.append("(" + val + ")");
                        if(temp.length > i+1) {
                            char next = temp[i+1];
                            if(operators.indexOf(next) == -1) { 
                                finalStr.append("*");
                            }
                        }
                    } else {
                        finalStr.append(temp[i]);
                    }
                }
            }
            expr = finalStr.toString();
            if(expr != null && !expr.isEmpty()) {
                ScriptEngineManager mgr = new ScriptEngineManager();
                ScriptEngine engine = mgr.getEngineByName("JavaScript");
                try {
                    System.out.println("Result: " + engine.eval(expr));
                    evaluate();
                } catch (ScriptException e) {
                    System.out.println(e.getMessage());
                }
            } else {
                System.out.println("Please give an expression");
                evaluate();
            }
        } else {
            System.out.println("Not a valid expression");
            evaluate();
        }
    }

    private static String replaceBefore(String expr) {
        expr = expr.replace("(", "*(");
        expr = expr.replace("+*", "+").replace("-*", "-").replace("**", "*").replace("/*", "/").replace("%*", "%");
        return expr;
    }

    private static boolean isProperExpression(String expr) {
        expr = expr.replaceAll("[^()]", "");
        char[] arr = expr.toCharArray();
        Stack<Character> stack = new Stack<Character>();
        int i =0;
        while(i < arr.length) {
            try {
                if(arr[i] == '(') {
                    stack.push(arr[i]);
                } else {
                    stack.pop();
                }
            } catch (EmptyStackException e) {
                stack.push(arr[i]);
            }
            i++;
        }
        return stack.isEmpty();
    }
}

Please find the updated gist anytime here. Also comment if any issues are there. Thanks.

eval command in Bash and its typical uses

I like the "evaluating your expression one additional time before execution" answer, and would like to clarify with another example.

var="\"par1 par2\""
echo $var # prints nicely "par1 par2"

function cntpars() {
  echo "  > Count: $#"
  echo "  > Pars : $*"
  echo "  > par1 : $1"
  echo "  > par2 : $2"

  if [[ $# = 1 && $1 = "par1 par2" ]]; then
    echo "  > PASS"
  else
    echo "  > FAIL"
    return 1
  fi
}

# Option 1: Will Pass
echo "eval \"cntpars \$var\""
eval "cntpars $var"

# Option 2: Will Fail, with curious results
echo "cntpars \$var"
cntpars $var

The Curious results in Option 2 are that we would have passed 2 parameters as follows:

  • First Parameter: "value
  • Second Parameter: content"

How is that for counter intuitive? The additional eval will fix that.

Adapted from https://stackoverflow.com/a/40646371/744133

How to modify a global variable within a function in bash?

It's because command substitution is performed in a subshell, so while the subshell inherits the variables, changes to them are lost when the subshell ends.

Reference:

Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

Escaping single quotes in JavaScript string for JavaScript evaluation

I agree that this var formattedString = string.replace(/'/g, "\\'"); works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.

The solution that worked for me is that you need to put three \ and escape the double quotes. "var string = \"l'avancement\"; var formattedString = string.replace(/'/g, \"\\\'\");"

I answer that question since I had trouble finding that three \ was the work around.

Evaluate expression given as a string

Similarly using rlang:

eval(parse_expr("5+5"))

How to print / echo environment variables?

This works too, with the semi-colon.

NAME=sam; echo $NAME

instantiate a class from a variable in PHP?

Put the classname into a variable first:

$classname=$var.'Class';

$bar=new $classname("xyz");

This is often the sort of thing you'll see wrapped up in a Factory pattern.

See Namespaces and dynamic language features for further details.

What is ":-!!" in C code?

It's creating a size 0 bitfield if the condition is false, but a size -1 (-!!1) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1 bitfield is created, of course).

Angular ngClass and click event for toggling class

If you want to toggle text with a toggle button.

HTMLfile which is using bootstrap:

<input class="btn" (click)="muteStream()"  type="button"
          [ngClass]="status ? 'btn-success' : 'btn-danger'" 
          [value]="status ? 'unmute' : 'mute'"/>

TS file:

muteStream() {
   this.status = !this.status;
}

Find distance between two points on map using Google Map API V2

simple util function to calculate distance between two geopoints:

public static long getDistanceMeters(double lat1, double lng1, double lat2, double lng2) {

    double l1 = toRadians(lat1);
    double l2 = toRadians(lat2);
    double g1 = toRadians(lng1);
    double g2 = toRadians(lng2);

    double dist = acos(sin(l1) * sin(l2) + cos(l1) * cos(l2) * cos(g1 - g2));
    if(dist < 0) {
        dist = dist + Math.PI;
    }

    return Math.round(dist * 6378100);
}

How to copy to clipboard in Vim?

I wasn't able to copy to my clipboard's system because I had this in my ~/.vimrc file:

 if has('mouse')
   set mouse=a
 endif

But if you add this line next, it will allow you to simply Ctrl+c to get whatever you have selected into your clipboard.

vmap <C-c> "+y

Original discussion and more details: Copy text out of vim with set mouse=a enabled

iPhone Safari Web App opens links in new window

This is slightly adapted version of Sean's which was preventing back button

// this function makes anchor tags work properly on an iphone

$(document).ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) {
  // For iOS Apps
  $("a").on("click", function(e){

    var new_location = $(this).attr("href");
    if (new_location != undefined && new_location.substr(0, 1) != "#" && new_location!='' && $(this).attr("data-method") == undefined){
      e.preventDefault();
      window.location = new_location;
    }
  });
}

});

jQuery: Clearing Form Inputs

Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.

I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.

I got this too work by adding a reset button to the form, which had an id of myform:

$("#myform > input[type=reset]").trigger('click');

This for me had the correct outcome on resetting the form, oh and dont forget the

event.preventDefault();

to stop the form submitting in browser, like I did :).

Regards

Jacko

Disable LESS-CSS Overwriting calc()

Using an escaped string (a.k.a. escaped value):

width: ~"calc(100% - 200px)";

Also, in case you need to mix Less math with escaped strings:

width: calc(~"100% - 15rem +" (10px+5px) ~"+ 2em");

Compiles to:

width: calc(100% - 15rem + 15px + 2em);

This works as Less concatenates values (the escaped strings and math result) with a space by default.

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="any" />

It won't have validation problems and the arrows will have step of "1"

Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.

The following range control only accepts values in the range 0..1, and allows 256 steps in that range:

<input name=opacity type=range min=0 max=1 step=0.00392156863>

The following control allows any time in the day to be selected, with any accuracy (e.g. thousandth-of-a-second accuracy or more):

<input name=favtime type=time step=any>

Normally, time controls are limited to an accuracy of one minute.

http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step

How to use UTF-8 in resource properties with ResourceBundle

For what it's worth my issue was that the files themselves were in the wrong encoding. Using iconv worked for me

iconv -f ISO-8859-15 -t UTF-8  messages_nl.properties > messages_nl.properties.new

Extracting text OpenCV

Here is an alternative approach that I used to detect the text blocks:

  1. Converted the image to grayscale
  2. Applied threshold (simple binary threshold, with a handpicked value of 150 as the threshold value)
  3. Applied dilation to thicken lines in image, leading to more compact objects and less white space fragments. Used a high value for number of iterations, so dilation is very heavy (13 iterations, also handpicked for optimal results).
  4. Identified contours of objects in resulted image using opencv findContours function.
  5. Drew a bounding box (rectangle) circumscribing each contoured object - each of them frames a block of text.
  6. Optionally discarded areas that are unlikely to be the object you are searching for (e.g. text blocks) given their size, as the algorithm above can also find intersecting or nested objects (like the entire top area for the first card) some of which could be uninteresting for your purposes.

Below is the code written in python with pyopencv, it should easy to port to C++.

import cv2

image = cv2.imread("card.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours

# for each contour found, draw a rectangle around it on original image
for contour in contours:
    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    # discard areas that are too large
    if h>300 and w>300:
        continue

    # discard areas that are too small
    if h<40 or w<40:
        continue

    # draw rectangle around contour on original image
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)

# write original image with added contours to disk  
cv2.imwrite("contoured.jpg", image) 

The original image is the first image in your post.

After preprocessing (grayscale, threshold and dilate - so after step 3) the image looked like this:

Dilated image

Below is the resulted image ("contoured.jpg" in the last line); the final bounding boxes for the objects in the image look like this:

enter image description here

You can see the text block on the left is detected as a separate block, delimited from its surroundings.

Using the same script with the same parameters (except for thresholding type that was changed for the second image like described below), here are the results for the other 2 cards:

enter image description here

enter image description here

Tuning the parameters

The parameters (threshold value, dilation parameters) were optimized for this image and this task (finding text blocks) and can be adjusted, if needed, for other cards images or other types of objects to be found.

For thresholding (step 2), I used a black threshold. For images where text is lighter than the background, such as the second image in your post, a white threshold should be used, so replace thesholding type with cv2.THRESH_BINARY). For the second image I also used a slightly higher value for the threshold (180). Varying the parameters for the threshold value and the number of iterations for dilation will result in different degrees of sensitivity in delimiting objects in the image.

Finding other object types:

For example, decreasing the dilation to 5 iterations in the first image gives us a more fine delimitation of objects in the image, roughly finding all words in the image (rather than text blocks):

enter image description here

Knowing the rough size of a word, here I discarded areas that were too small (below 20 pixels width or height) or too large (above 100 pixels width or height) to ignore objects that are unlikely to be words, to get the results in the above image.

How do you update Xcode on OSX to the latest version?

If you want the latest Beta, it will not be in the AppStore. Instead you have to login to https://developer.apple.com and download from there.

How to copy an object in Objective-C

This is probably unpopular way. But here how I do it:

object1 = // object to copy

YourClass *object2 = [[YourClass alloc] init];
object2.property1 = object1.property1;
object2.property2 = object1.property2;
..
etc.

Quite simple and straight forward. :P

Finding median of list in Python

I had some problems with lists of float values. I ended up using a code snippet from the python3 statistics.median and is working perfect with float values without imports. source

def calculateMedian(list):
    data = sorted(list)
    n = len(data)
    if n == 0:
        return None
    if n % 2 == 1:
        return data[n // 2]
    else:
        i = n // 2
        return (data[i - 1] + data[i]) / 2

Correlation heatmap

The code below will produce this plot:

enter image description here

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# A list with your data slightly edited
l = [1.0,0.00279981,0.95173379,0.02486161,-0.00324926,-0.00432099,
0.00279981,1.0,0.17728303,0.64425774,0.30735071,0.37379443,
0.95173379,0.17728303,1.0,0.27072266,0.02549031,0.03324756,
0.02486161,0.64425774,0.27072266,1.0,0.18336236,0.18913512,
-0.00324926,0.30735071,0.02549031,0.18336236,1.0,0.77678274,
-0.00432099,0.37379443,0.03324756,0.18913512,0.77678274,1.00]

# Split list
n = 6
data = [l[i:i + n] for i in range(0, len(l), n)]

# A dataframe
df = pd.DataFrame(data)

def CorrMtx(df, dropDuplicates = True):

    # Your dataset is already a correlation matrix.
    # If you have a dateset where you need to include the calculation
    # of a correlation matrix, just uncomment the line below:
    # df = df.corr()

    # Exclude duplicate correlations by masking uper right values
    if dropDuplicates:    
        mask = np.zeros_like(df, dtype=np.bool)
        mask[np.triu_indices_from(mask)] = True

    # Set background color / chart style
    sns.set_style(style = 'white')

    # Set up  matplotlib figure
    f, ax = plt.subplots(figsize=(11, 9))

    # Add diverging colormap from red to blue
    cmap = sns.diverging_palette(250, 10, as_cmap=True)

    # Draw correlation plot with or without duplicates
    if dropDuplicates:
        sns.heatmap(df, mask=mask, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
    else:
        sns.heatmap(df, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)


CorrMtx(df, dropDuplicates = False)

I put this together after it was announced that the outstanding seaborn corrplot was to be deprecated. The snippet above makes a resembling correlation plot based on seaborn heatmap. You can also specify the color range and select whether or not to drop duplicate correlations. Notice that I've used the same numbers as you, but that I've put them in a pandas dataframe. Regarding the choice of colors you can have a look at the documents for sns.diverging_palette. You asked for blue, but that falls out of this particular range of the color scale with your sample data. For both observations of 0.95173379, try changing to -0.95173379 and you'll get this:

enter image description here

What's the best way to select the minimum value from several columns?

A little twist on the union query:

DECLARE @Foo TABLE (ID INT, Col1 INT, Col2 INT, Col3 INT)

INSERT @Foo (ID, Col1, Col2, Col3)
VALUES
(1, 3, 34, 76),
(2, 32, 976, 24),
(3, 7, 235, 3),
(4, 245, 1, 792)

SELECT
    ID,
    Col1,
    Col2,
    Col3,
    (
        SELECT MIN(T.Col)
        FROM
        (
            SELECT Foo.Col1 AS Col UNION ALL
            SELECT Foo.Col2 AS Col UNION ALL
            SELECT Foo.Col3 AS Col 
        ) AS T
    ) AS TheMin
FROM
    @Foo AS Foo

Creating a script for a Telnet session?

Check for the SendCommand tool.

You can use it as follows:

perl sendcommand.pl -i login.txt -t cisco -c "show ip route"

How to get the current taxonomy term ID (not the slug) in WordPress?

Here's the whole code snippet needed:

$queried_object = get_queried_object();
$term_id = $queried_object->term_id;

How do you cache an image in Javascript

I use a similar technique to lazyload images, but can't help but notice that Javascript doesn't access the browser cache on first loading.

My example:

I have a rotating banner on my homepage with 4 images the slider wait 2 seconds, than the javascript loads the next image, waits 2 seconds, etc.

These images have unique urls that change whenever I modify them, so they get caching headers that will cache in the browser for a year.

max-age: 31536000, public

Now when I open Chrome Devtools and make sure de 'Disable cache' option is not active and load the page for the first time (after clearing the cache) all images get fetch and have a 200 status. After a full cycle of all images in the banner the network requests stop and the cached images are used.

Now when I do a regular refresh or go to a subpage and click back, the images that are in the cache seems to be ignored. I would expect to see a grey message "from disk cache" in the Network tab of Chrome devtools. In instead I see the requests pass by every two seconds with a Green status circle instead of gray, I see data being transferred, so it I get the impression the cache is not accessed at all from javascript. It simply fetches the image each time the page gets loaded.

So each request to the homepage triggers 4 requests regardless of the caching policy of the image.

Considering the above together and the new http2 standard most webservers and browsers now support, I think it's better to stop using lazyloading since http2 will load all images nearly simultaneously.

If this is a bug in Chrome Devtools it really surprises my nobody noticed this yet. ;)

If this is true, using lazyloading only increases bandwith usage.

Please correct me if I'm wrong. :)

Is it possible to set a number to NaN or infinity?

Yes, you can use numpy for that.

import numpy as np
a = arange(3,dtype=float)

a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf

a # is now [nan,inf,-inf]

np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True

Android: I lost my android key store, what should I do?

No, there is no chance to do that. You just learned how important a backup can be.

How do I read / convert an InputStream into a String in Java?

This Code is for New Java Learners:

     private String textDataFromFile;

public String getFromFile(InputStream myInputStream) throws FileNotFoundException, IOException {

      BufferedReader bufferReader = new BufferedReader (new InputStreamReader(myInputStream));

       StringBuilder stringBuilder = new StringBuilder();

  String eachStringLine;

    while((eachStringLine=bufferReader.readLine()) != null){          
        stringBuilder.append(eachStringLine).append("\n");
    }

   textDataFromFile = stringBuilder.toString(); 



  return textDataFromFile;

}

How to add an extra row to a pandas dataframe

A different approach that I found ugly compared to the classic dict+append, but that works:

df = df.T

df[0] = ['1/1/2013', 'Smith','test',123]

df = df.T

df
Out[6]: 
       Date   Name Action   ID
0  1/1/2013  Smith   test  123

How do I concatenate strings with variables in PowerShell?

Try this

Get-ChildItem  | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }

In your code,

  1. $build-Config is not a valid variable name.
  2. $.FullName should be $_.FullName
  3. $ should be $_.Name

Mobile Safari: Javascript focus() method on inputfield only works with click?

Actually, guys, there is a way. I struggled mightily to figure this out for [LINK REMOVED] (try it on an iPhone or iPad).

Basically, Safari on touchscreen devices is stingy when it comes to focus()ing textboxes. Even some desktop browsers do better if you do click().focus(). But the designers of Safari on touchscreen devices realized it's annoying to users when the keyboard keeps coming up, so they made the focus appear only on the following conditions:

1) The user clicked somewhere and focus() was called while executing the click event. If you are doing an AJAX call, then you must do it synchronously, such as with the deprecated (but still available) $.ajax({async:false}) option in jQuery.

2) Furthermore -- and this one kept me busy for a while -- focus() still doesn't seem to work if some other textbox is focused at the time. I had a "Go" button which did the AJAX, so I tried blurring the textbox on the touchstart event of the Go button, but that just made the keyboard disappear and moved the viewport before I had a chance to complete the click on the Go button. Finally I tried blurring the textbox on the touchend event of the Go button, and this worked like a charm!

When you put #1 and #2 together, you get a magical result that will set your login forms apart from all the crappy web login forms, by placing the focus in your password fields, and make them feel more native. Enjoy! :)

Call a stored procedure with parameter in c#

As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/

SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
    sqlAccess.Procedure()
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtFirstName.Text)
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtLastName.Text)
         .ExecuteNonQuery("StoredProcedureName");

How to count duplicate value in an array in javascript

I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):

_x000D_
_x000D_
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];_x000D_
var map = arr.reduce(function(prev, cur) {_x000D_
  prev[cur] = (prev[cur] || 0) + 1;_x000D_
  return prev;_x000D_
}, {});_x000D_
_x000D_
// map is an associative array mapping the elements to their frequency:_x000D_
document.write(JSON.stringify(map));_x000D_
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
_x000D_
_x000D_
_x000D_

How to use BufferedReader in Java

Try this to read a file:

BufferedReader reader = null;

try {
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Datagridview: How to set a cell in editing mode?

I know this is an old question, but none of the answers worked for me, because I wanted to reliably (always be able to) set the cell into edit mode when possibly executing other events like Toolbar Button clicks, menu selections, etc. that may affect the default focus after those events return. I ended up needing a timer and invoke. The following code is in a new component derived from DataGridView. This code allows me to simply make a call to myXDataGridView.CurrentRow_SelectCellFocus(myDataPropertyName); anytime I want to arbitrarily set a databound cell to edit mode (assuming the cell is Not in ReadOnly mode).

// If the DGV does not have Focus prior to a toolbar button Click, 
// then the toolbar button will have focus after its Click event handler returns.
// To reliably set focus to the DGV, we need to time it to happen After event handler procedure returns.

private string m_SelectCellFocus_DataPropertyName = "";
private System.Timers.Timer timer_CellFocus = null;

public void CurrentRow_SelectCellFocus(string sDataPropertyName)
{
  // This procedure is called by a Toolbar Button's Click Event to select and set focus to a Cell in the DGV's Current Row.
  m_SelectCellFocus_DataPropertyName = sDataPropertyName;
  timer_CellFocus = new System.Timers.Timer(10);
  timer_CellFocus.Elapsed += TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Start();
}


void TimerElapsed_CurrentRowSelectCellFocus(object sender, System.Timers.ElapsedEventArgs e)
{
  timer_CellFocus.Stop();
  timer_CellFocus.Elapsed -= TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Dispose();
  // We have to Invoke the method to avoid raising a threading error
  this.Invoke((MethodInvoker)delegate
  {
    Select_Cell(m_SelectCellFocus_DataPropertyName);
  });
}


private void Select_Cell(string sDataPropertyName)
{
  /// When the Edit Mode is Enabled, set the initial cell to the Description
  foreach (DataGridViewCell dgvc in this.SelectedCells) 
  {
    // Clear previously selected cells
    dgvc.Selected = false; 
  }
  foreach (DataGridViewCell dgvc in this.CurrentRow.Cells)
  {
    // Select the Cell by its DataPropertyName
    if (dgvc.OwningColumn.DataPropertyName == sDataPropertyName)
    {
      this.CurrentCell = dgvc;
      dgvc.Selected = true;
      this.Focus();
      return;
    }
  }
}

Python Infinity - Any caveats?

I found a caveat that no one so far has mentioned. I don't know if it will come up often in practical situations, but here it is for the sake of completeness.

Usually, calculating a number modulo infinity returns itself as a float, but a fraction modulo infinity returns nan (not a number). Here is an example:

>>> from fractions import Fraction
>>> from math import inf
>>> 3 % inf
3.0
>>> 3.5 % inf
3.5
>>> Fraction('1/3') % inf
nan

I filed an issue on the Python bug tracker. It can be seen at https://bugs.python.org/issue32968.

Update: this will be fixed in Python 3.8.

Determine direct shared object dependencies of a Linux binary?

You can use readelf to explore the ELF headers. readelf -d will list the direct dependencies as NEEDED sections.

 $ readelf -d elfbin

Dynamic section at offset 0xe30 contains 22 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libssl.so.1.0.0]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000000c (INIT)               0x400520
 0x000000000000000d (FINI)               0x400758
 ...

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
  <li>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
  </li>
<% end %>

This way you are using the locales for the error messages.

How to Install Font Awesome in Laravel Mix

Try in your webpack.mix.js to add the '*'

.copy('node_modules/font-awesome/fonts/*', 'public/fonts')

Read each line of txt file to new array element

<?php
$file = fopen("members.txt", "r");
$members = array();

while (!feof($file)) {
   $members[] = fgets($file);
}

fclose($file);

var_dump($members);
?>

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I am developing an app to version 2.2, API version would in the 8th ... had the same error and the error told me it was to google maps API, all we did was change my ADV for my project API 2.2 and also for the API.

This worked for me and found the library API needed.

How to search for occurrences of more than one space between words in a line

Here is my solution

[^0-9A-Z,\n]

This will remove all the digits, commas and new lines but select the middle space such as data set of

  • 20171106,16632 ESCG0000018SB
  • 20171107,280 ESCG0000018SB
  • 20171106,70476 ESCG0000018SB

What is the use of DesiredCapabilities in Selenium WebDriver?

I know I am very late to answer this question.
But would like to add for further references to the give answers.
DesiredCapabilities are used like setting your config with key-value pair.
Below is an example related to Appium used for Automating Mobile platforms like Android and IOS.
So we generally set DesiredCapabilities for conveying our WebDriver for specific things we will be needing to run our test to narrow down the performance and to increase the accuracy.

So we set our DesiredCapabilities as:

// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set android deviceName desired capability. Set your device name.
capabilities.setCapability("deviceName", "your Device Name");

// Set BROWSER_NAME desired capability.
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");

// Set android VERSION desired capability. Set your mobile device's OS version.
capabilities.setCapability(CapabilityType.VERSION, "5.1");

// Set android platformName desired capability. It's Android in our case here.
capabilities.setCapability("platformName", "Android");

// Set android appPackage desired capability.

//You need to check for your appPackage Name for your app, you can use this app for that APK INFO

// Set your application's appPackage if you are using any other app. 
capabilities.setCapability("appPackage", "com.android.appPackageName");

// Set android appActivity desired capability. You can use the same app for finding appActivity of your app
capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

This DesiredCapabilities are very specific to Appium on Android Platform. For more you can refer to the official site of Selenium desiredCapabilities class

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

How do I format my oracle queries so the columns don't wrap?

Never mind, figured it out:

set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)

Which I found by:

show all

And looking for some option that seemed relevant.

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

Confused about Service vs Factory

“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular.

So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.

app.service("Logger", Logger); // Injects a global object

When you define DI using a “factory” it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

app.factory("Customerfactory", CreateCustomer);

Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.

enter image description here

Factory should be used When we want to create different types of objects depending on scenarios. For example depending on scenario we want to create a simple “Customer” object , or “Customer” with “Address” object or “Customer” with “Phone” object. Here is a detailed explanation of this paragraph

Service should be used When we have utility or shared functions to be injected like Utility , Logger , Error handler etc.

Detecting arrow key presses in JavaScript

That's shorter.

function IsArrows (e) { return (e.keyCode >= 37 && e.keyCode <= 40); }

Most pythonic way to delete a file which may not exist

A KISS offering:

def remove_if_exists(filename):
  if os.path.exists(filename):
    os.remove(filename)

And then:

remove_if_exists("my.file")

If (Array.Length == 0)

do you mean empty or null, two different things,

if the array is instantiated but empty, then length is correct, if it has not been instantiated then test vs null

Converting a string to a date in a cell

The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here

How can I get a character in a string by index?

string s = "hello";
char c = s[1];
// now c == 'e'

See also Substring, to return more than one character.

Is an HTTPS query string secure?

Yes, your query strings will be encrypted.

The reason behind is that query strings are part of the HTTP protocol which is an application layer protocol, while the security (SSL/TLS) part comes from the transport layer. The SSL connection is established first and then the query parameters (which belong to the HTTP protocol) are sent to the server.

When establishing an SSL connection, your client will perform the following steps in order. Suppose you're trying to log in to a site named example.com and want to send your credentials using query parameters. Your complete URL may look like the following:

https://example.com/login?username=alice&password=12345)
  1. Your client (e.g., browser/mobile app) will first resolve your domain name example.com to an IP address (124.21.12.31) using a DNS request. When querying that information, only domain specific information is used, i.e., only example.com will be used.
  2. Now, your client will try to connect to the server with the IP address 124.21.12.31 and will attempt to connect to port 443 (SSL service port not the default HTTP port 80).
  3. Now, the server at example.com will send its certificates to your client.
  4. Your client will verify the certificates and start exchanging a shared secret key for your session.
  5. After successfully establishing a secure connection, only then will your query parameters be sent via the secure connection.

Therefore, you won't expose sensitive data. However, sending your credentials over an HTTPS session using this method is not the best way. You should go for a different approach.

How to get the parents of a Python class?

Use bases if you just want to get the parents, use __mro__ (as pointed out by @naught101) for getting the method resolution order (so to know in which order the init's were executed).

Bases (and first getting the class for an existing object):

>>> some_object = "some_text"
>>> some_object.__class__.__bases__
(object,)

For mro in recent Python versions:

>>> some_object = "some_text"
>>> some_object.__class__.__mro__
(str, object)

Obviously, when you already have a class definition, you can just call __mro__ on that directly:

>>> class A(): pass
>>> A.__mro__
(__main__.A, object)

Exception 'open failed: EACCES (Permission denied)' on Android

For anyone coming here from search results and are targeting Android 10: Android 10 (API 29) changes some permissions related to storage.

I fixed the issue when I replaced my previous instances of Environment.getExternalStorageDirectory() (which is deprecated with API 29) with context.getExternalFilesDir(null).

Note that context.getExternalFilesDir(type) can return null if the storage location isn't available, so be sure to check that whenever you're checking if you have external permissions.

Read more here.

c#: getter/setter

With the release of C# 6, you can now do something like this for private properties.

public constructor()
{
   myProp = "some value";
}

public string myProp { get; }

Is it possible to read the value of a annotation in java?

For the few people asking for a generic method, this should help you (5 years later :p).

For my below example, I'm pulling the RequestMapping URL value from methods that have the RequestMapping annotation. To adapt this for fields, just change the

for (Method method: clazz.getMethods())

to

for (Field field: clazz.getFields())

And swap usage of RequestMapping for whatever annotation you are looking to read. But make sure that the annotation has @Retention(RetentionPolicy.RUNTIME).

public static String getRequestMappingUrl(final Class<?> clazz, final String methodName)
{
    // Only continue if the method name is not empty.
    if ((methodName != null) && (methodName.trim().length() > 0))
    {
        RequestMapping tmpRequestMapping;
        String[] tmpValues;

        // Loop over all methods in the class.
        for (Method method: clazz.getMethods())
        {
            // If the current method name matches the expected method name, then keep going.
            if (methodName.equalsIgnoreCase(method.getName()))
            {
                // Try to extract the RequestMapping annotation from the current method.
                tmpRequestMapping = method.getAnnotation(RequestMapping.class);

                // Only continue if the current method has the RequestMapping annotation.
                if (tmpRequestMapping != null)
                {
                    // Extract the values from the RequestMapping annotation.
                    tmpValues = tmpRequestMapping.value();

                    // Only continue if there are values.
                    if ((tmpValues != null) && (tmpValues.length > 0))
                    {
                        // Return the 1st value.
                        return tmpValues[0];
                    }
                }
            }
        }
    }

    // Since no value was returned, log it and return an empty string.
    logger.error("Failed to find RequestMapping annotation value for method: " + methodName);

    return "";
}

jQuery textbox change event

$('#input').on("input",function () {alert('changed');});

works for me.

Replace a string in a file with nodejs

I ran into issues when replacing a small placeholder with a large string of code.

I was doing:

var replaced = original.replace('PLACEHOLDER', largeStringVar);

I figured out the problem was JavaScript's special replacement patterns, described here. Since the code I was using as the replacing string had some $ in it, it was messing up the output.

My solution was to use the function replacement option, which DOES NOT do any special replacement:

var replaced = original.replace('PLACEHOLDER', function() {
    return largeStringVar;
});

Apache2: 'AH01630: client denied by server configuration'

This drove me absolutely nuts for a day and a half but I found a solution if all other solutions have been tried unsuccessfully.

This is for macOS.

  • Go to activity Monitor (spotlight search for: activity)
  • In activity monitor search for httpd which is the Apache service
  • Select the one that belongs to root and click X on the top left to close it.

At that point I immediately stopped getting 403 errors and everything started working as expected. Weird thing is i didn't even have to restart apache it just worked, i guess it restarted itself when i went to my localhost, I honestly don't know but I guess the problem is Apache not actually restarting when using apachectl restart, or stop or start. Hope this helps someone.

Change the current directory from a Bash script

When you start your script, a new process is created that only inherits your environment. When it ends, it ends. Your current environment stays as it is.

Instead, you can start your script like this:

. myscript.sh

The . will evaluate the script in the current environment, so it might be altered

Difference between a virtual function and a pure virtual function

A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.

You denote that fact by appending the "= 0" to the declaration, like this:

class AbstractBase
{
    virtual void PureVirtualFunction() = 0;
}

Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:

class Derived : public AbstractBase
{
    virtual void PureVirtualFunction() override { }
}

By adding the override keyword, the compiler will ensure that there is a base class virtual function with the same signature.

What is the easiest way to ignore a JPA field during persistence?

Apparently, using Hibernate5Module, the @Transient will not be serialize if using ObjectMapper. Removing will make it work.

import javax.persistence.Transient;

import org.junit.Test;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TransientFieldTest {

    @Test
    public void Print_Json() throws JsonProcessingException {

        ObjectMapper objectEntityMapper = new ObjectMapper();
        //objectEntityMapper.registerModule(new Hibernate5Module());
        objectEntityMapper.setSerializationInclusion(Include.NON_NULL);

        log.info("object: {}", objectEntityMapper.writeValueAsString( //
                SampleTransient.builder()
                               .id("id")
                               .transientField("transientField")
                               .build()));

    }

    @Getter
    @Setter
    @Builder
    private static class SampleTransient {

        private String id;

        @Transient
        private String transientField;

        private String nullField;

    }
}

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

Check image width and height before upload with Javascript

function uploadfile(ctrl) {
    var validate = validateimg(ctrl);

    if (validate) {
        if (window.FormData !== undefined) {
            ShowLoading();
            var fileUpload = $(ctrl).get(0);
            var files = fileUpload.files;


            var fileData = new FormData();


            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }


            fileData.append('username', 'Wishes');

            $.ajax({
                url: 'UploadWishesFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function(result) {
                    var id = $(ctrl).attr('id');
                    $('#' + id.replace('txt', 'hdn')).val(result);

                    $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                    HideLoading();
                },
                error: function(err) {
                    alert(err.statusText);
                    HideLoading();
                }
            });
        } else {
            alert("FormData is not supported.");
        }

    }

How to delete shared preferences data from App in Android

You can always do it programmatically as suggested by the other answers over here. But for development purpose, I find this Plugin very helpful as it speeds up my development significantly.

PLUGIN: ADB Idea

It provides you with features to Clear App Data and Revoke Permission from your Android Studio itself, just with click of a button.

enter image description here

When to use single quotes, double quotes, and backticks in MySQL

SQL servers and MySQL, PostgreySQL, Oracle don't understand double quotes("). Thus your query should be free from double quotes(") and should only use single quotes(').

Back-trip(`) is optional to use in SQL and is used for table name, db name and column names.

If you are trying to write query in your back-end to call MySQL then you can use double quote(") or single quotes(') to assign query to a variable like:

let query = "select id, name from accounts";
//Or
let query = 'select id, name from accounts';

If ther's a where statement in your query and/or trying to insert a value and/or an update of value which is string use single quote(') for these values like:

let querySelect = "select id, name from accounts where name = 'John'";
let queryUpdate = "update accounts set name = 'John' where id = 8";
let queryInsert = "insert into accounts(name) values('John')";

//Please not that double quotes are only to be used in assigning string to our variable not in the query
//All these below will generate error

let querySelect = 'select id, name from accounts where name = "John"';
let queryUpdate = 'update accounts set name = "John" where id = 8';
let queryInsert = 'insert into accounts(name) values("John")';

//As MySQL or any SQL doesn't understand double quotes("), these all will generate error.

If you want to stay out of this confusion when to use double quotes(") and single quotes('), would recommend to stick with single quotes(') this will include backslash() like:

let query = 'select is, name from accounts where name = \'John\'';

Problem with double(") or single(') quotes arise when we had to assign some value dynamic and perform some string concatenation like:

let query = "select id, name from accounts where name = " + fName + " " + lName;
//This will generate error as it must be like name = 'John Smith' for SQL
//However our statement made it like name = John Smith

//In order to resolve such errors use
let query = "select id, name from accounts where name = '" + fName + " " + lName + "'";

//Or using backslash(\)
let query = 'select id, name from accounts where name = \'' + fName + ' ' + lName + '\'';

If need further clearance do follow quotes in JavaScript

Can I escape html special chars in javascript?

Try this, using the prototype.js library:

string.escapeHTML();

Try a demo

How to fill in proxy information in cntlm config file?

Without any configuration, you can simply issue the following command (modifying myusername and mydomain with your own information):

cntlm -u myusername -d mydomain -H

or

cntlm -u myusername@mydomain -H

It will ask you the password of myusername and will give you the following output:

PassLM          1AD35398BE6565DDB5C4EF70C0593492
PassNT          77B9081511704EE852F94227CF48A793
PassNTLMv2      A8FC9092D566461E6BEA971931EF1AEC    # Only for user 'myusername', domain 'mydomain'

Then create the file cntlm.ini (or cntlm.conf on Linux using default path) with the following content (replacing your myusername, mydomain and A8FC9092D566461E6BEA971931EF1AEC with your information and the result of the previous command):

Username    myusername
Domain      mydomain

Proxy       my_proxy_server.com:80
NoProxy     127.0.0.*, 192.168.*

Listen      127.0.0.1:5865
Gateway     yes

SOCKS5Proxy 5866

Auth        NTLMv2
PassNTLMv2  A8FC9092D566461E6BEA971931EF1AEC

Then you will have a local open proxy on local port 5865 and another one understanding SOCKS5 protocol at local port 5866.

Yes or No confirm box using jQuery

_x000D_
_x000D_
ConfirmDialog('Are you sure');_x000D_
_x000D_
function ConfirmDialog(message) {_x000D_
  $('<div></div>').appendTo('body')_x000D_
    .html('<div><h6>' + message + '?</h6></div>')_x000D_
    .dialog({_x000D_
      modal: true,_x000D_
      title: 'Delete message',_x000D_
      zIndex: 10000,_x000D_
      autoOpen: true,_x000D_
      width: 'auto',_x000D_
      resizable: false,_x000D_
      buttons: {_x000D_
        Yes: function() {_x000D_
          // $(obj).removeAttr('onclick');                                _x000D_
          // $(obj).parents('.Parent').remove();_x000D_
_x000D_
          $('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');_x000D_
_x000D_
          $(this).dialog("close");_x000D_
        },_x000D_
        No: function() {_x000D_
          $('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');_x000D_
_x000D_
          $(this).dialog("close");_x000D_
        }_x000D_
      },_x000D_
      close: function(event, ui) {_x000D_
        $(this).remove();_x000D_
      }_x000D_
    });_x000D_
};
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
_x000D_
_x000D_
_x000D_

How does GPS in a mobile phone work exactly?

There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing. Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.

If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.

Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.

Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.

How to update Python?

I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.

MVC DateTime binding with incorrect date format

  public class DateTimeFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.RequestType == "GET")
        {

            foreach (var parameter in filterContext.ActionParameters)
            {
                var properties = parameter.Value.GetType().GetProperties();

                foreach (var property in properties)
                {
                    Type type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;

                    if (property.PropertyType == typeof(System.DateTime) || property.PropertyType == typeof(DateTime?))
                    {
                        DateTime dateTime;

                        if (DateTime.TryParse(filterContext.HttpContext.Request.QueryString[property.Name], CultureInfo.CurrentUICulture, DateTimeStyles.None, out dateTime))
                            property.SetValue(parameter.Value, dateTime,null);
                    }
                }

            }
        }
    }
}

Java Regex Capturing Groups

Your understanding is correct. However, if we walk through:

  • (.*) will swallow the whole string;
  • it will need to give back characters so that (\\d+) is satistifed (which is why 0 is captured, and not 3000);
  • the last (.*) will then capture the rest.

I am not sure what the original intent of the author was, however.

How to get text from EditText?

If you are doing it before the setContentView() method call, then the values will be null.

This will result in null:

super.onCreate(savedInstanceState);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();

setContentView(R.layout.main_contacts);

while this will work fine:

super.onCreate(savedInstanceState);
setContentView(R.layout.main_contacts);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();

Why is using the JavaScript eval function a bad idea?

It's generally only an issue if you're passing eval user input.

pandas GroupBy columns with NaN (missing) values

I answered this already, but some reason the answer was converted to a comment. Nevertheless, this is the most efficient solution:

Not being able to include (and propagate) NaNs in groups is quite aggravating. Citing R is not convincing, as this behavior is not consistent with a lot of other things. Anyway, the dummy hack is also pretty bad. However, the size (includes NaNs) and the count (ignores NaNs) of a group will differ if there are NaNs.

dfgrouped = df.groupby(['b']).a.agg(['sum','size','count'])

dfgrouped['sum'][dfgrouped['size']!=dfgrouped['count']] = None

When these differ, you can set the value back to None for the result of the aggregation function for that group.

Show "loading" animation on button click

I know this a very much late reply but I saw this query recently And found a working scenario,

OnClick of Submit use the below code:

 $('#Submit').click(function ()
 { $(this).html('<img src="icon-loading.gif" />'); // A GIF Image of Your choice
 return false });

To Stop the Gif use the below code:

$('#Submit').ajaxStop();

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

Solution for UBUNTU Worked for me:

Installed tesseract in ubuntu by following below link

https://medium.com/quantrium-tech/installing-tesseract-4-on-ubuntu-18-04-b6fcd0cbd78f

Later added traindata language to tessdata by following below link

Tesseract running error

Program does not contain a static 'Main' method suitable for an entry point

Project Properties \ Output file -> Select Class Library :)

Does Java support default parameter values?

If you really want to, you can check it manually by using null:

public MyParameterizedFunction(String param1, int param2, boolean param3)
{
    if(param3 == null) {
        param3 = false;
    }
}

However i heavily recommend using something else, like overloading or a static factory. Maybe you can get away with this, but it can lead to unexcspected behavior. For example you could have an error in your code, so that your boolean never gets a value. In this case you would not get a NullPointerException. Instead it will look like it was set to false, which can be very confusing to debug.

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

What is App.config in C#.NET? How to use it?

You can access keys in the App.Config using:

ConfigurationSettings.AppSettings["KeyName"]

Take alook at this Thread

What does -XX:MaxPermSize do?

-XX:PermSize -XX:MaxPermSize are used to set size for Permanent Generation.

Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.

How can I get the full/absolute URL (with domain) in Django?

This worked for me in my template:

{{ request.scheme }}://{{ request.META.HTTP_HOST }}{% url 'equipos:marca_filter' %}

I needed the full url to pass it to a js fetch function. I hope this help you.

How do you add swap to an EC2 instance?

You can create swap space using the following steps Here we are creating swap at /home/

  1. dd if=/dev/zero of=/home/swapfile1 bs=1024 count=8388608
    Here count is kilobyte count of swap space

  2. mkswap /home/swapfile1

  3. vi /etc/fstab
    make entry :
    /home/swapfile1 swap swap defaults 0 0

  4. run:
    swapon -a

Get the string value from List<String> through loop for display

public static void main(String[] args) {

    List<String> ls=new ArrayList<String>();
    ls.add("1");
    ls.add("2");
    ls.add("3");
    ls.add("4");

//Then  you can use "foreache" loop to iterate.

    for(String item:ls){
        System.out.println(item);
    }

}

Is Tomcat running?

tomcat.sh helps you know this easily.

tomcat.sh usage doc says:

no argument: display the process-id of the tomcat, if it's running, otherwise do nothing

So, run command on your command prompt and check for pid:

$ tomcat.sh

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

How can I be notified when an element is added to the page?

Between the deprecation of mutation events and the emergence of MutationObserver, an efficent way to be notified when a specific element was added to the DOM was to exploit CSS3 animation events.

To quote the blog post:

Setup a CSS keyframe sequence that targets (via your choice of CSS selector) whatever DOM elements you want to receive a DOM node insertion event for. I used a relatively benign and little used css property, clip I used outline-color in an attempt to avoid messing with intended page styles – the code once targeted the clip property, but it is no longer animatable in IE as of version 11. That said, any property that can be animated will work, choose whichever one you like.

Next I added a document-wide animationstart listener that I use as a delegate to process the node insertions. The animation event has a property called animationName on it that tells you which keyframe sequence kicked off the animation. Just make sure the animationName property is the same as the keyframe sequence name you added for node insertions and you’re good to go.

Get difference between 2 dates in JavaScript?

I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....

So here's my answer and can be run out of the box.

<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>

a Fiddle can be seen here DEMO

How to change font size in a textbox in html

To actually do it in HTML with inline CSS (not with an external CSS style sheet)

<input type="text" style="font-size: 44pt">

A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html> or <body> tag, and such is appropriate there.

How to pass multiple parameters in json format to a web service using jquery?

i have same issue and resolved by

 data: "Id1=" + id1 + "&Id2=" + id2

How to Validate a DateTime in C#?

private void btnEnter_Click(object sender, EventArgs e)
{
    maskedTextBox1.Mask = "00/00/0000";
    maskedTextBox1.ValidatingType = typeof(System.DateTime);
    //if (!IsValidDOB(maskedTextBox1.Text)) 
    if (!ValidateBirthday(maskedTextBox1.Text))
        MessageBox.Show(" Not Valid");
    else
        MessageBox.Show("Valid");
}
// check date format dd/mm/yyyy. but not if year < 1 or > 2013.
public static bool IsValidDOB(string dob)
{ 
    DateTime temp;
    if (DateTime.TryParse(dob, out temp))
        return (true);
    else 
        return (false);
}
// checks date format dd/mm/yyyy and year > 1900!.
protected bool ValidateBirthday(String date)
{
    DateTime Temp;
    if (DateTime.TryParse(date, out Temp) == true &&
        Temp.Year > 1900 &&
       // Temp.Hour == 0 && Temp.Minute == 0 &&
        //Temp.Second == 0 && Temp.Millisecond == 0 &&
        Temp > DateTime.MinValue)
        return (true);
    else
        return (false);
}

Remove all constraints affecting a UIView

Swift

Following UIView Extension will remove all Edge constraints of a view:

extension UIView {
    func removeAllConstraints() {
        if let _superview = self.superview {
            self.removeFromSuperview()
            _superview.addSubview(self)
        }
    }
}

Python read-only property

Generally, Python programs should be written with the assumption that all users are consenting adults, and thus are responsible for using things correctly themselves. However, in the rare instance where it just does not make sense for an attribute to be settable (such as a derived value, or a value read from some static datasource), the getter-only property is generally the preferred pattern.

How to specify the default error page in web.xml?

On Servlet 3.0 or newer you could just specify

<web-app ...>
    <error-page>
        <location>/general-error.html</location>
    </error-page>
</web-app>

But as you're still on Servlet 2.5, there's no other way than specifying every common HTTP error individually. You need to figure which HTTP errors the enduser could possibly face. On a barebones webapp with for example the usage of HTTP authentication, having a disabled directory listing, using custom servlets and code which can possibly throw unhandled exceptions or does not have all methods implemented, then you'd like to set it for HTTP errors 401, 403, 500 and 503 respectively.

<error-page>
    <!-- Missing login -->
    <error-code>401</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Forbidden directory listing -->
    <error-code>403</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Missing resource -->
    <error-code>404</error-code>
    <location>/Error404.html</location>
</error-page>
<error-page>
    <!-- Uncaught exception -->
    <error-code>500</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Unsupported servlet method -->
    <error-code>503</error-code>
    <location>/general-error.html</location>
</error-page>

That should cover the most common ones.

Insert auto increment primary key to existing table

ALTER TABLE tableName MODIFY tableNameID MEDIUMINT NOT NULL AUTO_INCREMENT;

Here tableName is name of your table,

tableName is your column name which is primary has to be modified

MEDIUMINT is a data type of your existing primary key

AUTO_INCREMENT you have to add just auto_increment after not null

It will make that primary key auto_increment......

Hope this is helpful:)

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Pass CultureInfo.InvariantCulture as the second parameter of DateTime, it will return the string as what you want, even a very special format:

DateTime.Now.ToString("dd|MM|yyyy", CultureInfo.InvariantCulture)

will return: 28|02|2014

Get Android Phone Model programmatically

The following strings are all of use when you want to retrieve manufacturer, name of the device, and/or the model:

String manufacturer = Build.MANUFACTURER;
String brand        = Build.BRAND;
String product      = Build.PRODUCT;
String model        = Build.MODEL;

Shared-memory objects in multiprocessing

If you use an operating system that uses copy-on-write fork() semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).

The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy or array), place that in shared memory, wrap it with multiprocessing.Array, and pass that to your functions. This answer shows how to do that.

If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).

The Manager approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.

There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.

Error occurred during initialization of boot layer FindException: Module not found

I had the same issue and I fixed it this way:

  1. Deleted all projects from eclipse, not from the computer.
  2. Created a new project and as soon as you write the name of your project, you get another window, in which is written: "Create module-info.java". I just clicked "don't create".
  3. Created a package. Let us call the package mywork.
  4. Created a Java class inside the package myWork. Let us call the class HelloWorld.
  5. I run the file normally and it was working fine.

Note: First, make sure that Java is running properly using the CMD command in that way you will understand the problem is on eclipse and not on JDK.

Can you run GUI applications in a Docker container?

Xauthority becomes an issue with newer systems. I can either discard any protection with xhost + before running my docker containers, or I can pass in a well prepared Xauthority file. Typical Xauthority files are hostname specific. With docker, each container can have a different host name (set with docker run -h), but even setting the hostname of the container identical to the host system did not help in my case. xeyes (I like this example) simply would ignore the magic cookie and pass no credentials to the server. Hence we get an error message 'No protocol specified Cannot open display'

The Xauthority file can be written in a way so that the hostname does not matter. We need to set the Authentication Family to 'FamilyWild'. I am not sure, if xauth has a proper command line for this, so here is an example that combines xauth and sed to do that. We need to change the first 16 bits of the nlist output. The value of FamilyWild is 65535 or 0xffff.

docker build -t xeyes - << __EOF__
FROM debian
RUN apt-get update
RUN apt-get install -qqy x11-apps
ENV DISPLAY :0
CMD xeyes
__EOF__
XSOCK=/tmp/.X11-unix
XAUTH=/tmp/.docker.xauth
xauth nlist :0 | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge -
docker run -ti -v $XSOCK:$XSOCK -v $XAUTH:$XAUTH -e XAUTHORITY=$XAUTH xeyes

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

invalidate cache in android studio will resolve this issue. Go to file-> click on invalidate cache/restart option.

data.map is not a function

data is not an array, it is an object with an array of products so iterate over data.products

var allProducts = data.products.map(function (item) {
    return new getData(item);
});

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\ is an escape character in Python. \t gets interpreted as a tab. If you need \ character in a string, you have to use \\.

Your code should be:
test_file=open('c:\\Python27\\test.txt','r')

Action Image MVC3 Razor

This would be work very fine

<a href="<%:Url.Action("Edit","Account",new {  id=item.UserId }) %>"><img src="../../Content/ThemeNew/images/edit_notes_delete11.png" alt="Edit" width="25px" height="25px" /></a>

Setting multiple attributes for an element at once with JavaScript

you can simply add a method (setAttributes, with "s" at the end) to "Element" prototype like:

Element.prototype.setAttributes = function(obj){
  for(var prop in obj) {
    this.setAttribute(prop, obj[prop])
  }
}

you can define it in one line:

Element.prototype.setAttributes = function(obj){ for(var prop in obj) this.setAttribute(prop, obj[prop]) }

and you can call it normally as you call the other methods. The attributes are given as an object:

elem.setAttributes({"src": "http://example.com/something.jpeg", "height": "100%", "width": "100%"})

you can add an if statement to throw an error if the given argument is not an object.

Windows Application has stopped working :: Event Name CLR20r3

Make sure the client computer has the same or higher version of the .NET framework that you built your program to.

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

How can I get my Android device country code without using GPS?

Use the link http://ip-api.com/json. This will provide all the information as JSON. From this JSON content you can get the country easily. This site works using your current IP address. It automatically detects the IP address and sendback details.

Documentation

This is what I got:

{
"as": "AS55410 C48 Okhla Industrial Estate, New Delhi-110020",
"city": "Kochi",
"country": "India",
"countryCode": "IN",
"isp": "Vodafone India",
"lat": 9.9667,
"lon": 76.2333,
"org": "Vodafone India",
"query": "123.63.81.162",
"region": "KL",
"regionName": "Kerala",
"status": "success",
"timezone": "Asia/Kolkata",
"zip": ""
}

N.B. - As this is a third-party API, do not use it as the primary solution. And also I am not sure whether it's free or not.

Determine the process pid listening on a certain port

on windows, the netstat option to get the pid's is -o and -p selects a protocol filter, ex.: netstat -a -p tcp -o

jQuery UI Sortable, then write order into a database

Try with this solution: http://phppot.com/php/sorting-mysql-row-order-using-jquery/ where new order is saved in some HMTL element. Then you submit the form with this data to some PHP script, and iterate trough it with for loop.

Note: I had to add another db field of type INT(11) which is updated(timestamp'ed) on each iteration - it serves for script to know which row is recenty updated, or else you end up with scrambled results.

extract month from date in python

>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'

Kill tomcat service running on any port, Windows

1) Go to (Open) Command Prompt (Press Window + R then type cmd Run this).

2) Run following commands

For all listening ports

netstat -aon | find /i "listening"

Apply port filter

netstat -aon |find /i "listening" |find "8080"

Finally with the PID we can run the following command to kill the process

3) Copy PID from result set

taskkill /F /PID

Ex: taskkill /F /PID 189

Sometimes you need to run Command Prompt with Administrator privileges

Done !!! you can start your service now.

How to convert float to varchar in SQL Server

float only has a max. precision of 15 digits. Digits after the 15th position are therefore random, and conversion to bigint (max. 19 digits) or decimal does not help you.

Basic authentication with fetch?

This is not directly related to the initial issue, but probably will help somebody.

I faced same issue when was trying to send similar request using domain account. So mine issue was in not escaped character in login name.

Bad example:

'ABC\username'

Good example:

'ABC\\username'

Service Reference Error: Failed to generate code for the service reference

Restarting Visual Studio did the trick for me. I am using VS 2015.

Convert DataTable to IEnumerable<T>

If you are producing the DataTable from an SQL query, have you considered simply using Dapper instead?

Then, instead of making a SqlCommand with SqlParameters and a DataTable and a DataAdapter and on and on, which you then have to laboriously convert to a class, you just define the class, make the query column names match the field names, and the parameters are bound easily by name. You already have the TankReading class defined, so it will be really simple!

using Dapper;

// Below can be SqlConnection cast to DatabaseConnection, too.
DatabaseConnection connection = // whatever
IEnumerable<TankReading> tankReadings = connection.Query<TankReading>(
   "SELECT * from TankReading WHERE Value = @value",
   new { value = "tank1" } // note how `value` maps to `@value`
);
return tankReadings;

Now isn't that awesome? Dapper is very optimized and will give you darn near equivalent performance as reading directly with a DataAdapter.

If your class has any logic in it at all or is immutable or has no parameterless constructor, then you probably do need to have a DbTankReading class (as a pure POCO/Plain Old Class Object):

// internal because it should only be used in the data source project and not elsewhere
internal sealed class DbTankReading {
   int TankReadingsID { get; set; }
   DateTime? ReadingDateTime { get; set; }
   int ReadingFeet { get; set; }
   int ReadingInches { get; set; }
   string MaterialNumber { get; set; }
   string EnteredBy { get; set; }
   decimal ReadingPounds { get; set; }
   int MaterialID { get; set; }
   bool Submitted { get; set; }
}

You'd use that like this:

IEnumerable<TankReading> tankReadings = connection
   .Query<DbTankReading>(
      "SELECT * from TankReading WHERE Value = @value",
      new { value = "tank1" } // note how `value` maps to `@value`
   )
   .Select(tr => new TankReading(
      tr.TankReadingsID,
      tr.ReadingDateTime,
      tr.ReadingFeet,
      tr.ReadingInches,
      tr.MaterialNumber,
      tr.EnteredBy,
      tr.ReadingPounds,
      tr.MaterialID,
      tr.Submitted
   });

Despite the mapping work, this is still less painful than the data table method. This also lets you perform some kind of logic, though if the logic is any more than very simple straight-across mapping, I'd put the logic into a separate TankReadingMapper class.

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

How do I add a Font Awesome icon to input field?

simple way for new font awesome

  <div class="input-group">
                    <input type="text" class="form-control" placeholder="Search" name="txtSearch"  >
                    <div class="input-group-btn">
                        <button class="btn btn-default" type="submit"><i class="fas fa-search"></i></button>
                    </div>
                </div>

Can an Option in a Select tag carry multiple values?

put values for each options like

<SELECT NAME="val">
   <OPTION VALUE="1" value="1:2:3:4"> 1-4  
   <OPTION VALUE="2" value="5:6:7:8"> 5-8  
   <OPTION VALUE="3" value="9:10:11:12"> 9-12
</SELECT>

at server side in case of php, use functions like explode [array] = explode([delimeter],[posted value]);

$values = explode(':',$_POST['val']

the above code return an array have only the numbers and the ':' get removed

How to make JavaScript execute after page load?

Just define <body onload="aFunction()"> that will be called after the page has been loaded. Your code in the script is than enclosed by aFunction() { }.

What's the difference between ng-model and ng-bind

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.

Auto-Submit Form using JavaScript

Try this,

HtmlElement head = _windowManager.ActiveBrowser.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = _windowManager.ActiveBrowser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "window.onload = function() { document.forms[0].submit(); }";
head.AppendChild(scriptEl);
strAdditionalHeader = "";
_windowManager.ActiveBrowser.Document.InvokeScript("webBrowserControl");

NuGet Packages are missing

I am using VS2012 and facing the same error. I removed the following Target tag from the .csproj file and it started compiling without any error.

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
  -- Error messages within Target Tag
</Target>

Merging Cells in Excel using C#

Excel.Application xl = new Excel.ApplicationClass();

Excel.Workbook wb = xl.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorkshe et);

Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;

ws.Cells[1,1] = "Testing";

Excel.Range range = ws.get_Range(ws.Cells[1,1],ws.Cells[1,2]);

range.Merge(true);

range.Interior.ColorIndex =36;

xl.Visible =true;

How do I refresh the page in ASP.NET? (Let it reload itself by code)

for asp.net core 3.1

Response.Headers.Add("Refresh", "2");// in secound

and

Response.Headers.Remove("Refresh");

scp with port number specified

if you need copy local file to server (specify port )

scp -P 3838 /the/source/file [email protected]:/destination/file

Should I use Java's String.format() if performance is important?

Generally you should use String.Format because it's relatively fast and it supports globalization (assuming you're actually trying to write something that is read by the user). It also makes it easier to globalize if you're trying to translate one string versus 3 or more per statement (especially for languages that have drastically different grammatical structures).

Now if you never plan on translating anything, then either rely on Java's built in conversion of + operators into StringBuilder. Or use Java's StringBuilder explicitly.

Can I grep only the first n lines of a file?

Or use awk for a single process without |:

awk '/your_regexp/ && NR < 11' INPUTFILE

On each line, if your_regexp matches, and the number of records (lines) is less than 11, it executes the default action (which is printing the input line).

Or use sed:

sed -n '/your_regexp/p;10q' INPUTFILE 

Checks your regexp and prints the line (-n means don't print the input, which is otherwise the default), and quits right after the 10th line.

Encode String to UTF-8

String value = new String(myString.getBytes("UTF-8"));

and, if you want to read from text file with "ISO-8859-1" encoded:

String line;
String f = "C:\\MyPath\\MyFile.txt";
try {
    BufferedReader br = Files.newBufferedReader(Paths.get(f), Charset.forName("ISO-8859-1"));
    while ((line = br.readLine()) != null) {
        System.out.println(new String(line.getBytes("UTF-8")));
    }
} catch (IOException ex) {
    //...
}

Making a DateTime field in a database automatic?

Yes, here's an example:

CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )

You can INSERT into the table without indicating the createdDate and updatedDate columns:

INSERT INTO myTable (col1) VALUES (1)

Or use the keyword DEFAULT:

INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)

Then create a trigger for updating the updatedDate column:

CREATE TRIGGER dbo.updateMyTable 
ON dbo.myTable
FOR UPDATE 
AS 
BEGIN 
    IF NOT UPDATE(updatedDate) 
        UPDATE dbo.myTable SET updatedDate=GETDATE() 
        WHERE col1 IN (SELECT col1 FROM inserted) 
END 
GO

How to access global js variable in AngularJS directive

I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).

The easiest solution that I have found is to do the following:

In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.

Example:

'use strict';

//my data variable that I need access to.
var data = null;

angular.module('sample', [])

Then in your controller:

.controller('SampleApp', function ($scope, $location) {

$scope.availableList = [];

$scope.init = function () {
    $scope.availableList = data;
}

Finally, you have to init everything (order matters):

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="/path/to/your/angular/js/sample.js"></script>
  <script type="text/javascript">
      data = <?= json_encode($cproducts); ?>
  </script>

Finally initialize your controller and init function.

  <div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">

By doing this you will now have access to whatever data you stuffed into the global variable.

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

to pass many options you can pass a object to a @Input decorator with custom data in a single line.

In the template

<li *ngFor = 'let opt of currentQuestion.options' 
                [selectable] = 'opt'
                [myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
                (selectedOption) = 'onOptionSelection($event)' >
     {{opt.option}}
</li>

so in Directive class

@Directive({
  selector: '[selectable]'
})

export class SelectableDirective{
  private el: HTMLElement;
  @Input('selectable') option:any;
  @Input('myOptions') data;

  //do something with data.first
  ...
  // do something with data.second
}

How to pass List<String> in post method using Spring MVC?

You can pass input as ["apple","orange"]if you want to leave the method as it is.

It worked for me with a similar method signature.

Error message "Strict standards: Only variables should be passed by reference"

Consider the following code:

error_reporting(E_STRICT);
class test {
    function test_arr(&$a) {
        var_dump($a);
    }
    function get_arr() {
        return array(1, 2);
    }
}

$t = new test;
$t->test_arr($t->get_arr());

This will generate the following output:

Strict Standards: Only variables should be passed by reference in `test.php` on line 14
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

The reason? The test::get_arr() method is not a variable and under strict mode this will generate a warning. This behavior is extremely non-intuitive as the get_arr() method returns an array value.

To get around this error in strict mode, either change the signature of the method so it doesn't use a reference:

function test_arr($a) {
    var_dump($a);
}

Since you can't change the signature of array_shift you can also use an intermediate variable:

$inter = get_arr();
$el = array_shift($inter);

How to catch a unique constraint error in a PL/SQL block?

I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:

begin
    merge into some_table st
    using (select 'some' name, 'values' value from dual) v
    on (st.name=v.name)
    when matched then update set st.value=v.value
    when not matched then insert (name, value) values (v.name, v.value);
end;

(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).

Use Font Awesome icon as CSS content

As it says at FontAwesome website FontAwesome =>

HTML:

<span class="icon login"></span> Login</li>

CSS:

 .icon::before {
    display: inline-block;
    font-style: normal;
    font-variant: normal;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
  }

    .login::before {
        font-family: "Font Awesome 5 Free";
        font-weight: 900;
        content: "\f007";
   }

In .login::before -> edit content:''; to suit your unicode.

R: Comment out block of code

Wrap it in an unused function:

.f = function() {

## unwanted code here:

}

docker mounting volumes on host

The VOLUME command will mount a directory inside your container and store any files created or edited inside that directory on your hosts disk outside the container file structure, bypassing the union file system.

The idea is that your volumes can be shared between your docker containers and they will stay around as long as there's a container (running or stopped) that references them.

You can have other containers mount existing volumes (effectively sharing them between containers) by using the --volumes-from command when you run a container.

The fundamental difference between VOLUME and -v is this: -v will mount existing files from your operating system inside your docker container and VOLUME will create a new, empty volume on your host and mount it inside your container.

Example:

  1. You have a Dockerfile that defines a VOLUME /var/lib/mysql.
  2. You build the docker image and tag it some-volume
  3. You run the container

And then,

  1. You have another docker image that you want to use this volume
  2. You run the docker container with the following: docker run --volumes-from some-volume docker-image-name:tag
  3. Now you have a docker container running that will have the volume from some-volume mounted in /var/lib/mysql

Note: Using --volumes-from will mount the volume over whatever exists in the location of the volume. I.e., if you had stuff in /var/lib/mysql, it will be replaced with the contents of the volume.

PostgreSQL how to see which queries have run

I found the log file at /usr/local/var/log/postgres.log on a mac installation from brew.

Check if an array is empty or exists

This is what I use. The first condition covers truthy, which has both null and undefined. Second condition checks for an empty array.

if(arrayName && arrayName.length > 0){
    //do something.
}

or thanks to tsemer's comment I added a second version

if(arrayName && arrayName.length)

Then I made a test for the second condition, using Scratchpad in Firefox:

_x000D_
_x000D_
var array1;_x000D_
var array2 = [];_x000D_
var array3 = ["one", "two", "three"];_x000D_
var array4 = null;_x000D_
_x000D_
console.log(array1);_x000D_
console.log(array2);_x000D_
console.log(array3);_x000D_
console.log(array4);_x000D_
_x000D_
if (array1 && array1.length) {_x000D_
  console.log("array1! has a value!");_x000D_
}_x000D_
_x000D_
if (array2 && array2.length) {_x000D_
  console.log("array2! has a value!");_x000D_
}_x000D_
_x000D_
if (array3 && array3.length) {_x000D_
  console.log("array3! has a value!");_x000D_
}_x000D_
_x000D_
if (array4 && array4.length) {_x000D_
  console.log("array4! has a value!");_x000D_
}
_x000D_
_x000D_
_x000D_

which also proves that if(array2 && array2.length) and if(array2 && array2.length > 0) are exactly doing the same

How to show shadow around the linearlayout in Android?

There is also another solution to the problem by implementing a layer-list that will act as the background for the LinearLayoout.

Add background_with_shadow.xml file to res/drawable. Containing:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item >
        <shape 
            android:shape="rectangle">
        <solid android:color="@android:color/darker_gray" />
        <corners android:radius="5dp"/>
        </shape>
    </item>
    <item android:right="1dp" android:left="1dp" android:bottom="2dp">
        <shape 
            android:shape="rectangle">
        <solid android:color="@android:color/white"/>
        <corners android:radius="5dp"/>
        </shape>
    </item>
</layer-list>

Then add the the layer-list as background in your LinearLayout.

<LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="@drawable/background_with_shadow"/>

How to split data into trainset and testset randomly?

sklearn.cross_validation is deprecated since version 0.18, instead you should use sklearn.model_selection as show below

from sklearn.model_selection import train_test_split
import numpy

with open("datafile.txt", "rb") as f:
   data = f.read().split('\n')
   data = numpy.array(data)  #convert array to numpy type array

   x_train ,x_test = train_test_split(data,test_size=0.5)       #test_size=0.5(whole_data)

TypeScript enum to object array

There is a simple solution, So when you run Object.keys(Enum) that gonna give you a Array of Values and Keys, in first slice Values and in the second one keys, so why we don't just return the second slice, this code below works for me.

enum Enum {
   ONE,
   TWO,
   THREE,
   FOUR,
   FIVE,
   SIX,
   SEVEN
}
const keys = Object.keys(Enum); 
console.log(keys.slice(keys.length / 2));

Bootstrap: how do I change the width of the container?

Go to the Customize section on Bootstrap site and choose the size you prefer. You'll have to set @gridColumnWidth and @gridGutterWidth variables.

For example: @gridColumnWidth = 65px and @gridGutterWidth = 20px results on a 1000px layout.

Then download it.

Correctly Parsing JSON in Swift 3

A big change that happened with Xcode 8 Beta 6 for Swift 3 was that id now imports as Any rather than AnyObject.

This means that parsedData is returned as a dictionary of most likely with the type [Any:Any]. Without using a debugger I could not tell you exactly what your cast to NSDictionary will do but the error you are seeing is because dict!["currently"]! has type Any

So, how do you solve this? From the way you've referenced it, I assume dict!["currently"]! is a dictionary and so you have many options:

First you could do something like this:

let currentConditionsDictionary: [String: AnyObject] = dict!["currently"]! as! [String: AnyObject]  

This will give you a dictionary object that you can then query for values and so you can get your temperature like this:

let currentTemperatureF = currentConditionsDictionary["temperature"] as! Double

Or if you would prefer you can do it in line:

let currentTemperatureF = (dict!["currently"]! as! [String: AnyObject])["temperature"]! as! Double

Hopefully this helps, I'm afraid I have not had time to write a sample app to test it.

One final note: the easiest thing to do, might be to simply cast the JSON payload into [String: AnyObject] right at the start.

let parsedData = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as! Dictionary<String, AnyObject>

How to merge 2 JSON objects from 2 files using jq?

First, {"value": .value} can be abbreviated to just {value}.

Second, the --argfile option (available in jq 1.4 and jq 1.5) may be of interest as it avoids having to use the --slurp option.

Putting these together, the two objects in the two files can be combined in the specified way as follows:

$ jq -n --argfile o1 file1 --argfile o2 file2 '$o1 * $o2 | {value}'

The '-n' flag tells jq not to read from stdin, since inputs are coming from the --argfile options here.

Note on --argfile

The jq manual deprecates --argfile because its semantics are non-trivial: if the specified input file contains exactly one JSON entity, then that entity is read as is; otherwise, the items in the stream are wrapped in an array.

If you are uncomfortable using --argfile, there are several alternatives you may wish to consider. In doing so, be assured that using --slurpfile does not incur the inefficiencies of the -s command-line option when the latter is used with multiple files.

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

Definitions:

  • Frame Layout: This is designed to block out an area on the screen to display a single item.
  • Linear Layout: A layout that arranges its children in a single column or a single row.
  • Relative Layout: This layout is a view group that displays child views in relative positions.
  • Table Layout: A layout that arranges its children into rows and columns.

More Information:

FrameLayout

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.

Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).

RelativeLayout

A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.

(Current docs here)

TableLayout

A TableLayout consists of a number of TableRow objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

The width of a column is defined by the row with the widest cell in that column.


Note: Absolute Layout is deprecated.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Try this

$_SERVER['HTTP_CF_CONNECTING_IP'];

instead of

$_SERVER["REMOTE_ADDR"];

How to change the hosts file on android

Probably the easiest way would be use this app Hosts Editor . You need to have root

ThreadStart with parameters

Yep :

Thread t = new Thread (new ParameterizedThreadStart(myMethod));
t.Start (myParameterObject);

AngularJS ng-repeat handle empty list case

<ul>
    <li ng-repeat="item in items | filter:keyword as filteredItems">
        ...
    </li>
    <li ng-if="filteredItems.length===0">
        No items found
    </li>
</ul>

This is similar to @Konrad 'ktoso' Malawski but slightly easier to remember.

Tested with Angular 1.4

MySQL: Convert INT to DATETIME

The function STR_TO_DATE(COLUMN, '%input_format') can do it, you only have to specify the input format. Example : to convert p052011

SELECT STR_TO_DATE('p052011','p%m%Y') FROM your_table;

The result : 2011-05-00

"column not allowed here" error in INSERT statement

Try using varchar2 instead of varchar and use this :

INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');

How do I import a specific version of a package using go get?

It might be useful.

Just type this into your command prompt while cd your/package/src/

go get github.com/go-gl/[email protected]

You get specific revision of package in question right into your source code, ready to use in import statement.

How to add/subtract dates with JavaScript?

Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.

HTML:

<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />

JavaScript:

    var counter = 0;

$("#SubtractDay").click(function() {
    counter--;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
    counter++;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});

jsfiddle

Pass in an enum as a method parameter

Change the signature of the CreateFile method to expect a SupportedPermissions value instead of plain Enum.

public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions
    };

    return file.Id;
}

Then when you call your method you pass the SupportedPermissions value to your method

  var basicFile = CreateFile(myId, myName, myDescription, SupportedPermissions.basic);

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

TypeScript function overloading

This may be because, when both functions are compiled to JavaScript, their signature is totally identical. As JavaScript doesn't have types, we end up creating two functions taking same number of arguments. So, TypeScript restricts us from creating such functions.

TypeScript supports overloading based on number of parameters, but the steps to be followed are a bit different if we compare to OO languages. In answer to another SO question, someone explained it with a nice example: Method overloading?.

Basically, what we are doing is, we are creating just one function and a number of declarations so that TypeScript doesn't give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.

Getting and removing the first character of a string

substring is definitely best, but here's one strsplit alternative, since I haven't seen one yet.

> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"

or equivalently

> unlist(strsplit(x, ''))[1]
## [1] "h"

And you can paste the rest of the string back together.

> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"

In Django, how do I check if a user is in a certain group?

Your User object is linked to the Group object through a ManyToMany relationship.

You can thereby apply the filter method to user.groups.

So, to check if a given User is in a certain group ("Member" for the example), just do this :

def is_member(user):
    return user.groups.filter(name='Member').exists()

If you want to check if a given user belongs to more than one given groups, use the __in operator like so :

def is_in_multiple_groups(user):
    return user.groups.filter(name__in=['group1', 'group2']).exists()

Note that those functions can be used with the @user_passes_test decorator to manage access to your views :

from django.contrib.auth.decorators import login_required, user_passes_test
@login_required
@user_passes_test(is_member) # or @user_passes_test(is_in_multiple_groups)
def myview(request):
    # Do your processing

Hope this help

Is it possible to override / remove background: none!important with jQuery?

Several problems arise in this question.

Problem #1 - css Specificity (how to override important rule).

According to specification - to override this selector your selector should be 'stronger' which mean it should be!important and have at least 1 id, 1 class and something else - according to you creating this selector is impossible(as you can't alter page content). So the only possible option is to put something into element style which (could be done with js). Note: style rule should also have !important to override.

Problem #2 - background is not a single property - it is a set of properties (see specification)

So you really need to know what are exact names of properties you want to change (in your case it would be background-image)

Problem #3 - How to remove rule already applied (to get previous value)?

Unfortunately css have no mechanism to dismiss rule which qualify for an element - only to override with "stronger" rule. So you won't be able to solve this task with just setting value to something like 'inherit' or 'default' cause value you want to see is neither inherit from parent nor default. To solve this problem you have couple of options.

1) You may already know what is the value you want to apply. For example you can find out this value based on selector used. So in this case you may know that for selector ".image-list li" you need background-image: url("http://placekitten.com/150/50"). If so - just you this script:

jQuery(".image-list li").attr('style', 'background-image: url("http://placekitten.com/150/50") !important; ');

2) If you don't know the value then you can try to alter page content in such a way, that rule you want to dismiss is no longer qualify for element, whereas rule you want to be shown - still qualify. In this case you may temporary remove id from container element. Here is the code:

jQuery("#an-element").attr('id', '');
var backgroundImage = jQuery(".image-list li").css('background-image');
jQuery("#an-element").attr('id', 'an-element');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');

Here is link to fiddle http://jsfiddle.net/o3jn9mzo/

3) As third solution - you may generate element which will qualify for desired selection to find out property value - something like this:

var backgroundImage = jQuery("<div class='image-list'><li></li></div>").find('li').css('background-image');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');

P.S.: Sorry for really late response.

Exception.Message vs Exception.ToString()

Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.

How can I delete using INNER JOIN with SQL Server?

Try this query:

DELETE WorkRecord2, Employee 
FROM WorkRecord2 
INNER JOIN Employee ON (tbl_name.EmployeeRun=tbl_name.EmployeeNo)
WHERE tbl_name.Company = '1' 
AND tbl_name.Date = '2013-05-06';

How to delete a remote tag?

git push --delete origin $TAGNAME is the correct approach (in addition of a local delete).

But: make sure to use Git 2.31.

"git push $there --delete"(man) should have been diagnosed as an error, but instead turned into a matching push, which has been corrected with Git 2.31 (Q1 2021).

See commit 20e4164 (23 Feb 2021) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 1400458, 25 Feb 2021)

push: do not turn --delete '' into a matching push

Noticed-by: Tilman Vogel

When we added a syntax sugar "git push remote --delete"(man) <ref> to "git push"(man) as a synonym to the canonical git push remote(man) : syntax at f517f1f ("builtin-push: add(man) --delete as syntactic sugar for :foo", 2009-12-30, Git v1.7.0-rc0 -- merge), we weren't careful enough to make sure that <ref> is not empty.

Blindly rewriting "--delete " to ":" means that an empty string <ref> results in refspec ":", which is the syntax to ask for "matching" push that does not delete anything.

Worse yet, if there were matching refs that can be fast-forwarded, they would have been published prematurely, even if the user feels that they are not ready yet to be pushed out, which would be a real disaster.

How to use UIPanGestureRecognizer to move object? iPhone/iPad

-(IBAction)Method
{
      UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
      [panRecognizer setMinimumNumberOfTouches:1];
      [panRecognizer setMaximumNumberOfTouches:1];
      [ViewMain addGestureRecognizer:panRecognizer];
      [panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{

     CGPoint translation = [recognizer translationInView:self.view];
     recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
                                     recognizer.view.center.y + translation.y);
     [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

     if (recognizer.state == UIGestureRecognizerStateEnded) {

         CGPoint velocity = [recognizer velocityInView:self.view];
         CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
         CGFloat slideMult = magnitude / 200;
         NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

         float slideFactor = 0.1 * slideMult; // Increase for more of a slide
         CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor), 
                                     recognizer.view.center.y + (velocity.y * slideFactor));
         finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
         finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);

         [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
             recognizer.view.center = finalPoint;
         } completion:nil];

    }

}

How to perform runtime type checking in Dart?

Simply call

print(unknownDataType.runtimeType)

on the data.

How to check if a map contains a key in Go?

It is mentioned under "Index expressions".

An index expression on a map a of type map[K]V used in an assignment or initialization of the special form

v, ok = a[x] 
v, ok := a[x] 
var v, ok = a[x]

yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.

Replace all double quotes within String

Would not that have to be:

.replaceAll("\"","\\\\\"")

FIVE backslashes in the replacement String.

Laravel whereIn OR whereIn

Yes, orWhereIn is a method that you can use.

I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode to create a string and then explode it (this is a guess at your array structure):

$values = implode(',', array_map(function($value)
{
    return trim($value, ',');
}, $filters));

$query->whereIn('products.value', explode(',' $values));

How do I disable TextBox using JavaScript?

You can use disabled attribute to disable the textbox.

document.getElementById('color').disabled = true;

Problems with Android Fragment back stack

executePendingTransactions() , commitNow() not worked (

Worked in androidx (jetpack).

private final FragmentManager fragmentManager = getSupportFragmentManager();

public void removeFragment(FragmentTag tag) {
    Fragment fragmentRemove = fragmentManager.findFragmentByTag(tag.toString());
    if (fragmentRemove != null) {
        fragmentManager.beginTransaction()
                .remove(fragmentRemove)
                .commit();

        // fix by @Ogbe
        fragmentManager.popBackStackImmediate(tag.toString(), 
            FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
}

Maven 3 warnings about build.plugins.plugin.version

Add a <version> element after the <plugin> <artifactId> in your pom.xml file. Find the following text:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>

Add the version tag to it:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.3.2</version>

The warning should be resolved.

Regarding this:

'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing

Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version> tag as shown above.

To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ entities ---

Take that version number (as in the 2.3.2 above) and add it to your POM, as shown.

Javascript/DOM: How to remove all events of a DOM object?

You can add a hook function to intercept all calls to addEventHandler. The hook will push the handler to a list that can be used for cleanup. For example,

if (EventTarget.prototype.original_addEventListener == null) {
    EventTarget.prototype.original_addEventListener = EventTarget.prototype.addEventListener;

    function addEventListener_hook(typ, fn, opt) {
        console.log('--- add event listener',this.nodeName,typ);
        this.all_handlers = this.all_handlers || [];
        this.all_handlers.push({typ,fn,opt});
        this.original_addEventListener(typ, fn, opt);  
    }

    EventTarget.prototype.addEventListener = addEventListener_hook;
}

You should insert this code near the top of your main web page (e.g. index.html). During cleanup, you can loop thru all_handlers, and call removeEventHandler for each. Don't worry about calling removeEventHandler multiple times with the same function. It is harmless.

For example,

function cleanup(elem) {
    for (let t in elem) if (t.startsWith('on') && elem[t] != null) {
        elem[t] = null;
        console.log('cleanup removed listener from '+elem.nodeName,t);
    } 
    for (let t of elem.all_handlers || []) {
        elem.removeEventListener(t.typ, t.fn, t.opt);
        console.log('cleanup removed listener from '+elem.nodeName,t.typ);
    } 
}

Note: for IE use Element instead of EventTarget, and change => to function, and various other things.

How to compute the similarity between two text documents?

If you are more interested in measuring semantic similarity of two pieces of text, I suggest take a look at this gitlab project. You can run it as a server, there is also a pre-built model which you can use easily to measure the similarity of two pieces of text; even though it is mostly trained for measuring the similarity of two sentences, you can still use it in your case.It is written in java but you can run it as a RESTful service.

Another option also is DKPro Similarity which is a library with various algorithm to measure the similarity of texts. However, it is also written in java.

code example:

// this similarity measure is defined in the dkpro.similarity.algorithms.lexical-asl package
// you need to add that to your .pom to make that example work
// there are some examples that should work out of the box in dkpro.similarity.example-gpl 
TextSimilarityMeasure measure = new WordNGramJaccardMeasure(3);    // Use word trigrams

String[] tokens1 = "This is a short example text .".split(" ");   
String[] tokens2 = "A short example text could look like that .".split(" ");

double score = measure.getSimilarity(tokens1, tokens2);

System.out.println("Similarity: " + score);

When is each sorting algorithm used?

The Wikipedia page on sorting algorithms has a great comparison chart.

http://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms

jQuery - determine if input element is textbox or select list

alternatively you can retrieve DOM properties with .prop

here is sample code for select box

if( ctrl.prop('type') == 'select-one' ) { // for single select }

if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }

for textbox

  if( ctrl.prop('type') == 'text' ) { // for text box }

The mysqli extension is missing. Please check your PHP configuration

I encountered this problem today and eventually I realize it was the comment on the line before the mysql dll's that was causing the problem.

This is what you should have in php.ini by default for PHP 5.5.16:

;extension=php_exif.dll       Must be after mbstring as it depends on it
;extension=php_mysql.dll
;extension=php_mysqli.dll

Besides removing the semi-colons, you also need to delete the line of comment that came after php_exif.dll. This leaves you with

extension=php_exif.dll      
extension=php_mysql.dll
extension=php_mysqli.dll

This solves the problem in my case.

How to write unit testing for Angular / TypeScript for private methods with Jasmine

You can call private methods.

If you encountered the following error:

expect(new FooBar(/*...*/).initFooBar()).toEqual(/*...*/);
// TS2341: Property 'initFooBar' is private and only accessible within class 'FooBar'

just use // @ts-ignore:

// @ts-ignore
expect(new FooBar(/*...*/).initFooBar()).toEqual(/*...*/);

jQuery if checkbox is checked

to check input and get confirm by check box ,use this script...

_x000D_
_x000D_
 $(document).on("change", ".inputClass", function () {
    if($(this).is(':checked')){
     confirm_message = $(this).data('confirm');
       var confirm_status = confirm(confirm_message);
                        if (confirm_status == true) {
                           //doing somethings...
                         }
                   }});  
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> check action </lable>
<input class="inputClass" type="checkbox" data-confirm="are u sure to do ...?" >
_x000D_
_x000D_
_x000D_

Define constant variables in C++ header

It seems that bames53's answer can be extended to defining integer and non-integer constant values in namespace and class declarations even if they get included in multiple source files. It is not necessary to put the declarations in a header file but the definitions in a source file. The following example works for Microsoft Visual Studio 2015, for z/OS V2.2 XL C/C++ on OS/390, and for g++ (GCC) 8.1.1 20180502 on GNU/Linux 4.16.14 (Fedora 28). Note that the constants are declared/defined in only a single header file that gets included in multiple source files.

In foo.cc:

#include <cstdio>               // for puts

#include "messages.hh"
#include "bar.hh"
#include "zoo.hh"

int main(int argc, const char* argv[])
{
  puts("Hello!");
  bar();
  zoo();
  puts(Message::third);
  return 0;
}

In messages.hh:

#ifndef MESSAGES_HH
#define MESSAGES_HH

namespace Message {
  char const * const first = "Yes, this is the first message!";
  char const * const second = "This is the second message.";
  char const * const third = "Message #3.";
};

#endif

In bar.cc:

#include "messages.hh"
#include <cstdio>

void bar(void)
{
  puts("Wow!");
  printf("bar: %s\n", Message::first);
}

In zoo.cc:

#include <cstdio>
#include "messages.hh"

void zoo(void)
{
  printf("zoo: %s\n", Message::second);
}

In bar.hh:

#ifndef BAR_HH
#define BAR_HH

#include "messages.hh"

void bar(void);

#endif

In zoo.hh:

#ifndef ZOO_HH
#define ZOO_HH

#include "messages.hh"

void zoo(void);

#endif

This yields the following output:

Hello!
Wow!
bar: Yes, this is the first message!
zoo: This is the second message.
Message #3.

The data type char const * const means a constant pointer to an array of constant characters. The first const is needed because (according to g++) "ISO C++ forbids converting a string constant to 'char*'". The second const is needed to avoid link errors due to multiple definitions of the (then insufficiently constant) constants. Your compiler might not complain if you omit one or both of the consts, but then the source code is less portable.

MySQL case sensitive query

Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.

In my case this amounted to defining my column as:

`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''

This is in my opinion preferential to adjusting your queries.

How to enable bulk permission in SQL Server

SQL Server may also return this error if the service account does not have permission to read the file being imported. Ensure that the service account has read access to the file location. For example:

icacls D:\ImportFiles /Grant "NT Service\MSSQLServer":(OI)(CI)R

What does $@ mean in a shell script?

$@ is all of the parameters passed to the script.

For instance, if you call ./someScript.sh foo bar then $@ will be equal to foo bar.

If you do:

./someScript.sh foo bar

and then inside someScript.sh reference:

umbrella_corp_options "$@"

this will be passed to umbrella_corp_options with each individual parameter enclosed in double quotes, allowing to take parameters with blank space from the caller and pass them on.

How to determine the Boost version on a system?

#include <boost/version.hpp>
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "Boost version: " 
          << BOOST_VERSION / 100000
          << "."
          << BOOST_VERSION / 100 % 1000
          << "."
          << BOOST_VERSION % 100 
          << std::endl;
    return 0;
}

Update: the answer has been fixed.

Inject service in app.config

Short answer: you can't. AngularJS won't allow you to inject services into the config because it can't be sure they have been loaded correctly.

See this question and answer: AngularJS dependency injection of value inside of module.config

A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:

Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

How to send control+c from a bash script?

You can get the PID of a particular process like MySQL by using following commands: ps -e | pgrep mysql

This command will give you the PID of MySQL rocess. e.g, 13954 Now, type following command on terminal. kill -9 13954 This will kill the process of MySQL.

CSS: How to remove pseudo elements (after, before,...)?

This depends on what's actually being added by the pseudoselectors. In your situation, setting content to "" will get rid of it, but if you're setting borders or backgrounds or whatever, you need to zero those out specifically. As far as I know, there's no one cure-all for removing everything about a before/after element regardless of what it is.

Invoking JavaScript code in an iframe from the parent page

There are some quirks to be aware of here.

  1. HTMLIFrameElement.contentWindow is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. This is because the DOM Level 1 HTML standard has nothing to say about the window object.

  2. You can also try HTMLIFrameElement.contentDocument.defaultView, which a couple of older browsers allow but IE doesn't. Even so, the standard doesn't explicitly say that you get the window object back, for the same reason as (1), but you can pick up a few extra browser versions here if you care.

  3. window.frames['name'] returning the window is the oldest and hence most reliable interface. But you then have to use a name="..." attribute to be able to get a frame by name, which is slightly ugly/deprecated/transitional. (id="..." would be better but IE doesn't like that.)

  4. window.frames[number] is also very reliable, but knowing the right index is the trick. You can get away with this eg. if you know you only have the one iframe on the page.

  5. It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it inaccessible. You may find it easier to reverse the flow of communications: that is, have the child iframe notify its window.parent script when it has finished loaded and is ready to be called back. By passing one of its own objects (eg. a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to worry about what HTMLIFrameElement it is associated with.

What are the most common naming conventions in C?

Coding in C#, java, C, C++ and objective C at the same time, I've adopted a very simple and clear naming convention to simplify my life.

First of all, it relies on the power of modern IDEs (such as eclipse, Xcode...), with the possibility to get fast information by hovering or ctrl click... Accepting that, I suppressed the use of any prefix, suffix and other markers that are simply given by the IDE.

Then, the convention:

  • Any names MUST be a readable sentence explaining what you have. Like "this is my convention".
  • Then, 4 methods to get a convention out of a sentence:
    1. THIS_IS_MY_CONVENTION for macros, enum members
    2. ThisIsMyConvention for file name, object name (class, struct, enum, union...), function name, method name, typedef
    3. this_is_my_convention global and local variables,
      parameters, struct and union elements
    4. thisismyconvention [optional] very local and temporary variables (such like a for() loop index)

And that's it.

It gives

class MyClass {
    enum TheEnumeration {
        FIRST_ELEMENT,
        SECOND_ELEMENT,
    }

    int class_variable;

    int MyMethod(int first_param, int second_parameter) {
        int local_variable;
        TheEnumeration local_enum;
        for(int myindex=0, myindex<class_variable, myindex++) {
             localEnum = FIRST_ELEMENT;
        }
    }
}

How to programmatically set the SSLContext of a JAX-WS client?

The above is fine (as I said in comment) unless your WSDL is accessible with https:// too.

Here is my workaround for this:

Set you SSLSocketFactory as default:

HttpsURLConnection.setDefaultSSLSocketFactory(...);

For Apache CXF which I use you need also add these lines to your config:

<http-conf:conduit name="*.http-conduit">
  <http-conf:tlsClientParameters useHttpsURLConnectionDefaultSslSocketFactory="true" />
<http-conf:conduit>

Get current URL with jQuery?

var path = location.pathname returns the path of the current URL (jQuery is not needed). The use of window.location is optional.

Why can't I declare static methods in an interface?

The reason why you can't have a static method in an interface lies in the way Java resolves static references. Java will not bother looking for an instance of a class when attempting to execute a static method. This is because static methods are not instance dependent and hence can be executed straight from the class file. Given that all methods in an interface are abstract, the VM would have to look for a particular implementation of the interface in order to find the code behind the static method so that it could be executed. This then contradicts how static method resolution works and would introduce an inconsistency into the language.

How to get a value from a cell of a dataframe?

It doesn't need to be complicated:

val = df.loc[df.wd==1, 'col_name'].values[0]

How do I view the list of functions a Linux shared library is exporting?

What you need is nm and its -D option:

$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
         U atanf
         U calloc
.
.
.

Exported sumbols are indicated by a T. Required symbols that must be loaded from other shared objects have a U. Note that the symbol table does not include just functions, but exported variables as well.

See the nm manual page for more information.

Cannot access wamp server on local network

Wamp server share in local network

Reference Link: http://forum.aminfocraft.com/blog/view/141/wamp-server-share-in-local-netword

Edit your Apache httpd.conf:

Options FollowSymLinks
AllowOverride None
Order deny,allow
Allow from all
#Deny from all

and

#onlineoffline tag - don't remove
Order Deny,Allow
Allow from all
#Deny from all

to share mysql server:

edit wamp/alias/phpmyadmin.conf

<Directory "E:/wamp/apps/phpmyadmin3.2.0.1/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
    Order Deny,Allow
    #Deny from all
    Allow from all


SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

If you use MAMP, you might have to set the socket: unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock

Directly export a query to CSV using SQL Developer

Click in the grid so it has focus.

Ctrl+End

This will force the rest of the records back into the grid.

All credit to http://www.thatjeffsmith.com/archive/2012/03/how-to-export-sql-developer-query-results-without-re-running-the-query/

Python: Best way to add to sys.path relative to the current running script

This is what I use:

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))

FPDF utf-8 encoding (HOW-TO)

You can apply this function on your text :

 $yourtext = iconv('UTF-8', 'windows-1252', $yourtext);

Thanks

What is the difference between a pandas Series and a single-column DataFrame?

Quoting the Pandas docs

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure.

So, the Series is the data structure for a single column of a DataFrame, not only conceptually, but literally, i.e. the data in a DataFrame is actually stored in memory as a collection of Series.

Analogously: We need both lists and matrices, because matrices are built with lists. Single row matricies, while equivalent to lists in functionality still cannot exist without the list(s) they're composed of.

They both have extremely similar APIs, but you'll find that DataFrame methods always cater to the possibility that you have more than one column. And, of course, you can always add another Series (or equivalent object) to a DataFrame, while adding a Series to another Series involves creating a DataFrame.