Programs & Examples On #Plist

A plist file, also known as a "Property List" file, stores serialized objects such as arrays, dictionaries, and strings.

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

[UPDATED privacy keys list to iOS 13 - see below]

There is a list of all Cocoa Keys that you can specify in your Info.plist file:

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

(Xcode: Target -> Info -> Custom iOS Target Properties)

iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).

Privacy keys with example description: cheatsheet

Source

Alternatively, you can open Info.plist as source code: source code

Source

And add privacy keys like this:

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>

List of all privacy keys: [UPDATED to iOS 13]

NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription

Update 2019:

In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.

I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo to ${PRODUCT_NAME} need access to the camera to update your avatar even though the app context was obvious (user tapped on the avatar).

It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.

NSCameraUsageDescription in iOS 10.0 runtime crash?

You have to add this below key in info.plist.

NSCameraUsageDescription Or Privacy - Camera usage description

And add description of usage.

Detailed screenshots are available in this link

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

In my case everything was set up correctly but still the InfoPlist.strings file was not found.

The only thing that really worked was, to remove and add the InfoPlist.strings files again to the project.

Using Pipes within ngModel on INPUT Elements in Angular

you must use [ngModel] instead of two way model binding with [(ngModel)]. then use manual change event with (ngModelChange). this is public rule for all two way input in components.

because pipe on event emitter is wrong.

Ways to insert javascript into URL?

It depends on your application and its use as to the level of security you need.

In terms of security, you should be validating all values you get from the querystring or post parameters, to ensure they're valid.

You may also wish to add logging for others, including analysis of weblogs so you can determine if an attempt to hack your system is occuring.

I don't believe it's possible to inject javascript into a URL and have this run, unless your application is using parameters without validating them first.

PHP Fatal error: Cannot access empty property

As I see in your code, it seems you are following an old documentation/tutorial about OOP in PHP based on PHP4 (OOP wasn't supported but adapted somehow to be used in a simple ways), since PHP5 an official support was added and the notation has been changed from what it was.

Please see this code review here:

<?php
class my_class{

    public $my_value = array();

    function __construct( $value ) { // the constructor name is __construct instead of the class name
        $this->my_value[] = $value;
    }
    function set_value ($value){
    // Error occurred from here as Undefined variable: my_value
        $this->my_value = $value; // remove the $ sign
    }

}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c'); // your array variable here will be replaced by a simple string 
// $a->my_class('d'); // you can call this if you mean calling the contructor 


// at this stage you can't loop on the variable since it have been replaced by a simple string ('c')
foreach ($a->my_value as &$value) { // look for foreach samples to know how to use it well
    echo $value;
}

?>

I hope it helps

How to drop a database with Mongoose?

Tried @hellslam's and @silverfighter's answers. I found a race condition holding my tests back. In my case I'm running mocha tests and in the before function of the test I want to erase the entire DB. Here's what works for me.

var con = mongoose.connect('mongodb://localhost/mydatabase');
mongoose.connection.on('open', function(){
    con.connection.db.dropDatabase(function(err, result){
        done();
    });
});

You can read more https://github.com/Automattic/mongoose/issues/1469

Sort Pandas Dataframe by Date

sort method has been deprecated and replaced with sort_values. After converting to datetime object using df['Date']=pd.to_datetime(df['Date'])

df.sort_values(by=['Date'])

Note: to sort in-place and/or in a descending order (the most recent first):

df.sort_values(by=['Date'], inplace=True, ascending=False)

Pointers in JavaScript?

Since JavaScript does not support passing parameters by reference, you'll need to make the variable an object instead:

_x000D_
_x000D_
var x = {Value: 0};_x000D_
_x000D_
function a(obj)_x000D_
{_x000D_
    obj.Value++;_x000D_
}_x000D_
_x000D_
a(x);_x000D_
document.write(x.Value); //Here i want to have 1 instead of 0
_x000D_
_x000D_
_x000D_

In this case, x is a reference to an object. When x is passed to the function a, that reference is copied over to obj. Thus, obj and x refer to the same thing in memory. Changing the Value property of obj affects the Value property of x.

Javascript will always pass function parameters by value. That's simply a specification of the language. You could create x in a scope local to both functions, and not pass the variable at all.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

Key value pairs using JSON

I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.

Simple Key Pair JSON structure

var data = {
    'XXXXXX' : '100.0',
    'YYYYYYY' : '200.0',
    'ZZZZZZZ' : '500.0',
}

Usage JavaScript code to access the key pairs

for (var key in data) 
  { if (!data.hasOwnProperty(key))
    { continue; } 
    console.log(key + ' -> ' +  data[key]);
  };

Console output should look like this

XXXXXX -> 100.0 
YYYYYYY -> 200.0 
ZZZZZZZ -> 500.0

Here is a JSFiddle to show how it works.

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}

or

${string:(-3)}

(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:

${parameter:offset}
${parameter:offset:length}

Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:

${string:${#string}<3?0:-3}

This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.


Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

HTML select dropdown list

_x000D_
_x000D_
<select>_x000D_
    <option value="" style="display:none">Choose one provider</option>_x000D_
    <option value="1">One</option>_x000D_
    <option value="2">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

This way the user cannot see this option, but it shows in the select box.

Recursively find files with a specific extension

Recurisvely with ls: (-al for include hidden folders)

ftype="jpg"
ls -1R *.${ftype}  2> /dev/null

How to store standard error in a variable

Capture AND Print stderr

ERROR=$( ./useless.sh 3>&1 1>&2 2>&3 | tee /dev/fd/2 )

Breakdown

You can use $() to capture stdout, but you want to capture stderr instead. So you swap stdout and stderr. Using fd 3 as the temporary storage in the standard swap algorithm.

If you want to capture AND print use tee to make a duplicate. In this case the output of tee will be captured by $() rather than go to the console, but stderr(of tee) will still go to the console so we use that as the second output for tee via the special file /dev/fd/2 since tee expects a file path rather than a fd number.

NOTE: That is an awful lot of redirections in a single line and the order matters. $() is grabbing the stdout of tee at the end of the pipeline and the pipeline itself routes stdout of ./useless.sh to the stdin of tee AFTER we swapped stdin and stdout for ./useless.sh.

Using stdout of ./useless.sh

The OP said he still wanted to use (not just print) stdout, like ./useless.sh | sed 's/Output/Useless/'.

No problem just do it BEFORE swapping stdout and stderr. I recommend moving it into a function or file (also-useless.sh) and calling that in place of ./useless.sh in the line above.

However, if you want to CAPTURE stdout AND stderr, then I think you have to fall back on temporary files because $() will only do one at a time and it makes a subshell from which you cannot return variables.

Removing legend on charts with chart.js v2

You simply need to add that line legend: { display: false }

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).

The reason I wanted that version in particular is because that's what ships with MVC currently.

Here's the code:

$(document).ready(function() {
    $("#topBar").css("position", "absolute");
});

$(window).scroll(function() {
    $("#topBar").css("top", $(window).scrollTop() + "px");
});

Getting String value from enum in Java

if status is of type Status enum, status.name() will give you its defined name.

How can I check for an empty/undefined/null string in JavaScript?

I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".

As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.

What is the difference between dim and set in vba

There's no reason to use set unless referring to an object reference. It's good practice to only use it in that context. For all other simple data types, just use an assignment operator. It's a good idea to dim (dimension) ALL variables however:

Examples of simple data types would be integer, long, boolean, string. These are just data types and do not have their own methods and properties.

Dim i as Integer
i = 5

Dim myWord as String
myWord = "Whatever I want"

An example of an object would be a Range, a Worksheet, or a Workbook. These have their own methods and properties.

Dim myRange as Range
Set myRange = Sheet1.Range("A1")

If you try to use the last line without Set, VB will throw an error. Now that you have an object declared you can access its properties and methods.

myString = myRange.Value

How can I remove text within parentheses with a regex?

For those who want to use Python, here's a simple routine that removes parenthesized substrings, including those with nested parentheses. Okay, it's not a regex, but it'll do the job!

def remove_nested_parens(input_str):
    """Returns a copy of 'input_str' with any parenthesized text removed. Nested parentheses are handled."""
    result = ''
    paren_level = 0
    for ch in input_str:
        if ch == '(':
            paren_level += 1
        elif (ch == ')') and paren_level:
            paren_level -= 1
        elif not paren_level:
            result += ch
    return result

remove_nested_parens('example_(extra(qualifier)_text)_test(more_parens).ext')

Search for "does-not-contain" on a DataFrame in pandas

I was having trouble with the not (~) symbol as well, so here's another way from another StackOverflow thread:

df[df["col"].str.contains('this|that')==False]

VB.NET: how to prevent user input in a ComboBox

---- in form level Declaration of cbx veriable---

Dim cbx as string

Private Sub comboBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comboBox1.Enter
    cbx = Me.comboBox1.Text
End Sub

Private Sub comboBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comboBox1.Leave
    Me.comboBox1.Text = cbx
End Sub

Array or List in Java. Which is faster?

I'm guessing the original poster is coming from a C++/STL background which is causing some confusion. In C++ std::list is a doubly linked list.

In Java [java.util.]List is an implementation-free interface (pure abstract class in C++ terms). List can be a doubly linked list - java.util.LinkedList is provided. However, 99 times out of 100 when you want a make a new List, you want to use java.util.ArrayList instead, which is the rough equivalent of C++ std::vector. There are other standard implementations, such as those returned by java.util.Collections.emptyList() and java.util.Arrays.asList().

From a performance standpoint there is a very small hit from having to go through an interface and an extra object, however runtime inlining means this rarely has any significance. Also remember that String are typically an object plus array. So for each entry, you probably have two other objects. In C++ std::vector<std::string>, although copying by value without a pointer as such, the character arrays will form an object for string (and these will not usually be shared).

If this particular code is really performance-sensitive, you could create a single char[] array (or even byte[]) for all the characters of all the strings, and then an array of offsets. IIRC, this is how javac is implemented.

Regex to remove all special characters from string?

tmp = Regex.Replace(n, @"\W+", "");

\w matches letters, digits, and underscores, \W is the negated version.

How to use log4net in Asp.net core 2.0

I am porting a .Net Framework console app to .Net Core and found a similar issue with log files not getting created under certain circumstances.

When using "CreateRepository" there appears to be a difference between .net framework and .net standard.

Under .Net Framework this worked to create a unique Log instance with it's own filename using the same property from log4net.config

GlobalContext.Properties["LogName"] = LogName;
var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository);

Under .Net Standard this didn't work and if you turn on tracing you see it can't find the configuration file ".config". It wasn't loading the previous known configuration. Once I added the configuration to the configurator it still didn't log, while not complaining about it either.

To get it working under .Net Standard with similar behavior as before, this is what I did.

var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository,new FileInfo("log4net.config"));
var hierarchy = (Hierarchy) loggerRepository;
var appender = (RollingFileAppender)hierarchy.Root.GetAppender("RollingLogFileAppender");
appender.File = Path.Combine(Directory.GetCurrentDirectory(), "logs", $"{LogName}.log");

I didn't want to create a configuration file for every repo, so this works. Perhaps there is a better way to get the .Net Framework behavior as before and if there is please let me know below.

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

Both methods are used by many of the large players. It's a matter of preference. My preference is REST because it's simpler to use and understand.

