Programs & Examples On #Msflexgrid

Microsoft FlexGrid control displays and operates on tabular data.

OpenCV !_src.empty() in function 'cvtColor' error

must please see guys that the error is in the cv2.imread() .Give the right path of the image. and firstly, see if your system loads the image or not. this can be checked first by simple load of image using cv2.imread(). after that ,see this code for the face detection

import numpy as np
import cv2

cascPath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-   packages/cv2/data/haarcascade_frontalface_default.xml"

eyePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_eye.xml"

smilePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_smile.xml"

face_cascade = cv2.CascadeClassifier(cascPath)
eye_cascade = cv2.CascadeClassifier(eyePath)
smile_cascade = cv2.CascadeClassifier(smilePath)

img = cv2.imread('WhatsApp Image 2020-04-04 at 8.43.18 PM.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, cascPath ,eyePath ,smilePath should have the right actual path that's picked up from lib/python3.7/site-packages/cv2/data here this path should be to picked up the haarcascade files

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

The solution for me was sooo dumb!!

I was using Python 3.8 in my environment. I made a new environment using Python 3.7, and the install worked fine.

source

How to replace multiple white spaces with one white space

Regex regex = new Regex(@"\W+");
string outputString = regex.Replace(inputString, " ");

How do I get the directory that a program is running from?

If you want a standard way without libraries: No. The whole concept of a directory is not included in the standard.

If you agree that some (portable) dependency on a near-standard lib is okay: Use Boost's filesystem library and ask for the initial_path().

IMHO that's as close as you can get, with good karma (Boost is a well-established high quality set of libraries)

How to overlay density plots in R?

You can use the ggjoy package. Let's say that we have three different beta distributions such as:

set.seed(5)
b1<-data.frame(Variant= "Variant 1", Values = rbeta(1000, 101, 1001))
b2<-data.frame(Variant= "Variant 2", Values = rbeta(1000, 111, 1011))
b3<-data.frame(Variant= "Variant 3", Values = rbeta(1000, 11, 101))


df<-rbind(b1,b2,b3)

You can get the three different distributions as follows:

library(tidyverse)
library(ggjoy)


ggplot(df, aes(x=Values, y=Variant))+
    geom_joy(scale = 2, alpha=0.5) +
    scale_y_discrete(expand=c(0.01, 0)) +
    scale_x_continuous(expand=c(0.01, 0)) +
    theme_joy()

enter image description here

Raise an event whenever a property's value changed?

I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY

public class TheClass : INotifyPropertyChanged {
    private int _property1;
    private string _property2;
    private double _property3;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if(handler != null) {
            handler(this, e);
        }
    }

    protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
        if(!EqualityComparer<T>.Default.Equals(field, newValue)) {
            field = newValue;
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }

    public int Property1 {
        get { return _property1; }
        set { SetPropertyField("Property1", ref _property1, value); }
    }
    public string Property2 {
        get { return _property2; }
        set { SetPropertyField("Property2", ref _property2, value); }
    }
    public double Property3 {
        get { return _property3; }
        set { SetPropertyField("Property3", ref _property3, value); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.

How to update Ruby with Homebrew?

Adding to the selected answer (as I haven't enough rep to add comment), one way to see the list of available versions (from ref) try:

$ rbenv install -l

How are VST Plugins made?

If you know a .NET language (C#/VB.NET etc) then checkout VST.NET. This framework allows you to create (unmanaged) VST 2.4 plugins in .NET. It comes with a framework that structures and simplifies the creation of a VST Plugin with support for Parameters, Programs and Persistence.

There are several samples that demonstrate the typical plugin scenarios. There's also documentation that explains how to get started and some of the concepts behind VST.NET.

Hope it helps. Marc Jacobi

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

rngYourRange.Address(,,,TRUE)

Shows External Address, Full Address

How to simulate browsing from various locations?

The only thing that springs to mind for this is to use a proxy server based in Europe. Either have your colleague set one up [if possible] or find a free proxy. A quick Google search came up with http://www.anonymousinet.com/ as the top result.

How to view Plugin Manager in Notepad++

A direct process to install / configure Plugin Manager :

  1. Download the latest version of NotepadPlus Plugin Manager from the official Github handle.
  2. Extract the zip file.
  3. Copy the pluginmanager.dll file and paste in C:\Program Files\Notepad++\Plugins\PluginManager directory.
  4. Restart the Notepad++

Note: Create the PluginManager directory if it is not present.

Efficient way to rotate a list in python

If efficiency is your goal, (cycles? memory?) you may be better off looking at the array module: http://docs.python.org/library/array.html

Arrays do not have the overhead of lists.

As far as pure lists go though, what you have is about as good as you can hope to do.

SQL error "ORA-01722: invalid number"

Suppose telephone number is defined as NUMBER then the blanks cannot be converted into a number:

create table telephone_number (tel_number number);
insert into telephone_number values ('0419 853 694');

The above gives you a

ORA-01722: invalid number

Reading from a text file and storing in a String

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

jQuery remove options from select

if your dropdown is in a table and you do not have id for it then you can use the following jquery:

var select_object = purchasing_table.rows[row_index].cells[cell_index].childNodes[1];
$(select_object).find('option[value='+site_name+']').remove();

What is the difference between require_relative and require in Ruby?

Summary

Use require for installed gems

Use require_relative for local files

require uses your $LOAD_PATH to find the files.
require_relative uses the current location of the file using the statement


require

Require relies on you having installed (e.g. gem install [package]) a package somewhere on your system for that functionality.

When using require you can use the "./" format for a file in the current directory, e.g. require "./my_file" but that is not a common or recommended practice and you should use require_relative instead.

require_relative

This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use

require_relative '../../../filename'

(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).

Note that require_relative uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative path "stable" as it always be relative to the file requiring it in the same way.

If statement in select (ORACLE)

So simple you can use case statement here.

CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 
         CASE WHEN  ISSUE_DIVISION is null then "Null Value found" //give your option
         Else 1 End
ELSE 0 END As Issue_Division_Result

Angular + Material - How to refresh a data source (mat-table)

In Angular 9, the secret is this.dataSource.data = this.dataSource.data;

Example:

import { MatTableDataSource } from '@angular/material/table';

dataSource: MatTableDataSource<MyObject>;

refresh(): void {
    this.applySomeModif();
    // Do what you want with dataSource

    this.dataSource.data = this.dataSource.data;
}

applySomeModif(): void {
    // add some data
    this.dataSource.data.push(new MyObject());
    // delete index number 4
    this.dataSource.data.splice(4, 0);
}

C++ - Hold the console window open?

You can also lean on the IDE a little. If you run the program using the "Start without debugging" command (Ctrl+F5 for me), the console window will stay open even after the program ends with a "Press any key to continue . . ." message.

Of course, if want to use the "Hit any key" to keep your program running (i.e. keep a thread alive), this won't work. And it does not work when you run "with debugging". But then you can use break points to hold the window open.

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

How to put a jpg or png image into a button in HTML

This may work for you, try it and see if it works:

<input type="image" src="/library/graphics/cecb2.gif">

How to add new column to MYSQL table?

your table:

q1 | q2 | q3 | q4 | q5

you can also do

ALTER TABLE yourtable ADD q6 VARCHAR( 255 ) after q5

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

If you know from external means that an expression is not null or undefined, you can use the non-null assertion operator ! to coerce away those types:

// Error, some.expr may be null or undefined
let x = some.expr.thing;
// OK
let y = some.expr!.thing;

How can I show/hide a specific alert with twitter bootstrap?

Add the "collapse" class to the alert div and the alert will be "collapsed" (hidden) by default. You can still call it using "show"

<div class="alert alert-error collapse" role="alert" id="passwordsNoMatchRegister">
  <span>
  <p>Looks like the passwords you entered don't match!</p>
  </span>
</div>

time data does not match format

While the above answer is 100% helpful and correct, I'd like to add the following since only a combination of the above answer and reading through the pandas doc helped me:

2-digit / 4-digit year

It is noteworthy, that in order to parse through a 2-digit year, e.g. '90' rather than '1990', a %y is required instead of a %Y.

Infer the datetime automatically

If parsing with a pre-defined format still doesn't work for you, try using the flag infer_datetime_format=True, for example:

yields_df['Date'] = pd.to_datetime(yields_df['Date'], infer_datetime_format=True)

Be advised that this solution is slower than using a pre-defined format.

Running an outside program (executable) in Python?

I'd try inserting an 'r' in front of your path if I were you, to indicate that it's a raw string - and then you won't have to use forward slashes. For example:

os.system(r"C:\Documents and Settings\flow_model\flow.exe")

Initializing multiple variables to the same value in Java

I do not think that is possible you have to set all the values individualling (like the first example you provided.)

The Second example you gave, will only Initialize the last varuable to "" and not the others.

Get list of certificates from the certificate store in C#

Yes -- the X509Store.Certificates property returns a snapshot of the X.509 certificate store.

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

How to include js file in another js file?

It is not possible directly. You may as well write some preprocessor which can handle that.

If I understand it correctly then below are the things that can be helpful to achieve that:

  • Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)

  • If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.

  • Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.

JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".

Hope it helps.

How can I represent an 'Enum' in Python?

def M_add_class_attribs(attribs):
    def foo(name, bases, dict_):
        for v, k in attribs:
            dict_[k] = v
        return type(name, bases, dict_)
    return foo

def enum(*names):
    class Foo(object):
        __metaclass__ = M_add_class_attribs(enumerate(names))
        def __setattr__(self, name, value):  # this makes it read-only
            raise NotImplementedError
    return Foo()

Use it like this:

Animal = enum('DOG', 'CAT')
Animal.DOG # returns 0
Animal.CAT # returns 1
Animal.DOG = 2 # raises NotImplementedError

if you just want unique symbols and don't care about the values, replace this line:

__metaclass__ = M_add_class_attribs(enumerate(names))

with this:

__metaclass__ = M_add_class_attribs((object(), name) for name in names)

Generate JSON string from NSDictionary in iOS

Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).

@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end

.

@implementation NSDictionary (BVJSONString)

  -(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
     NSError *error;
     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                   options:(NSJSONWritingOptions)    (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                     error:&error];

     if (! jsonData) {
        NSLog(@"%s: error: %@", __func__, error.localizedDescription);
        return @"{}";
     } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
     } 
 }
@end

.

@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end

.

@implementation NSArray (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                       options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                         error:&error];

    if (! jsonData) {
        NSLog(@"%s: error: %@", __func__, error.localizedDescription);
        return @"[]";
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}
@end

Installing tensorflow with anaconda in windows

1) Update conda

Run the anaconda prompt as administrator

conda update -n base -c defaults conda

2) Create an environment for python new version say, 3.6

conda create --name py36 python=3.6

3) Activate the new environment

conda activate py36

4) Upgrade pip

pip install --upgrade pip

5) Install tensorflow

pip install https://testpypi.python.org/packages/db/d2/876b5eedda1f81d5b5734277a155fa0894d394a7f55efa9946a818ad1190/tensorflow-0.12.1-cp36-cp36m-win_amd64.whl

If it doesn't work

If you have problem with wheel at the environment location, or pywrap_tensorflow problem,

 pip install tensorflow --upgrade --force-reinstall

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Your problem is in this line: Message messageObject = new Message ();
This error says that the Message class is not known at compile time.