Simple Object Access Protocol (SOAP):

  • SOAP builds an XML protocol on top of HTTP or sometimes TCP/IP.
  • SOAP describes functions, and types of data.
  • SOAP is a successor of XML-RPC and is very similar, but describes a standard way to communicate.
  • Several programming languages have native support for SOAP, you typically feed it a web service URL and you can call its web service functions without the need of specific code.
  • Binary data that is sent must be encoded first into a format such as base64 encoded.
  • Has several protocols and technologies relating to it: WSDL, XSDs, SOAP, WS-Addressing

Representational state transfer (REST):

  • REST need not be over HTTP but most of my points below will have an HTTP bias.
  • REST is very lightweight, it says wait a minute, we don't need all of this complexity that SOAP created.
  • Typically uses normal HTTP methods instead of a big XML format describing everything. For example to obtain a resource you use HTTP GET, to put a resource on the server you use HTTP PUT. To delete a resource on the server you use HTTP DELETE.
  • REST is a very simple in that it uses HTTP GET, POST and PUT methods to update resources on the server.
  • REST typically is best used with Resource Oriented Architecture (ROA). In this mode of thinking everything is a resource, and you would operate on these resources.
  • As long as your programming language has an HTTP library, and most do, you can consume a REST HTTP protocol very easily.
  • Binary data or binary resources can simply be delivered upon their request.

There are endless debates on REST vs SOAP on google.

My favorite is this one. Update 27 Nov 2013: Paul Prescod's site appears to have gone offline and this article is no longer available, copies though can be found on the Wayback Machine or as a PDF at CiteSeerX.

Determine if map contains a value for a key?

Does something along these lines exist?

No. With the stl map class, you use ::find() to search the map, and compare the returned iterator to std::map::end()

so

map<int,Bar>::iterator it = m.find('2');
Bar b3;
if(it != m.end())
{
   //element found;
   b3 = it->second;
}

Obviously you can write your own getValue() routine if you want (also in C++, there is no reason to use out), but I would suspect that once you get the hang of using std::map::find() you won't want to waste your time.

Also your code is slightly wrong:

m.find('2'); will search the map for a keyvalue that is '2'. IIRC the C++ compiler will implicitly convert '2' to an int, which results in the numeric value for the ASCII code for '2' which is not what you want.

Since your keytype in this example is int you want to search like this: m.find(2);

Call Class Method From Another Class

update: Just saw the reference to call_user_func_array in your post. that's different. use getattr to get the function object and then call it with your arguments

class A(object):
    def method1(self, a, b, c):
        # foo

method = A.method1

method is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A.

a = A()
method = a.method1
method(1, 2)

You have three options for doing this

  1. Use an instance of A to call method1 (using two possible forms)
  2. apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.
  3. apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.

Some examples:

class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
    def method1(self, a, b):
        return a + b

    @staticmethod
    def method2(a, b):
        return a + b

    @classmethod
    def method3(cls, a, b):
        return cls.method2(a, b)

t = Test1()  # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2)        # form two (the common one) essentially reduces to form one

Test1.method2(1, 2)  #the static method can be called with just arguments
t.method2(1, 2)      # on an instance or the class

Test1.method3(1, 2)  # ditto for the class method. It will have access to the class
t.method3(1, 2)      # that it's called on (the subclass if called on a subclass) 
                     # but will not have access to the instance it's called on 
                     # (if it is called on an instance)

Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable but those are the customary values.

Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

What does yield mean in PHP?

This function is using yield:

function a($items) {
    foreach ($items as $item) {
        yield $item + 1;
    }
}

It is almost the same as this one without:

function b($items) {
    $result = [];
    foreach ($items as $item) {
        $result[] = $item + 1;
    }
    return $result;
}

The only one difference is that a() returns a generator and b() just a simple array. You can iterate on both.

Also, the first one does not allocate a full array and is therefore less memory-demanding.

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

I got some errors that the software was unavailable from the update server when trying

xcode-select --install

What fixed it for me was going here https://developer.apple.com/download/more/ and downloading Command Line Tools (macOS 10.14) for Xcode 10 and then installing it manually.

After that, the errors should be gone when you open up a new terminal.

Is it possible to run .APK/Android apps on iPad/iPhone devices?

There is another option not mentioned previously:

  • Pieceable Viewer has unfortunately stopped its service at December 31, 2012 but open-sourced its software. You need to compile your iOS application for the emulator and Pieceable's software will embed it in a webpage which hosts the application. This webpage can be used to run the iOS application. See Pieceable's for more details.

Creating a SearchView that looks like the material design guidelines

I know its a old thread but still posting the library I just made. Hope this might help someone.

https://github.com/Shahroz16/material-searchview

Meterial Search View

How do I break out of nested loops in Java?

Like other answerers, I'd definitely prefer to put the loops in a different method, at which point you can just return to stop iterating completely. This answer just shows how the requirements in the question can be met.

You can use break with a label for the outer loop. For example:

public class Test {
    public static void main(String[] args) {
        outerloop:
        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                if (i * j > 6) {
                    System.out.println("Breaking");
                    break outerloop;
                }
                System.out.println(i + " " + j);
            }
        }
        System.out.println("Done");
    }
}

This prints:

0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
Breaking
Done

What Content-Type value should I send for my XML sitemap?

both are fine.

text/xxx means that in case the program does not understand xxx it makes sense to show the file to the user as plain text. application/xxx means that it is pointless to show it.

Please note that those content-types were originally defined for E-Mail attachment before they got later used in Web world.

How to resolve Value cannot be null. Parameter name: source in linq?

When you call a Linq statement like this:

// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));

You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:

var count = Enumerable.Count(x, s => s.StartsWith("x"));

So the error you are getting above is because the first parameter, source (which would be x in the sample above) is null.

Installing Oracle Instant Client

I was able to setup Oracle Instant Client (Basic) 11g2 and Oracle ODBC (32bit) drivers on my 32bit Windows 7 PC. Note: you'll need a 'tnsnames.ora' file because it doesn't come with one. You can Google examples and copy/paste into a text file, change the parameters for your environment.

Setting up Oracle Instant Client-Basic 11g2 (Win7 32-bit)
(I think there's another step or two if your using 64-bit)

Oracle Instant Client

  • Unzip Oracle Instant Client - Basic
  • Put contents in folder like "C:\instantclient"
  • Edit PATH evironment variable, add path to Instant Client folder to the Variable Value.
  • Add new Variable called "TNS_ADMIN" point to same folder as Instant Client.
  • I had to create a "tnsnames.ora" file because it doesn't come with one. Put it in same folder as the client.
  • reboot or use Task Manager to kill "explorer.exe" and restart it to refresh the PATH environment variables.

ODBC Drivers

  • Unzip ODBC drivers
  • Copy all files into same folder as client "C:\instantclient"
  • Use command prompt to run "odbc_install.exe" (should say it was successful)

Note: The "un-documented" things that were hanging me up where...
- All files (Client and Drivers) needed to be in the same folder (nothing in sub-folders).
- Running the ODBC driver from the command prompt will allow you to see if it installs successfully. Double-clicking the installer just flashed a box on the screen, no idea it was failing because no error dialog.

After you've done this you should be able to setup a new DSN Data Source using the Oracle ODBC driver.
-Hope this helps someone else.

How do I delete multiple rows with different IDs?

Delete from BA_CITY_MASTER where CITY_NAME in (select CITY_NAME from BA_CITY_MASTER group by CITY_NAME having count(CITY_NAME)>1);

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:

import numpy as np
from sklearn import linear_model
from sklearn import svm

classifiers = [
    svm.SVR(),
    linear_model.SGDRegressor(),
    linear_model.BayesianRidge(),
    linear_model.LassoLars(),
    linear_model.ARDRegression(),
    linear_model.PassiveAggressiveRegressor(),
    linear_model.TheilSenRegressor(),
    linear_model.LinearRegression()]

trainingData    = np.array([ [2.3, 4.3, 2.5],  [1.3, 5.2, 5.2],  [3.3, 2.9, 0.8],  [3.1, 4.3, 4.0]  ])
trainingScores  = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData  = np.array([ [2.5, 2.4, 2.7],  [2.7, 3.2, 1.2] ])

for item in classifiers:
    print(item)
    clf = item
    clf.fit(trainingData, trainingScores)
    print(clf.predict(predictionData),'\n')

What is an API key?

Think of it this way, the "Public API Key" is similar to a user name that your database is using as a login to a verification server. The "Private API Key" would then be similar to the password. By the site/databse using this method, the security is maintained on the third party/verification server in order to authentic request of posting or editing your site/database.

The API string is just the URL of the login for your site/database to contact the verification server.

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

How to get screen width and height

From service:

Display  display= ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth(); 
int height = display.getHeight(); 

Android: How can I print a variable on eclipse console?

toast is a bad idea, it's far too "complex" to print the value of a variable. use log or s.o.p, and as drawnonward already said, their output goes to logcat. it only makes sense if you want to expose this information to the end-user...

What is setBounds and how do I use it?

You can use setBounds(x, y, width, height) to specify the position and size of a GUI component if you set the layout to null. Then (x, y) is the coordinate of the upper-left corner of that component.

Detect Windows version in .net

One way:

public string GetOSVersion()
{
  int _MajorVersion = Environment.OSVersion.Version.Major;

  switch (_MajorVersion) {
    case 5:
      return "Windows XP";
    case 6:
      switch (Environment.OSVersion.Version.Minor) {
        case 0:
          return "Windows Vista";
        case 1:
          return "Windows 7";
        default:
          return "Windows Vista & above";
      }
      break;
    default:
      return "Unknown";
  }
}

Then simply do wrap a select case around the function.

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

I had to install the NVIDIA 367.57 driver and CUDA 7.5 with Tensorflow on the g2.2xlarge Ubuntu 14.04LTS instance. e.g. nvidia-graphics-drivers-367_367.57.orig.tar

Now the GRID K520 GPU is working while I train tensorflow models:

ubuntu@ip-10-0-1-70:~$ nvidia-smi
Sat Apr  1 18:03:32 2017       
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 367.57                 Driver Version: 367.57                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GRID K520           Off  | 0000:00:03.0     Off |                  N/A |
| N/A   39C    P8    43W / 125W |   3800MiB /  4036MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0      2254    C   python                                        3798MiB |
+-----------------------------------------------------------------------------+

ubuntu@ip-10-0-1-70:~/NVIDIA_CUDA-7.0_Samples/1_Utilities/deviceQuery$ ./deviceQuery 
./deviceQuery Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

Detected 1 CUDA Capable device(s)

Device 0: "GRID K520"
  CUDA Driver Version / Runtime Version          8.0 / 7.0
  CUDA Capability Major/Minor version number:    3.0
  Total amount of global memory:                 4036 MBytes (4232052736 bytes)
  ( 8) Multiprocessors, (192) CUDA Cores/MP:     1536 CUDA Cores
  GPU Max Clock rate:                            797 MHz (0.80 GHz)
  Memory Clock rate:                             2500 Mhz
  Memory Bus Width:                              256-bit
  L2 Cache Size:                                 524288 bytes
  Maximum Texture Dimension Size (x,y,z)         1D=(65536), 2D=(65536, 65536), 3D=(4096, 4096, 4096)
  Maximum Layered 1D Texture Size, (num) layers  1D=(16384), 2048 layers
  Maximum Layered 2D Texture Size, (num) layers  2D=(16384, 16384), 2048 layers
  Total amount of constant memory:               65536 bytes
  Total amount of shared memory per block:       49152 bytes
  Total number of registers available per block: 65536
  Warp size:                                     32
  Maximum number of threads per multiprocessor:  2048
  Maximum number of threads per block:           1024
  Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
  Max dimension size of a grid size    (x,y,z): (2147483647, 65535, 65535)
  Maximum memory pitch:                          2147483647 bytes
  Texture alignment:                             512 bytes
  Concurrent copy and kernel execution:          Yes with 2 copy engine(s)
  Run time limit on kernels:                     No
  Integrated GPU sharing Host Memory:            No
  Support host page-locked memory mapping:       Yes
  Alignment requirement for Surfaces:            Yes
  Device has ECC support:                        Disabled
  Device supports Unified Addressing (UVA):      Yes
  Device PCI Domain ID / Bus ID / location ID:   0 / 0 / 3
  Compute Mode:
     < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 8.0, CUDA Runtime Version = 7.0, NumDevs = 1, Device0 = GRID K520
Result = PASS

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

wmic can call an uninstaller. I haven't tried this, but I think it might work.

wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall

If you don't know exactly what the program calls itself, do

wmic product get name | sort

and look for it. You can also uninstall using SQL-ish wildcards.

wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall

... for example would perform a case-insensitive search for *j2se* and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se% is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%.)

If wmic prompts for y/n confirmation before completing the uninstall, try this:

echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall

... to pass a y to it before it even asks.

I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.

C non-blocking keyboard input

select() is a bit too low-level for convenience. I suggest you use the ncurses library to put the terminal in cbreak mode and delay mode, then call getch(), which will return ERR if no character is ready:

WINDOW *w = initscr();
cbreak();
nodelay(w, TRUE);

At that point you can call getch without blocking.

Efficient way to remove ALL whitespace from String?

Just an alternative because it looks quite nice :) - NOTE: Henks answer is the quickest of these.

input.ToCharArray()
 .Where(c => !Char.IsWhiteSpace(c))
 .Select(c => c.ToString())
 .Aggregate((a, b) => a + b);

Testing 1,000,000 loops on "This is a simple Test"

This method = 1.74 seconds
Regex = 2.58 seconds
new String (Henks) = 0.82 seconds

How do I change the font size and color in an Excel Drop Down List?

I work on 60-70% zoom vue and my dropdown are unreadable so I made this simple code to overcome the issue

Note that I selected first all my dropdown lsts (CTRL+mouse click), went on formula tab, clicked "define name" and called them "ProduktSelection"

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim KeyCells As Range
Set KeyCells = Range("ProduktSelection")
    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

ActiveWindow.Zoom = 100

End If

End Sub

I then have another sub

Private Sub Worksheet_Change(ByVal Target As Range) 

where I come back to 65% when value is changed.

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

I had the similar issue. I solved it the following way after a number of attempts to follow the pieces of advice in the forums. I am reposting the solution because it could be helpful for others.

I am running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file "httpd.conf" (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if "php.ini" is read from the right directory. Just type in your browser "localhost/index.php". The code of index.php is the following:

<?php echo phpinfo(); ?>

There is the row (not far from the top) called "Loaded Configuration File". So, if there is nothing added, then the problem could be that your "php.ini" is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from

PHPIniDir 'c:\PHP\'

to

PHPIniDir 'c:\PHP'

Pay the attention that the last slash disturbed everything!

Now the row "Loaded Configuration File" gets "C:\PHP\php.ini" after refreshing "localhost/index.php" (before I restarted Apache2.2) as well as mysql block is there. MySQL and PHP are working together!

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

Encrypt and Decrypt text with RSA in PHP

You can use phpseclib, a pure PHP RSA implementation:

<?php
include('Crypt/RSA.php');

$privatekey = file_get_contents('private.key');

$rsa = new Crypt_RSA();
$rsa->loadKey($privatekey);

$plaintext = new Math_BigInteger('aaaaaa');
echo $rsa->_exponentiate($plaintext)->toBytes();
?>

Browser Caching of CSS files

That depends on what headers you are sending along with your CSS files. Check your server configuration as you are probably not sending them manually. Do a google search for "http caching" to learn about different caching options you can set. You can force the browser to download a fresh copy of the file everytime it loads it for instance, or you can cache the file for one week...

How to make (link)button function as hyperlink?

There is a middle way. If you want a HTML control but you need to access it server side you can simply add the runat="server" attribute:

<a runat="server" Id="lnkBack">Back</a>

You can then alter the href server side using Attributes

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       lnkBack.Attributes.Add("href", url);
    }
}

resulting in:

<a id="ctl00_ctl00_mainContentPlaceHolder_contentPlaceHolder_lnkBack" 
      href="url.aspx">Back</a>

Running Groovy script from the command line

#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;

println("hello");

Http Basic Authentication in Java using HttpClient?

while using Header array

String auth = Base64.getEncoder().encodeToString(("test1:test1").getBytes());
Header[] headers = {
    new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()),
    new BasicHeader("Authorization", "Basic " +auth)
};

Is it possible to use 'else' in a list comprehension?

Great answers, but just wanted to mention a gotcha that "pass" keyword will not work in the if/else part of the list-comprehension (as posted in the examples mentioned above).

#works
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else x**2 for x in list1 ]
print(newlist2, type(newlist2))

#but this WONT work
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else pass for x in list1 ]
print(newlist2, type(newlist2))

This is tried and tested on python 3.4. Error is as below:

newlist2 = [x if x > 30 else pass for x in list1 ]                                    
SyntaxError: invalid syntax

So, try to avoid pass-es in list comprehensions

perform an action on checkbox checked or unchecked event on html form

We can do this using JavaScript, no need of jQuery. Just pass the changed element and let JavaScript handle it.

HTML

<form id="myform">
    syn<input type="checkbox" name="checkfield" id="g01-01"  onchange="doalert(this)"/>
</form>

JS

function doalert(checkboxElem) {
  if (checkboxElem.checked) {
    alert ("hi");
  } else {
    alert ("bye");
  }
}

Demo Here

CSS display:table-row does not expand when width is set to 100%

Note that according to the CSS3 spec, you do NOT have to wrap your layout in a table-style element. The browser will infer the existence of containing elements if they do not exist.

Virtual Serial Port for Linux

Would you be able to use a USB->RS232 adapter? I have a few, and they just use the FTDI driver. Then, you should be able to rename /dev/ttyUSB0 (or whatever gets created) as /dev/ttyS2 .

Filter an array using a formula (without VBA)

Today, in Office 365, Excel has so called 'array functions'. The filter function does exactly what you want. No need to use CTRL+SHIFT+ENTER anymore, a simple enter will suffice.

In Office 365, your problem would be simply solved by using:

=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)

Making HTTP Requests using Chrome Developer tools

If your web page has jquery in your page, then you can do it writing on chrome developers console:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

Its jquery way of doing it!

TypeError: $ is not a function when calling jQuery function

This should fix it:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  var body = $( 'body' );
});

Put simply, WordPress runs their own scripting before you can and they release the $ var so it won't collide with other libraries. This makes total sense, as WordPress is used for all kinds of web sites, apps, and of course, blogs.

From their documentation:

The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.

In the noConflict() mode, the global $ shortcut for jQuery is not available...

Is it possible to insert HTML content in XML document?

You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.

Another might be using CDATA tags.

Example using CDATA:

<xml>
    <title>Your HTML title</title>
    <htmlData><![CDATA[<html>
        <head>
            <script/>
        </head>
        <body>
        Your HTML's body
        </body>
        </html>
     ]]>
    </htmlData>
</xml>

Please note:

CDATA's opening character sequence: <![CDATA[

CDATA's closing character sequence: ]]>

How to generate class diagram from project in Visual Studio 2013?

For creating real UML class diagrams:

In Visual Studio 2013 Ultimate you can do this without any external tools.

  • In the menu, click on Architecture, New Diagram Select UML Class Diagram
  • This will ask you to create a new Modeling Project if you don't have one already.

You will have a empty UMLClassDiagram.classdiagram.

  • Again, go to Architecture, Windows, Architecture Explorer.
  • A window will pop up with your namespaces, Choose Class View.
  • Then a list of sub-namespaces will appear, if any. Choose one, select the classes and drag them to the empty UMLClassDiagram1.classdiagram window.

Reference: Create UML Class Diagrams from Code

In Unix, how do you remove everything in the current directory and below it?

Use

rm -rf *

Update: The . stands for current directory, but we cannot use this. The command seems to have explicit checks for . and ... Use the wildcard globbing instead. But this can be risky.

A safer version IMO is to use:

rm -ri * 

(this prompts you for confirmation before deleting every file/directory.)

PHP - concatenate or directly insert variables in string

I know this question already has a chosen answer, but I found this article that evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.

NSAttributedString add text alignment

In swift 4:

    let paraStyle = NSMutableParagraphStyle.init()
    paraStyle.alignment = .left

    let str = "Test Message"
    let attribute = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 12)]

    let attrMessage = NSMutableAttributedString(string: str, attributes: attribute)


    attrMessage.addAttribute(kCTParagraphStyleAttributeName as NSAttributedStringKey, value: paraStyle, range: NSMakeRange(0, str.count))

How to format dateTime in django template?

{{ wpis.entry.lastChangeDate|date:"SHORT_DATETIME_FORMAT" }}

Compute mean and standard deviation by group for multiple variables in a data.frame

There is a helpful function in the psych package.

You should try the following implementation:

psych::describeBy(data$dependentvariable, group = data$groupingvariable)

Copy folder recursively, excluding some folders

inspired by @SteveLazaridis's answer, which would fail, here is a POSIX shell function - just copy and paste into a file named cpx in yout $PATH and make it executible (chmod a+x cpr). [Source is now maintained in my GitLab.

#!/bin/sh

# usage: cpx [-n|--dry-run] "from_path" "to_path" "newline_separated_exclude_list"
# limitations: only excludes from "from_path", not it's subdirectories

cpx() {
# run in subshell to avoid collisions
  (_CopyWithExclude "$@")
}

_CopyWithExclude() {
  case "$1" in
    -n|--dry-run) { DryRun='echo'; shift; } ;;
  esac

  from="$1"
  to="$2"
  exclude="$3"

  $DryRun mkdir -p "$to"

  if [ -z "$exclude" ]; then
      cp "$from" "$to"
      return
  fi

  ls -A1 "$from" \
    | while IFS= read -r f; do
        unset excluded
        if [ -n "$exclude" ]; then
          for x in $(printf "$exclude"); do
          if [ "$f" = "$x" ]; then
              excluded=1
              break
          fi
          done
        fi
        f="${f#$from/}"
        if [ -z "$excluded" ]; then
          $DryRun cp -R "$f" "$to"
        else
          [ -n "$DryRun" ] && echo "skip '$f'"
        fi
      done
}

# Do not execute if being sourced
[ "${0#*cpx}" != "$0" ] && cpx "$@"

Example usage

EXCLUDE="
.git
my_secret_stuff
"
cpr "$HOME/my_stuff" "/media/usb" "$EXCLUDE"

How to declare an array inside MS SQL Server Stored Procedure?

Great question and great idea, but in SQL you'll need to do this:

For data type datetime, something like this-

declare @BeginDate    datetime = '1/1/2016',
        @EndDate      datetime = '12/1/2016'