So you need to import the Message class.

Something like this:

import package1.package2.Message;

Check this out.

http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

simplest options ls :

dict  = {'A':a,'B':b}
df = pd.DataFrame(dict, index = np.arange(1) )

Python: list of lists

The list variable (which I would recommend to rename to something more sensible) is a reference to a list object, which can be changed.

On the line

listoflists.append((list, list[0]))

You actually are only adding a reference to the object reference by the list variable. You've got multiple possibilities to create a copy of the list, so listoflists contains the values as you seem to expect:

Use the copy library

import copy
listoflists.append((copy.copy(list), list[0]))

use the slice notation

listoflists.append((list[:], list[0]))

How to execute a bash command stored as a string with quotes and asterisk

To eliminate the need for the cmd variable, you can do this:

eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'

java get file size efficiently

Well, I tried to measure it up with the code below:

For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of:

LENGTH sum: 10626, per Iteration: 10626.0

CHANNEL sum: 5535, per Iteration: 5535.0

URL sum: 660, per Iteration: 660.0

For runs = 5 and iterations = 50 the picture draws different.

LENGTH sum: 39496, per Iteration: 157.984

CHANNEL sum: 74261, per Iteration: 297.044

URL sum: 95534, per Iteration: 382.136

File must be caching the calls to the filesystem, while channels and URL have some overhead.

Code:

import java.io.*;
import java.net.*;
import java.util.*;

public enum FileSizeBench {

    LENGTH {
        @Override
        public long getResult() throws Exception {
            File me = new File(FileSizeBench.class.getResource(
                    "FileSizeBench.class").getFile());
            return me.length();
        }
    },
    CHANNEL {
        @Override
        public long getResult() throws Exception {
            FileInputStream fis = null;
            try {
                File me = new File(FileSizeBench.class.getResource(
                        "FileSizeBench.class").getFile());
                fis = new FileInputStream(me);
                return fis.getChannel().size();
            } finally {
                fis.close();
            }
        }
    },
    URL {
        @Override
        public long getResult() throws Exception {
            InputStream stream = null;
            try {
                URL url = FileSizeBench.class
                        .getResource("FileSizeBench.class");
                stream = url.openStream();
                return stream.available();
            } finally {
                stream.close();
            }
        }
    };

    public abstract long getResult() throws Exception;

    public static void main(String[] args) throws Exception {
        int runs = 5;
        int iterations = 50;

        EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class);

        for (int i = 0; i < runs; i++) {
            for (FileSizeBench test : values()) {
                if (!durations.containsKey(test)) {
                    durations.put(test, 0l);
                }
                long duration = testNow(test, iterations);
                durations.put(test, durations.get(test) + duration);
                // System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations));
            }
        }

        for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) {
            System.out.println();
            System.out.println(entry.getKey() + " sum: " + entry.getValue() + ", per Iteration: " + ((double)entry.getValue() / (double)(runs * iterations)));
        }

    }

    private static long testNow(FileSizeBench test, int iterations)
            throws Exception {
        long result = -1;
        long before = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            if (result == -1) {
                result = test.getResult();
                //System.out.println(result);
            } else if ((result = test.getResult()) != result) {
                 throw new Exception("variance detected!");
             }
        }
        return (System.nanoTime() - before) / 1000;
    }

}

How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

How to determine if a decimal/double is an integer?

static bool IsWholeNumber(double x) 
{
    return Math.Abs(x % 1) < double.Epsilon;
}

Laravel: getting a a single value from a MySQL query

[EDIT] The expected output of the pluck function has changed from Laravel 5.1 to 5.2. Hence why it is marked as deprecated in 5.1

In Laravel 5.1, pluck gets a single column's value from the first result of a query.

In Laravel 5.2, pluck gets an array with the values of a given column. So it's no longer deprecated, but it no longer do what it used to.

So short answer is use the value function if you want one column from the first row and you are using Laravel 5.1 or above.

Thanks to Tomas Buteler for pointing this out in the comments.

[ORIGINAL] For anyone coming across this question who is using Laravel 5.1, pluck() has been deprecated and will be removed completely in Laravel 5.2.

Consider future proofing your code by using value() instead.

return DB::table('users')->where('username', $username)->value('groupName');

Sort a Custom Class List<T>

Thanks for all the fast Answers.

This is my solution:

Week.Sort(delegate(cTag c1, cTag c2) { return DateTime.Parse(c1.date).CompareTo(DateTime.Parse(c2.date)); });

Thanks

Python 101: Can't open file: No such file or directory

I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder

What does 'git blame' do?

The git blame command is used to examine the contents of a file line by line and see when each line was last modified and who the author of the modifications was.

If there was a bug in code,use it to identify who cased it,then you can blame him. Git blame is get blame(d).

If you need to know history of one line code,use git log -S"code here", simpler than git blame.

git log vs git blame

Apply multiple functions to multiple groupby columns

For the first part you can pass a dict of column names for keys and a list of functions for the values:

In [28]: df
Out[28]:
          A         B         C         D         E  GRP
0  0.395670  0.219560  0.600644  0.613445  0.242893    0
1  0.323911  0.464584  0.107215  0.204072  0.927325    0
2  0.321358  0.076037  0.166946  0.439661  0.914612    1
3  0.133466  0.447946  0.014815  0.130781  0.268290    1

In [26]: f = {'A':['sum','mean'], 'B':['prod']}

In [27]: df.groupby('GRP').agg(f)
Out[27]:
            A                   B
          sum      mean      prod
GRP
0    0.719580  0.359790  0.102004
1    0.454824  0.227412  0.034060

UPDATE 1:

Because the aggregate function works on Series, references to the other column names are lost. To get around this, you can reference the full dataframe and index it using the group indices within the lambda function.

Here's a hacky workaround:

In [67]: f = {'A':['sum','mean'], 'B':['prod'], 'D': lambda g: df.loc[g.index].E.sum()}

In [69]: df.groupby('GRP').agg(f)
Out[69]:
            A                   B         D
          sum      mean      prod  <lambda>
GRP
0    0.719580  0.359790  0.102004  1.170219
1    0.454824  0.227412  0.034060  1.182901

Here, the resultant 'D' column is made up of the summed 'E' values.

UPDATE 2:

Here's a method that I think will do everything you ask. First make a custom lambda function. Below, g references the group. When aggregating, g will be a Series. Passing g.index to df.ix[] selects the current group from df. I then test if column C is less than 0.5. The returned boolean series is passed to g[] which selects only those rows meeting the criteria.

In [95]: cust = lambda g: g[df.loc[g.index]['C'] < 0.5].sum()

In [96]: f = {'A':['sum','mean'], 'B':['prod'], 'D': {'my name': cust}}

In [97]: df.groupby('GRP').agg(f)
Out[97]:
            A                   B         D
          sum      mean      prod   my name
GRP
0    0.719580  0.359790  0.102004  0.204072
1    0.454824  0.227412  0.034060  0.570441

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

What is the difference between & and && in Java?

it's as specified in the JLS (15.22.2):

When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.

For &, the result value is true if both operand values are true; otherwise, the result is false.

For ^, the result value is true if the operand values are different; otherwise, the result is false.

For |, the result value is false if both operand values are false; otherwise, the result is true.

The "trick" is that & is an Integer Bitwise Operator as well as an Boolean Logical Operator. So why not, seeing this as an example for operator overloading is reasonable.

How to pass prepareForSegue: an object

I used this solution so that I could keep the invocation of the segue and the data communication within the same function:

private var segueCompletion : ((UIStoryboardSegue, Any?) -> Void)?

func performSegue(withIdentifier identifier: String, sender: Any?, completion: @escaping (UIStoryboardSegue, Any?) -> Void) {
    self.segueCompletion = completion;
    self.performSegue(withIdentifier: identifier, sender: sender);
    self.segueCompletion = nil
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    self.segueCompletion?(segue, sender)
}

A use case would be something like:

func showData(id : Int){
    someService.loadSomeData(id: id) {
        data in
        self.performSegue(withIdentifier: "showData", sender: self) {
            storyboard, sender in
            let dataView = storyboard.destination as! DataView
            dataView.data = data
        }
    }
}

This seems to work for me, however, I'm not 100% sure that the perform and prepare functions are always executed on the same thread.

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

using namespaces and subqueries You can do it:

declare @data table (RequestID varchar(20), CreatedDate datetime, HistoryStatus varchar(20))
insert into @data values ('CF-0000001','8/26/2009 1:07:01 PM','For Review');
insert into @data values ('CF-0000001','8/26/2009 1:07:01 PM','Completed');  
insert into @data values ('CF-0000112','8/26/2009 1:07:01 PM','For Review');   
insert into @data values ('CF-0000113','8/26/2009 1:07:01 PM','For Review');  
insert into @data values ('CF-0000114','8/26/2009 1:07:01 PM','Completed');  
insert into @data values ('CF-0000115','8/26/2009 1:07:01 PM','Completed');

select d1.RequestID,d1.CreatedDate,d1.HistoryStatus 
from @data d1 
where d1.HistoryStatus = 'Completed'
union all 
select d2.RequestID,d2.CreatedDate,d2.HistoryStatus 
from @data d2 
where d2.HistoryStatus = 'For Review' 
    and d2.RequestID not in (
        select RequestID 
        from @data 
        where HistoryStatus = 'Completed' 
            and CreatedDate = d2.CreatedDate
    )

Above query returns

CF-0000001, 2009-08-26 13:07:01.000,    Completed
CF-0000114, 2009-08-26 13:07:01.000,    Completed
CF-0000115, 2009-08-26 13:07:01.000,    Completed
CF-0000112, 2009-08-26 13:07:01.000,    For Review
CF-0000113, 2009-08-26 13:07:01.000,    For Review

Java 8: How do I work with exception throwing methods in streams?

More readable way:

class A {
  void foo() throws MyException() {
    ...
  }
}

Just hide it in a RuntimeException to get it past forEach()

  void bar() throws MyException {
      Stream<A> as = ...
      try {
          as.forEach(a -> {
              try {
                  a.foo();
              } catch(MyException e) {
                  throw new RuntimeException(e);
              }
          });
      } catch(RuntimeException e) {
          throw (MyException) e.getCause();
      }
  }

Although at this point I won't hold against someone if they say skip the streams and go with a for loop, unless:

  • you're not creating your stream using Collection.stream(), i.e. not straight forward translation to a for loop.
  • you're trying to use parallelstream()

How to use Git and Dropbox together?

For my 2 cents Dropbox only makes sence for personal use where you don't want to bother getting a central repo host. For any professional development you'll probably create more problems than you'll solve, as have been mentioned several times in the thread already, Dropbox isn't designed for this use case. That said, a perfectly safe method to dump repositories on Dropbox without any third-party plugins or tools is to use bundles. I have the following aliases in my .gitconfig to save typing:

[alias]
        bundle-push = "!cd \"${GIT_PREFIX:-.}\" && if path=\"$(git config remote.\"$1\".url)\" && [ \"${path:0:1}\" = / ]; then git bundle create \"$path\" --all && git fetch \"$1\"; else echo \"Not a bundle remote\"; exit 1; fi #"
        bundle-fetch = "!cd \"${GIT_PREFIX:-.}\" && if path=\"$(git config remote.\"$1\".url)\" && [ \"${path:0:1}\" = / ]; then git bundle verify \"$path\" && git fetch \"$1\"; else echo \"Not a bundle remote\"; exit 1; fi #"
        bundle-new = "!cd \"${GIT_PREFIX:-.}\" && if [ -z \"${1:-}\" -o -z \"${2:-}\" ]; then echo \"Usage: git bundle-new <file> <remote name>\"; exit 1; elif [ -e \"$2\" ]; then echo \"File exist\"; exit 1; else git bundle create \"$2\" --all && git remote add -f \"$1\" \"$(realpath \"$2\")\"; fi #"

Example:

# Create bundle remote (in local repo)
$ git bundle-new dropbox ~/Dropbox/my-repo.bundle
# Fetch updates from dropbox
$ git bundle-fetch dropbox
# NOTE: writes over previous bundle. Thus, roughly equivalent to push --force --prune --all
$ git bundle-push

How do I instantiate a JAXBElement<String> object?

Other alternative:

JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
                                                String.class, "Your message");

Then:

System.out.println(element.getValue()); // Result: Your message

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The reject actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject() the exception value is undefined, hence the "undefined" part in the error that you get.

You do not show the code that uses the promise, but I reckon it is something like this:

var promise = doSth();
promise.then(function() { doSthHere(); });

Try adding an empty failure call, like this:

promise.then(function() { doSthHere(); }, function() {});

This will prevent the error to appear.

However, I would consider calling reject only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.

python, sort descending dataframe with pandas

Edit: This is out of date, see @Merlin's answer.

[False], being a nonempty list, is not the same as False. You should write:

test = df.sort('one', ascending=False)

Write string to text file and ensure it always overwrites the existing content.

Use the File.WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.

iterating through json object javascript

My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.

{
"dialog":
{
    "trunks":[
    {
        "trunk_id" : "1",
        "message": "This is just a JSON Test"
    },
    {
        "trunk_id" : "2",
        "message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
    }
    ]
}
}

At that point, I was able to do a fairly simple for loop based on the total number of objects.

var totalMessages = Object.keys(messages.dialog.trunks).length;

    for ( var i = 0; i < totalMessages; i++)
    {
        console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
    }

My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.

Java's L number (long) specification

By default any integral primitive data type (byte, short, int, long) will be treated as int type by java compiler. For byte and short, as long as value assigned to them is in their range, there is no problem and no suffix required. If value assigned to byte and short exceeds their range, explicit type casting is required.

Ex:

byte b = 130; // CE: range is exceeding.

to overcome this perform type casting.

byte b = (byte)130; //valid, but chances of losing data is there.

In case of long data type, it can accept the integer value without any hassle. Suppose we assign like

Long l = 2147483647; //which is max value of int

in this case no suffix like L/l is required. By default value 2147483647 is considered by java compiler is int type. Internal type casting is done by compiler and int is auto promoted to Long type.

Long l = 2147483648; //CE: value is treated as int but out of range 

Here we need to put suffix as L to treat the literal 2147483648 as long type by java compiler.

so finally

Long l = 2147483648L;// works fine.

jQuery How to Get Element's Margin and Padding?

Border

I believe you can get the border width using .css('border-left-width'). You can also fetch top, right, and bottom and compare them to find the max value. The key here is that you have to specify a specific side.

Padding

See jQuery calculate padding-top as integer in px

Margin

Use the same logic as border or padding.

Alternatively, you could use outerWidth. The pseudo-code should be
margin = (outerWidth(true) - outerWidth(false)) / 2. Note that this only works for finding the margin horizontally. To find the margin vertically, you would need to use outerHeight.

How to display HTML <FORM> as inline element?

According to HTML spec both <form> and <p> are block elements and you cannot nest them. Maybe replacing the <p> with <span> would work for you?

EDIT: Sorry. I was to quick in my wording. The <p> element doesn't allow any block content within - as specified by HTML spec for paragraphs.

Google Geocoding API - REQUEST_DENIED

Until the end of 2014, a common source of this error was omitting the mandatory sensor parameter from the request, as below. However since then this is no longer required:

The sensor Parameter

The Google Maps API previously required that you include the sensor parameter to indicate whether your application used a sensor to determine the user's location. This parameter is no longer required.


Did you specify the sensor parameter on the request?

"REQUEST_DENIED" indicates that your request was denied, generally because of lack of a sensor parameter.

sensor (required) — Indicates whether or not the geocoding request comes from a device with a location sensor. This value must be either true or false

How to remove provisioning profiles from Xcode

Here is how I do it.

Open Finder
Enable it to show hidden files (CMD_SHIFT_.)
Go to ~/Library/MobileDevice/Provisioning\ Profiles
Delete the profile you wish ...

How to do relative imports in Python?

On top of what John B said, it seems like setting the __package__ variable should help, instead of changing __main__ which could screw up other things. But as far as I could test, it doesn't completely work as it should.

I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in sys.path, as far as I could understand.

I should also mention that I did not find how to format the string that should go into those variables. Is it "package_head.subfolder.module_name" or what?

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

I am on Windows 10, I had the problem with a new fresh installation of Anaconda on python 3.7.4, this post on github solved my problem:

( source: https://github.com/conda/conda/issues/8273)

I cite:

" My workaround: I have copied the following files

libcrypto-1_1-x64.*
libssl-1_1-x64.*

from D:\Anaconda3\Library\bin to D:\Anaconda3\DLLs.

And it works as a charm! "

Check if a string is not NULL or EMPTY

You don't necessarily have to use the [string]:: prefix. This works in the same way:

if ($version)
{
    $request += "/" + $version
}

A variable that is null or empty string evaluates to false.

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

firebase-core & firebase-database ... should be same version:

implementation 'com.google.firebase:firebase-core:16.0.1' implementation 'com.google.firebase:firebase-database:16.0.1'

How to get current time in milliseconds in PHP?

Short answer:

64 bits platforms only!

function milliseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}

[ If you are running 64 bits PHP then the constant PHP_INT_SIZE equals to 8 ]


Long answer:

If you want an equilvalent function of time() in milliseconds first you have to consider that as time() returns the number of seconds elapsed since the "epoch time" (01/01/1970), the number of milliseconds since the "epoch time" is a big number and doesn't fit into a 32 bits integer.

The size of an integer in PHP can be 32 or 64 bits depending on platform.

From http://php.net/manual/en/language.types.integer.php

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

If you have 64 bits integers then you may use the following function:

function milliseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}

microtime() returns the number of seconds since the "epoch time" with precision up to microseconds with two numbers separated by space, like...

0.90441300 1409263371

The second number is the seconds (integer) while the first one is the decimal part.

The above function milliseconds() takes the integer part multiplied by 1000

1409263371000

then adds the decimal part multiplied by 1000 and rounded to 0 decimals

1409263371904

Note that both $mt[1] and the result of round are casted to int. This is necessary because they are floats and the operation on them without casting would result in the function returning a float.

Finally, that function is slightly more precise than

round(microtime(true)*1000);

that with a ratio of 1:10 (approx.) returns 1 more millisecond than the correct result. This is due to the limited precision of the float type (microtime(true) returns a float). Anyway if you still prefer the shorter round(microtime(true)*1000); I would suggest casting to int the result.


Even if it's beyond the scope of the question it's worth mentioning that if your platform supports 64 bits integers then you can also get the current time in microseconds without incurring in overflow.

If fact 2^63 - 1 (biggest signed integer) divided by 10^6 * 3600 * 24 * 365 (approximately the microseconds in one year) gives 292471.

That's the same value you get with

echo (int)( PHP_INT_MAX / ( 1000000 * 3600 * 24 * 365 ) );

In other words, a signed 64 bits integer have room to store a timespan of over 200,000 years measured in microseconds.

You may have then

function microseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000000 + ((int)round($mt[0] * 1000000));
}

Draggable div without jQuery UI

Dragging like jQueryUI: JsFiddle

You can drag the element from any point without weird centering.

$(document).ready(function() {

        var $body = $('body');
        var $target = null;
        var isDraggEnabled = false;

        $body.on("mousedown", "div", function(e) {

            $this = $(this);
            isDraggEnabled = $this.data("draggable");

            if (isDraggEnabled) {
                if(e.offsetX==undefined){
                    x = e.pageX-$(this).offset().left;
                    y = e.pageY-$(this).offset().top;
                }else{
                    x = e.offsetX;
                    y = e.offsetY;
                };

                $this.addClass('draggable');
                $body.addClass('noselect');
                $target = $(e.target);
            };

        });

         $body.on("mouseup", function(e) {
            $target = null;
            $body.find(".draggable").removeClass('draggable');
            $body.removeClass('noselect');
        });

         $body.on("mousemove", function(e) {
            if ($target) {
                $target.offset({
                    top: e.pageY  - y,
                    left: e.pageX - x
                });
            };     
         });

    });

Javascript - Open a given URL in a new tab by clicking a button

I just used target="_blank" under form tag and it worked fine with FF and Chrome where it opens in a new tag but with IE it opens in a new window.

How to select option in drop down protractorjs e2e tests

You can select dropdown options by value: $('#locregion').$('[value="1"]').click();

Attach Authorization header for all axios requests

If you use "axios": "^0.17.1" version you can do like this:

Create instance of axios:

// Default config options
  const defaultOptions = {
    baseURL: <CHANGE-TO-URL>,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

Then for any request the token will be select from localStorage and will be added to the request headers.

I'm using the same instance all over the app with this code:

import axios from 'axios';

const fetchClient = () => {
  const defaultOptions = {
    baseURL: process.env.REACT_APP_API_PATH,
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

  return instance;
};

export default fetchClient();

Good luck.

Java stack overflow error - how to increase the stack size in Eclipse?

It may be curable by increasing the stack size - but a better solution would be to work out how to avoid recursing so much. A recursive solution can always be converted to an iterative solution - which will make your code scale to larger inputs much more cleanly. Otherwise you'll really be guessing at how much stack to provide, which may not even be obvious from the input.

Are you absolutely sure it's failing due to the size of the input rather than a bug in the code, by the way? Just how deep is this recursion?

EDIT: Okay, having seen the update, I would personally try to rewrite it to avoid using recursion. Generally having a Stack<T> of "things still do to" is a good starting point to remove recursion.

GET URL parameter in PHP

Use this:

$parameter = $_SERVER['QUERY_STRING'];
echo $parameter;

Or just use:

$parameter = $_GET['link'];
echo $parameter ;

What is the difference between localStorage, sessionStorage, session and cookies?

Local storage: It keeps store the user information data without expiration date this data will not be deleted when user closed the browser windows it will be available for day, week, month and year.

In Local storage can store 5-10mb offline data.

//Set the value in a local storage object
localStorage.setItem('name', myName);

//Get the value from storage object
localStorage.getItem('name');

//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege

Session Storage: It is same like local storage date except it will delete all windows when browser windows closed by a web user.

In Session storage can store upto 5 mb data

//set the value to a object in session storege
sessionStorage.myNameInSession = "Krishna";

Session: A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values.

Cookies: Cookies are data, stored in small text files as name-value pairs, on your computer. Once a cookie has been set, all page requests that follow return the cookie name and value.

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

I needed to add this to the solution posted in 12 as I was using a list with a mixture of ordered list and unordered lists components. content: no-close-quote seems like an odd thing to add I know, but it works...

ol ul li:before {
    content: no-close-quote;
    counter-increment: none;
    display: list-item;
    margin-right: 100%;
    position: absolute;
    right: 10px;
}

Best practices for copying files with Maven

For a simple copy-tasks I can recommend copy-rename-maven-plugin. It's straight forward and simple to use:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>com.coderplus.maven.plugins</groupId>
        <artifactId>copy-rename-maven-plugin</artifactId>
        <version>1.0</version>
        <executions>
          <execution>
            <id>copy-file</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <sourceFile>src/someDirectory/test.environment.properties</sourceFile>
              <destinationFile>target/someDir/environment.properties</destinationFile>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

If you would like to copy more than one file, replace the <sourceFile>...</destinationFile> part with

<fileSets>
  <fileSet>
    <sourceFile>src/someDirectory/test.environment.properties</sourceFile>
    <destinationFile>target/someDir/environment.properties</destinationFile>
  </fileSet>
  <fileSet>
    <sourceFile>src/someDirectory/test.logback.xml</sourceFile>
    <destinationFile>target/someDir/logback.xml</destinationFile>
  </fileSet>                
</fileSets>

Furthermore you can specify multiple executions in multiple phases if needed, the second goal is "rename", which simply does what it says while the rest of the configuration stays the same. For more usage examples refer to the Usage-Page.

Note: This plugin can only copy files, not directories. (Thanks to @james.garriss for finding this limitation.)

How to refer environment variable in POM.xml?

Also, make sure that your environment variable is composed only by UPPER CASE LETTERS.... I don't know why (the documentation doesn't say nothing explicit about it, at least the link provided by @Andrew White), but if the variable is a lower case word (e.g. env.dummy), the variable always came empty or null...

i was struggling with this like an hour, until I decided to try an UPPER CASE VARIABLE, and problem solved.

OK Variables Examples:

  • DUMMY
  • DUMMY_ONE
  • JBOSS_SERVER_PATH

(NOTE: I was using maven v3.0.5)

I Hope that this can help someone....

rsync: difference between --size-only and --ignore-times

On a Scientific Linux 6.7 system, the man page on rsync says:

--ignore-times          don't skip files that match size and time

I have two files with identical contents, but with different creation dates:

[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron

[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/new/usercron

With --size-only, the two files are regarded the same:

[root@windstorm ~]# rsync -v --size-only -n  /tmp/new/usercron /tmp/master/usercron

sent 29 bytes  received 12 bytes  82.00 bytes/sec
total size is 1595  speedup is 38.90 (DRY RUN)

With --ignore-times, the two files are regarded different:

[root@windstorm ~]# rsync -v --ignore-times -n  /tmp/new/usercron /tmp/master/usercron
usercron

sent 32 bytes  received 15 bytes  94.00 bytes/sec
total size is 1595  speedup is 33.94 (DRY RUN)

So it does not looks like --ignore-times has any effect at all.

How do I format a Microsoft JSON date?

You can use this to get a date from JSON:

var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));

And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.

Singleton design pattern vs Singleton beans in Spring container

All the answers, so far at least, concentrate on explaining the difference between the design pattern and Spring singleton and do not address your actual question: Should a Singleton design pattern be used or a Spring singleton bean? what is better?

Before I answer let me just state that you can do both. You can implement the bean as a Singleton design pattern and use Spring to inject it into the client classes as a Spring singleton bean.

Now, the answer to the question is simple: Do not use the Singleton design pattern!
Use Spring's singleton bean implemented as a class with public constructor.
Why? Because the Singleton design pattern is considered an anti-pattern. Mostly because it complicates testing. (And if you don't use Spring to inject it then all classes that use the singleton are now tightly bound to it), and you can't replace or extend it. One can google "Singleton anti-pattern" to get more info on this, e.g. Singleton anti-pattern

Using Spring singleton is the way to go (with a the singleton bean implemented NOT as a Singleton design pattern, but rather with a public constructor) so that the Spring singleton bean can easily be tested and classes that use it are not tightly coupled to it, but rather, Spring injects the singleton (as an interface) into all the beans that need it, and the singleton bean can be replaced any time with another implementation without affecting the client classes that use it.

Python slice first and last element in list

You can do it like this:

some_list[0::len(some_list)-1]

How to call a VbScript from a Batch File without opening an additional command prompt

rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"

OR

rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"

You can also add the option //e:vbscript to make sure the scripting engine will recognize your script as a vbscript.

Windows/DOS batch files doesn't require escaping \ like *nix.

You can still use "C:\Users\guest\Desktop\123\MyScript.vbs", but this requires the user has *.vbs associated to wscript.

Saving image from PHP URL

$content = file_get_contents('http://example.com/image.php');
file_put_contents('/my/folder/flower.jpg', $content);

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

$_SERVER['HTTP_REFERER'] missing

Referer is not a compulsory header. It may or may not be there or could be modified/fictitious. Rely on it at your own risk. Anyways, you should wrap your call so you do not get an undefined index error:

$server = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";

Write variable to a file in Ansible

An important comment from tmoschou:

As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content
field will result in unpredictable output.

For more details see this and an explanation


Original answer:

You could use the copy module, with the content parameter:

- copy: content="{{ your_json_feed }}" dest=/path/to/destination/file

The docs here: copy module

Change directory in Node.js command prompt

That isn't the Node.js command prompt window. That is a language shell to run JavaScript commands, also known as a REPL.

In Windows, there should be a Node.js command prompt in your Start menu or start screen:

Windows Search for node.js

Which will open a command prompt window that looks like this:

Node.js command prompt window

From there you can switch directories using the cd command.

how to convert milliseconds to date format in android?

Just Try this Sample code:-

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class Test {

/**
 * Main Method
 */
public static void main(String[] args) {
    System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS"));
}


/**
 * Return date in specified format.
 * @param milliSeconds Date in milliseconds
 * @param dateFormat Date format 
 * @return String representing date in specified format
 */
public static String getDate(long milliSeconds, String dateFormat)
{
    // Create a DateFormatter object for displaying date in specified format.
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);

    // Create a calendar object that will convert the date and time value in milliseconds to date. 
     Calendar calendar = Calendar.getInstance();
     calendar.setTimeInMillis(milliSeconds);
     return formatter.format(calendar.getTime());
}
}

I hope this help...

UNIX export command

When you execute a program the child program inherits its environment variables from the parent. For instance if $HOME is set to /root in the parent then the child's $HOME variable is also set to /root.

This only applies to environment variable that are marked for export. If you set a variable at the command-line like

$ FOO="bar"

That variable will not be visible in child processes. Not unless you export it:

$ export FOO

You can combine these two statements into a single one in bash (but not in old-school sh):

$ export FOO="bar"

Here's a quick example showing the difference between exported and non-exported variables. To understand what's happening know that sh -c creates a child shell process which inherits the parent shell's environment.

$ FOO=bar
$ sh -c 'echo $FOO'

$ export FOO
$ sh -c 'echo $FOO'
bar

Note: To get help on shell built-in commands use help export. Shell built-ins are commands that are part of your shell rather than independent executables like /bin/ls.

How to truncate milliseconds off of a .NET DateTime

Here is an extension method based on a previous answer that will let you truncate to any resolution...

Usage:

DateTime myDateSansMilliseconds = myDate.Truncate(TimeSpan.TicksPerSecond);
DateTime myDateSansSeconds = myDate.Truncate(TimeSpan.TicksPerMinute)

Class:

public static class DateTimeUtils
{
    /// <summary>
    /// <para>Truncates a DateTime to a specified resolution.</para>
    /// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
    /// </summary>
    /// <param name="date">The DateTime object to truncate</param>
    /// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
    /// <returns>Truncated DateTime</returns>
    public static DateTime Truncate(this DateTime date, long resolution)
    {
        return new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
    }
}

How to compare two double values in Java?

Instead of using doubles for decimal arithemetic, please use java.math.BigDecimal. It would produce the expected results.

For reference take a look at this stackoverflow question

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

$ git push origin develop:master

or, more generally

$ git push <remote> <local branch name>:<remote branch to push into>

What does 'foo' really mean?

The sound of the french fou, (like: amour fou) [crazy] written in english, would be foo, wouldn't it. Else furchtbar -> foobar -> foo, bar -> barfoo -> barfuß (barefoot). Just fou. A foot without teeth.

I agree with all, who mentioned it means: nothing interesting, just something, usually needed to complete a statement/expression.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

In my case I followed this. Summary, in gradle app level: change this :

variant.outputs.all { output ->
    variant.assemble.doLast {
        ....
    }
}

to

variant.outputs.all { output ->
variant.getAssembleProvider().configure() {
    it.doLast { 
        ....
    }
}

Press Enter to move to next control

Tab as Enter: create a user control which inherits textbox, override the KeyPress method. If the user presses enter you can either call SendKeys.Send("{TAB}") or System.Windows.Forms.Control.SelectNextControl(). Note you can achieve the same using the KeyPress event.

Focus Entire text: Again, via override or events, target the GotFocus event and then call TextBox.Select method.

Filename timestamp in Windows CMD batch script getting truncated

In the past, I've used a .cmd script I found on the Internet. I hate the way localization normally messes with dates. Anytime you have dates in filenames (or anywhere else, if I may be so bold) I figure you want them in ISO 8601 format:

2015-02-19T14:54:51Z

or something else that has Y M D H M in that order, such as

2015-02-19 14:54

because it fixes the MDY / DMY ambiguity and because it's sortable as text.

I don't know where I got that .cmd script, but it may have been http://ss64.com/nt/syntax-getdate.html, which works beautifully on my YYYY-MM-DD Windows 8.1 and on a M/D/YYYY vanilla install of Windows 7. Both give the same format:

2015-02-09 04:43

Git push won't do anything (everything up-to-date)

I tried many methods including defined here. What I got is,

  • Make sure the name of repository is valid. The best way is to copy the link from repository site and paste in git bash.

  • Make sure you have commited the selected files.

    git commit -m "Your commit here"
    
  • If both steps don't work, try

    git push -u -f origin master

Iterating over all the keys of a map

Is there a way to get a list of all the keys in a Go language map?

ks := reflect.ValueOf(m).MapKeys()

how do I iterate over all the keys?

Use the accepted answer:

for k, _ := range m { ... }

Use of True, False, and None as return values in Python functions

In the examples in PEP 8 (Style Guide for Python Code) document, I have seen that foo is None or foo is not None are being used instead of foo == None or foo != None.

Also using if boolean_value is recommended in this document instead of if boolean_value == True or if boolean_value is True. So I think if this is the official Python way. We Python guys should go on this way, too.

How to draw an empty plot?

This is marginally simpler than your original solution:

plot(0,type='n',axes=FALSE,ann=FALSE)

How to add a scrollbar to an HTML5 table?

I first tried the accepted answer by Mr Green, but I found my columns didn't align, that float:left seems very suspicious. When I went from no scollbar to scrollbar -- my table body shifted a few pixels and I lost alignment.

CODE PEN https://codepen.io/majorp/pen/gjrRMx

CSS

.width50px {
    width: 100px !important;
}

.width100px {
    width: 100px !important;
}


.fixed_headers {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;
}

th {
    padding: 5px;
    text-align: left;
    font-weight:bold;
    height:50px;
}

td {
    padding: 5px;
    text-align: left;
}

thead, tr 
{
    display: block;
    position: relative;
}


tbody {
    display: block;
    overflow: auto;
    width: 100%;
    height: 500px;
}

.tableColumnHeader {
    height: 50px;
    font-weight: bold;
}




.lime {
    background-color: lime;
}

Change URL and redirect using jQuery

tell you the true, I still don't get what you need, but

window.location(url);

should be

window.location = url;

a search on window.location reference will tell you that.

jQuery: Handle fallback for failed AJAX Request

I believe that what you are looking for is error option for the jquery ajax object

getJSON is a wrapper to the $.ajax object, but it doesn't provide you with access to the error option.

EDIT: dcneiner has given a good example of the code you would need to use. (Even before I could post my reply)

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

You can get lat, lng from the place object i.e.

var place = autocomplete.getPlace();

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();

How can I use an http proxy with node.js http.Client?

Tim Macfarlane's answer was close with regards to using a HTTP proxy.

Using a HTTP proxy (for non secure requests) is very simple. You connect to the proxy and make the request normally except that the path part includes the full url and the host header is set to the host you want to connect to.
Tim was very close with his answer but he missed setting the host header properly.

var http = require("http");

var options = {
  host: "proxy",
  port: 8080,
  path: "http://www.google.com",
  headers: {
    Host: "www.google.com"
  }
};
http.get(options, function(res) {
  console.log(res);
  res.pipe(process.stdout);
});

For the record his answer does work with http://nodejs.org/ but that's because their server doesn't care the host header is incorrect.

PHP: Calling another class' method

//file1.php
<?php

class ClassA
{
   private $name = 'John';

   function getName()
   {
     return $this->name;
   }   
}
?>

//file2.php
<?php
   include ("file1.php");

   class ClassB
   {

     function __construct()
     {
     }

     function callA()
     {
       $classA = new ClassA();
       $name = $classA->getName();
       echo $name;    //Prints John
     }
   }

   $classb = new ClassB();
   $classb->callA();
?>

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

I suggest creating an additional connection for the second command, would solve it. Try to combine both queries in one query. Create a subquery for the count.

while (dr3.Read())
{
    dados_historico[4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}

Why override the same value again and again?

if (dr3.Read())
{
    dados_historico[4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}

Would be enough.

parent & child with position fixed, parent overflow:hidden bug

As an alternative to using clip you could also use {border-radius: 0.0001px} on a parent element. It works not only with absolute/fixed positioned elements.

Table with fixed header and fixed column on pure css

To fix both Headers and Columns, you can use the following plugin:


Updated in July 2019

Recently is emerged also a pure CSS solution that is based on CSS property position: sticky; (here for more details about it) applied onto each TH item (instead of their parent container)

Can I call a function of a shell script from another shell script?

Refactor your second.sh script like this:

function func1 {
   fun=$1
   book=$2
   printf "fun=%s,book=%s\n" "${fun}" "${book}"
}

function func2 {
   fun2=$1
   book2=$2
   printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
}

And then call these functions from script first.sh like this:

source ./second.sh
func1 love horror
func2 ball mystery

OUTPUT:

fun=love,book=horror
fun2=ball,book2=mystery

Store multiple values in single key in json

{
    "success": true,
    "data": {
        "BLR": {
            "origin": "JAI",
            "destination": "BLR",
            "price": 127,
            "transfers": 0,
            "airline": "LB",
            "flight_number": 655,
            "departure_at": "2017-06-03T18:20:00Z",
            "return_at": "2017-06-07T08:30:00Z",
            "expires_at": "2017-03-05T08:40:31Z"
        }
    }
};

How to use lodash to find and return an object from Array?

You don't need Lodash or Ramda or any other extra dependency.

Just use the ES6 find() function in a functional way:

savedViews.find(el => el.description === view)

Sometimes you need to use 3rd-party libraries to get all the goodies that come with them. However, generally speaking, try avoiding dependencies when you don't need them. Dependencies can:

  • bloat your bundled code size,
  • you will have to keep them up to date,
  • and they can introduce bugs or security risks

Split page vertically using CSS

There can also be a solution by having both float to left.

Try this out:

Working Demo

P.S. This is just an improvement of Ankit's Answer

Turning off eslint rule for a specific file

You can turn off specific rule for a file by using /*eslint [<rule: "off"], >]*/

/* eslint no-console: "off", no-mixed-operators: "off" */

Version: [email protected]

How do I read any request header in PHP

Here's how I'm doing it. You need to get all headers if $header_name isn't passed:

<?php
function getHeaders($header_name=null)
{
    $keys=array_keys($_SERVER);

    if(is_null($header_name)) {
            $headers=preg_grep("/^HTTP_(.*)/si", $keys);
    } else {
            $header_name_safe=str_replace("-", "_", strtoupper(preg_quote($header_name)));
            $headers=preg_grep("/^HTTP_${header_name_safe}$/si", $keys);
    }

    foreach($headers as $header) {
            if(is_null($header_name)){
                    $headervals[substr($header, 5)]=$_SERVER[$header];
            } else {
                    return $_SERVER[$header];
            }
    }

    return $headervals;
}
print_r(getHeaders());
echo "\n\n".getHeaders("Accept-Language");
?>

It looks a lot simpler to me than most of the examples given in other answers. This also gets the method (GET/POST/etc.) and the URI requested when getting all of the headers which can be useful if you're trying to use it in logging.

Here's the output:

Array ( [HOST] => 127.0.0.1 [USER_AGENT] => Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0 [ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [ACCEPT_LANGUAGE] => en-US,en;q=0.5 [ACCEPT_ENCODING] => gzip, deflate [COOKIE] => PHPSESSID=MySessionCookieHere [CONNECTION] => keep-alive )

en-US,en;q=0.5

How to print jquery object/array

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});

How to set Java SDK path in AndroidStudio?

C:\Program Files\Android\Android Studio\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)

Somehow the Studio installer would install another version under:

C:\Program Files\Android\Android Studio\jre\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)

where the latest version was installed the Java DevKit installer in:

C:\Program Files\Java\jre1.8.0_121\bin>java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

Need to clean up the Android Studio so it would use the proper latest 1.8.0 versions.

According to How to set Java SDK path in AndroidStudio? one could override with a specific JDK but when I renamed

C:\Program Files\Android\Android Studio\jre\jre\

to:

C:\Program Files\Android\Android Studio\jre\oldjre\

And restarted Android Studio, it would complain that the jre was invalid. When I tried to aecify an JDK to pick the one in C:\Program Files\Java\jre1.8.0_121\bin or:

C:\Program Files\Java\jre1.8.0_121\

It said that these folders are invalid. So I guess that the embedded version must have some special purpose.

Cannot read property 'map' of undefined

The error occur mainly becuase the array isnt found. Just check if you have mapped to the correct array. Check the array name or declaration.

Force overwrite of local file with what's in origin repo?

Full sync has few tasks:

  • reverting changes
  • removing new files
  • get latest from remote repository

git reset HEAD --hard

git clean -f

git pull origin master

Or else, what I prefer is that, I may create a new branch with the latest from the remote using:

git checkout origin/master -b <new branch name>

origin is my remote repository reference, and master is my considered branch name. These may different from yours.

How can I convert a PFX certificate file for use with Apache on a linux server?

To get it to work with Apache, we needed one extra step.

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain_encrypted.key
openssl rsa -in domain_encrypted.key -out domain.key

The final command decrypts the key for use with Apache. The domain.key file should look like this:

-----BEGIN RSA PRIVATE KEY-----
MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3
LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp
YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG
A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq
-----END RSA PRIVATE KEY-----

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

Difference between setTimeout with and without quotes and parentheses

    ##If i want to wait for some response from server or any action we use setTimeOut.

    functionOne =function(){
    console.info("First");

    setTimeout(()=>{
    console.info("After timeOut 1");
    },5000);
    console.info("only setTimeOut() inside code waiting..");
    }

    functionTwo =function(){
    console.info("second");
    }
    functionOne();
    functionTwo();

## So here console.info("After timeOut 1"); will be executed after time elapsed.
Output:
******************************************************************************* 
First
only setTimeOut() inside code waiting..
second
undefined
After timeOut 1  // executed after time elapsed.

Is there a simple way to remove unused dependencies from a maven pom.xml?

Have you looked at the Maven Dependency Plugin ? That won't remove stuff for you but has tools to allow you to do the analysis yourself. I'm thinking particularly of

mvn dependency:tree

The term "Add-Migration" is not recognized

I tried doing all the above and no luck. I downloaded the latest .net core 2.0 package and ran the commands again and it worked.

How to import a jar in Eclipse

In eclipse I included a compressed jar file i.e. zip file. Eclipse allowed me to add this zip file as an external jar but when I tried to access the classes in the jar they weren't showing up.

After a lot of trial and error I found that using a zip format doesn't work. When I added a jar file then it worked for me.

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

You may also use a ResultSetExtractor instead of a RowMapper. Both are just as easy as one another, the only difference is you call ResultSet.next().

public String test() {
    String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN "
                 + " where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
    return jdbc.query(sql, new ResultSetExtractor<String>() {
        @Override
        public String extractData(ResultSet rs) throws SQLException,
                                                       DataAccessException {
            return rs.next() ? rs.getString("ID_NMB_SRZ") : null;
        }
    });
}

The ResultSetExtractor has the added benefit that you can handle all cases where there are more than one row or no rows returned.

UPDATE: Several years on and I have a few tricks to share. JdbcTemplate works superbly with java 8 lambdas which the following examples are designed for but you can quite easily use a static class to achieve the same.

While the question is about simple types, these examples serve as a guide for the common case of extracting domain objects.

First off. Let's suppose that you have an account object with two properties for simplicity Account(Long id, String name). You would likely wish to have a RowMapper for this domain object.

private static final RowMapper<Account> MAPPER_ACCOUNT =
        (rs, i) -> new Account(rs.getLong("ID"),
                               rs.getString("NAME"));

You may now use this mapper directly within a method to map Account domain objects from a query (jt is a JdbcTemplate instance).

public List<Account> getAccounts() {
    return jt.query(SELECT_ACCOUNT, MAPPER_ACCOUNT);
}

Great, but now we want our original problem and we use my original solution reusing the RowMapper to perform the mapping for us.

public Account getAccount(long id) {
    return jt.query(
            SELECT_ACCOUNT,
            rs -> rs.next() ? MAPPER_ACCOUNT.mapRow(rs, 1) : null,
            id);
}

Great, but this is a pattern you may and will wish to repeat. So you can create a generic factory method to create a new ResultSetExtractor for the task.

public static <T> ResultSetExtractor singletonExtractor(
        RowMapper<? extends T> mapper) {
    return rs -> rs.next() ? mapper.mapRow(rs, 1) : null;
}

Creating a ResultSetExtractor now becomes trivial.

private static final ResultSetExtractor<Account> EXTRACTOR_ACCOUNT =
        singletonExtractor(MAPPER_ACCOUNT);

public Account getAccount(long id) {
    return jt.query(SELECT_ACCOUNT, EXTRACTOR_ACCOUNT, id);
}

I hope this helps to show that you can now quite easily combine parts in a powerful way to make your domain simpler.

UPDATE 2: Combine with an Optional for optional values instead of null.

public static <T> ResultSetExtractor<Optional<T>> singletonOptionalExtractor(
        RowMapper<? extends T> mapper) {
    return rs -> rs.next() ? Optional.of(mapper.mapRow(rs, 1)) : Optional.empty();
}

Which now when used could have the following:

private static final ResultSetExtractor<Optional<Double>> EXTRACTOR_DISCOUNT =
        singletonOptionalExtractor(MAPPER_DISCOUNT);

public double getDiscount(long accountId) {
    return jt.query(SELECT_DISCOUNT, EXTRACTOR_DISCOUNT, accountId)
            .orElse(0.0);
}

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

I know this is a very old topic, but the correct answer is still not here.

The accepted answer works with a space, but the user can remove this space - so this answer is not reliable. The answer of Georg works, but is needlessly complex.

To test if the user pressed cancel, just use the following code:

Dim Answer As String = InputBox("Question")
If String.ReferenceEquals(Answer, String.Empty) Then
    'User pressed cancel
Else if Answer = "" Then
    'User pressed ok with an empty string in the box
Else
    'User gave an answer

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

This error

Failure [INSTALL_FAILED_OLDER_SDK]

Means that you're trying to install an app that has a higher minSdkVersion specified in its manifest than the device's API level. Change that number to 8 and it should work. I'm not sure about the other error, but it may be related to this one.

Fling gesture detection on grid layout

My version of solution proposed by Thomas Fankhauser and Marek Sebera (does not handle vertical swipes):

SwipeInterface.java

import android.view.View;

public interface SwipeInterface {

    public void onLeftToRight(View v);

    public void onRightToLeft(View v);
}

ActivitySwipeDetector.java

import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class ActivitySwipeDetector implements View.OnTouchListener {

    static final String logTag = "ActivitySwipeDetector";
    private SwipeInterface activity;
    private float downX, downY;
    private long timeDown;
    private final float MIN_DISTANCE;
    private final int VELOCITY;
    private final float MAX_OFF_PATH;

    public ActivitySwipeDetector(Context context, SwipeInterface activity){
        this.activity = activity;
        final ViewConfiguration vc = ViewConfiguration.get(context);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        MIN_DISTANCE = vc.getScaledPagingTouchSlop() * dm.density;
        VELOCITY = vc.getScaledMinimumFlingVelocity();
        MAX_OFF_PATH = MIN_DISTANCE * 2;            
    }

    public void onRightToLeftSwipe(View v){
        Log.i(logTag, "RightToLeftSwipe!");
        activity.onRightToLeft(v);
    }

    public void onLeftToRightSwipe(View v){
        Log.i(logTag, "LeftToRightSwipe!");
        activity.onLeftToRight(v);
    }

    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN: {
            Log.d("onTouch", "ACTION_DOWN");
            timeDown = System.currentTimeMillis();
            downX = event.getX();
            downY = event.getY();
            return true;
        }
        case MotionEvent.ACTION_UP: {
            Log.d("onTouch", "ACTION_UP");
            long timeUp = System.currentTimeMillis();
            float upX = event.getX();
            float upY = event.getY();

            float deltaX = downX - upX;
            float absDeltaX = Math.abs(deltaX); 
            float deltaY = downY - upY;
            float absDeltaY = Math.abs(deltaY);

            long time = timeUp - timeDown;

            if (absDeltaY > MAX_OFF_PATH) {
                Log.i(logTag, String.format("absDeltaY=%.2f, MAX_OFF_PATH=%.2f", absDeltaY, MAX_OFF_PATH));
                return v.performClick();
            }

            final long M_SEC = 1000;
            if (absDeltaX > MIN_DISTANCE && absDeltaX > time * VELOCITY / M_SEC) {
                if(deltaX < 0) { this.onLeftToRightSwipe(v); return true; }
                if(deltaX > 0) { this.onRightToLeftSwipe(v); return true; }
            } else {
                Log.i(logTag, String.format("absDeltaX=%.2f, MIN_DISTANCE=%.2f, absDeltaX > MIN_DISTANCE=%b", absDeltaX, MIN_DISTANCE, (absDeltaX > MIN_DISTANCE)));
                Log.i(logTag, String.format("absDeltaX=%.2f, time=%d, VELOCITY=%d, time*VELOCITY/M_SEC=%d, absDeltaX > time * VELOCITY / M_SEC=%b", absDeltaX, time, VELOCITY, time * VELOCITY / M_SEC, (absDeltaX > time * VELOCITY / M_SEC)));
            }

        }
        }
        return false;
    }

}