create table #months (dates datetime)
declare @var datetime = @BeginDate
   while @var < dateadd(MONTH, +1, @EndDate)
   Begin
          insert into #months Values(@var)
          set @var = Dateadd(MONTH, +1, @var)
   end

If all you really want is numbers, do this-

create table #numbas (digit int)
declare @var int = 1        --your starting digit
    while @var <= 12        --your ending digit
    begin
        insert into #numbas Values(@var)
        set @var = @var +1
    end

Where can I find MySQL logs in phpMyAdmin?

In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.

What is difference between Lightsail and EC2?

Testing¹ reveals that Lightsail instances in fact are EC2 instances, from the t2 class of burstable instances.

EC2, of course, has many more instance families and classes other than the t2, almost all of which are more "powerful" (or better equipped for certain tasks) than these, but also much more expensive. But for meaningful comparisons, the 512 MiB Lightsail instance appears to be completely equivalent in specifications to the similarly-priced t2.nano, the 1GiB is a t2.micro, the 2 GiB is a t2.small, etc.

Lightsail is a lightweight, simplified product offering -- hard disks are fixed size EBS SSD volumes, instances are still billable when stopped, security group rules are much less flexible, and only a very limited subset of EC2 features and options are accessible.

It also has a dramatically simplified console, and even though the machines run in EC2, you can't see them in the EC2 section of the AWS console. The instances run in a special VPC, but this aspect is also provisioned automatically, and invisible in the console. Lightsail supports optionally peering this hidden VPC with your default VPC in the same AWS region, allowing Lightsail instances to access services like EC2 and RDS in the default VPC within the same AWS account.²

Bandwidth is unlimited, but of course free bandwidth is not -- however, Lightsail instances do include a significant monthly bandwidth allowance before any bandwidth-related charges apply.³ Lightsail also has a simplified interface to Route 53 with limited functionality.

But if those sound like drawbacks, they aren't. The point of Lightsail seems to be simplicity. The flexibility of EC2 (and much of AWS) leads inevitably to complexity. The target market for Lightsail appears to be those who "just want a simple VPS" without having to navigate the myriad options available in AWS services like EC2, EBS, VPC, and Route 53. There is virtually no learning curve, here. You don't even technically need to know how to use SSH with a private key -- the Lightsail console even has a built-in SSH client -- but there is no requirement that you use it. You can access these instances normally, with a standard SSH client.


¹Lightsail instances, just like "regular" EC2 (VPC and Classic) instances, have access to the instance metadata service, which allows an instance to discover things about itself, such as its instance type and availability zone. Lightsail instances are identified in the instance metadata as t2 machines.

²The Lightsail docs are not explicit about the fact that peering only works with your Default VPC, but this appears to be the case. If your AWS account was created in 2013 or before, then you may not actually have a VPC with the "Default VPC" designation. This can be resolved by submitting a support request, as I explained in Can't establish VPC peering connection from Amazon Lightsail (at Server Fault).

³The bandwidth allowance applies to both inbound and outbound traffic; after this total amount of traffic is exceeded, inbound traffic continues to be free, but outbound traffic becomes billable. See "What does data transfer cost?" in the Lightsail FAQ.

startsWith() and endsWith() functions in PHP

If speed is important for you, try this.(I believe it is the fastest method)

Works only for strings and if $haystack is only 1 character

function startsWithChar($needle, $haystack)
{
   return ($needle === $haystack[0]);
}

function endsWithChar($needle, $haystack)
{
   return ($needle === $haystack[strlen($haystack) - 1]);
}

$str='|apples}';
echo startsWithChar('|',$str); //Returns true
echo endsWithChar('}',$str); //Returns true
echo startsWithChar('=',$str); //Returns false
echo endsWithChar('#',$str); //Returns false

How to get subarray from array?

Take a look at Array.slice(begin, end)

_x000D_
_x000D_
const ar  = [1, 2, 3, 4, 5];

// slice from 1..3 - add 1 as the end index is not included

const ar2 = ar.slice(1, 3 + 1);

console.log(ar2);
_x000D_
_x000D_
_x000D_

How to pad a string to a fixed length with spaces in Python?

First check to see if the string's length needs to be shortened, then add spaces until it is as long as the field length.

fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
    rand += " "

jquery UI dialog: how to initialize without a title bar?

I like overriding jQuery widgets.

(function ($) {
    $.widget("sauti.dialog", $.ui.dialog, {
        options: {
            headerVisible: false
        },
        _create: function () {
            // ready to generate button
            this._super("_create"); // for 18 would be $.Widget.prototype._create.call(this);
            // decide if header is visible
            if(this.options.headerVisible == false)
                this.uiDialogTitlebar.hide();
        },
        _setOption: function (key, value) {
            this._super(key, value); // for 1.8 would be $.Widget.prototype._setOption.apply( this, arguments );
            if (key === "headerVisible") {
                if (key == false)
                    this.uiDialogTitlebar.hide();
                else
                    this.uiDialogTitlebar.show();
                return;
            }
        }
    });
})(jQuery);

So you can now setup if you want to show title bar or not

   $('#mydialog').dialog({
      headerVisible: false // or true
});

What is the difference between syntax and semantics in programming languages?

Syntax: It is referring to grammatically structure of the language.. If you are writing the c language . You have to very care to use of data types, tokens [ it can be literal or symbol like "printf()". It has 3 tokes, "printf, (, )" ]. In the same way, you have to very careful, how you use function, function syntax, function declaration, definition, initialization and calling of it.

While semantics, It concern to logic or concept of sentence or statements. If you saying or writing something out of concept or logic, then you are semantically wrong.

Difference between h:button and h:commandButton

Here is what the JSF javadocs have to say about the commandButton action attribute:

MethodExpression representing the application action to invoke when this component is activated by the user. The expression must evaluate to a public method that takes no parameters, and returns an Object (the toString() of which is called to derive the logical outcome) which is passed to the NavigationHandler for this application.

It would be illuminating to me if anyone can explain what that has to do with any of the answers on this page. It seems pretty clear that action refers to some page's filename and not a method.

How to use multiple databases in Laravel

In Laravel 5.1, you specify the connection:

$users = DB::connection('foo')->select(...);

Default, Laravel uses the default connection. It is simple, isn't it?

Read more here: http://laravel.com/docs/5.1/database#accessing-connections

hide div tag on mobile view only?

Set the display property to none as the default, then use a media query to apply the desired styles to the div when the browser reaches a certain width. Replace 768px in the media query with whatever the minimum px value is where your div should be visible.

#title_message {
    display: none;
}

@media screen and (min-width: 768px) {
    #title_message {
        clear: both;
        display: block;
        float: left;
        margin: 10px auto 5px 20px;
        width: 28%;
    }
}

how to use DEXtoJar

Follow the below steps to do so_

  1. Rename your APK file(e.g., rename your APK file to .zip Ex- test.apk -> test.zip) & extract resultant zip file.
  2. Copy your .dex file in to dex2jar folder.
  3. Run setclasspath.bat. This should be run because this data is used in the next step.
  4. Go to Windows Command prompt, change the folder path to the path of your dex2jar folder and run the command as follows: d2j-dex2jar.bat classes.dex
  5. enjoy!! Your jar file will be ready in the same folder with name classes_dex2jar.jar.

Hope this helps you and All reading this... :)

Force browser to download image files on click

In 2020 I use Blob to make local copy of image, which browser will download as a file. You can test it on this site.

enter image description here

(function(global) {
  const next = () => document.querySelector('.search-pagination__button-text').click();
  const uuid = () => Math.random().toString(36).substring(7);
  const toBlob = (src) => new Promise((res) => {
    const img = document.createElement('img');
    const c = document.createElement("canvas");
    const ctx = c.getContext("2d");
    img.onload = ({target}) => {
      c.width = target.naturalWidth;
      c.height = target.naturalHeight;
      ctx.drawImage(target, 0, 0);
      c.toBlob((b) => res(b), "image/jpeg", 0.75);
    };
    img.crossOrigin = "";
    img.src = src;
  });
  const save = (blob, name = 'image.png') => {
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.target = '_blank';
    a.download = name;
    a.click();
  };
  global.download = () => document.querySelectorAll('.search-content__gallery-results figure > img[src]').forEach(async ({src}) => save(await toBlob(src), `${uuid()}.png`));
  global.next = () => next();
})(window);

How can I center <ul> <li> into div

This is a better way to center UL's inside of any DIV container.

This CSS solution does not use Width and Float properties. Float:Left and Width: 70%, will cause you headaches when you need to duplicate your menu on different pages with different menu items.

Instead of using width, we use padding and margin to determine the space around the text/menu item. Also, instead of using Float:Left in the LI element, use display:inline-block.

By floating your LI left, you literally float your content to the left and then you must use one of the Hacks mentioned above to center your UL. Display:inline-block creates your Float property for you (sort of). It takes your LI element and turns it into a block element that lays side by side each other (not floating).

With Responsive design and using frameworks like Bootstrap or Foundation, there will be issues when trying to float and center content. They have some built-in classes, but it's always better to do it from scratch. This solution is much better for dynamic menus (Such as Adobe Business Catalyst menu system).

Reference for this tutorial can be found at: http://html-tuts.com/center-div-image-table-ul-inside-div/

HTML

<div class="container">
        <ul>
            <li><a href="#">Button</a></li>
            <li><a href="#">Button</a></li>
            <li><a href="#">Button</a></li>
            <li><a href="#">Button</a></li>
            <li><a href="#">Button</a></li>
        </ul>
    </div>

CSS

.container {
    text-align: center;
    border: 1px solid green;
}
.container ul {
    border: 2px solid red;
    display: inline-block;
    margin: 10px 0;
    padding: 2px;
}
.container li {
    display: inline-block;
}
.container li a {
    display: inline-block;
    background: #444;
    color: #FFF;
    padding: 5px;
    text-decoration: none;
}

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

What does this format means T00:00:00.000Z?

i suggest you use moment.js for this. In moment.js you can:

var localTime = moment().format('YYYY-MM-DD'); // store localTime
var proposedDate = localTime + "T00:00:00.000Z";

now that you have the right format for a time, parse it if it's valid:

var isValidDate = moment(proposedDate).isValid();
// returns true if valid and false if it is not.

and to get time parts you can do something like:

var momentDate = moment(proposedDate)
var hour = momentDate.hours();
var minutes = momentDate.minutes();
var seconds = momentDate.seconds();

// or you can use `.format`:
console.log(momentDate.format("YYYY-MM-DD hh:mm:ss A Z"));

More info about momentjs http://momentjs.com/

How to clear cache of Eclipse Indigo

It's very simple. Right click inside the internal browser and click "refresh".

Static Initialization Blocks

static block is used for any technology to initialize static data member in dynamic way,or we can say for the dynamic initialization of static data member static block is being used..Because for non static data member initialization we have constructor but we do not have any place where we can dynamically initialize static data member

Eg:-class Solution{
         // static int x=10;
           static int x;
       static{
        try{
          x=System.out.println();
          }
         catch(Exception e){}
        }
       }

     class Solution1{
      public static void main(String a[]){
      System.out.println(Solution.x);
        }
        }

Now my static int x will initialize dynamically ..Bcoz when compiler will go to Solution.x it will load Solution Class and static block load at class loading time..So we can able to dynamically initialize that static data member..

}

How to create a listbox in HTML without allowing multiple selection?

For Asp.Net MVC

@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList, 
 new { 
 @class = "chosen-select form-control"
 }) 