Creating threads - Task.Factory.StartNew vs new Thread()

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Note that in both cases you can make your code slightly simpler with method group conversions:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

Calculating bits required to store decimal number

Assuming that the question is asking what's the minimum bits required for you to store

  1. 3 digits number

My approach to this question would be:

  • what's the maximum number of 3 digits number we need to store? Ans: 999
  • what's the minimum amount of bits required for me to store this number?

This problem can be solved this way by dividing 999 by 2 recursively. However, it's simpler to use the power of maths to help us. Essentially, we're solving n for the equation below:

2^n = 999
nlog2 = log999
n ~ 10

You'll need 10 bits to store 3 digit number.

Use similar approach to solve the other subquestions!

Hope this helps!

Avoid browser popup blockers

I tried multiple solutions, but his is the only one that actually worked for me in all the browsers

let newTab = window.open(); newTab.location.href = url;

CSS - center two images in css side by side

I understand that this question is old, but there is a good solution for it in HTML5. You can wrap it all in a <figure></figure> tag. The code would look something like this:

<div id="wrapper">
<figure>

<a href="mailto:[email protected]">
<img id="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp- 
content/uploads/2012/07/email-icon-e1343123697991.jpg"/>
</a>

<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img id="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp- 
content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
</a>

</figure>
</div>

and the CSS:

#wrapper{
 text-align:center;
}

Getting the array length of a 2D array in Java

If you have this array:

String [][] example = {{{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"}},
                       {{"Why?", "Where?", "When?", "Who?"}, {"Yes!"}}};

You can do this:

example.length;

= 2

example[0].length;

= 2

example[1].length;

= 2

example[0][1].length;

= 3

example[1][0].length;

= 4

What is the difference between an abstract function and a virtual function?

Most of the above examples use code - and they are very very good. I need not add to what they say, but the following is a simple explanation that makes use of analogies rather than code/technical terms.

Simple Explanation - Explanation using analogies

Abstract Method

Think George W Bush. He says to his soldiers: "Go fight in Iraq". And that's it. All he has specified is that fighting must be done. He does not specify how exactly that will happen. But I mean, you can't just go out and "fight": what does that mean exactly? do I fight with a B-52 or my derringer? Those specific details are left to someone else. This is an abstract method.

Virtual Method

David Petraeus is high up in the army. He has defined what fight means:

  1. Find the enemy
  2. Neutralise him.
  3. Have a beer afterwards

The problem is that it is a very general method. It's a good method that works, but sometimes is not specific enough. Good thing for Petraeus is that his orders have leeway and scope - he has allowed others to change his definition of "fight", according to their particular requirements.

Private Job Bloggs reads Petraeus' order and is given permission to implement his own version of fight, according to his particular requirements:

  1. Find enemy.
  2. Shoot him in the head.
  3. Go Home
  4. Have beer.

Nouri al Maliki also receives the same orders from Petraeus. He is to fight also. But he is a politician, not an infantry man. Obviously he cannot go around shooting his politican enemies in the head. Because Petraeus has given him a virtual method, then Maliki can implement his own version of the fight method, according to his particular circumstances:

  1. Find enemy.
  2. Have him arrested with some BS trumped up charges.
  3. Go Home
  4. Have beer.

IN other words, a virtual method provides boilerplate instructions - but these are general instructions, which can be made more specific by people down the army heirarchy, according to their particular circumstances.

The difference between the two

  • George Bush does not prove any implementation details. This must be provided by someone else. This is an abstract method.

  • Petraeus on the other hand does provide implementation details but he has given permission for his subordinates to override his orders with their own version, if they can come up with something better.

hope that helps.

Add numpy array as column to Pandas data frame

df = pd.DataFrame(np.arange(1,10).reshape(3,3))
df['newcol'] = pd.Series(your_2d_numpy_array)

java.lang.ClassNotFoundException: org.apache.log4j.Level

You also need to include the Log4J JAR file in the classpath.

Note that slf4j-log4j12-1.6.4.jar is only an adapter to make it possible to use Log4J via the SLF4J API. It does not contain the actual implementation of Log4J.

How to localise a string inside the iOS info.plist file?

Step by step localize Info.plist:

  1. Find in the Xcode the folder Resources (is placed in root)
  2. Select the folder Resources
  3. Then press the main menu File->New->File...
  4. Select in section "Resource" Strings File and press Next
  5. Then in Save As field write InfoPlist ONLY ("I" capital and "P" capital)
  6. Then press Create
  7. Then select the file InfoPlist.strings that created in Resources folder and press in the right menu the button "Localize"
  8. Then you Select the Project from the Project Navigator and select the The project from project list
  9. In the info tab at the bottom you can as many as language you want (There is in section Localizations)
  10. The language you can see in Resources Folder
  11. To localize the values ("key") from info.plist file you can open with a text editor and get all the keys you want to localize
  12. You write any key as the example in any InfoPlist.strings like the above example

"NSLocationAlwaysAndWhenInUseUsageDescription"="blabla";

"NSLocationAlwaysUsageDescription"="blabla2";

That's all work and you have localize your info.plist file!

a href link for entire div in HTML/CSS

put display:block on the anchor element. and/or zoom:1;

but you should just really do this.

a#parentdivimage{position:relative; width:184px; height:235px; 
                 border:2px solid #000; text-align:center; 
                 background-image:url("myimage.jpg"); 
                 background-position: 50% 50%; 
                 background-repeat:no-repeat; display:block; 
                 text-indent:-9999px}

<a id="parentdivimage">whatever your alt attribute was</a>

How do I format currencies in a Vue component?

You can use this example

formatPrice(value) {
  return value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
},

How to align the text middle of BUTTON

Sometime it is fixed by the Padding .. if you can play with that, then, it should fix your problem

<style type=text/css>

YourbuttonByID {Padding: 20px 80px; "for example" padding-left:50px; 
 padding-right:30px "to fix the text in the middle 
 without interfering with the text itself"}

</style>

It worked for me

How to make graphics with transparent background in R using ggplot2?

Just to improve YCR's answer:

1) I added black lines on x and y axis. Otherwise they are made transparent too.

2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.

Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.

MyTheme_transparent <- theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
    legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
    axis.line = element_line(colour = "black") # adding a black line for x and y axis
)

How do I left align these Bootstrap form items?

Just add style="text-align: left" to your label.

Difference between git stash pop and git stash apply

git stash pop applies the top stashed element and removes it from the stack. git stash apply does the same, but leaves it in the stash stack.

How to download/checkout a project from Google Code in Windows?