or

  @Html.ListBoxFor(model => model.parameterName,
  ViewBag.ParameterValueList as MultiSelectList,
   new{
       data_placeholder = "Select Options ",
       @class = "chosen-select form-control"
   })

SQL Server ORDER BY date and nulls last

If your SQL doesn't support NULLS FIRST or NULLS LAST, the simplest way to do this is to use the value IS NULL expression:

ORDER BY Next_Contact_Date IS NULL, Next_Contact_Date

to put the nulls at the end (NULLS LAST) or

ORDER BY Next_Contact_Date IS NOT NULL, Next_Contact_Date

to put the nulls at the front. This doesn't require knowing the type of the column and is easier to read than the CASE expression.

EDIT: Alas, while this works in other SQL implementations like PostgreSQL and MySQL, it doesn't work in MS SQL Server. I didn't have a SQL Server to test against and relied on Microsoft's documentation and testing with other SQL implementations. According to Microsoft, value IS NULL is an expression that should be usable just like any other expression. And ORDER BY is supposed to take expressions just like any other statement that takes an expression. But it doesn't actually work.

The best solution for SQL Server therefore appears to be the CASE expression.

How to access PHP session variables from jQuery function in a .js file?

This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.

Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.

createCookie = function(name, value, days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
}
else var expires = "";

document.cookie = name + "=" + value + expires + "; path=/";
}

readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
   createCookie(name, "", -1);
}

To call them you need to create a small PHP function, normally as part of your support library, as follows:

<?php
 function createjavaScriptCookie($sessionVarible) {
 $s =  "<script>";
 $s = $s.'createCookie('. '"'. $sessionVarible                 
 .'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
 $s = $s."</script>";
 echo $s;
}
?>

So to use all you now have to include within your index.php file is

$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");

Now in your javascript library.js you can recover the cookie with the following code:

var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';

I hope this helps.

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Convert Substring (Swift 3) to String Slicing (Swift 4)

Examples In Swift 3, 4:

let newStr = str.substring(to: index) // Swift 3
let newStr = String(str[..<index]) // Swift 4

let newStr = str.substring(from: index) // Swift 3
let newStr = String(str[index...]) // Swift 4 

let range = firstIndex..<secondIndex // If you have a range
let newStr = = str.substring(with: range) // Swift 3
let newStr = String(str[range])  // Swift 4

Running npm command within Visual Studio Code

VSCode User Setup is a new installer which installs VSCode and its dependencies in directories which don't require system-level / administrator permissions to modify. This is because New VSCode runs with user privileges. Your Nodejs installation added npm's path as System variable which VSCode cannot read.

Adding NPM path to Path variable in the User variable, you will be able to run NPM from the integrated command line.

How do I force Postgres to use a particular index?

Check your random_page_cost

This problem typically happens when the estimated cost of an index scan is too high and doesn't correctly reflect reality. You may need to lower the random_page_cost configuration parameter to fix this. From the Postgres documentation:

Reducing this value [...] will cause the system to prefer index scans; raising it will make index scans look relatively more expensive.

You can do a quick test whether this will actually make Postgres use the index:

EXPLAIN <query>;              # Uses sequential scan
SET random_page_cost = 1;
EXPLAIN <query>;              # May use index scan now

You can restore the default value with SET random_page_cost = DEFAULT; again.

Background

Index scans require non-sequential disk page fetches. Postgres uses random_page_cost to estimate the cost of such non-sequential fetches in relation to sequential fetches. The default value is 4.0, thus assuming an average cost factor of 4 compared to sequential fetches (taking caching effects into account).

The problem however is that this default value is unsuitable in the following important real-life scenarios:

1) Solid-state drives

As per the documentation:

Storage that has a low random read cost relative to sequential, e.g. solid-state drives, might be better modeled with a lower value for random_page_cost, e.g., 1.1.

This slide from a speak at PostgresConf 2018 also says that random_page_cost should be set to something between 1.0 and 2.0 for solid-state drives.

2) Cached data

If the required index data is already cached in RAM, an index scan will always be significantly faster than a sequential scan. The documentation says:

If your data is likely to be completely in cache, [...] decreasing random_page_cost can be appropriate.

The problem is that you of course can't easily know whether the relevant data is already cached. However, if a specific index is frequently used, and if the system has sufficient RAM, then data is likely to be cached eventually, and random_page_cost should be set to a lower value. You'll have to experiment with different values and see what works for you.

You might also want to use the pg_prewarm extension for explicit data caching.


String concatenation in MySQL

Try:

select concat(first_name,last_name) as "Name" from test.student

or, better:

select concat(first_name," ",last_name) as "Name" from test.student

ImportError: No module named pandas

I fixed the same problem with the below commands... Type python on your terminal. If you see python version 2.x then run these two commands to install pandas:

sudo python -m pip install wheel

and

sudo python -m pip install pandas

Else if you see python version 3.x then run these two commands to install pandas:

sudo python3 -m pip install wheel

and

sudo python3 -m pip install pandas

Good Luck!

Load an image from a url into a PictureBox

yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"

Oracle comparing timestamp with date

You can truncate the date part:

select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')

The trouble with this approach is that any index on field1 wouldn't be used due to the function call.

Alternatively (and more index friendly)

select * from table1 
 where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD') 
   and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')

How to parse JSON data with jQuery / JavaScript?

Setting dataType:'json' will parse JSON for you:

$.ajax({
  type: 'GET',
  url: 'http://example/functions.php',
  data: {get_param: 'value'},
  dataType: 'json',
  success: function (data) {
    var names = data
    $('#cand').html(data);
  }
});

Or else you can use parseJSON:

var parsedJson = $.parseJSON(jsonToBeParsed);

Then you can iterate the following:

var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';

...by using $().each:

var json = $.parseJSON(j);
$(json).each(function (i, val) {
  $.each(val, function (k, v) {
    console.log(k + " : " + v);
  });
}); 

JSFiddle

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

For CGSize

CGSize(width: self.view.frame.width * 3, height: self.view.frame.size.height)

How to put php inside JavaScript?

As others have pointed out you need the quotes, but I just want to point out that there's a shorthand method of writing this same line of code

var htmlString="<?=$htmlString?>";

See you can leave out the "php echo" stuff and replace it with a simple "=".

mailto link multiple body lines

You can use URL encoding to encode the newline as %0A.

mailto:[email protected]?subject=test&body=type%20your%0Amessage%20here

While the above appears to work in many cases, user olibre points out that the RFC governing the mailto URI scheme specifies that %0D%0A (carriage return + line feed) should be used instead of %0A (line feed). See also: Newline Representations.

What is a None value?

largest=none
smallest =none 
While True :
          num =raw_input ('enter a number ') 
          if num =="done ": break 
          try :
           inp =int (inp) 
          except:
              Print'Invalid input' 
           if largest is none :
               largest=inp
           elif inp>largest:
                largest =none 
           print 'maximum', largest

          if smallest is none:
               smallest =none
          elif inp<smallest :
               smallest =inp
          print 'minimum', smallest 

print 'maximum, minimum, largest, smallest 

What does int argc, char *argv[] mean?

argv and argc are how command line arguments are passed to main() in C and C++.

argc will be the number of strings pointed to by argv. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.

The variables are named argc (argument count) and argv (argument vector) by convention, but they can be given any valid identifier: int main(int num_args, char** arg_strings) is equally valid.

They can also be omitted entirely, yielding int main(), if you do not intend to process command line arguments.

Try the following program:

#include <iostream>

int main(int argc, char** argv) {
    std::cout << "Have " << argc << " arguments:" << std::endl;
    for (int i = 0; i < argc; ++i) {
        std::cout << argv[i] << std::endl;
    }
}

Running it with ./test a1 b2 c3 will output

Have 4 arguments:
./test
a1
b2
c3

Apple Cover-flow effect using jQuery or other library?

http://www.jacksasylum.eu/ContentFlow/

  • is the best I ever found. a true 'CoverFlow', highly configurable, cross-browser, very smooth action, has relections and supports scroll wheel + keyboard control. - has to be what your looking for!

Using group by on two fields and count in SQL

You must group both columns, group and sub-group, then use the aggregate function COUNT().

SELECT
  group, subgroup, COUNT(*)
FROM
  groups
GROUP BY
  group, subgroup

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

In Mycase
In mongodb version 2.6.11 default databse directory is /var/lib/mongodb/

  1. $ sudo chown -R id -u /var/lib/mongodb/

  2. $ sudo chown -R id -u /var/lib/mongodb/mongod.lock

  3. $ sudo /etc/init.d/mongod stop

  4. $ sudo /etc/init.d/mongod start

How to move certain commits to be based on another branch in git?

This is a classic case of rebase --onto:

 # let's go to current master (X, where quickfix2 should begin)
 git checkout master

 # replay every commit *after* quickfix1 up to quickfix2 HEAD.
 git rebase --onto master quickfix1 quickfix2 

So you should go from

o-o-X (master HEAD)
     \ 
      q1a--q1b (quickfix1 HEAD)
              \
               q2a--q2b (quickfix2 HEAD)

to:

      q2a'--q2b' (new quickfix2 HEAD)
     /
o-o-X (master HEAD)
     \ 
      q1a--q1b (quickfix1 HEAD)

This is best done on a clean working tree.
See git config --global rebase.autostash true, especially after Git 2.10.

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

How to remove undefined and null values from an object using lodash?

With lodash (or underscore) You may do

var my_object = { a:undefined, b:2, c:4, d:undefined, e:null };

var passedKeys = _.reject(Object.keys(my_object), function(key){ return _.isUndefined(my_object[key]) || _.isNull(my_object[key]) })

newObject = {};
_.each(passedKeys, function(key){
    newObject[key] = my_object[key];
});

Otherwise, with vanilla JavaScript, you can do

var my_object = { a:undefined, b:2, c:4, d:undefined };
var new_object = {};

Object.keys(my_object).forEach(function(key){
    if (typeof my_object[key] != 'undefined' && my_object[key]!=null){
        new_object[key] = my_object[key];
    }
});

Not to use a falsey test, because not only "undefined" or "null" will be rejected, also is other falsey value like "false", "0", empty string, {}. Thus, just to make it simple and understandable, I opted to use explicit comparison as coded above.

How to pretty print XML from Java?

Kevin Hakanson said: "However, if you know your XML string is valid, and you don't want to incur the memory overhead of parsing a string into a DOM, then running a transform over the DOM to get a string back - you could just do some old fashioned character by character parsing. Insert a newline and spaces after every characters, keep and indent counter (to determine the number of spaces) that you increment for every <...> and decrement for every you see."

Agreed. Such an approach is much faster and has far fewer dependencies.

Example solution:

/**
 * XML utils, including formatting.
 */
public class XmlUtils
{
  private static XmlFormatter formatter = new XmlFormatter(2, 80);

  public static String formatXml(String s)
  {
    return formatter.format(s, 0);
  }

  public static String formatXml(String s, int initialIndent)
  {
    return formatter.format(s, initialIndent);
  }

  private static class XmlFormatter
  {
    private int indentNumChars;
    private int lineLength;
    private boolean singleLine;

    public XmlFormatter(int indentNumChars, int lineLength)
    {
      this.indentNumChars = indentNumChars;
      this.lineLength = lineLength;
    }

    public synchronized String format(String s, int initialIndent)
    {
      int indent = initialIndent;
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < s.length(); i++)
      {
        char currentChar = s.charAt(i);
        if (currentChar == '<')
        {
          char nextChar = s.charAt(i + 1);
          if (nextChar == '/')
            indent -= indentNumChars;
          if (!singleLine)   // Don't indent before closing element if we're creating opening and closing elements on a single line.
            sb.append(buildWhitespace(indent));
          if (nextChar != '?' && nextChar != '!' && nextChar != '/')
            indent += indentNumChars;
          singleLine = false;  // Reset flag.
        }
        sb.append(currentChar);
        if (currentChar == '>')
        {
          if (s.charAt(i - 1) == '/')
          {
            indent -= indentNumChars;
            sb.append("\n");
          }
          else
          {
            int nextStartElementPos = s.indexOf('<', i);
            if (nextStartElementPos > i + 1)
            {
              String textBetweenElements = s.substring(i + 1, nextStartElementPos);

              // If the space between elements is solely newlines, let them through to preserve additional newlines in source document.
              if (textBetweenElements.replaceAll("\n", "").length() == 0)
              {
                sb.append(textBetweenElements + "\n");
              }
              // Put tags and text on a single line if the text is short.
              else if (textBetweenElements.length() <= lineLength * 0.5)
              {
                sb.append(textBetweenElements);
                singleLine = true;
              }
              // For larger amounts of text, wrap lines to a maximum line length.
              else
              {
                sb.append("\n" + lineWrap(textBetweenElements, lineLength, indent, null) + "\n");
              }
              i = nextStartElementPos - 1;
            }
            else
            {
              sb.append("\n");
            }
          }
        }
      }
      return sb.toString();
    }
  }

  private static String buildWhitespace(int numChars)
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < numChars; i++)
      sb.append(" ");
    return sb.toString();
  }

  /**
   * Wraps the supplied text to the specified line length.
   * @lineLength the maximum length of each line in the returned string (not including indent if specified).
   * @indent optional number of whitespace characters to prepend to each line before the text.
   * @linePrefix optional string to append to the indent (before the text).
   * @returns the supplied text wrapped so that no line exceeds the specified line length + indent, optionally with
   * indent and prefix applied to each line.
   */
  private static String lineWrap(String s, int lineLength, Integer indent, String linePrefix)
  {
    if (s == null)
      return null;

    StringBuilder sb = new StringBuilder();
    int lineStartPos = 0;
    int lineEndPos;
    boolean firstLine = true;
    while(lineStartPos < s.length())
    {
      if (!firstLine)
        sb.append("\n");
      else
        firstLine = false;

      if (lineStartPos + lineLength > s.length())
        lineEndPos = s.length() - 1;
      else
      {
        lineEndPos = lineStartPos + lineLength - 1;
        while (lineEndPos > lineStartPos && (s.charAt(lineEndPos) != ' ' && s.charAt(lineEndPos) != '\t'))
          lineEndPos--;
      }
      sb.append(buildWhitespace(indent));
      if (linePrefix != null)
        sb.append(linePrefix);

      sb.append(s.substring(lineStartPos, lineEndPos + 1));
      lineStartPos = lineEndPos + 1;
    }
    return sb.toString();
  }

  // other utils removed for brevity
}

How do I remove the file suffix and path portion from a path string in Bash?

Here's how to do it with the # and % operators in Bash.

$ x="/foo/fizzbuzz.bar"
$ y=${x%.bar}
$ echo ${y##*/}
fizzbuzz

${x%.bar} could also be ${x%.*} to remove everything after a dot or ${x%%.*} to remove everything after the first dot.

Example:

$ x="/foo/fizzbuzz.bar.quux"
$ y=${x%.*}
$ echo $y
/foo/fizzbuzz.bar
$ y=${x%%.*}
$ echo $y
/foo/fizzbuzz

Documentation can be found in the Bash manual. Look for ${parameter%word} and ${parameter%%word} trailing portion matching section.

How to use a jQuery plugin inside Vue

Suppose you have Vue project created with vue-cli (e.g. vue init webpack my-project). Go to project dir and run

npm install jquery --save

Open file build/webpack.base.conf.js and add plugins:

module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jquery: 'jquery',
      'window.jQuery': 'jquery',
      jQuery: 'jquery'
    })
  ]
  ...
}

Also at top of file add:

const webpack = require('webpack')

If you are using ESLint, open .eslintrc.js and add next globals: {

module.exports = {
  globals: {
    "$": true,
    "jQuery": true
  },
  ...

Now you are ready to go. Use $ anywhere in your js.

NOTE You don't need to include expose loader or any other stuff to use this.

Originally from https://maketips.net/tip/223/how-to-include-jquery-into-vuejs

Passing properties by reference in C#

To vote on this issue, here is one active suggestion of how this could be added to the language. I'm not saying this is the best way to do this (at all), feel free to put out your own suggestion. But allowing properties to be passed by ref like Visual Basic already can do would hugely help simplify some code, and quite often!

https://github.com/dotnet/csharplang/issues/1235

Copying an array of objects into another array in javascript

Easy way to get this working is using:

var cloneArray = JSON.parse(JSON.stringify(originalArray));

I have issues with getting arr.concat() or arr.splice(0) to give a deep copy. Above snippet works perfectly.

How to adjust gutter in Bootstrap 3 grid system?

(Posted on behalf of the OP).

I believe I figured it out.

In my case, I added [class*="col-"] {padding: 0 7.5px;};.

Then added .row {margin: 0 -7.5px;}.

This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;} to .row {margin: 0 -8.5px;}, then it works perfectly.

I have no idea why there is a 1px margin. Maybe someone can explain it?

See the sample I created:

Demo
Code

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

I had this problem and it took me hours to figure out. The mainly reason of this error is the SoapClient cannot stream the web service file from the host. I uncommented this line "extension=php_openssl.dll" in my php.ini file and it works.

Check if a string contains another string

Building on Rene's answer, you could also write a function that returned either TRUE if the substring was present, or FALSE if it wasn't:

Public Function Contains(strBaseString As String, strSearchTerm As String) As Boolean
'Purpose: Returns TRUE if one string exists within another
On Error GoTo ErrorMessage
    Contains = InStr(strBaseString, strSearchTerm)
Exit Function
ErrorMessage:
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"
End
End Function

How to set focus on input field?

I've written a two-way binding focus directive, just like model recently.

You can use the focus directive like this:

<input focus="someFocusVariable">

If you make someFocusVariable scope variable true in anywhere in your controller, the input get focused. And if you want to "blur" your input then, someFocusVariable can be set to false. It's like Mark Rajcok's first answer but with two-way binding.

Here is the directive:

function Ctrl($scope) {
  $scope.model = "ahaha"
  $scope.someFocusVariable = true; // If you want to focus initially, set this to true. Else you don't need to define this at all.
}

angular.module('experiement', [])
  .directive('focus', function($timeout, $parse) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
          scope.$watch(attrs.focus, function(newValue, oldValue) {
              if (newValue) { element[0].focus(); }
          });
          element.bind("blur", function(e) {
              $timeout(function() {
                  scope.$apply(attrs.focus + "=false"); 
              }, 0);
          });
          element.bind("focus", function(e) {
              $timeout(function() {
                  scope.$apply(attrs.focus + "=true");
              }, 0);
          })
      }
    }
  });

Usage:

<div ng-app="experiement">
  <div ng-controller="Ctrl">
    An Input: <input ng-model="model" focus="someFocusVariable">
    <hr>
        <div ng-click="someFocusVariable=true">Focus!</div>  
        <pre>someFocusVariable: {{ someFocusVariable }}</pre>
        <pre>content: {{ model }}</pre>
  </div>
</div>

Here is the fiddle:

http://fiddle.jshell.net/ubenzer/9FSL4/8/

Running ASP.Net on a Linux based server

Now a days .Net is run in multiple platforms,like linux ,Mac os etc. but mono is not fully platform independent ,Because to deploy .NET in another OS required third party software.so it is not like java platform independent.

Mono is running in different platform ,because of JIT is there in different os.

Mono is not fully success in moonlight(silver light in .NET) .Not only Research is going on.

Mono uses XSP2 server or apache . some of the big companies are using this project,Some of the robotic project are also running on mono.

For more details http://www.mono-project.com/Main_Page.

Gson: How to exclude specific fields from Serialization without annotations

I'm working just by putting the @Expose annotation, here my version that I use

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

In Model class:

@Expose
int number;

public class AdapterRestApi {

In the Adapter class:

public EndPointsApi connectRestApi() {
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(90000, TimeUnit.SECONDS)
            .readTimeout(90000,TimeUnit.SECONDS).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ConstantRestApi.ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    return retrofit.create  (EndPointsApi.class);
}

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

1: Create a class WebMvcConfig and extend it as shown from the WebMvcConfiguration and override addCorsMappings method.

2: Most importantly don't forget to make it @Configuration annotation because it should be loaded with Main Spring class to allow Cross-Origin.

  @Configuration
    public class WebMvcCofig implements WebMvcConfigurer{
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/*")
                    .allowedOrigins("*")
                    .allowedMethods("*")
                    .allowedHeaders("*")
                    .allowCredentials(true);
        }
    }

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

Remove leading or trailing spaces in an entire column of data

If it's the same number of characters at the beginning of the cell each time, you can use the text to columns command and select the fixed width option to chop the cell data into two columns. Then just delete the unwanted stuff in the first column.

How to display HTML <FORM> as inline element?

Move your form tag just outside the paragraph and set margins / padding to zero:

<form style="margin: 0; padding: 0;">
  <p>
    Read this sentence 
    <input style="display: inline;" type="submit" value="or push this button" />
  </p>
</form>

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

if you are using maven:

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

Spring @Value is not resolving to value from property file

I was using spring boot, and for me upgrading the version from 1.4.0.RELEASE to 1.5.6.RELEASE solved this issue.

npm WARN package.json: No repository field

Yes, probably you can re/create one by including -f at the end of your command

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

How to change package name in android studio?

It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:

  1. right click on the root folder of your project.
  2. Click "Open Module Setting".
  3. Go to the Flavours tab.
  4. Change the applicationID to whatever package name you want. Press OK.

What is the difference between a data flow diagram and a flow chart?

A flow chart details the processes to follow. A DFD details the flow of data through a system.

In a flow chart, the arrows represent transfer of control (not data) between elements and the elements are instructions or decision (or I/O, etc).

In a DFD, the arrows are actually data transfer between the elements, which are themselves parts of a system.

Wikipedia has a good article on DFDs here.

Histogram Matplotlib

If you're willing to use pandas:

pandas.DataFrame({'x':hist[1][1:],'y':hist[0]}).plot(x='x',kind='bar')

How to set a Default Route (To an Area) in MVC

routes.MapRoute(
                "Area",
                "{area}/",
                new { area = "AreaZ", controller = "ControlerX ", action = "ActionY " }
            );

Have you tried that ?

Eclipse: How to install a plugin manually?

  1. Download your plugin
  2. Open Eclipse
  3. From the menu choose: Help / Install New Software...
  4. Click the Add button
  5. In the Add Repository dialog that appears, click the Archive button next to the Location field
  6. Select your plugin file, click OK

You could also just copy plugins to the eclipse/plugins directory, but it's not recommended.

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

Cannot find pkg-config error

For Ubuntu/Debian OS,

apt-get install -y pkg-config

For Redhat/Yum OS,

yum install -y pkgconfig

For Archlinux OS,

pacman -S pkgconf

Should IBOutlets be strong or weak under ARC?

The current recommended best practice from Apple is for IBOutlets to be strong unless weak is specifically needed to avoid a retain cycle. As Johannes mentioned above, this was commented on in the "Implementing UI Designs in Interface Builder" session from WWDC 2015 where an Apple Engineer said:

And the last option I want to point out is the storage type, which can either be strong or weak. In general you should make your outlet strong, especially if you are connecting an outlet to a subview or to a constraint that's not always going to be retained by the view hierarchy. The only time you really need to make an outlet weak is if you have a custom view that references something back up the view hierarchy and in general that's not recommended.

I asked about this on Twitter to an engineer on the IB team and he confirmed that strong should be the default and that the developer docs are being updated.

https://twitter.com/_danielhall/status/620716996326350848 https://twitter.com/_danielhall/status/620717252216623104

%Like% Query in spring JpaRepository

Try this.

@Query("Select c from Registration c where c.place like '%'||:place||'%'")

Laravel - Model Class not found

For me it was really silly I had created a ModelClass file without the .php extension. So calling that was giving model not found. So check the extension has .php

Is there a way to access an iteration-counter in Java's for-each loop?

Idiomatic Solution:

final Set<Double> doubles; // boilerplate
final Iterator<Double> iterator = doubles.iterator();
for (int ordinal = 0; iterator.hasNext(); ordinal++)
{
    System.out.printf("%d:%f",ordinal,iterator.next());
    System.out.println();
}

this is actually the solution that Google suggests in the Guava discussion on why they did not provide a CountingIterator.

How to count how many values per level in a given factor?

Or using the dplyr library:

library(dplyr)
set.seed(1)
dat <- data.frame(ID = sample(letters,100,rep=TRUE))
dat %>% 
  group_by(ID) %>%
  summarise(no_rows = length(ID))

Note the use of %>%, which is similar to the use of pipes in bash. Effectively, the code above pipes dat into group_by, and the result of that operation is piped into summarise.

The result is:

Source: local data frame [26 x 2]

   ID no_rows
1   a       2
2   b       3
3   c       3
4   d       3
5   e       2
6   f       4
7   g       6
8   h       1
9   i       6
10  j       5
11  k       6
12  l       4
13  m       7
14  n       2
15  o       2
16  p       2
17  q       5
18  r       4
19  s       5
20  t       3
21  u       8
22  v       4
23  w       5
24  x       4
25  y       3
26  z       1

See the dplyr introduction for some more context, and the documentation for details regarding the individual functions.

Hibernate: hbm2ddl.auto=update in production?

I wouldn't risk it because you might end up losing data that should have been preserved. hbm2ddl.auto=update is purely an easy way to keep your dev database up to date.

Best way to check if object exists in Entity Framework?

If you don't want to execute SQL directly, the best way is to use Any(). This is because Any() will return as soon as it finds a match. Another option is Count(), but this might need to check every row before returning.

Here's an example of how to use it:

if (context.MyEntity.Any(o => o.Id == idToMatch))
{
    // Match!
}

And in vb.net

If context.MyEntity.Any(function(o) o.Id = idToMatch) Then
    ' Match!
End If

TS1086: An accessor cannot be declared in ambient context

I had this error when i deleted several components while the server was on(after running the ng serve command). Although i deleted the references from the routes component and module, it didnt solve the problem. Then i followed these steps:

  1. Ended the server
  2. Restored those files
  3. Ran the ng serve command (at this point it solved the error)
  4. Ended the server
  5. Deleted the components which previously led to the error
  6. Ran the ng serve command (At this point no error as well).

Open Facebook Page in Facebook App (if installed) on Android

I already have answered here and it's working for me, please refer this link https://stackoverflow.com/a/40133225/3636561

    String socailLink="https://www.facebook.com/kfc";
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String facebookUrl = Utils.getFacebookUrl(getActivity(), socailLink);
    if (facebookUrl == null || facebookUrl.length() == 0) {
        Log.d("facebook Url", " is coming as " + facebookUrl);
        return;
    }
    intent.setData(Uri.parse(facebookUrl));
    startActivity(intent);

please refer link to get rest part.

Assert that a method was called in a Python unit test

Yes if you are using Python 3.3+. You can use the built-in unittest.mock to assert method called. For Python 2.6+ use the rolling backport Mock, which is the same thing.

Here is a quick example in your case:

from unittest.mock import MagicMock
aw = aps.Request("nv1")
aw.Clear = MagicMock()
aw2 = aps.Request("nv2", aw)
assert aw.Clear.called

Force IE compatibility mode off using tags

If you're working with a page in the Intranet Zone, you may find that IE9 no matter what you do, is going into IE7 Compat mode.

This is due to the setting within IE Compatibility settings which says that all Intranet sites should run in compatibility mode. You can untick this via a group policy (or just plain unticking it in IE), or you can set the following:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

This works (as detailed in other answers), but may not initially appear so: it needs to come before the stylesheets are declared. If you don't, it is ignored.

Set the value of a variable with the result of a command in a Windows batch file

One needs to be somewhat careful, since the Windows batch command:

for /f "delims=" %%a in ('command') do @set theValue=%%a

does not have the same semantics as the Unix shell statement:

theValue=`command`

Consider the case where the command fails, causing an error.

In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.

In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.

To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:

set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a

Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.

How to change background color in the Notepad++ text editor?

Go to Settings -> Style Configurator

Select Theme: Choose whichever you like best (the top two are easiest to read by most people's preference)

Bootstrap 3.0 Popovers and tooltips

You have a syntax error in your script and, as noted by xXPhenom22Xx, you must instantiate the tooltip.

<script type="text/javascript">

    $(document).ready(function() {

        $('.btn-danger').tooltip();

    }); //END $(document).ready()

</script>

Note that I used your class "btn-danger". You can create a different class, or use an id="someidthatimakeup".

How to load all modules in a folder?

I have also encountered this problem and this was my solution:

import os

def loadImports(path):
    files = os.listdir(path)
    imps = []

    for i in range(len(files)):
        name = files[i].split('.')
        if len(name) > 1:
            if name[1] == 'py' and name[0] != '__init__':
               name = name[0]
               imps.append(name)

    file = open(path+'__init__.py','w')

    toWrite = '__all__ = '+str(imps)

    file.write(toWrite)
    file.close()

This function creates a file (in the provided folder) named __init__.py, which contains an __all__ variable that holds every module in the folder.

For example, I have a folder named Test which contains:

Foo.py
Bar.py

So in the script I want the modules to be imported into I will write:

loadImports('Test/')
from Test import *

This will import everything from Test and the __init__.py file in Test will now contain:

__all__ = ['Foo','Bar']

Difference between array_push() and $array[] =

You should always use $array[] if possible because as the box states there is no overhead for the function call. Thus it is a bit faster than the function call.

Block direct access to a file over http but allow php script access

How about custom module based .htaccess script (like its used in CodeIgniter)? I tried and it worked good in CodeIgniter apps. Any ideas to use it on other apps?

<IfModule authz_core_module>
    Require all denied
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

How do I use su to execute the rest of the bash script as that user?

It's not possible to change user within a shell script. Workarounds using sudo described in other answers are probably your best bet.

If you're mad enough to run perl scripts as root, you can do this with the $< $( $> $) variables which hold real/effective uid/gid, e.g.:

#!/usr/bin/perl -w
$user = shift;
if (!$<) {
    $> = getpwnam $user;
    $) = getgrnam $user;
} else {
    die 'must be root to change uid';
}
system('whoami');

How to convert string to boolean php

When working with JSON, I had to send a Boolean value via $_POST. I had a similar problem when I did something like:

if ( $_POST['myVar'] == true) {
    // do stuff;
}

In the code above, my Boolean was converted into a JSON string.

To overcome this, you can decode the string using json_decode():

//assume that : $_POST['myVar'] = 'true';
 if( json_decode('true') == true ) { //do your stuff; }

(This should normally work with Boolean values converted to string and sent to the server also by other means, i.e., other than using JSON.)

EditText, inputType values (xml)

You can use the properties tab in eclipse to set various values.

here are all the possible values

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

How to enable scrolling on website that disabled scrolling?

With Chrome, one way to automatically re-enable scrolling on a website is to download the Tampermonkey extension, then add this script (click "Install this script").

In general, if you have a URL for a script where the URL ends in .user.js and have Tampermonkey installed, you can paste it into Chrome's Omnibox to install the script. More ways to install scripts with Tampermonkey can be found here.

Calling a Fragment method from a parent Activity

I think the best is to check if fragment is added before calling method in fragment. Do something like this to avoid null exception.

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
if(fragment.isAdded()){
  fragment.<specific_function_name>(); 
}

Python argparse command line flags without arguments

As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look here (specifically store_true and store_false)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')

where action='store_true' implies default=False.

Conversely, you could haveaction='store_false', which implies default=True.

How can I get terminal output in python?

The easiest way is to use the library commands

import commands
print commands.getstatusoutput('echo "test" | wc')

How to not wrap contents of a div?

A combination of both float: left; white-space: nowrap; worked for me.

Each of them independently didn't accomplish the desired result.

What is the syntax for adding an element to a scala.collection.mutable.Map?

var test = scala.collection.mutable.Map.empty[String, String]
test("myKey") = "myValue"

Using grep to search for hex strings in a file

I just used this:

grep -c $'\x0c' filename

To search for and count a page control character in the file..

So to include an offset in the output:

grep -b -o $'\x0c' filename | less

I am just piping the result to less because the character I am greping for does not print well and the less displays the results cleanly. Output example:

21:^L
23:^L
2005:^L

Disable activity slide-in animation when launching new activity?

IMHO this answer here solve issue in the most elegant way..

Developer should create a style,

<style name="noAnimTheme" parent="android:Theme">
  <item name="android:windowAnimationStyle">@null</item>
</style>

then in manifest set it as theme for activity or whole application.

<activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
</activity>

Voila! Nice and easy..

P.S. credits to original author please

Is there a way to change the spacing between legend items in ggplot2?

Looks like the best approach (in 2018) is to use legend.key.size under the theme object. (e.g., see here).

#Set-up:
    library(ggplot2)
    library(gridExtra)

    gp <- ggplot(data = mtcars, aes(mpg, cyl, colour = factor(cyl))) +
        geom_point()

This is real easy if you are using theme_bw():

  gpbw <- gp + theme_bw()

#Change spacing size:

  g1bw <- gpbw + theme(legend.key.size = unit(0, 'lines'))
  g2bw <- gpbw + theme(legend.key.size = unit(1.5, 'lines'))
  g3bw <- gpbw + theme(legend.key.size = unit(3, 'lines'))

  grid.arrange(g1bw,g2bw,g3bw,nrow=3)

enter image description here

However, this doesn't work quite so well otherwise (e.g., if you need the grey background on your legend symbol):

  g1 <- gp + theme(legend.key.size = unit(0, 'lines'))
  g2 <- gp + theme(legend.key.size = unit(1.5, 'lines'))
  g3 <- gp + theme(legend.key.size = unit(3, 'lines'))

  grid.arrange(g1,g2,g3,nrow=3)

#Notice that the legend symbol squares get bigger (that's what legend.key.size does). 

#Let's [indirectly] "control" that, too:
  gp2 <- g3
  g4 <- gp2 + theme(legend.key = element_rect(size = 1))
  g5 <- gp2 + theme(legend.key = element_rect(size = 3))
  g6 <- gp2 + theme(legend.key = element_rect(size = 10))

  grid.arrange(g4,g5,g6,nrow=3)   #see picture below, left

Notice that white squares begin blocking legend title (and eventually the graph itself if we kept increasing the value).

  #This shows you why:
    gt <- gp2 + theme(legend.key = element_rect(size = 10,color = 'yellow' ))

enter image description here

I haven't quite found a work-around for fixing the above problem... Let me know in the comments if you have an idea, and I'll update accordingly!

  • I wonder if there is some way to re-layer things using $layers...

Add Custom Headers using HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
{
    const string WEBSERVICE_URL = "<<Web Service URL>>";
    try
    {
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "GET";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

What is the JUnit XML format specification that Hudson supports?

I've decided to post a new answer, because some existing answers are outdated or incomplete.

First of all: there is nothing like JUnit XML Format Specification, simply because JUnit doesn't produce any kind of XML or HTML report.

The XML report generation itself comes from the Ant JUnit task/ Maven Surefire Plugin/ Gradle (whichever you use for running your tests). The XML report format was first introduced by Ant and later adapted by Maven (and Gradle).

If somebody just needs an official XML format then:

  1. There exists a schema for a maven surefire-generated XML report and it can be found here: surefire-test-report.xsd.
  2. For an ant-generated XML there is a 3rd party schema available here (but it might be slightly outdated).

Hope it will help somebody.

Add or change a value of JSON key with jquery or javascript

var temp = data.oldKey; // or data['oldKey']
data.newKey = temp;
delete data.oldKey;

How to save an image to localStorage and display it on the next page?

To whoever also needs this problem solved:

Firstly, I grab my image with getElementByID, and save the image as a Base64. Then I save the Base64 string as my localStorage value.

bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);

Here is the function that converts the image to a Base64 string:

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Then, on my next page I created an image with a blank src like so:

<img src="" id="tableBanner" />

And straight when the page loads, I use these next three lines to get the Base64 string from localStorage, and apply it to the image with the blank src I created:

var dataImage = localStorage.getItem('imgData');
bannerImg = document.getElementById('tableBanner');
bannerImg.src = "data:image/png;base64," + dataImage;

Tested it in quite a few different browsers and versions, and it seems to work quite well.

MongoDB/Mongoose querying at a specific date?

Yeah, Date object complects date and time, so comparing it with just date value does not work.

You can simply use the $where operator to express more complex condition with Javascript boolean expression :)

db.posts.find({ '$where': 'this.created_on.toJSON().slice(0, 10) == "2012-07-14"' })

created_on is the datetime field and 2012-07-14 is the specified date.

Date should be exactly in YYYY-MM-DD format.

Note: Use $where sparingly, it has performance implications.

How to create dictionary and add key–value pairs dynamically?

You can use maps with Map, like this:

var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');

mysql: get record count between two date-time

select * from yourtable where created < now() and created > '2011-04-25 04:00:00'

How to parse a query string into a NameValueCollection in .NET

To do this without System.Web, without writing it yourself, and without additional NuGet packages:

  1. Add a reference to System.Net.Http.Formatting
  2. Add using System.Net.Http;
  3. Use this code:

    new Uri(uri).ParseQueryString()
    

https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx

How to sort alphabetically while ignoring case sensitive?

Here is an example to sort an array : Case-insensitive

import java.text.Collator;
import java.util.Arrays;

public class Main {
  public static void main(String args[]) {

    String[] myArray = new String[] { "A", "B", "b" };
    Arrays.sort(myArray, Collator.getInstance());

  System.out.println(Arrays.toString(myArray));

 }

}

/* Output:[A, b, B] */

Delete statement in SQL is very slow

Older topic but one still relevant. Another issue occurs when an index has become fragmented to the extent of becoming more of a problem than a help. In such a case, the answer would be to rebuild or drop and recreate the index and issuing the delete statement again.

How to install Python package from GitHub?

To install Python package from github, you need to clone that repository.

git clone https://github.com/jkbr/httpie.git

Then just run the setup.py file from that directory,

sudo python setup.py install

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

http://developers.facebook.com/docs/opengraph/using-app-tokens/

"An App Access Token does not expire unless you refresh the application secret through your app settings."

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")

Python MYSQL update statement

@Esteban Küber is absolutely right.

Maybe one additional hint for bloody beginners like me. If you speciify the variables with %s, you have to follow this principle for EVERY input value, which means for the SET-variables as well as for the WHERE-variables.

Otherwise, you will have to face a termination message like 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s WHERE'

how to set the background image fit to browser using html

Try This Code: It may help you

<html>
    <head>
<style>
    body
        {
            background:url('images/top-left.jpg') no-repeat center center fixed;
            background-size: cover;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            margin: 0;
            padding: 0;
        }

    </style>
</head>
    <body>
    <form action="LoginCheck.jsp"method="post">
    </br>Username:<input type="text" name="username">
    </br>Password:<input type="password" name="password">
    </br>
    <input type="submit" value="Submit">
    </form>
    </center> 
    </body>


</html>

How to include External CSS and JS file in Laravel 5

I have been making use of

<script type="text/javascript" src="{{ URL::asset('js/jquery.js') }}"></script> 
for javascript and 
     <link rel="stylesheet" href="{{ URL::asset('css/main.css') }}">
for css, this points to the public directory, so you need to keep your css and js files there.

What is the difference between Html.Hidden and Html.HiddenFor

Html.Hidden('name', 'value') creates a hidden tag with name = 'name' and value = 'value'.

Html.HiddenFor(x => x.nameProp) creates a hidden tag with a name = 'nameProp' and value = x.nameProp.

At face value these appear to do similar things, with one just more convenient than the other. But its actual value is for model binding. When MVC tries to associate the html to the model, it needs to have the name of the property, and for Html.Hidden, we chose 'name', and not 'nameProp', and thus the binding wouldn't work. You'd have to have a custom binding object, or get the values from the form data. If you are redisplaying the page, you'd have to set the model to the values again.

So you can use Html.Hidden, but if you get the name wrong, or if you change the property name in the model, the auto binding will fail when you submit the form. But by using a type checked expression, you'll get code completion, and when you change the property name, you will get a compile time error. And then you are guaranteed to have the correct name in the form.

One of the better features of MVC.

Android and setting width and height programmatically in dp units

I know this is an old question however I've found a much neater way of doing this conversion.

Java

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, getResources().getDisplayMetrics());

Kotlin

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65f, resources.displayMetrics)

SQL server ignore case in a where expression

In the default configuration of a SQL Server database, string comparisons are case-insensitive. If your database overrides this setting (through the use of an alternate collation), then you'll need to specify what sort of collation to use in your query.

SELECT * FROM myTable WHERE myField = 'sOmeVal' COLLATE SQL_Latin1_General_CP1_CI_AS

Note that the collation I provided is just an example (though it will more than likely function just fine for you). A more thorough outline of SQL Server collations can be found here.

incompatible character encodings: ASCII-8BIT and UTF-8

I had the same problem when parsing CSV files on Ruby 1.9.2 that were correctly parsed on Ruby 1.8. I found the answer here. When opening the CSV file with Ruby CSV module it is necessary to specify UTF-8 enconding as following:

CSV.foreach("file.txt", encoding: "UTF-8") do |row|
   # foo and bar correctly encoded
   foo, bar, ... = row
end

Get the filename of a fileupload in a document through JavaScript

Using code like this in a form I can capture the original source upload filename, copy it to a second simple input field. This is so user can provide an alternate upload filename in submit request since the file upload filename is immutable.

    <input type="file" id="imgup1" name="imagefile">
      onchange="document.getElementsByName('imgfn1')[0].value = document.getElementById('imgup1').value;">
    <input type="text" name="imgfn1" value="">

How do you copy and paste into Git Bash

Press Insert.

Also, to copy from the window, try clicking the console's window icon (topleft) and choosing Edit -> Mark, then drag a box on the text, then press Enter. (You can also paste via the window icon menu, but the key is faster.)

UPDATE

Starting from Windows 10 the CTRL + C, CTRL + V and a lot of other feature are implemented in conhost.exe so they should work with every console utility on Windows. (You have to enable Properties -> Option tab -> Quick Edit Mode)

Ref: http://blogs.windows.com/buildingapps/2014/10/07/console-improvements-in-the-windows-10-technical-preview/

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options.

import timeit

setup = '''
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
'''

timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500)
timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500)
timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500)

Results:

1.1214002349999777 s  # WouterOvermeire
1.1922008498571748 s  # Jeff
1.7034366211428602 s  # Kikohs

C# looping through an array

i++ is the standard use of a loop, but not the only way. Try incrementing by 3 each time:

 for (int i = 0; i < theData.Length - 2; i+=3) 
    { 

        // use theData[i], theData[i+1], theData[i+2]

    } 

TLS 1.2 in .NET Framework 4.0

If you are not able to add a property to system.net class library.

Then, add in Global.asax file:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768; //TLS 1.1

And you can use it in a function, at the starting line:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;

And, it's being useful for STRIPE payment gateway, which only supports TLS 1.1, TLS 1.2.

EDIT: After so many questions on .NET 4.5 is installed on my server or not... here is the screenshot of Registry on my production server:

I have only .NET framework 4.0 installed.

registry

Which characters need to be escaped in HTML?

The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):

Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.

For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.

These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "), or (iv) unquoted — with the following restrictions:

... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.

Responsive iframe using Bootstrap

So, youtube gives out the iframe tag as follows:

<iframe width="560" height="315" src="https://www.youtube.com/embed/2EIeUlvHAiM" frameborder="0" allowfullscreen></iframe>

In my case, i just changed it to width="100%" and left the rest as is. It's not the most elegant solution (after all, in different devices you'll get weird ratios) But the video itself does not get deformed, just the frame.

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

http://allu.wordpress.com/2006/11/08/difference-between-final-finally-and-finalize/

final – constant declaration.

finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Did you try searching on google, and need clarification for an explanation?

SQL order string as number

This will handle negative numbers, fractions, string, everything:

ORDER BY ISNUMERIC(col) DESC, Try_Parse(col AS decimal(10,2)), col;

How to navigate to a directory in C:\ with Cygwin?

Create a file named "overrideBashCdForWindowsPaths" in your HOME folder. Paste the following lines into that file and save it:

#!/bin/bash

function cd() {
    CD_PATH="$(history | tail -1 | sed -e "s,.*${FUNCNAME[0]}\s*,,g")"

    if [ -z "${CD_PATH}" -o "${CD_PATH}" = "~" ]; then
        CD_PATH="${HOME}"
    fi

    builtin cd "$(cygpath "$CD_PATH")"
}

Next, type the following command in a terminal, while you are in your HOME folder:

echo ". overrideBashCdForWindowsPaths" >> .bashrc

Close your terminal and open a new one. You can now easily change into that Windows folder by simply typing

cd C:\Python31\sip

The script reads the last command, extracts the path and passes it to Cygwin's path-conversion tool. By naming the function "cd" we sort of 'override' Bash's builtin "cd" and delegate the actual call to it in the very last line.

How to right align widget in horizontal linear layout Android?

Try to change the layout_width to android:layout_width="match_parent" because gravity:"right" aligns the text inside the layout_width, and if you choose wrap content it does not have where to go, but if you choose match parent it can go to the right.