Thanks Mr. Tom Chantler adding that to get the exe http://downloadsvn.codeplex.com/ to pull the SVN source

just note that suppose you're downloading the below project: you have to enter exactly the following to donwload it in the exe URL:

http://myproject.googlecode.com/svn/trunk/

developer not taking care of appending the h t t p : / / if it does not exist. Hope it saves somebody's time.

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :

-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache 
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440

Looping through the content of a file in Bash

Use a while loop, like this:

while IFS= read -r line; do
   echo "$line"
done <file

Notes:

  1. If you don't set the IFS properly, you will lose indentation.

  2. You should almost always use the -r option with read.

  3. Don't read lines with for

jQuery UI Alert Dialog as a replacement for alert()

I took @EkoJR's answer, and added an additional parameter to pass in with a callback function to occur when the user closes the dialog.

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: onCloseCallback
    });
}

You can then call it and pass it a function, that will occur when the user closes the dialog, as so:

jqAlert('Your payment maintenance has been saved.', 
        'Processing Complete', 
        function(){ window.location = 'search.aspx' })

Convert Xml to Table SQL Server

The sp_xml_preparedocument stored procedure will parse the XML and the OPENXML rowset provider will show you a relational view of the XML data.

For details and more examples check the OPENXML documentation.

As for your question,

DECLARE @XML XML
SET @XML = '<rows><row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row></rows>'

DECLARE @handle INT  
DECLARE @PrepareXmlStatus INT  

EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML  

SELECT  *
FROM    OPENXML(@handle, '/rows/row', 2)  
    WITH (
    IdInvernadero INT,
    IdProducto INT,
    IdCaracteristica1 INT,
    IdCaracteristica2 INT,
    Cantidad INT,
    Folio INT
    )  


EXEC sp_xml_removedocument @handle 

JavaScript or jQuery browser back button click detector

The 'popstate' event only works when you push something before. So you have to do something like this:

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    window.history.pushState('forward', null, './#forward');

    $(window).on('popstate', function() {
      alert('Back button was pressed.');
    });

  }
});

For browser backward compatibility I recommend: history.js

How do I check if a column is empty or null in MySQL?

While checking null or Empty value for a column in my project, I noticed that there are some support concern in various Databases.

Every Database doesn't support TRIM method.

Below is the matrix just to understand the supported methods by different databases.

The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:

  • MySQL: TRIM(), RTRIM(), LTRIM()
  • Oracle: RTRIM(), LTRIM()
  • SQL Server: RTRIM(), LTRIM()

How to Check Empty/Null :-

Below are two different ways according to different Databases-

The syntax for these trim functions are:

  1. Use of Trim to check-

    SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL

  2. Use of LTRIM & RTRIM to check-

    SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL

Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName from UserDetails table if it has an empty LastName

Hoping this will help you :)

Leverage browser caching, how on apache or .htaccess?

I was doing the same thing a couple days ago. Added this to my .htaccess file:

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif¦jpe?g¦png¦ico¦css¦js¦swf)$">
Header set Cache-Control "public"
</FilesMatch>

And now when I run google speed page, leverage browwer caching is no longer a high priority.

Hope this helps.

AutoComplete TextBox in WPF

or you can add the AutoCompleteBox into the toolbox by clicking on it and then Choose Items, go to WPF Components, type in the filter AutoCompleteBox, which is on the System.Windows.Controls namespace and the just drag into your xaml file. This is way much easier than doing these other stuff, since the AutoCompleteBox is a native control.

How to do integer division in javascript (Getting division answer in int not float)?

var x = parseInt(455/10);

The parseInt() function parses a string and returns an integer.

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

This was the best solution I found after more time than I care to admit. Basically, add target="_self" to each link that you need to insure a page reload.

http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/

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

On a MAC, you need to use nm *.o | c++filt, as there is no -C option in nm.

How do I specify "close existing connections" in sql script

You can disconnect everyone and roll back their transactions with:

alter database [MyDatbase] set single_user with rollback immediate

After that, you can safely drop the database :)

How to start an application without waiting in a batch file?

I used start /b for this instead of just start and it ran without a window for each command, so there was no waiting.

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

The most important thing is add tzinfo when you define a datetime object.

from datetime import datetime, timezone
from tzinfo_examples import HOUR, Eastern
u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
for i in range(4):
     u = u0 + i*HOUR
     t = u.astimezone(Eastern)
     print(u.time(), 'UTC =', t.time(), t.tzname())

Must declare the scalar variable

This is most likely not an answer to the issue itself but this question pops up as first result when searching for Sql declare scalar variable hence i share a possible solution to this error.

In my case this error was caused by the use of ; after a SQL statement. Just remove it and the error will be gone.

I guess the cause is the same as @IronSean already posted in an comment above:

it's worth noting that using GO (or in this case ;) causes a new branch where declared variables aren't visible past the statement.

For example:

DECLARE @id int
SET @id = 78

SELECT * FROM MyTable WHERE Id = @var; <-- remove this character to avoid the error message
SELECT * FROM AnotherTable WHERE MyTableId = @var

Default parameters with C++ constructors

Either approach works. But if you have a long list of optional parameters make a default constructor and then have your set function return a reference to this. Then chain the settors.

class Thingy2
{
public:
    enum Color{red,gree,blue};
    Thingy2();

    Thingy2 & color(Color);
    Color color()const;

    Thingy2 & length(double);
    double length()const;
    Thingy2 & width(double);
    double width()const;
    Thingy2 & height(double);
    double height()const;

    Thingy2 & rotationX(double);
    double rotationX()const;
    Thingy2 & rotatationY(double);
    double rotatationY()const;
    Thingy2 & rotationZ(double);
    double rotationZ()const;
}

main()
{
    // gets default rotations
    Thingy2 * foo=new Thingy2().color(ret)
        .length(1).width(4).height(9)
    // gets default color and sizes
    Thingy2 * bar=new Thingy2()
        .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);
    // everything specified.
    Thingy2 * thing=new Thingy2().color(ret)
        .length(1).width(4).height(9)
        .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);
}

Now when constructing the objects you can pick an choose which properties to override and which ones you have set are explicitly named. Much more readable :)

Also, you no longer have to remember the order of the arguments to the constructor.

How do I correct this Illegal String Offset?

if ($inputs['type'] == 'attach') {

The code is valid, but it expects the function parameter $inputs to be an array. The "Illegal string offset" warning when using $inputs['type'] means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type' is not suitable.)

So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.

However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type' to 0, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)

You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs); in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:

if (is_array($inputs) && $inputs['type'] == 'attach') {

NoSql vs Relational database

NoSQL is better than RDBMS because of the following reasons/properities of NoSQL

  1. It supports semi-structured data and volatile data
  2. It does not have schema
  3. Read/Write throughput is very high
  4. Horizontal scalability can be achieved easily
  5. Will support Bigdata in volumes of Terra Bytes & Peta Bytes
  6. Provides good support for Analytic tools on top of Bigdata
  7. Can be hosted in cheaper hardware machines
  8. In-memory caching option is available to increase the performance of queries
  9. Faster development life cycles for developers

EDIT:

To answer "why RDBMS cannot scale", please take a look at RDBMS Overheads pdf written by Stavros Harizopoulos,Daniel J. Abadi,Samuel Madden and Michael Stonebraker

RDBMS's have challenges in handling huge data volumes of Terabytes & Peta bytes. Even if you have Redundant Array of Independent/Inexpensive Disks (RAID) & data shredding, it does not scale well for huge volume of data. You require very expensive hardware.

Logging: Assembling log records and tracking down all changes in database structures slows performance. Logging may not be necessary if recoverability is not a requirement or if recoverability is provided through other means (e.g., other sites on the network).

Locking: Traditional two-phase locking poses a sizeable overhead since all accesses to database structures are governed by a separate entity, the Lock Manager.

Latching: In a multi-threaded database, many data structures have to be latched before they can be accessed. Removing this feature and going to a single-threaded approach has a noticeable performance impact.

Buffer management: A main memory database system does not need to access pages through a buffer pool, eliminating a level of indirection on every record access.

This does not mean that we have to use NoSQL over SQL.

Still, RDBMS is better than NoSQL for the following reasons/properties of RDBMS

  1. Transactions with ACID properties - Atomicity, Consistency, Isolation & Durability
  2. Adherence to Strong Schema of data being written/read
  3. Real time query management ( in case of data size < 10 Tera bytes )
  4. Execution of complex queries involving join & group by clauses

We have to use RDBMS (SQL) and NoSQL (Not only SQL) depending on the business case & requirements

How to get just the responsive grid from Bootstrap 3?

It looks like you can download just the grid now on Bootstrap 4s new download features.

Trouble setting up git with my GitHub Account error: could not lock config file

I've gotten this error when a lock file exists for gitconfig. Try and find and remove .gitconfig.lock (on my linux box it was in my home dir)

Is there a TRY CATCH command in Bash

Based on some answers I found here, I made myself a small helper file to source for my projects:

trycatch.sh

#!/bin/bash

function try()
{
    [[ $- = *e* ]]; SAVED_OPT_E=$?
    set +e
}

function throw()
{
    exit $1
}

function catch()
{
    export ex_code=$?
    (( $SAVED_OPT_E )) && set +e
    return $ex_code
}

function throwErrors()
{
    set -e
}

function ignoreErrors()
{
    set +e
}

here is an example how it looks like in use:

#!/bin/bash
export AnException=100
export AnotherException=101

# start with a try
try
(   # open a subshell !!!
    echo "do something"
    [ someErrorCondition ] && throw $AnException

    echo "do something more"
    executeCommandThatMightFail || throw $AnotherException

    throwErrors # automaticatly end the try block, if command-result is non-null
    echo "now on to something completely different"
    executeCommandThatMightFail

    echo "it's a wonder we came so far"
    executeCommandThatFailsForSure || true # ignore a single failing command

    ignoreErrors # ignore failures of commands until further notice
    executeCommand1ThatFailsForSure
    local result = $(executeCommand2ThatFailsForSure)
    [ result != "expected error" ] && throw $AnException # ok, if it's not an expected error, we want to bail out!
    executeCommand3ThatFailsForSure

    echo "finished"
)
# directly after closing the subshell you need to connect a group to the catch using ||
catch || {
    # now you can handle
    case $ex_code in
        $AnException)
            echo "AnException was thrown"
        ;;
        $AnotherException)
            echo "AnotherException was thrown"
        ;;
        *)
            echo "An unexpected exception was thrown"
            throw $ex_code # you can rethrow the "exception" causing the script to exit if not caught
        ;;
    esac
}

maven error: package org.junit does not exist

if you are using Eclipse watch your POM dependencies and your Eclipse buildpath dependency on junit

if you select use Junit4 eclipse create TestCase using org.junit package but your POM use by default Junit3 (junit.framework package) that is the cause, like this picture:

see JUNIT conflict

Just update your Junit dependency in your POM file to Junit4 or your Eclipse BuildPath to Junit3

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

Java, How to add values to Array List used as value in HashMap

Java 8+ has computeIfAbsent

examList.computeIfAbsent(map.get(id), k -> new ArrayList<>());
map.get(id).add(value);

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-

Create array of regex matches

        Set<String> keyList = new HashSet();
        Pattern regex = Pattern.compile("#\\{(.*?)\\}");
        Matcher matcher = regex.matcher("Content goes here");
        while(matcher.find()) {
            keyList.add(matcher.group(1)); 
        }
        return keyList;

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had the same problem with the laravel initiation. The solution was as follows.

1st - I checked the version of my PHP. That it was 5.6 would soon give problem with the laravel.

2nd - I changed the version of my PHP to PHP 7.1.1. ATTENTION, in my case I changed my environment variable that was getting Xampp's PHP version 5.6 I changed to 7.1.1 for laragon.

3rd - I went to the terminal / console and navigated to my folder where my project was and typed the following command: php artisan serves. And it worked! In my case it started at the port: 8000 see example below.

C: \ laragon \ www \ first> php artisan serves Laravel development server started: http://127.0.0.1:8000

I hope I helped someone who has been through the same problem as me.

What is a good practice to check if an environmental variable exists or not?

I'd recommend the following solution.

It prints the env vars you didn't include, which lets you add them all at once. If you go for the for loop, you're going to have to rerun the program to see each missing var.

from os import environ

REQUIRED_ENV_VARS = {"A", "B", "C", "D"}
diff = REQUIRED_ENV_VARS.difference(environ)
if len(diff) > 0:
    raise EnvironmentError(f'Failed because {diff} are not set')

How to use MapView in android using google map V2?

More complete sample from here and here.

Or you can check out my layout sample. p.s no need to put API key in the map view.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
            android:id="@+id/map_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="2"
            />

    <ListView android:id="@+id/nearby_lv"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/white"
              android:layout_weight="1"
            />

</LinearLayout>

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

In my case the issue was due to incorrect build order. One project had an xcopy command on post-build events to copy files from bin folder to another folder. But because of incorrect dependencies new files were getting created in bin folder while xcopy is in progress.

In VS right click on the project where you have post-build events. Go to Build Dependencies > Project Dependencies and make sure its correct. Verify the project build order(next tab to dependencies) as well.

Html.DropdownListFor selected value not being set

For me was not working so worked this way:

Controller:

int selectedId = 1;

ViewBag.ItemsSelect = new SelectList(db.Items, "ItemId", "ItemName",selectedId);

View:

@Html.DropDownListFor(m => m.ItemId,(SelectList)ViewBag.ItemsSelect)

JQuery:

$("document").ready(function () {
    $('#ItemId').val('@Model.ItemId');
});

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Based on Jakub's answer you can configure the following git aliases for convenience:

accept-ours = "!f() { git checkout --ours -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"
accept-theirs = "!f() { git checkout --theirs -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"

They optionally take one or several paths of files to resolve and default to resolving everything under the current directory if none are given.

Add them to the [alias] section of your ~/.gitconfig or run

git config --global alias.accept-ours '!f() { git checkout --ours -- "${@:-.}"; git add -u "${@:-.}"; }; f'
git config --global alias.accept-theirs '!f() { git checkout --theirs -- "${@:-.}"; git add -u "${@:-.}"; }; f'

Split string into array of characters?

According to this code golfing solution by Gaffi, the following works:

a = Split(StrConv(s, 64), Chr(0))

How to preserve request url with nginx proxy_pass

In my scenario i have make this via below code in nginx vhost configuration

server {
server_name dashboards.etilize.com;

location / {
    proxy_pass http://demo.etilize.com/dashboards/;
    proxy_set_header Host $http_host;
}}

$http_host will set URL in Header same as requested

How do I send a file in Android from a mobile device to server using http?

This can be done with a HTTP Post request to the server:

HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost("http://url-to-server");

method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));

HttpResponse response = http.execute(method);

How to write an inline IF statement in JavaScript?

FYI, you can compose conditional operators

var a = (truthy) ? 1 : (falsy) ? 2 : 3;

If your logic is sufficiently complex, then you might consider using an IIFE

var a = (function () {
  if (truthy) return 1;
  else if (falsy) return 2;
  return 3;
})();

Of course, if you plan to use this logic more than once, then you aught to encapsulate it in a function to keep things nice and DRY.

Applying CSS styles to all elements inside a DIV

You could try:

#applyCSS .ui-bar-a {property:value}
#applyCSS .ui-bar-a .ui-link-inherit {property:value}

Etc, etc... Is that what you're looking for?

Row names & column names in R

Just to expand a little on Dirk's example:

It helps to think of a data frame as a list with equal length vectors. That's probably why names works with a data frame but not a matrix.

The other useful function is dimnames which returns the names for every dimension. You will notice that the rownames function actually just returns the first element from dimnames.

Regarding rownames and row.names: I can't tell the difference, although rownames uses dimnames while row.names was written outside of R. They both also seem to work with higher dimensional arrays:

>a <- array(1:5, 1:4)
> a[1,,,]
> rownames(a) <- "a"
> row.names(a)
[1] "a"
> a
, , 1, 1    
  [,1] [,2]
a    1    2

> dimnames(a)
[[1]]
[1] "a"

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

Convert java.util.date default format to Timestamp in Java

You can use

  long startTime = date.getTime() * 1000000;;
  long estimatedTime = System.nanoTime() - startTime;

To get time in nano.

Java Docs

How to select different app.config for several build configurations

You should consider ConfigGen. It was developed for this purpose. It produces a config file for each deployment machine, based on a template file and a settings file. I know that this doesn't answer your question specifically, but it might well answer your problem.

So rather than Debug, Release etc, you might have Test, UAT, Production etc. You can also have different settings for each developer machine, so that you can generate a config specific to your dev machine and change it without affecting any one else's deployment.

An example of usage might be...

<Target Name="BeforeBuild">
    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t       
        $(ProjectDir)App.config.template.xml -o $(SolutionDir)ConfigGen" />

    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t
        $(ProjectDir)App.config.template.xml -l -n $(ProjectDir)App.config" />
</Target>

If you place this in your .csproj file, and you have the following files...

$(ProjectDir)App.Config.Settings.xls

MachineName        ConfigFilePath   SQLServer        

default             App.config      DEVSQL005
Test                App.config      TESTSQL005
UAT                 App.config      UATSQL005
Production          App.config      PRODSQL005
YourLocalMachine    App.config      ./SQLEXPRESS


$(ProjectDir)App.config.template.xml 

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=[%SQLServer%]; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

... then this will be the result...

From the first command, a config file generated for each environment specified in the xls file, placed in the output directory $(SolutionDir)ConfigGen

.../solutiondir/ConfigGen/Production/App.config

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=PRODSQL005; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

From the second command, the local App.config used on your dev machine will be replaced with the generated config specified by the local (-l) switch and the filename (-n) switch.

How to have an auto incrementing version number (Visual Studio)?

You could use the T4 templating mechanism in Visual Studio to generate the required source code from a simple text file :

I wanted to configure version information generation for some .NET projects. It’s been a long time since I investigated available options, so I searched around hoping to find some simple way of doing this. What I’ve found didn’t look very encouraging: people write Visual Studio add-ins and custom MsBuild tasks just to obtain one integer number (okay, maybe two). This felt overkill for a small personal project.

The inspiration came from one of the StackOverflow discussions where somebody suggested that T4 templates could do the job. And of course they can. The solution requires a minimal effort and no Visual Studio or build process customization. Here what should be done:

  1. Create a file with extension ".tt" and place there T4 template that will generate AssemblyVersion and AssemblyFileVersion attributes:
<#@ template language="C#" #>
// 
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// 

using System.Reflection;

[assembly: AssemblyVersion("1.0.1.<#= this.RevisionNumber #>")]
[assembly: AssemblyFileVersion("1.0.1.<#= this.RevisionNumber #>")]
<#+
    int RevisionNumber = (int)(DateTime.UtcNow - new DateTime(2010,1,1)).TotalDays;
#>

You will have to decide about version number generation algorithm. For me it was sufficient to auto-generate a revision number that is set to the number of days since January 1st, 2010. As you can see, the version generation rule is written in plain C#, so you can easily adjust it to your needs.

  1. The file above should be placed in one of the projects. I created a new project with just this single file to make version management technique clear. When I build this project (actually I don’t even need to build it: saving the file is enough to trigger a Visual Studio action), the following C# is generated:
// 
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// 

using System.Reflection;

[assembly: AssemblyVersion("1.0.1.113")]
[assembly: AssemblyFileVersion("1.0.1.113")]

Yes, today it’s 113 days since January 1st, 2010. Tomorrow the revision number will change.

  1. Next step is to remove AssemblyVersion and AssemblyFileVersion attributes from AssemblyInfo.cs files in all projects that should share the same auto-generated version information. Instead choose “Add existing item” for each projects, navigate to the folder with T4 template file, select corresponding “.cs” file and add it as a link. That will do!

What I like about this approach is that it is lightweight (no custom MsBuild tasks), and auto-generated version information is not added to source control. And of course using C# for version generation algorithm opens for algorithms of any complexity.

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

This is very simple that we have already a javascript inbuilt function "isNaN" is there.

$("#numeric").keydown(function(e){
  if (isNaN(String.fromCharCode(e.which))){ 
    return false; 
  }
});

What is the best IDE to develop Android apps in?

One good system is Basic4Android - great for anyone familiar with Basic,

  • Includes a visual designer for screen layouts
  • Can connect to the emulators available as part of the Android SDK
  • Makes it relatively easy to develop programs.

How to call loading function with React useEffect only once

we developed a module on GitHub that has hooks for fetching data so you can use it like this for your purpose:

import { useFetching } from "react-concurrent";

const app = () => {
  const { data, isLoading, error , refetch } = useFetching(() =>
    fetch("http://example.com"),
  );
};

You can fork that out, but any PRs are welcome. https://github.com/hosseinmd/react-concurrent#react-concurrent

Relative path to absolute path in C#?

Have you tried Server.MapPath method. Here is an example

string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg

How to use aria-expanded="true" to change a css property

If you were open to using JQuery, you could modify the background color for any link that has the property aria-expanded set to true by doing the following...

$("a[aria-expanded='true']").css("background-color", "#42DCA3");

Depending on how specific you want to be regarding which links this applies to, you may have to slightly modify your selector.

jQuery checkbox change and click event

I am not sure why everyone is making this so complicated. This is all I did.

if(!$(this).is(":checked")){ console.log("on"); }

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

javascript how to create a validation error message without using alert

I would strongly suggest you start using jQuery. Your code would look like:

$(function() {
    $('form[name="myform"]').submit(function(e) {
        var username = $('form[name="myform"] input[name="username"]').val();
        if ( username == '') {
            e.preventDefault();
            $('#errors').text('*Please enter a username*');
        }
    });
});

How to use clock() in C++

On Windows at least, the only practically accurate measurement mechanism is QueryPerformanceCounter (QPC). std::chrono is implemented using it (since VS2015, if you use that), but it is not accurate to the same degree as using QueryPerformanceCounter directly. In particular it's claim to report at 1 nanosecond granularity is absolutely not correct. So, if you're measuring something that takes a very short amount of time (and your case might just be such a case), then you should use QPC, or the equivalent for your OS. I came up against this when measuring cache latencies, and I jotted down some notes that you might find useful, here; https://github.com/jarlostensen/notesandcomments/blob/master/stdchronovsqcp.md

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle