Programs & Examples On #960.gs

The 960 Grid is a CSS layout system that can be used with or without a web development framework.

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

It's the term slug you want.Looks like you can get the id like this if that's what you need:

function get_term_link( $term, $taxonomy = '' ) {
    global $wp_rewrite;

    if ( !is_object($term) ) {
        if ( is_int( $term ) ) {
            $term = get_term( $term, $taxonomy );
        } else {
            $term = get_term_by( 'slug', $term, $taxonomy );
        }
    }

Change date format in a Java string

The answer is of course to create a SimpleDateFormat object and use it to parse Strings to Date and to format Dates to Strings. If you've tried SimpleDateFormat and it didn't work, then please show your code and any errors you may receive.

Addendum: "mm" in the format String is not the same as "MM". Use MM for months and mm for minutes. Also, yyyyy is not the same as yyyy. e.g.,:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2011-01-18 00:00:00.0";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"  
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dt1.format(date));
    }

}

Static Classes In Java

Yes there is a static nested class in java. When you declare a nested class static, it automatically becomes a stand alone class which can be instantiated without having to instantiate the outer class it belongs to.

Example:

public class A
{

 public static class B
 {
 }
}

Because class B is declared static you can explicitly instantiate as:

B b = new B();

Note if class B wasn't declared static to make it stand alone, an instance object call would've looked like this:

A a= new A();
B b = a.new B();

How would I stop a while loop after n amount of time?

I have read this but I just want to ask something, wouldn't something like I have written work at all? I have done the testing for 5,10 and 20 seconds. Its time isn't exactly accurate but they are really close to the actual values.

import time

begin_time=0
while begin_time<5:

    begin_time+=1
    time.sleep(1.0)
print("The Work is Done")

How to convert JSON to XML or XML to JSON?

Here is a simple snippet that converts a XmlNode (recursively) into a hashtable, and groups multiple instances of the same child into an array (as an ArrayList). The Hashtable is usually accepted to convert into JSON by most of the JSON libraries.

protected object convert(XmlNode root){
    Hashtable obj = new Hashtable();
    for(int i=0,n=root.ChildNodes.Count;i<n;i++){
        object result = null;
        XmlNode current = root.ChildNodes.Item(i);

        if(current.NodeType != XmlNodeType.Text)
            result = convert(current);
        else{
            int resultInt;
            double resultFloat;
            bool resultBoolean;
            if(Int32.TryParse(current.Value, out resultInt)) return resultInt;
            if(Double.TryParse(current.Value, out resultFloat)) return resultFloat;
            if(Boolean.TryParse(current.Value, out resultBoolean)) return resultBoolean;
            return current.Value;
        }

        if(obj[current.Name] == null)
            obj[current.Name] = result;
        else if(obj[current.Name].GetType().Equals(typeof(ArrayList)))
            ((ArrayList)obj[current.Name]).Add(result);
        else{
            ArrayList collision = new ArrayList();
            collision.Add(obj[current.Name]);
            collision.Add(result);
            obj[current.Name] = collision;
        }
    }

    return obj;
}

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

Retrieving a List from a java.util.stream.Stream in Java 8

You can rewrite code as below :

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = sourceLongList.stream().filter(l -> l > 100).collect(Collectors.toList());

How to convert image file data in a byte array to a Bitmap?

The answer of Uttam didnt work for me. I just got null when I do:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:

//Create bitmap with width, height, and 4 bytes color (RGBA)    
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options

How to change XAMPP apache server port?

To answer the original question:

To change the XAMPP Apache server port here the procedure :

1. Choose a free port number

The default port used by Apache is 80.

Take a look to all your used ports with Netstat (integrated to XAMPP Control Panel).

Screenshot of xampp control netstat

Then you can see all used ports and here we see that the 80port is already used by System.

screenshot netstat port 80

Choose a free port number (8012, for this exemple).

2. Edit the file "httpd.conf"

This file should be found in C:\xampp\apache\conf on Windows or in bin/apache for Linux.:

Listen 80
ServerName localhost:80

Replace them by:

Listen 8012
ServerName localhost:8012

Save the file.

Access to : http://localhost:8012 for check if it's work.

If not, you must to edit the http-ssl.conf file as explain in step 3 below. ?

3. Edit the file "http-ssl.conf"

This file should be found in C:\xampp\apache\conf\extra on Windows or see this link for Linux.

Locate the following lines:

Listen 443
<VirtualHost _default_:443>
ServerName localhost:443

Replace them by with a other port number (8013 for this example) :

Listen 8013
<VirtualHost _default_:8013>
ServerName localhost:8013

Save the file.

Restart the Apache Server.

Access to : http://localhost:8012 for check if it's work.

4. Configure XAMPP Apache server settings

If your want to access localhost without specify the port number in the URL
http://localhost instead of http://localhost:8012.

  • Open Xampp Control Panel
  • Go to Config ? Service and Port Settings ? Apache
  • Replace the Main Port and SSL Port values ??with those chosen (e.g. 8012 and 8013).
  • Save Service settings
  • Save Configuration of Control Panel
  • Restart the Apache Server xampp apache setting port It should work now.

4.1. Web browser configuration

If this configuration isn't hiding port number in URL it's because your web browser is not configured for. See : Tools ? Options ? General ? Connection Settings... will allow you to choose different ports or change proxy settings.

4.2. For the rare cases of ultimate bad luck

If step 4 and Web browser configuration are not working for you the only way to do this is to change back to 80, or to install a listener on port 80 (like a proxy) that redirects all your traffic to port 8012.

To answer your problem :

If you still have this message in Control Panel Console :

Apache Started [Port 80]

  • Find location of xampp-control.exe file (probably in C:\xampp)
  • Create a file XAMPP.INI in that directory (so XAMPP.ini and xampp-control.exe are in the same directory)

Put following lines in the XAMPP.INI file:

[PORTS]
apache = 8012

Now , you will always get:

Apache started [Port 8012]

Please note that, this is for display purpose only. It has no relation with your httpd.conf.

Attempt to set a non-property-list object as an NSUserDefaults

First off, rmaddy's answer (above) is right: implementing NSCoding doesn't help. However, you need to implement NSCoding to use NSKeyedArchiver and all that, so it's just one more step... converting via NSData.

Example methods

- (NSUserDefaults *) defaults {
    return [NSUserDefaults standardUserDefaults];
}

- (void) persistObj:(id)value forKey:(NSString *)key {
    [self.defaults setObject:value  forKey:key];
    [self.defaults synchronize];
}

- (void) persistObjAsData:(id)encodableObject forKey:(NSString *)key {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:encodableObject];
    [self persistObj:data forKey:key];
}    

- (id) objectFromDataWithKey:(NSString*)key {
    NSData *data = [self.defaults objectForKey:key];
    return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

So you can wrap your NSCoding objects in an NSArray or NSDictionary or whatever...

expected assignment or function call: no-unused-expressions ReactJS

I encountered the same error, with the below code.

    return this.state.employees.map((employee) => {
      <option value={employee.id}>
        {employee.name}
      </option>
    });

Above issue got resolved, when I changed curly braces to parenthesis, as indicated in the below modified code snippet.

      return this.state.employees.map((employee) => (
          <option value={employee.id}>
            {employee.name}
          </option>
        ));

Change string color with NSAttributedString?

You can create NSAttributedString

NSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor redColor] };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"My Color String" attributes:attrs];

OR NSMutableAttributedString to apply custom attributes with Ranges.

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", methodPrefix, method] attributes: @{ NSFontAttributeName : FONT_MYRIADPRO(48) }];
[attributedString addAttribute:NSFontAttributeName value:FONT_MYRIADPRO_SEMIBOLD(48) range:NSMakeRange(methodPrefix.length, method.length)];

Available Attributes: NSAttributedStringKey


UPDATE:

Swift 5.1

let message: String = greeting + someMessage
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2.0
    
// Note: UIFont(appFontFamily:ofSize:) is extended init.
let regularAttributes: [NSAttributedString.Key : Any] = [.font : UIFont(appFontFamily: .regular, ofSize: 15)!, .paragraphStyle : paragraphStyle]
let boldAttributes = [NSAttributedString.Key.font : UIFont(appFontFamily: .semiBold, ofSize: 15)!]

let mutableString = NSMutableAttributedString(string: message, attributes: regularAttributes)
mutableString.addAttributes(boldAttributes, range: NSMakeRange(0, greeting.count))

How to target only IE (any version) within a stylesheet?

Internet Explorer 9 and lower : You could use conditional comments to load an IE-specific stylesheet for any version (or combination of versions) that you wanted to specifically target.like below using external stylesheet.

<!--[if IE]>
  <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->

However, beginning in version 10, conditional comments are no longer supported in IE.

Internet Explorer 10 & 11 : Create a media query using -ms-high-contrast, in which you place your IE 10 and 11-specific CSS styles. Because -ms-high-contrast is Microsoft-specific (and only available in IE 10+), it will only be parsed in Internet Explorer 10 and greater.

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
     /* IE10+ CSS styles go here */
}

Microsoft Edge 12 : Can use the @supports rule Here is a link with all the info about this rule

@supports (-ms-accelerator:true) {
  /* IE Edge 12+ CSS styles go here */ 
}

Inline rule IE8 detection

I have 1 more option but it is only detect IE8 and below version.

  /* For IE css hack */
  margin-top: 10px\9 /* apply to all ie from 8 and below */
  *margin-top:10px;  /* apply to ie 7 and below */
  _margin-top:10px; /* apply to ie 6 and below */

As you specefied for embeded stylesheet. I think you need to use media query and condition comment for below version.

BeautifulSoup Grab Visible Webpage Text

Using BeautifulSoup the easiest way with less code to just get the strings, without empty lines and crap.

tag = <Parent_Tag_that_contains_the_data>
soup = BeautifulSoup(tag, 'html.parser')

for i in soup.stripped_strings:
    print repr(i)

What's the complete range for Chinese characters in Unicode?

The exact ranges for Chinese characters (except the extensions) are [\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD].

  1. [\u2e80-\u2fd5]

CJK Radicals Supplement is a Unicode block containing alternative, often positional, forms of the Kangxi radicals. They are used headers in dictionary indices and other CJK ideograph collections organized by radical-stroke.

  1. [\u3190-\u319f]

Kanbun is a Unicode block containing annotation characters used in Japanese copies of classical Chinese texts, to indicate reading order.

  1. [\u3400-\u4DBF]

CJK Unified Ideographs Extension-A is a Unicode block containing rare Han ideographs.

  1. [\u4E00-\u9FCC]

CJK Unified Ideographs is a Unicode block containing the most common CJK ideographs used in modern Chinese and Japanese.

  1. [\uF900-\uFAAD]

CJK Compatibility Ideographs is a Unicode block created to contain Han characters that were encoded in multiple locations in other established character encodings, in addition to their CJK Unified Ideographs assignments, in order to retain round-trip compatibility between Unicode and those encodings.

For the details please refer to here, and the extensions are provided in other answers.

How to debug SSL handshake using cURL?

curl -iv https://your.domain.io

That will give you cert and header output if you do not wish to use openssl command.

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['http://example.com', 'http://example2.com']

How to find GCD, LCM on a set of numbers

int lcm = 1;
int y = 0;
boolean flag = false;
for(int i=2;i<=n;i++){
            if(lcm%i!=0){
                for(int j=i-1;j>1;j--){
                    if(i%j==0){
                        flag =true;
                        y = j;
                        break;
                    }
                }
                if(flag){
                    lcm = lcm*i/y;
                }
                else{
                    lcm = lcm*i;
                }
            }
            flag = false;
        }

here, first for loop is for getting every numbers starting from '2'. then if statement check whether the number(i) divides lcm if it does then it skip that no. and if it doesn't then next for loop is for finding a no. which can divides the number(i) if this happens we don't need that no. we only wants its extra factor. so here if the flag is true this means there already had some factors of no. 'i' in lcm. so we divide that factors and multiply the extra factor to lcm. If the number isn't divisible by any of its previous no. then when simply multiply it to the lcm.

Clicking at coordinates without identifying element

    WebElement button = driver.findElement(By.xpath("//button[@type='submit']"));
    int height = button.getSize().getHeight();
    int width = button.getSize().getWidth();
    Actions act = new Actions(driver);
    act.moveToElement(button).moveByOffset((width/2)+2,(height/2)+2).click();

BeanFactory vs ApplicationContext

  1. ApplicationContext is more preferred way than BeanFactory

  2. In new Spring versions BeanFactory is replaced with ApplicationContext. But still BeanFactory exists for backward compatability

  3. ApplicationContext extends BeanFactory and has the following benefits
    • it supports internationalization for text messages
    • it supports event publication to the registered listeners
    • access to the resources such as URLs and files

How to check if Thread finished execution

Use Thread.Join(TimeSpan.Zero) It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle classes as well.

Getting value of select (dropdown) before change

(function() {

    var value = $('[name=request_status]').change(function() {
        if (confirm('You are about to update the status of this request, please confirm')) {
            $(this).closest('form').submit(); // submit the form
        }else {
            $(this).val(value); // set the value back
        }
    }).val();
})();

Write output to a text file in PowerShell

Another way this could be accomplished is by using the Start-Transcript and Stop-Transcript commands, respectively before and after command execution. This would capture the entire session including commands.

Start-Transcript

Stop-Transcript

For this particular case Out-File is probably your best bet though.

How to get current working directory in Java?

File currentDirectory = new File(new File(".").getAbsolutePath());
System.out.println(currentDirectory.getCanonicalPath());
System.out.println(currentDirectory.getAbsolutePath());

Prints something like:

/path/to/current/directory
/path/to/current/directory/.

Note that File.getCanonicalPath() throws a checked IOException but it will remove things like ../../../

Remove all whitespace from C# string with regex

No need for regex. This will also remove tabs, newlines etc

var newstr = String.Join("",str.Where(c=>!char.IsWhiteSpace(c)));

WhiteSpace chars : 0009 , 000a , 000b , 000c , 000d , 0020 , 0085 , 00a0 , 1680 , 180e , 2000 , 2001 , 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 200a , 2028 , 2029 , 202f , 205f , 3000.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

By experience I say that you need to check if the server is running first and then try configuring MySQL. The last solution is to re-install MySQL.

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

An item with the same key has already been added

I had 2 model properties like this

public int LinkId {get;set;}
public int LinkID {get;set;}

it is strange that it threw this error for these 2 haha..

printf not printing on console

Try setting this before you print:

setvbuf (stdout, NULL, _IONBF, 0);

Pass in an enum as a method parameter

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

    return file.Id;
}

Invalidating JSON Web Tokens

IAM solution like Keycloak (which I'have worked on) provide Token Revocation endpoint like

Token Revocation Endpoint /realms/{realm-name}/protocol/openid-connect/revoke

Of if you simply want to logout an useragent(or user), you could call an endpoint as well(this would simply invalidate the Tokens). Again, in the case of Keycloak, the Relying Party just needs to call the endpoint

/realms/{realm-name}/protocol/openid-connect/logout

Link in case if you want to learn more

How to flush output after each `echo` call?

Sometimes, the problem come from Apache settings. Apache can be set to gzip the output. In the file .htaccess you can add for instance :

SetEnv no-gzip 1

How to configure postgresql for the first time?

The other answers were not completely satisfying to me. Here's what worked for postgresql-9.1 on Xubuntu 12.04.1 LTS.

  1. Connect to the default database with user postgres:

    sudo -u postgres psql template1

  2. Set the password for user postgres, then exit psql (Ctrl-D):

    ALTER USER postgres with encrypted password 'xxxxxxx';

  3. Edit the pg_hba.conf file:

    sudo vim /etc/postgresql/9.1/main/pg_hba.conf

    and change "peer" to "md5" on the line concerning postgres:

    local      all     postgres     peer md5

    To know what version of postgresql you are running, look for the version folder under /etc/postgresql. Also, you can use Nano or other editor instead of VIM.

  4. Restart the database :

    sudo /etc/init.d/postgresql restart

    (Here you can check if it worked with psql -U postgres).

  5. Create a user having the same name as you (to find it, you can type whoami):

    sudo createuser -U postgres -d -e -E -l -P -r -s <my_name>

    The options tell postgresql to create a user that can login, create databases, create new roles, is a superuser, and will have an encrypted password. The really important ones are -P -E, so that you're asked to type the password that will be encrypted, and -d so that you can do a createdb.

    Beware of passwords: it will first ask you twice the new password (for the new user), repeated, and then once the postgres password (the one specified on step 2).

  6. Again, edit the pg_hba.conf file (see step 3 above), and change "peer" to "md5" on the line concerning "all" other users:

    local      all     all     peer md5

  7. Restart (like in step 4), and check that you can login without -U postgres:

    psql template1

    Note that if you do a mere psql, it will fail since it will try to connect you to a default database having the same name as you (i.e. whoami). template1 is the admin database that is here from the start.

  8. Now createdb <dbname> should work.

How to determine whether an object has a given property in JavaScript

One feature of my original code

if ( typeof(x.y) != 'undefined' ) ...

that might be useful in some situations is that it is safe to use whether x exists or not. With either of the methods in gnarf's answer, one should first test for x if there is any doubt if it exists.

So perhaps all three methods have a place in one's bag of tricks.

Batch script to find and replace a string in text file within a minute for files up to 12 MB

This uses a helper batch file called repl.bat - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

Place repl.bat in the same folder as the batch file or in a folder that is on the path.

Repl.bat is a hybrid batch file using native Windows scripting and is far faster than a regular batch script.

The L switch makes the text search and replace a literal string and I'd expect the 12 MB file to complete in several seconds on a modern PC.

@echo off &setlocal
set "search=%~1"
set "replace=%~2"
set "textfile=Input.txt"
set "newfile=Output.txt"
call repl.bat "%search%" "%replace%" L < "%textfile%" >"%newfile%"
del "%textfile%"
rename "%newfile%" "%textfile%"

How to use if-else logic in Java 8 stream forEach

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.


Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:

    animalMap.forEach(
            (key, value) -> {
                if (value != null) {
                    myMap.put(key, value);
                } else {
                    myList.add(key);
                }
            }
    );

Get column from a two dimensional array

Use Array.prototype.map() with an arrow function:

_x000D_
_x000D_
const arrayColumn = (arr, n) => arr.map(x => x[n]);_x000D_
_x000D_
const twoDimensionalArray = [_x000D_
  [1, 2, 3],_x000D_
  [4, 5, 6],_x000D_
  [7, 8, 9],_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 0));
_x000D_
_x000D_
_x000D_

Note: Array.prototype.map() and arrow functions are part of ECMAScript 6 and not supported everywhere, see ECMAScript 6 compatibility table.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I've added upon the code submitted by jSnake04 and Dasun herein. I've added code to create lists of objects from JArray instances. It has two-way recursion but as it is functioning on a fixed, finite tree model, there is no risk of stack overflow unless the data is massive.

/// <summary>
/// Deserialize the given JSON string data (<paramref name="data"/>) into a
///   dictionary.
/// </summary>
/// <param name="data">JSON string.</param>
/// <returns>Deserialized dictionary.</returns>
private IDictionary<string, object> DeserializeData(string data)
{
    var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);

    return DeserializeData(values);
}

/// <summary>
/// Deserialize the given JSON object (<paramref name="data"/>) into a dictionary.
/// </summary>
/// <param name="data">JSON object.</param>
/// <returns>Deserialized dictionary.</returns>
private IDictionary<string, object> DeserializeData(JObject data)
{
    var dict = data.ToObject<Dictionary<String, Object>>();

    return DeserializeData(dict);
}

/// <summary>
/// Deserialize any elements of the given data dictionary (<paramref name="data"/>) 
///   that are JSON object or JSON arrays into dictionaries or lists respectively.
/// </summary>
/// <param name="data">Data dictionary.</param>
/// <returns>Deserialized dictionary.</returns>
private IDictionary<string, object> DeserializeData(IDictionary<string, object> data)
{
    foreach (var key in data.Keys.ToArray()) 
    {
        var value = data[key];

        if (value is JObject)
            data[key] = DeserializeData(value as JObject);

        if (value is JArray)
            data[key] = DeserializeData(value as JArray);
    }

    return data;
}

/// <summary>
/// Deserialize the given JSON array (<paramref name="data"/>) into a list.
/// </summary>
/// <param name="data">Data dictionary.</param>
/// <returns>Deserialized list.</returns>
private IList<Object> DeserializeData(JArray data)
{
    var list = data.ToObject<List<Object>>();

    for (int i = 0; i < list.Count; i++)
    {
        var value = list[i];

        if (value is JObject)
            list[i] = DeserializeData(value as JObject);

        if (value is JArray)
            list[i] = DeserializeData(value as JArray);
    }

    return list;
}

How to download dependencies in gradle

For Intellij go to View > Tool Windows > Gradle > Refresh All Projects (the blue circular arrows at the top of the Gradle window. enter image description here

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

When I first wrote this.

10 PRINT "What is your name?"
20 INPUT A$
30 PRINT "Hello " A$
40 GOTO 30

It blew people away! The computer remembered their name!

EDIT: Just to add to this. If you can convince a new programmer this is the coolest thing they can do, they will become the good programmers. These days, you can do almost anything you want with one line of code to run a library somebody else wrote. I personally get absolutely no satisfaction from doing that and see little benefit in teaching it.

How do I read the contents of a Node.js stream into a string variable?

In my case, the content type response headers was Content-Type: text/plain. So, I've read the data from Buffer like:

let data = [];
stream.on('data', (chunk) => {
 console.log(Buffer.from(chunk).toString())
 data.push(Buffer.from(chunk).toString())
});

How to create .ipa file using Xcode?

Here is the steps I followed to export the .ipa

  • Validate the archive
  • Click on on distribute the app
  • Click the distribution method
  • Choose the export in the next screen (The screen shown only if the archive is validated)

CSS3 :unchecked pseudo-class

There is no :unchecked pseudo class however if you use the :checked pseudo class and the sibling selector you can differentiate between both states. I believe all of the latest browsers support the :checked pseudo class, you can find more info from this resource: http://www.whatstyle.net/articles/18/pretty_form_controls_with_css

Your going to get better browser support with jquery... you can use a click function to detect when the click happens and if its checked or not, then you can add a class or remove a class as necessary...

How to unapply a migration in ASP.NET Core with EF Core

Simply you can target a Migration by value

 Update-Database -Migration:0

Then go ahead and remove it

 Remove-Migration

Export data from Chrome developer tool

Right-click and export as HAR, then view it using Jan Odvarko's HAR Viewer

This helps in visualising the already captured HAR logs.

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

well distinct can be slower than group by on some occasions in postgres (dont know about other dbs).

tested example:

postgres=# select count(*) from (select distinct i from g) a;

count 

10001
(1 row)

Time: 1563,109 ms

postgres=# select count(*) from (select i from g group by i) a;

count
10001
(1 row)

Time: 594,481 ms

http://www.pgsql.cz/index.php/PostgreSQL_SQL_Tricks_I

so be careful ... :)

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

Not directly answering the question, but does it really have to be a regex?

I used to do lots of Perl, and got used to solving problems with regexes. However, when they get more complicated with all the look-aheads and other quirks, you need to write dozens of unit tests to kill all those little bugs.

Furthermore, a regex is typically a few times slower than an imperative or a functional solution.

For example, the following (not very FP) Scala function solves the original question about three times faster than the regex of the most popular answer. What it does is also so clear that you don't need a unit test at all:

def validatePassword(password: String): Boolean = {
  if (password.length < 8)
    return false

  var lower = false
  var upper = false
  var numbers = false
  var special = false

  password.foreach { c =>
    if (c.isDigit)       numbers = true
    else if (c.isLower)  lower = true
    else if (c.isUpper)  upper = true
    else                 special = true
  }

  lower && upper && numbers && special
}

Invariant Violation: _registerComponent(...): Target container is not a DOM element

the ready function can be used like this:

$(document).ready(function () {
  React.render(<App />, document.body);
});

If you don't want to use jQuery, you can use the onload function:

<body onload="initReact()">...</body>

Regular Expressions and negating a whole character group

Simplest way is to pull the negation out of the regular expression entirely:

if (!userName.matches("^([Ss]ys)?admin$")) { ... }

Mysql: Select rows from a table that are not in another

SELECT *
FROM Table1 AS a
WHERE NOT EXISTS (
  SELECT *
  FROM Table2 AS b 
  WHERE a.FirstName=b.FirstName AND a.LastName=b.Last_Name
)

EXISTS will help you...

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

Pointer-to-pointer dynamic two-dimensional array

What you describe for the second method only gives you a 1D array:

int *board = new int[10];

This just allocates an array with 10 elements. Perhaps you meant something like this:

int **board = new int*[4];
for (int i = 0; i < 4; i++) {
  board[i] = new int[10];
}

In this case, we allocate 4 int*s and then make each of those point to a dynamically allocated array of 10 ints.

So now we're comparing that with int* board[4];. The major difference is that when you use an array like this, the number of "rows" must be known at compile-time. That's because arrays must have compile-time fixed sizes. You may also have a problem if you want to perhaps return this array of int*s, as the array will be destroyed at the end of its scope.

The method where both the rows and columns are dynamically allocated does require more complicated measures to avoid memory leaks. You must deallocate the memory like so:

for (int i = 0; i < 4; i++) {
  delete[] board[i];
}
delete[] board;

I must recommend using a standard container instead. You might like to use a std::array<int, std::array<int, 10> 4> or perhaps a std::vector<std::vector<int>> which you initialise to the appropriate size.

Get the value in an input text box

You can only select a value with the following two ways:

// First way to get a value
value = $("#txt_name").val(); 

// Second way to get a value
value = $("#txt_name").attr('value');

If you want to use straight JavaScript to get the value, here is how:

document.getElementById('txt_name').value 

How can I start PostgreSQL server on Mac OS X?

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

https://hub.docker.com/_/postgres

How to fix git error: RPC failed; curl 56 GnuTLS

Check your Network is properly working...this problem also occures because of internet issues

How to terminate a process in vbscript

Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.

Makefile If-Then Else and Loops

Conditional Forms

Simple

conditional-directive
text-if-true
endif

Moderately Complex

conditional-directive
text-if-true
else
text-if-false
endif

More Complex

conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif

Conditional Directives

If Equal Syntax

ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"

If Not Equal Syntax

ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"

If Defined Syntax

ifdef variable-name

If Not Defined Syntax

ifndef variable-name  

foreach Function

foreach Function Syntax

$(foreach var, list, text)  

foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.

What exactly does an #if 0 ..... #endif block do?

When the preprocessor sees #if it checks whether the next token has a non-zero value. If it does, it keeps the code around for the compiler. If it doesn't, it gets rid of that code so the compiler never sees it.

If someone says #if 0 they are effectively commenting out the code so it will never be compiled. You can think of this the same as if they had put /* ... */ around it. It's not quite the same, but it has the same effect.

If you want to understand what happened in detail, you can often look. Many compilers will allow you to see the files after the preprocessor has run. For example, on Visual C++ the switch /P command will execute the preprocessor and put the results in a .i file.

Detect if page has finished loading

Without jquery or anything like that beacuse why not ?

var loaded=0;
var loaded1min=0;
document.addEventListener("DOMContentLoaded", function(event) {
   loaded=1;
    setTimeout(function () {
      loaded1min=1;
    }, 60000);
});

How to multiply values using SQL

You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.

SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC

Change the background color in a twitter bootstrap modal?

remove bootstrap modal background try this one

.modal-backdrop {
   background: none;
}

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Concatenating two one-dimensional NumPy arrays

Some more facts from the numpy docs :

With syntax as numpy.concatenate((a1, a2, ...), axis=0, out=None)

axis = 0 for row-wise concatenation axis = 1 for column-wise concatenation

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])

# Appending below last row
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])

# Appending after last column
>>> np.concatenate((a, b.T), axis=1)    # Notice the transpose
array([[1, 2, 5],
       [3, 4, 6]])

# Flattening the final array
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])

I hope it helps !

How to get column values in one comma separated value

For Oracle versions which does not support the WM_CONCAT, the following can be used

  select "User", RTRIM(
     XMLAGG (XMLELEMENT(e, department||',') ORDER BY department).EXTRACT('//text()') , ','
     ) AS departments 
  from yourtable 
  group by "User"

This one is much more powerful and flexible - you can specify both delimiters and sort order within each group as in listagg.

Relational Database Design Patterns?

After many years of database development I can say there are some no goes and some question that you should answer before you begin:

questions:

  • Do you want use in the future another DBMS? If yes then does not use to special SQL stuff of the current DBMS. Remove logic in your application.

Does not use:

  • white spaces in table names and column names
  • Non Ascii characters in table and column names
  • binding to a specific lower case or upper case. And never use 2 tables or columns that differ only with lower case and upper case.
  • does not use SQL keywords for tables or columns names like "FROM", "BETWEEN", "DELETE", etc

recomendations:

  • Use NVARCHAR or equivalents for unicode support then you have no problems with codepages.
  • Give every column a unique name. This make it easer on join to select the column. It is very difficult if every table has a column "ID" or "Name" or "Description". Use XyzID and AbcID.
  • Use a resource bundle or equals for complex SQL expressions. It make it easer to switch to another DBMS.
  • Does not cast hard on any data type. Another DBMS can not have this data type. FOr example Oracle daes not have a SMALLINT only a number.

I hope this is a good starting point.

How to animate the change of image in an UIImageView?

Try this:

_imageView.image = image;
[_imageView.layer addAnimation:[CATransition animation] forKey:kCATransition];

Length of the String without using length() method

Since nobody's posted the naughty back door way yet:

public int getLength(String arg) {
  Field count = String.class.getDeclaredField("count");
  count.setAccessible(true); //may throw security exception in "real" environment
  return count.getInt(arg);
}

;)

Where can I find error log files?

On CentoS with cPanel installed my logs were in:

/usr/local/apache/logs/error_log

To watch: tail -f /usr/local/apache/logs/error_log

Compress images on client side before uploading

If you are looking for a library to carry out client-side image compression, you can check this out:compress.js. This will basically help you compress multiple images purely with JavaScript and convert them to base64 string. You can optionally set the maximum size in MB and also the preferred image quality.

Remove '\' char from string c#

Try using

String sOld = ...;
String sNew =     sOld.Replace("\\", String.Empty);

How do I efficiently iterate over each entry in a Java Map?

Try this with Java 1.4:

for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){

  Entry entry = (Entry) entries.next();

  System.out.println(entry.getKey() + "/" + entry.getValue());

  //...
}

Angular 4 default radio button checked by default

We can use [(ngModel)] in following way and have a value selection variable radioSelected

Example tutorial

Demo Link

app.component.html

  <div class="text-center mt-5">
  <h4>Selected value is {{radioSel.name}}</h4>

  <div>
    <ul class="list-group">
          <li class="list-group-item"  *ngFor="let item of itemsList">
            <input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/> 
            {{item.name}}

          </li>
    </ul>
  </div>


  <h5>{{radioSelectedString}}</h5>

  </div>

app.component.ts

  import {Item} from '../app/item';
  import {ITEMS} from '../app/mock-data';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent {
    title = 'app';
    radioSel:any;
    radioSelected:string;
    radioSelectedString:string;
    itemsList: Item[] = ITEMS;


      constructor() {
        this.itemsList = ITEMS;
        //Selecting Default Radio item here
        this.radioSelected = "item_3";
        this.getSelecteditem();
      }

      // Get row item from array  
      getSelecteditem(){
        this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
        this.radioSelectedString = JSON.stringify(this.radioSel);
      }
      // Radio Change Event
      onItemChange(item){
        this.getSelecteditem();
      }

  }

Sample Data for Listing

        export const ITEMS: Item[] = [
            {
                name:'Item 1',
                value:'item_1'
            },
            {
                name:'Item 2',
                value:'item_2'
            },
            {
                name:'Item 3',
                value:'item_3'
            },
            {
                name:'Item 4',
                value:'item_4'
                },
                {
                    name:'Item 5',
                    value:'item_5'
                }
        ];

Where is the application.properties file in a Spring Boot project?

You can also create the application.properties file manually.

SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:

  • A /config subdirectory of the current directory.
  • The current directory
  • A classpath /config package
  • The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations). (From the Spring boot features external configuration doc page)

So just go ahead and create it

How to open Visual Studio Code from the command line on OSX?

On OSX Mavericks I created a bash script named vscode (adapted from the .bashrc in VSCode Setup) in ~/bin:

#!/bin/bash

if [[ $# = 0 ]]
then
    open -a "Visual Studio Code"
else
    [[ $1 = /* ]] && F="$1" || F="$PWD/${1#./}"
    open -a "Visual Studio Code" --args "$F"
fi

vscode <file or directory> now works as expected.

Sending and Parsing JSON Objects in Android

Other answers have noted Jackson and GSON - the popular add-on JSON libraries for Android, and json.org, the bare-bones JSON package that is included in Android.

But I think it is also worth noting that Android now has its own full featured JSON API.

This was added in Honeycomb: API level 11.

This comprises
- android.util.JsonReader: docs, and source
- android.util.JsonWriter: docs, and source

I will also add one additional consideration that pushes me back towards Jackson and GSON: I have found it useful to use 3rd party libraries rather then android.* packages because then the code I write can be shared between client and server. This is particularly relevant for something like JSON, where you might want to serialize data to JSON on one end for sending to the other end. For use cases like that, if you use Java on both ends it helps to avoid introducing android.* dependencies.

Or I guess one could grab the relevant android.* source code and add it to your server project, but I haven't tried that...

CSS Div stretch 100% page height

With HTML5, the easiest way is simply to do height: 100vh. Where 'vh' stands for viewport height of the browser window. Responsive to resizing of browser and mobile devices.

How to stop text from taking up more than 1 line?

Sometimes using &nbsp; instead of spaces will work. Clearly it has drawbacks, though.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

SQL Server command line backup statement

You can use sqlcmd to run a backup, or any other T-SQL script. You can find the detailed instructions and examples on various useful sqlcmd switches in this article: Working with the SQL Server command line (sqlcmd)

Converting HTML to XML

I did found a way to convert (even bad) html into well formed XML. I started to base this on the DOM loadHTML function. However during time several issues occurred and I optimized and added patches to correct side effects.

  function tryToXml($dom,$content) {
    if(!$content) return false;

    // xml well formed content can be loaded as xml node tree
    $fragment = $dom->createDocumentFragment();
    // wonderfull appendXML to add an XML string directly into the node tree!

    // aappendxml will fail on a xml declaration so manually skip this when occurred
    if( substr( $content,0, 5) == '<?xml' ) {
      $content = substr($content,strpos($content,'>')+1);
      if( strpos($content,'<') ) {
        $content = substr($content,strpos($content,'<'));
      }
    }

    // if appendXML is not working then use below htmlToXml() for nasty html correction
    if(!@$fragment->appendXML( $content )) {
      return $this->htmlToXml($dom,$content);
    }

    return $fragment;
  }



  // convert content into xml
  // dom is only needed to prepare the xml which will be returned
  function htmlToXml($dom, $content, $needEncoding=false, $bodyOnly=true) {

    // no xml when html is empty
    if(!$content) return false;

    // real content and possibly it needs encoding
    if( $needEncoding ) {
      // no need to convert character encoding as loadHTML will respect the content-type (only)
      $content =  '<meta http-equiv="Content-Type" content="text/html;charset='.$this->encoding.'">' . $content;
    }

    // return a dom from the content
    $domInject = new DOMDocument("1.0", "UTF-8");
    $domInject->preserveWhiteSpace = false;
    $domInject->formatOutput = true;

    // html type
    try {
      @$domInject->loadHTML( $content );
    } catch(Exception $e){
      // do nothing and continue as it's normal that warnings will occur on nasty HTML content
    }
        // to check encoding: echo $dom->encoding
        $this->reworkDom( $domInject );

    if( $bodyOnly ) {
      $fragment = $dom->createDocumentFragment();

      // retrieve nodes within /html/body
      foreach( $domInject->documentElement->childNodes as $elementLevel1 ) {
       if( $elementLevel1->nodeName == 'body' and $elementLevel1->nodeType == XML_ELEMENT_NODE ) {
         foreach( $elementLevel1->childNodes as $elementInject ) {
           $fragment->insertBefore( $dom->importNode($elementInject, true) );
         }
        }
      }
    } else {
      $fragment = $dom->importNode($domInject->documentElement, true);
    }

    return $fragment;
  }



    protected function reworkDom( $node, $level = 0 ) {

        // start with the first child node to iterate
        $nodeChild = $node->firstChild;

        while ( $nodeChild )  {
            $nodeNextChild = $nodeChild->nextSibling;

            switch ( $nodeChild->nodeType ) {
                case XML_ELEMENT_NODE:
                    // iterate through children element nodes
                    $this->reworkDom( $nodeChild, $level + 1);
                    break;
                case XML_TEXT_NODE:
                case XML_CDATA_SECTION_NODE:
                    // do nothing with text, cdata
                    break;
                case XML_COMMENT_NODE:
                    // ensure comments to remove - sign also follows the w3c guideline
                    $nodeChild->nodeValue = str_replace("-","_",$nodeChild->nodeValue);
                    break;
                case XML_DOCUMENT_TYPE_NODE:  // 10: needs to be removed
                case XML_PI_NODE: // 7: remove PI
                    $node->removeChild( $nodeChild );
                    $nodeChild = null; // make null to test later
                    break;
                case XML_DOCUMENT_NODE:
                    // should not appear as it's always the root, just to be complete
                    // however generate exception!
                case XML_HTML_DOCUMENT_NODE:
                    // should not appear as it's always the root, just to be complete
                    // however generate exception!
                default:
                    throw new exception("Engine: reworkDom type not declared [".$nodeChild->nodeType. "]");
            }
            $nodeChild = $nodeNextChild;
        } ;
    }

Now this also allows to add more html pieces into one XML which I needed to use myself. In general it can be used like this:

        $c='<p>test<font>two</p>';
    $dom=new DOMDocument('1.0', 'UTF-8');

$n=$dom->appendChild($dom->createElement('info')); // make a root element

if( $valueXml=tryToXml($dom,$c) ) {
  $n->appendChild($valueXml);
}
    echo '<pre/>'. htmlentities($dom->saveXml($n)). '</pre>';

In this example '<p>test<font>two</p>' will nicely be outputed in well formed XML as '<info><p>test<font>two</font></p></info>'. The info root tag is added as it will also allow to convert '<p>one</p><p>two</p>' which is not XML as it has not one root element. However if you html does for sure have one root element then the extra root <info> tag can be skipped.

With this I'm getting real nice XML out of unstructured and even corrupted HTML!

I hope it's a bit clear and might contribute to other people to use it.

SimpleDateFormat parsing date with 'Z' literal

tl;dr

Instant.parse ( "2010-04-05T17:16:00Z" )

ISO 8601 Standard

Your String complies with the ISO 8601 standard (of which the mentioned RFC 3339 is a profile).

Avoid java.util.Date

The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.

Instead use either the Joda-Time library or the new java.time package in Java 8. Both use ISO 8601 as their defaults for parsing and generating string representations of date-time values.

java.time

The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.

The Instant class in java.time represents a moment on the timeline in UTC time zone.

The Z at the end of your input string means Zulu which stands for UTC. Such a string can be directly parsed by the Instant class, with no need to specify a formatter.

String input = "2010-04-05T17:16:00Z";
Instant instant = Instant.parse ( input );

Dump to console.

System.out.println ( "instant: " + instant );

instant: 2010-04-05T17:16:00Z

From there you can apply a time zone (ZoneId) to adjust this Instant into a ZonedDateTime. Search Stack Overflow for discussion and examples.

If you must use a java.util.Date object, you can convert by calling the new conversion methods added to the old classes such as the static method java.util.Date.from( Instant ).

java.util.Date date = java.util.Date.from( instant );

Joda-Time

Example in Joda-Time 2.5.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ):
DateTime dateTime = new DateTime( "2010-04-05T17:16:00Z", timeZone );

Convert to UTC.

DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );

Convert to a java.util.Date if necessary.

java.util.Date date = dateTime.toDate();

Does bootstrap 4 have a built in horizontal divider?

_x000D_
_x000D_
   <div class="form-group col-12">_x000D_
            <hr>_x000D_
   </div>
_x000D_
_x000D_
_x000D_

iterating through Enumeration of hastable keys throws NoSuchElementException error

You call nextElement() twice in your loop. This call moves the enumeration pointer forward. You should modify your code like the following:

while (e.hasMoreElements()) {
    String param = e.nextElement();
    System.out.println(param);
}

Meaning of end='' in the statement print("\t",end='')?

See the documentation for the print function: print()

The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.

How to clean project cache in Intellij idea like Eclipse's clean?

Maybe not THE answer, but it's definitely AN answer.

If nothing else is working for you, go the nuclear option: Close IDEA and delete the ".../.IntelliJIdea/system" directory using your local file system tools.

The .IntelliJIdea directory is usually found in your home directory. Your IDE configuration is in the ".../.IntelliJIdea/config" directory, so it should be fine.

Obviously, this is not the "IDEA" way to do it and would be completely unsupported by JetBrains. Also - I don't use Android Studio so I dunno if this will cause problems, but there you go.

It's worked for me before when I've had problems getting IDEA to start and nothing else works to get me going. Maybe back up your entire .IntelliJIdea directory if you have a morbid fear of losing all your work >.<

Send JSON data from Javascript to PHP?

This is a summary of the main solutions with easy-to-reproduce code:

Method 1 (application/json or text/plain + JSON.stringify)

var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/json") // or "text/plain"
xhr.send(JSON.stringify(data)); 

PHP side, you can get the data with:

print_r(json_decode(file_get_contents('php://input'), true));

Method 2 (x-www-form-urlencoded + JSON.stringify)

var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("json=" + encodeURIComponent(JSON.stringify(data))); 

Note: encodeURIComponent(...) is needed for example if the JSON contains & character.

PHP side, you can get the data with:

print_r(json_decode($_POST['json'], true));

Method 3 (x-www-form-urlencoded + URLSearchParams)

var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(new URLSearchParams(data).toString()); 

PHP side, you can get the data with:

print_r($_POST);

Note: https://caniuse.com/#search=URLSearchParams

How do I make entire div a link?

Using

<a href="foo.html"><div class="xyz"></div></a>

works in browsers, even though it violates current HTML specifications. It is permitted according to HTML5 drafts.

When you say that it does not work, you should explain exactly what you did (including jsfiddle code is a good idea), what you expected, and how the behavior different from your expectations.

It is unclear what you mean by “all the content in that div is in the css”, but I suppose it means that the content is really empty in HTML markup and you have CSS like

.xyz:before { content: "Hello world"; }

The entire block is then clickable, with the content text looking like link text there. Isn’t this what you expected?

How to make audio autoplay on chrome

You could use <iframe src="link/to/file.mp3" allow="autoplay">, if the origin has an autoplay permission. More info here.

Loop through an array of strings in Bash?

This is similar to user2533809's answer, but each file will be executed as a separate command.

#!/bin/bash
names="RA
RB
R C
RD"

while read -r line; do
    echo line: "$line"
done <<< "$names"

Get free disk space

I wanted a similar method for my project but in my case the input paths were either from local disk volumes or clustered storage volumes (CSVs). So DriveInfo class did not work for me. CSVs have a mount point under another drive, typically C:\ClusterStorage\Volume*. Note that C: will be a different Volume than C:\ClusterStorage\Volume1

This is what I finally came up with:

    public static ulong GetFreeSpaceOfPathInBytes(string path)
    {
        if ((new Uri(path)).IsUnc)
        {
            throw new NotImplementedException("Cannot find free space for UNC path " + path);
        }

        ulong freeSpace = 0;
        int prevVolumeNameLength = 0;

        foreach (ManagementObject volume in
                new ManagementObjectSearcher("Select * from Win32_Volume").Get())
        {
            if (UInt32.Parse(volume["DriveType"].ToString()) > 1 &&                             // Is Volume monuted on host
                volume["Name"] != null &&                                                       // Volume has a root directory
                path.StartsWith(volume["Name"].ToString(), StringComparison.OrdinalIgnoreCase)  // Required Path is under Volume's root directory 
                )
            {
                // If multiple volumes have their root directory matching the required path,
                // one with most nested (longest) Volume Name is given preference.
                // Case: CSV volumes monuted under other drive volumes.

                int currVolumeNameLength = volume["Name"].ToString().Length;

                if ((prevVolumeNameLength == 0 || currVolumeNameLength > prevVolumeNameLength) &&
                    volume["FreeSpace"] != null
                    )
                {
                    freeSpace = ulong.Parse(volume["FreeSpace"].ToString());
                    prevVolumeNameLength = volume["Name"].ToString().Length;
                }
            }
        }

        if (prevVolumeNameLength > 0)
        {
            return freeSpace;
        }

        throw new Exception("Could not find Volume Information for path " + path);
    }

vector vs. list in STL

Most answers here miss one important detail: what for?

What do you want to keep in the containter?

If it is a collection of ints, then std::list will lose in every scenario, regardless if you can reallocate, you only remove from the front, etc. Lists are slower to traverse, every insertion costs you an interaction with the allocator. It would be extremely hard to prepare an example, where list<int> beats vector<int>. And even then, deque<int> may be better or close, not justyfing the use of lists, which will have greater memory overhead.

However, if you are dealing with large, ugly blobs of data - and few of them - you don't want to overallocate when inserting, and copying due to reallocation would be a disaster - then you may, maybe, be better off with a list<UglyBlob> than vector<UglyBlob>.

Still, if you switch to vector<UglyBlob*> or even vector<shared_ptr<UglyBlob> >, again - list will lag behind.

So, access pattern, target element count etc. still affects the comparison, but in my view - the elements size - cost of copying etc.

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

The method show() must be called from the User-Interface (UI) thread, while doInBackground() runs on different thread which is the main reason why AsyncTask was designed.

You have to call show() either in onProgressUpdate() or in onPostExecute().

For example:

class ExampleTask extends AsyncTask<String, String, String> {

    // Your onPreExecute method.

    @Override
    protected String doInBackground(String... params) {
        // Your code.
        if (condition_is_true) {
            this.publishProgress("Show the dialog");
        }
        return "Result";
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        connectionProgressDialog.dismiss();
        downloadSpinnerProgressDialog.show();
    }
}

Replace Div with another Div

You can use .replaceWith()

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $(".region").click(function(e) {_x000D_
    e.preventDefault();_x000D_
    var content = $(this).html();_x000D_
    $('#map').replaceWith('<div class="region">' + content + '</div>');_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="map">_x000D_
  <div class="region"><a href="link1">region1</a></div>_x000D_
  <div class="region"><a href="link2">region2</a></div>_x000D_
  <div class="region"><a href="link3">region3</a></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can you detect "dragging" in jQuery?

Make sure you set the element's draggable attribute to false so you don't have side effects when listening to mouseup events:

<div class="thing" draggable="false">text</div>

Then, you can use jQuery:

$(function() {
  var pressed, pressX, pressY,
      dragged,
      offset = 3; // helps detect when the user really meant to drag

  $(document)
  .on('mousedown', '.thing', function(e) {
    pressX = e.pageX;
    pressY = e.pageY;
    pressed = true;
  })
  .on('mousemove', '.thing', function(e) {
    if (!pressed) return;
    dragged = Math.abs(e.pageX - pressX) > offset ||
              Math.abs(e.pageY - pressY) > offset;
  })
  .on('mouseup', function() {
    dragged && console.log('Thing dragged');
    pressed = dragged = false;
  });
});

Get folder name of the file in Python

os.path.dirname is what you are looking for -

os.path.dirname(r"C:\folder1\folder2\filename.xml")

Make sure you prepend r to the string so that its considered as a raw string.

Demo -

In [46]: os.path.dirname(r"C:\folder1\folder2\filename.xml")
Out[46]: 'C:\\folder1\\folder2'

If you just want folder2 , you can use os.path.basename with the above, Example -

os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))

Demo -

In [48]: os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))
Out[48]: 'folder2'

Twitter bootstrap remote modal shows same content every time

This works with Bootstrap 3 FYI

$('#myModal').on('hidden.bs.modal', function () {
  $(this).removeData('bs.modal');
});

inline conditionals in angular.js

EDIT: 2Toad's answer below is what you're looking for! Upvote that thing

If you're using Angular <= 1.1.4 then this answer will do:

One more answer for this. I'm posting a separate answer, because it's more of an "exact" attempt at a solution than a list of possible solutions:

Here's a filter that will do an "immediate if" (aka iif):

app.filter('iif', function () {
   return function(input, trueValue, falseValue) {
        return input ? trueValue : falseValue;
   };
});

and can be used like this:

{{foo == "bar" | iif : "it's true" : "no, it's not"}}

CentOS: Copy directory to another directory

As I understand, you want to recursively copy test directory into /home/server/ path...

This can be done as:

-cp -rf /home/server/folder/test/* /home/server/

Hope this helps

INSERT with SELECT

Yes, it is. You can write :

INSERT INTO courses (name, location, gid) 
SELECT name, location, 'whatever you want' 
FROM courses 
WHERE cid = $ci

or you can get values from another join of the select ...

Regexp Java for password validation

All the previously given answers use the same (correct) technique to use a separate lookahead for each requirement. But they contain a couple of inefficiencies and a potentially massive bug, depending on the back end that will actually use the password.

I'll start with the regex from the accepted answer:

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$

First of all, since Java supports \A and \z I prefer to use those to make sure the entire string is validated, independently of Pattern.MULTILINE. This doesn't affect performance, but avoids mistakes when regexes are recycled.

\A(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}\z

Checking that the password does not contain whitespace and checking its minimum length can be done in a single pass by using the all at once by putting variable quantifier {8,} on the shorthand \S that limits the allowed characters:

\A(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])\S{8,}\z

If the provided password does contain a space, all the checks will be done, only to have the final check fail on the space. This can be avoided by replacing all the dots with \S:

\A(?=\S*[0-9])(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[@#$%^&+=])\S{8,}\z

The dot should only be used if you really want to allow any character. Otherwise, use a (negated) character class to limit your regex to only those characters that are really permitted. Though it makes little difference in this case, not using the dot when something else is more appropriate is a very good habit. I see far too many cases of catastrophic backtracking because the developer was too lazy to use something more appropriate than the dot.

Since there's a good chance the initial tests will find an appropriate character in the first half of the password, a lazy quantifier can be more efficient:

\A(?=\S*?[0-9])(?=\S*?[a-z])(?=\S*?[A-Z])(?=\S*?[@#$%^&+=])\S{8,}\z

But now for the really important issue: none of the answers mentions the fact that the original question seems to be written by somebody who thinks in ASCII. But in Java strings are Unicode. Are non-ASCII characters allowed in passwords? If they are, are only ASCII spaces disallowed, or should all Unicode whitespace be excluded.

By default \s matches only ASCII whitespace, so its inverse \S matches all Unicode characters (whitespace or not) and all non-whitespace ASCII characters. If Unicode characters are allowed but Unicode spaces are not, the UNICODE_CHARACTER_CLASS flag can be specified to make \S exclude Unicode whitespace. If Unicode characters are not allowed, then [\x21-\x7E] can be used instead of \S to match all ASCII characters that are not a space or a control character.

Which brings us to the next potential issue: do we want to allow control characters? The first step in writing a proper regex is to exactly specify what you want to match and what you don't. The only 100% technically correct answer is that the password specification in the question is ambiguous because it does not state whether certain ranges of characters like control characters or non-ASCII characters are permitted or not.

Can CSS force a line break after each word in an element?

The best solution is the word-spacing property.

Add the <p> in a container with a specific size (example 300px) and after you have to add that size as the value in the word-spacing.

HTML

<div>
 <p>Sentence Here</p>
</div>

CSS

div {
 width: 300px;
}

p {
 width: auto;
 text-align: center;
 word-spacing: 300px;
}

In this way, your sentence will be always broken and set in a column, but the with of the paragraph will be dynamic.

Here an example Codepen

How to retrieve images from MySQL database and display in an html tag

You need to retrieve and disect the information into what you need.

while($row = mysql_fetch_array($result)) {
 echo "img src='",$row['filename'],"' width='175' height='200' />";
}

How to use jQuery to show/hide divs based on radio button selection?

$(document).ready(function(){ 
    $("input[name=group1]").change(function() {
        var test = $(this).val();
        $(".desc").hide();
        $("#"+test).show();
    }); 
});

It's correct input[name=group1] in this example. However, thanks for the code!

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

I ran into this problem when using tomcat-embed-core::7.0.47, from Maven. I'm not sure why they didn't add tomcat-util as a runtime dependency, so I added my own runtime dependency to my own project.

<dependency>
  <groupId>org.apache.tomcat</groupId>
  <artifactId>tomcat-util</artifactId>
  <version><!-- version from tomcat-embed-core --></version>
  <scope>runtime</scope>
</dependency>

Programmatically read from STDIN or input file in Perl

You need to use <> operator:

while (<>) {
    print $_; # or simply "print;"
}

Which can be compacted to:

print while (<>);

Arbitrary file:

open F, "<file.txt" or die $!;
while (<F>) {
    print $_;
}
close F;

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

This is now a multiple-year old question, but being very popular, it's worth mentioning a fantastic resource for learning about the C++11 memory model. I see no point in summing up his talk in order to make this yet another full answer, but given this is the guy who actually wrote the standard, I think it's well worth watching the talk.

Herb Sutter has a three hour long talk about the C++11 memory model titled "atomic<> Weapons", available on the Channel9 site - part 1 and part 2. The talk is pretty technical, and covers the following topics:

  1. Optimizations, Races, and the Memory Model
  2. Ordering – What: Acquire and Release
  3. Ordering – How: Mutexes, Atomics, and/or Fences
  4. Other Restrictions on Compilers and Hardware
  5. Code Gen & Performance: x86/x64, IA64, POWER, ARM
  6. Relaxed Atomics

The talk doesn't elaborate on the API, but rather on the reasoning, background, under the hood and behind the scenes (did you know relaxed semantics were added to the standard only because POWER and ARM do not support synchronized load efficiently?).

Change icon-bar (?) color in bootstrap

I do not know if your still looking for the answer to this problem but today I happened the same problem and solved it. You need to specify in the HTML code,

**<Div class = "navbar"**>
         div class = "container">
               <Div class = "navbar-header">

or

**<Div class = "navbar navbar-default">**
        div class = "container">
               <Div class = "navbar-header">

You got that place in your CSS

.navbar-default-toggle .navbar .icon-bar {
  background-color: # 0000ff;
}

and what I did was add above

.navbar .navbar-toggle .icon-bar {
  background-color: # ff0000;
}

Because my html code is

**<Div class = "navbar">**
         div class = "container">
               <Div class = "navbar-header">

and if you associate a file less / css

search this section and also here placed the color you want to change, otherwise it will self-correct the css file to the state it was before

// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-default-toggle-icon-bar-bg: # 888;**
@ Navbar-default-toggle-border-color: #ddd;

if your html code is like mine and is not navbar-default, add it as you did with the css.

// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-toggle-icon-bar-bg : #888;**
@ Navbar-default-toggle-icon-bar-bg: # 888;
@ Navbar-default-toggle-border-color: #ddd;

good luck

Is there a float input type in HTML5?

I have started using inputmode="decimal" which works flawlessly with smartphones:

<input type="text" inputmode="decimal" value="1.5">

Note that we have to use type="text" instead of number. However, on desktop it still allows letters as values.

For desktop you could use:

<input type="number" inputmode="decimal">

which allows 0-9 and . as input and only numbers.

Note that some countries use , as decimal dividor which is activated as default on the NumPad. Thus entering a float number by Numpad would not work as the input field expects a . (in Chrome). That's why you should use type="text" if you have international users on your website.


You can try this on desktop (also with Numpad) and your phone:

_x000D_
_x000D_
<p>Input with type text:</p>
<input type="text" inputmode="decimal" value="1.5">
<br>
<p>Input with type number:</p>
<input type="number" inputmode="decimal" value="1.5">
_x000D_
_x000D_
_x000D_


Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode

Git - Ignore node_modules folder everywhere

Use the universal one-liner in terminal in the project directory:

touch .gitignore && echo "node_modules/" >> .gitignore && git rm -r --cached node_modules ; git status

It works no matter if you've created a .gitignore or not, no matter if you've added node_modules to git tracking or not.

Then commit and push the .gitignore changes.

Explanation

touch will generate the .gitignore file if it doesn't already exist.

echo and >> will append node_modules/ at the end of .gitignore, causing the node_modules folder and all subfolders to be ignored.

git rm -r --cached removes the node_modules folder from git control if it was added before. Otherwise, this will show a warning pathspec 'node_modules' did not match any files, which has no side effects and you can safely ignore. The flags cause the removal to be recursive and include the cache.

git status displays the new changes. A change to .gitignore will appear, while node_modules will not appear as it is no longer being tracked by git.

How does one capture a Mac's command key via JavaScript?

I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ?+x:, you can detect the x key AND check if event.metaKey is set to true. For example:

var key = event.keyCode || event.charCode || 0;
console.log(key, event.metaKey);

When pressing x on it's own, this will output 120, false. When pressing ?+x, it will output 120, true

This only seems to work in Safari - not Chrome

estimating of testing effort as a percentage of development time

The Google Testing Blog discussed this problem recently:

So a naive answer is that writing test carries a 10% tax. But, we pay taxes in order to get something in return.

(snip)

These benefits translate to real value today as well as tomorrow. I write tests, because the additional benefits I get more than offset the additional cost of 10%. Even if I don't include the long term benefits, the value I get from test today are well worth it. I am faster in developing code with test. How much, well that depends on the complexity of the code. The more complex the thing you are trying to build is (more ifs/loops/dependencies) the greater the benefit of tests are.

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

Changing project port number in Visual Studio 2013

This is the only solution that worked for me after trying several of those above. Switch to your c:\users folder and search for .sln and then remove all .sln files that have your project name. Then restart your computer and rebuild the solution (F5) and it worked!

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

Unresolved Import Issues with PyDev and Eclipse

I had some issues importing additional libraries, after trying to resolve the problem, by understanding PYTHONPATH, Interpreter, and Grammar I found that I did everything write but the problems continue. After that, I just add a new empty line in the files that had the import errors and saved them and the error was resolved.

Rails Object to hash

Old question, but heavily referenced ... I think most people use other methods, but there is infact a to_hash method, it has to be setup right. Generally, pluck is a better answer after rails 4 ... answering this mainly because I had to search a bunch to find this thread or anything useful & assuming others are hitting the same problem...

Note: not recommending this for everyone, but edge cases!


From the ruby on rails api ... http://api.rubyonrails.org/classes/ActiveRecord/Result.html ...

This class encapsulates a result returned from calling #exec_query on any database connection adapter. For example:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>

...

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ] ...

How can you represent inheritance in a database?

The another way to do it, is using the INHERITS component. For example:

CREATE TABLE person (
    id int ,
    name varchar(20),
    CONSTRAINT pessoa_pkey PRIMARY KEY (id)
);

CREATE TABLE natural_person (
    social_security_number varchar(11),
    CONSTRAINT pessoaf_pkey PRIMARY KEY (id)
) INHERITS (person);


CREATE TABLE juridical_person (
    tin_number varchar(14),
    CONSTRAINT pessoaj_pkey PRIMARY KEY (id)
) INHERITS (person);

Thus it's possible to define a inheritance between tables.

Returning a C string from a function

Your function signature needs to be:

const char * myFunction()
{
    return "My String";
}

Background:

It's so fundamental to C & C++, but little more discussion should be in order.

In C (& C++ for that matter), a string is just an array of bytes terminated with a zero byte - hence the term "string-zero" is used to represent this particular flavour of string. There are other kinds of strings, but in C (& C++), this flavour is inherently understood by the language itself. Other languages (Java, Pascal, etc.) use different methodologies to understand "my string".

If you ever use the Windows API (which is in C++), you'll see quite regularly function parameters like: "LPCSTR lpszName". The 'sz' part represents this notion of 'string-zero': an array of bytes with a null (/zero) terminator.

Clarification:

For the sake of this 'intro', I use the word 'bytes' and 'characters' interchangeably, because it's easier to learn this way. Be aware that there are other methods (wide-characters, and multi-byte character systems (mbcs)) that are used to cope with international characters. UTF-8 is an example of an mbcs. For the sake of intro, I quietly 'skip over' all of this.

Memory:

This means that a string like "my string" actually uses 9+1 (=10!) bytes. This is important to know when you finally get around to allocating strings dynamically.

So, without this 'terminating zero', you don't have a string. You have an array of characters (also called a buffer) hanging around in memory.

Longevity of data:

The use of the function this way:

const char * myFunction()
{
    return "My String";
}

int main()
{
    const char* szSomeString = myFunction(); // Fraught with problems
    printf("%s", szSomeString);
}

... will generally land you with random unhandled-exceptions/segment faults and the like, especially 'down the road'.

In short, although my answer is correct - 9 times out of 10 you'll end up with a program that crashes if you use it that way, especially if you think it's 'good practice' to do it that way. In short: It's generally not.

For example, imagine some time in the future, the string now needs to be manipulated in some way. Generally, a coder will 'take the easy path' and (try to) write code like this:

const char * myFunction(const char* name)
{
    char szBuffer[255];
    snprintf(szBuffer, sizeof(szBuffer), "Hi %s", name);
    return szBuffer;
}

That is, your program will crash because the compiler (may/may not) have released the memory used by szBuffer by the time the printf() in main() is called. (Your compiler should also warn you of such problems beforehand.)

There are two ways to return strings that won't barf so readily.

  1. returning buffers (static or dynamically allocated) that live for a while. In C++ use 'helper classes' (for example, std::string) to handle the longevity of data (which requires changing the function's return value), or
  2. pass a buffer to the function that gets filled in with information.

Note that it is impossible to use strings without using pointers in C. As I have shown, they are synonymous. Even in C++ with template classes, there are always buffers (that is, pointers) being used in the background.

So, to better answer the (now modified question). (There are sure to be a variety of 'other answers' that can be provided.)

Safer Answers:

Example 1, using statically allocated strings:

const char* calculateMonth(int month)
{
    static char* months[] = {"Jan", "Feb", "Mar" .... };
    static char badFood[] = "Unknown";
    if (month<1 || month>12)
        return badFood; // Choose whatever is appropriate for bad input. Crashing is never appropriate however.
    else
        return months[month-1];
}

int main()
{
    printf("%s", calculateMonth(2)); // Prints "Feb"
}

What the 'static' does here (many programmers do not like this type of 'allocation') is that the strings get put into the data segment of the program. That is, it's permanently allocated.

If you move over to C++ you'll use similar strategies:

class Foo
{
    char _someData[12];
public:
    const char* someFunction() const
    { // The final 'const' is to let the compiler know that nothing is changed in the class when this function is called.
        return _someData;
    }
}

... but it's probably easier to use helper classes, such as std::string, if you're writing the code for your own use (and not part of a library to be shared with others).

Example 2, using caller-defined buffers:

This is the more 'foolproof' way of passing strings around. The data returned isn't subject to manipulation by the calling party. That is, example 1 can easily be abused by a calling party and expose you to application faults. This way, it's much safer (albeit uses more lines of code):

void calculateMonth(int month, char* pszMonth, int buffersize)
{
    const char* months[] = {"Jan", "Feb", "Mar" .... }; // Allocated dynamically during the function call. (Can be inefficient with a bad compiler)
    if (!pszMonth || buffersize<1)
        return; // Bad input. Let junk deal with junk data.
    if (month<1 || month>12)
    {
        *pszMonth = '\0'; // Return an 'empty' string
        // OR: strncpy(pszMonth, "Bad Month", buffersize-1);
    }
    else
    {
        strncpy(pszMonth, months[month-1], buffersize-1);
    }
    pszMonth[buffersize-1] = '\0'; // Ensure a valid terminating zero! Many people forget this!
}

int main()
{
    char month[16]; // 16 bytes allocated here on the stack.
    calculateMonth(3, month, sizeof(month));
    printf("%s", month); // Prints "Mar"
}

There are lots of reasons why the second method is better, particularly if you're writing a library to be used by others (you don't need to lock into a particular allocation/deallocation scheme, third parties can't break your code, and you don't need to link to a specific memory management library), but like all code, it's up to you on what you like best. For that reason, most people opt for example 1 until they've been burnt so many times that they refuse to write it that way anymore ;)

Disclaimer:

I retired several years back and my C is a bit rusty now. This demo code should all compile properly with C (it is OK for any C++ compiler though).

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

This is caused because there is a database running on your computer. In my case, it was an Oracle data base. By default, everytime you start your computer, the services of the database automatically starts.

Go to Start >> find Oracle or whatever data-base in the list of programms >> and manually stop the database. It appears that there is a conflict of port.

jQuery find and replace string

You could do something like this:

HTML

<div class="element">
   <span>Hi, I am Murtaza</span>
</div>


jQuery

$(".element span").text(function(index, text) { 
    return text.replace('am', 'am not'); 
});

Passing a String by Reference in Java?

In Java nothing is passed by reference. Everything is passed by value. Object references are passed by value. Additionally Strings are immutable. So when you append to the passed String you just get a new String. You could use a return value, or pass a StringBuffer instead.

What's the difference between window.location= and window.location.replace()?

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it? or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off. Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out. For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

Convert between UIImage and Base64 string

For iOS 7+, Objective-C, here's how to make the conversion starting with an image URL:

NSURL *url = [NSURL URLWithString:self.groove.thumbnailURL];

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

NSString *base64String = [UIImagePNGRepresentation(image)
base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

URL string format for connecting to Oracle database with JDBC

I'm not a Java developer so unfortunatly I can't comment on your code directly however I found this in an Oracle FAQ regarding the form of a connection string

jdbc:oracle:<drivertype>:<username/password>@<database>

From the Oracle JDBC FAQ

http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#05_03

Hope that helps

ActionBarActivity is deprecated

Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity.

Read here and here for more information.

Download a specific tag with Git

Working off of Peter Johnson's answer, I created a nice little alias for myself:

alias gcolt="git checkout $(git tag | sort -V | tail -1)"

aka 'git checkout latest tag'.

This relies on the GNU version of sort, which appropriately handles situations like the one lOranger pointed out:

v1.0.1
...
v1.0.9
v1.0.10

If you're on a mac, brew install coreutils and then call gsort instead.

Flutter : Vertically center column

For me the problem was there was was Expanded inside the column which I had to remove and it worked.

Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded( // remove this
              flex: 2,
              child: Text("content here"),
            ),
          ],
        )

Is there StartsWith or Contains in t sql with variables?

It seems like what you want is http://msdn.microsoft.com/en-us/library/ms186323.aspx.

In your example it would be (starts with):

set @isExpress = (CharIndex('Express Edition', @edition) = 1)

Or contains

set @isExpress = (CharIndex('Express Edition', @edition) >= 1)

ASP.NET MVC Razor render without encoding

As well as the already mentioned @Html.Raw(string) approach, if you output an MvcHtmlString it will not be encoded. This can be useful when adding your own extensions to the HtmlHelper, or when returning a value from your view model that you know may contain html.

For example, if your view model was:

public class SampleViewModel
{
  public string SampleString { get; set; }
  public MvcHtmlString SampleHtmlString { get; set; }
}

For Core 1.0+ (and MVC 5+) use HtmlString

public class SampleViewModel
{
  public string SampleString { get; set; }
  public HtmlString SampleHtmlString { get; set; }
}

then

<!-- this will be encoded -->
<div>@Model.SampleString</div>
<!-- this will not be encoded -->
<div>@Html.Raw(Model.SampleString)</div>
<!-- this will not be encoded either -->
<div>@Model.SampleHtmlString</div>

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

It could be your Hibernate entity relationship causing the issue...simply stop lazy loading of that related entity...for example...I resolved below by setting lazy="false" for customerType.

<class name="Customer" table="CUSTOMER">
        <id name="custId" type="long">
            <column name="CUSTID" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="phone" type="java.lang.String">
            <column name="PHONE" />
        </property>
        <property name="pan" type="java.lang.String">
            <column name="PAN" />
        </property>

        <many-to-one name="customerType" not-null="true" lazy="false"></many-to-one>
    </class>
</hibernate-mapping>

How to validate phone numbers using regex

/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i

This matches:

 - (+351) 282 43 50 50
 - 90191919908
 - 555-8909
 - 001 6867684
 - 001 6867684x1
 - 1 (234) 567-8901
 - 1-234-567-8901 x1234
 - 1-234-567-8901 ext1234
 - 1-234 567.89/01 ext.1234
 - 1(234)5678901x1234
 - (123)8575973
 - (0055)(123)8575973

On $n, it saves:

  1. Country indicator
  2. Phone number
  3. Extension

You can test it on https://www.regexpal.com/?fam=99127

ALTER TABLE on dependent column

I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.

ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl) 
    REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back

However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

Browser (webapi):

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

Python: split a list based on a condition?

good.append(x) if x in goodvals else bad.append(x)

This elegant and concise answer by @dansalmo showed up buried in the comments, so I'm just reposting it here as an answer so it can get the prominence it deserves, especially for new readers.

Complete example:

good, bad = [], []
for x in my_list:
    good.append(x) if x in goodvals else bad.append(x)

Authentication issues with WWW-Authenticate: Negotiate

Putting this information here for future readers' benefit.

  • 401 (Unauthorized) response header -> Request authentication header

  • Here are several WWW-Authenticate response headers. (The full list is at IANA: HTTP Authentication Schemes.)

    • WWW-Authenticate: Basic-> Authorization: Basic + token - Use for basic authentication
    • WWW-Authenticate: NTLM-> Authorization: NTLM + token (2 challenges)
    • WWW-Authenticate: Negotiate -> Authorization: Negotiate + token - used for Kerberos authentication
      • By the way: IANA has this angry remark about Negotiate: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).

You can set the Authorization: Basic header only when you also have the WWW-Authenticate: Basic header on your 401 challenge.

But since you have WWW-Authenticate: Negotiate this should be the case for Kerberos based authentication.

Error CS2001: Source file '.cs' could not be found

I had this problem, too.

Possible causes in my case: I had deleted a duplicated view twice and a view model. I reverted one of the deletes and then the InitializeComponent error appeared. I took these steps.

  1. I checked all of the solutions mentioned on this question. The class name and build action were correct.
  2. I Cleaned my Solution and rebuilt. Another error appeared. "Error CS2001: Source file '.cs' could not be found"
  3. I found this answer and followed the steps.
  4. I reloaded the project and cleaned/rebuilt again.
  5. My solution builds without errors and my application works now.

How to set ObjectId as a data type in mongoose

Unlike traditional RBDMs, mongoDB doesn't allow you to define any random field as the primary key, the _id field MUST exist for all standard documents.

For this reason, it doesn't make sense to create a separate uuid field.

In mongoose, the ObjectId type is used not to create a new uuid, rather it is mostly used to reference other documents.

Here is an example:

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Product = new Schema({
    categoryId  : ObjectId, // a product references a category _id with type ObjectId
    title       : String,
    price       : Number
});

As you can see, it wouldn't make much sense to populate categoryId with a ObjectId.

However, if you do want a nicely named uuid field, mongoose provides virtual properties that allow you to proxy (reference) a field.

Check it out:

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
    title       : String,
    sortIndex   : String
});

Schema_Category.virtual('categoryId').get(function() {
    return this._id;
});

So now, whenever you call category.categoryId, mongoose just returns the _id instead.

You can also create a "set" method so that you can set virtual properties, check out this link for more info

Create a variable name with "paste" in R?

In my case the symbols I create (Tax1, Tax2, etc.) already had values but I wanted to use a loop and assign the symbols to another variable. So the above two answers gave me a way to accomplish this. This may be helpful in answering your question as the assignment of a value can take place anytime later.

output=NULL
for(i in 1:8){
   Tax=eval(as.symbol(paste("Tax",i,sep="")))
   L_Data1=L_Data_all[which(L_Data_all$Taxon==Tax[1] | L_Data_all$Taxon==Tax[2] | L_Data_all$Taxon==Tax[3] | L_Data_all$Taxon==Tax[4] | L_Data_all$Taxon==Tax[5]),]
   L_Data=L_Data1$Length[which(L_Data1$Station==Plant[1] | L_Data1$Station==Plant[2])]
   h=hist(L_Data,breaks=breaks,plot=FALSE)
   output=cbind(output,h$counts)
}

What is the difference between synchronous and asynchronous programming (in node.js)

The function makes the second one asynchronous.

The first one forces the program to wait for each line to finish it's run before the next one can continue. The second one allows each line to run together (and independently) at once.

Languages and frameworks (js, node.js) that allow asynchronous or concurrency is great for things that require real time transmission (eg. chat, stock applications).

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

What if you do this (as was suggested earlier):

new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000

Keyboard shortcut to comment lines in Sublime Text 3

I prefer pressing Ctrl + / to (un)comment the current line. Plus, I want the cursor to move down one line, thus this way I can (un)comment several lines easily. If you install the "Chain of Command" plugin, you can combine these two operations:

[
    { 
        "keys": ["ctrl+keypad_divide"], 
        "command": "chain",
        "args": {
            "commands": [
                ["toggle_comment", { "block": false }],
                ["move", {"by": "lines", "forward": true}]
            ]
        }
    }
]

Check if a JavaScript string is a URL

Here's just a very simple check to make sure there's a valid protocol, and the domain extension must be two or more characters.

is_valid_url = ( $url ) => {

    let $url_object = null;

    try {
        $url_object = new URL( $url );
    } catch ( $error ) {
        return false;
    }

    const $protocol = $url_object.protocol;
    const $protocol_position = $url.lastIndexOf( $protocol );
    const $domain_extension_position = $url.lastIndexOf( '.' );

    return (
        $protocol_position === 0 &&
        [ 'http:', 'https:' ].indexOf( $protocol ) !== - 1 &&
        $domain_extension_position > 2 && $url.length - $domain_extension_position > 2
    );

};

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

The excellent library Type::Tiny provides an framework with which to build type-checking into your Perl code. What I show here is only the thinnest tip of the iceberg and is using Type::Tiny in the most simplistic and manual way.

Be sure to check out the Type::Tiny::Manual for more information.

use Types::Common::String qw< NonEmptyStr >;

if ( NonEmptyStr->check($name) ) {
    # Do something here.
}

NonEmptyStr->($name);  # Throw an exception if validation fails

Quicksort: Choosing the pivot

In a truly optimized implementation, the method for choosing pivot should depend on the array size - for a large array, it pays off to spend more time choosing a good pivot. Without doing a full analysis, I would guess "middle of O(log(n)) elements" is a good start, and this has the added bonus of not requiring any extra memory: Using tail-call on the larger partition and in-place partitioning, we use the same O(log(n)) extra memory at almost every stage of the algorithm.

Convert text into number in MySQL query

if your primary key is a string in a format like

ABC/EFG/EE/13/123(sequence number)
this sort of string can be easily used for sorting with the delimiter("/")

we can use the following query to order a table with this type of key

SELECT * FROM `TABLE_NAME` ORDER BY 
CONVERT(REVERSE(SUBSTRING(REVERSE(`key_column_name`), 1, LOCATE('/', REVERSE(`key_column_name`)) - 1)) , UNSIGNED INTEGER) DESC

How to add a recyclerView inside another recyclerView

you can use LayoutInflater to inflate your dynamic data as a layout file.

UPDATE : first create a LinearLayout inside your CardView's layout and assign an ID for it. after that create a layout file that you want to inflate. at last in your onBindViewHolder method in your "RAdaper" class. write these codes :

  mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

  view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);

after that you can initialize data and ClickListeners with your RAdapter Data. hope it helps.

this and this may useful :)

Swift_TransportException Connection could not be established with host smtp.gmail.com

Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.gmail.com [Connection refused #111]

Connection refused is a very explicit and clear error message. It means that the socket connection could not be established because the remote end actively refused to connect.

It's very unlikely that Google is blocking the connection.

It's very likely that your web hosting provider has firewall settings that block outgoing connections on port 465, or that they are blocking SMTP to Gmail. 465 is the "wrong" port for secure SMTP, though it is often used, and Gmail does listen there. Try port 587 instead. If the connection is still refused, call your host and ask them what's up.

Printing Batch file results to a text file

Have you tried moving DEL %FILE%.txt% to after @echo %FILE% deleted. >> results.txt so that it looks like this?

@echo %FILE% deleted. >> results.txt
DEL %FILE%.txt

How to list files inside a folder with SQL Server

Create a SQLCLR assembly with external access permission that returns the list of files as a result set. There are many examples how to do this, eg. Yet another TVF: returning files from a directory or Trading in xp_cmdshell for SQLCLR (Part 1) - List Directory Contents.

How do I get and set Environment variables in C#?

This will work for an environment variable that is machine setting. For Users, just change to User instead.

String EnvironmentPath = System.Environment
                .GetEnvironmentVariable("Variable_Name", EnvironmentVariableTarget.Machine);

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Staging Deleted files

You can use this command

git add  `git ls-files --deleted`

Inserting created_at data with Laravel

You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:

protected $fillable = ['name', 'created_at']; 

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

For me this was thrown when running unit tests under MSTest (VS2015). Had to add

<startup useLegacyV2RuntimeActivationPolicy="true">
</startup>

in

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\TE.ProcessHost.Managed.exe.config

Mixed-Mode Assembly MSTest Failing in VS2015

Is it correct to use DIV inside FORM?

As the others have said, it's all good, you can do it just fine. For me personally, I try to keep a form of hierarchical structure with my elements with a div being the outer most parent element. I try to use only table p ul and span inside forms. Just makes it easier for me to keep track of parent/children relationships inside my webpages.

Confused about __str__ on list in Python

Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.

One is __str__, the other is __repr__

__str__ will return a human readable string. __repr__ will return an internal representation.

__repr__ can be invoked on an object by calling repr(obj) or by using backticks `obj`.

When printing lists as well as other container classes, the contained elements will be printed using __repr__.

How to select all rows which have same value in some column

SELECT * FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Update : for better performance and faster query its good to add e1 before *

SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

How to stop (and restart) the Rails Server?

Press Ctrl+C

When you start the server it mentions this in the startup text.

Send Email to multiple Recipients with MailMessage?

As suggested by Adam Miller in the comments, I'll add another solution.

The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:

MailMessage Msg = new MailMessage(fromMail, addresses);

In this particular case, we can replace the ';' for ',' and still make use of the constructor.

MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));

Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.

Return 0 if field is null in MySQL

You can use coalesce(column_name,0) instead of just column_name. The coalesce function returns the first non-NULL value in the list.

I should mention that per-row functions like this are usually problematic for scalability. If you think your database may get to be a decent size, it's often better to use extra columns and triggers to move the cost from the select to the insert/update.

This amortises the cost assuming your database is read more often than written (and most of them are).

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

CSS Float: Floating an image to the left of the text

I almost always just use overflow:hidden on my text-elements in those situations, it often works like a charm ;)

.post-container {
 margin: 20px 20px 0 0;
 border:5px solid #333;
}
.post-thumb img {
 float: left;
}
.post-content {
 overflow:hidden;
}

How to delete all data from solr and hbase

When clearing out a Solr index, you should also do a commit and optimize after running the delete-all query. Full steps required (curl is all you need): http://www.alphadevx.com/a/365-Clearing-a-Solr-search-index

Show/hide image with JavaScript

This is working code:

<html>
  <body bgcolor=cyan>
    <img src ="backgr1.JPG" id="my" width="310" height="392" style="position: absolute; top:92px; left:375px; visibility:hidden"/>
    <script type="text/javascript">
      function tend() {
        document.getElementById('my').style.visibility='visible';
      }
      function tn() {
        document.getElementById('my').style.visibility='hidden';
      }
    </script>
    <input type="button" onclick="tend()" value="back">
    <input type="button" onclick="tn()" value="close">
  </body>
</html>

How to extend an existing JavaScript array with another array, without creating a new array

You should use a loop-based technique. Other answers on this page that are based on using .apply can fail for large arrays.

A fairly terse loop-based implementation is:

Array.prototype.extend = function (other_array) {
    /* You should include a test to check whether other_array really is an array */
    other_array.forEach(function(v) {this.push(v)}, this);
}

You can then do the following:

var a = [1,2,3];
var b = [5,4,3];
a.extend(b);

DzinX's answer (using push.apply) and other .apply based methods fail when the array that we are appending is large (tests show that for me large is > 150,000 entries approx in Chrome, and > 500,000 entries in Firefox). You can see this error occurring in this jsperf.

An error occurs because the call stack size is exceeded when 'Function.prototype.apply' is called with a large array as the second argument. (MDN has a note on the dangers of exceeding call stack size using Function.prototype.apply - see the section titled "apply and built-in functions".)

For a speed comparison with other answers on this page, check out this jsperf (thanks to EaterOfCode). The loop-based implementation is similar in speed to using Array.push.apply, but tends to be a little slower than Array.slice.apply.

Interestingly, if the array you are appending is sparse, the forEach based method above can take advantage of the sparsity and outperform the .apply based methods; check out this jsperf if you want to test this for yourself.

By the way, do not be tempted (as I was!) to further shorten the forEach implementation to:

Array.prototype.extend = function (array) {
    array.forEach(this.push, this);
}

because this produces garbage results! Why? Because Array.prototype.forEach provides three arguments to the function it calls - these are: (element_value, element_index, source_array). All of these will be pushed onto your first array for every iteration of forEach if you use "forEach(this.push, this)"!

Conveniently map between enum and int / String

I'm not sure if it's the same in Java, but enum types in C are automatically mapped to integers as well so you can use either the type or integer to access it. Have you tried simply accessing it with integer yet?

SQL Query for Selecting Multiple Records

Try the following code:

SELECT *
FROM users
WHERE firstname IN ('joe','jane');

How can I get a list of all open named pipes in Windows?

Try the following instead:

String[] listOfPipes = System.IO.Directory.GetFiles(@"\\.\pipe\");

What's the simplest way of detecting keyboard input in a script from the terminal?

Well, since the date of this question post, a Python library addressed this topic. pynput library, from Moses Palmer, is GREAT to catch keyboard and mouse events in a very simple way.

(mind the missing 'i' in pynput - I missed it too... ;-) )

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

Set multiple system properties Java command line

Answer is NO. You might have seen an example where somebody would have set something like :

-DArguments=a=1,b=2,c=3,d=4,e=cow

Then the application would parse value of Arguments property string to get individual values. In your main you can get the key values as(Assuming input format is guaranteed):

String line = System.getProperty("Arguments");
if(line != null) {
  String str[] = line.split(",");
    for(int i=1;i<str.length;i++){
        String arr[] = str[i].split("=");
        System.out.println("Key = " + arr[0]);
        System.out.println("Value = " +  arr[1]);
    }
}

Also, the -D should be before the main class or the jar file in the java command line. Example : java -DArguments=a=1,b=2,c=3,d=4,e=cow MainClass

PYODBC--Data source name not found and no default driver specified

I've met same problem and fixed it changing connection string like below. Write

'DRIVER={ODBC Driver 13 for SQL Server}'

instead of

'DRIVER={SQL Server}'

Rotate a div using javascript

Can be pretty easily done assuming you're using jQuery and css3:

http://jsfiddle.net/S7JDU/8/

HTML:

<div id="clicker">Click Here</div>
<div id="rotating"></div>

CSS:

#clicker { 
    width: 100px; 
    height: 100px; 
    background-color: Green; 
}

#rotating { 
    width: 100px; 
    height: 100px; 
    background-color: Red; 
    margin-top: 50px; 
    -webkit-transition: all 0.3s ease-in-out;
    -moz-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
}

.rotated { 
    transform:rotate(25deg); 
    -webkit-transform:rotate(25deg); 
    -moz-transform:rotate(25deg); 
    -o-transform:rotate(25deg); 
}

JS:

$(document).ready(function() {
    $('#clicker').click(function() {
        $('#rotating').toggleClass('rotated');
    });
});

Remove duplicated rows

the general answer can be for example:

df <-  data.frame(rbind(c(2,9,6),c(4,6,7),c(4,6,7),c(4,6,7),c(2,9,6))))



new_df <- df[-which(duplicated(df)), ]

output:

      X1 X2 X3
    1  2  9  6
    2  4  6  7

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

For me I used axios and by deafult it sends header

content-type: application/x-www-form-urlencoded

so i change to send:

content-type: application/octet-stream

and also had to add this Content-Type to AWS signature

const params = {
    Bucket: bucket,
    Key: key,
    Expires: expires,
    ContentType = 'application/octet-stream'
}

const s3 = new AWS.S3()
s3.getSignedUrl('putObject', params)

How to dump raw RTSP stream to file?

You can use mplayer.

mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi

The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.

In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.

An invalid XML character (Unicode: 0xc) was found

The character 0x0C is be invalid in XML 1.0 but would be a valid character in XML 1.1. So unless the xml file specifies the version as 1.1 in the prolog it is simply invalid and you should complain to the producer of this file.

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

For now I just switched registry URL from https to http. Like this:

npm config set registry="http://registry.npmjs.org/"

How does PHP 'foreach' actually work?

Great question, because many developers, even experienced ones, are confused by the way PHP handles arrays in foreach loops. In the standard foreach loop, PHP makes a copy of the array that is used in the loop. The copy is discarded immediately after the loop finishes. This is transparent in the operation of a simple foreach loop. For example:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    echo "{$item}\n";
}

This outputs:

apple
banana
coconut

So the copy is created but the developer doesn't notice, because the original array isn’t referenced within the loop or after the loop finishes. However, when you attempt to modify the items in a loop, you find that they are unmodified when you finish:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $item = strrev ($item);
}

print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
)

Any changes from the original can't be notices, actually there are no changes from the original, even though you clearly assigned a value to $item. This is because you are operating on $item as it appears in the copy of $set being worked on. You can override this by grabbing $item by reference, like so:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $item = strrev($item);
}
print_r($set);

This outputs:

Array
(
    [0] => elppa
    [1] => ananab
    [2] => tunococ
)

So it is evident and observable, when $item is operated on by-reference, the changes made to $item are made to the members of the original $set. Using $item by reference also prevents PHP from creating the array copy. To test this, first we’ll show a quick script demonstrating the copy:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $set[] = ucfirst($item);
}
print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
    [3] => Apple
    [4] => Banana
    [5] => Coconut
)

As it is shown in the example, PHP copied $set and used it to loop over, but when $set was used inside the loop, PHP added the variables to the original array, not the copied array. Basically, PHP is only using the copied array for the execution of the loop and the assignment of $item. Because of this, the loop above only executes 3 times, and each time it appends another value to the end of the original $set, leaving the original $set with 6 elements, but never entering an infinite loop.

However, what if we had used $item by reference, as I mentioned before? A single character added to the above test:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $set[] = ucfirst($item);
}
print_r($set);

Results in an infinite loop. Note this actually is an infinite loop, you’ll have to either kill the script yourself or wait for your OS to run out of memory. I added the following line to my script so PHP would run out of memory very quickly, I suggest you do the same if you’re going to be running these infinite loop tests:

ini_set("memory_limit","1M");

So in this previous example with the infinite loop, we see the reason why PHP was written to create a copy of the array to loop over. When a copy is created and used only by the structure of the loop construct itself, the array stays static throughout the execution of the loop, so you’ll never run into issues.

Print all key/value pairs in a Java ConcurrentHashMap

Work 100% sure try this code for the get all hashmap key and value

static HashMap<String, String> map = new HashMap<>();

map.put("one"  " a " );
map.put("two"  " b " );
map.put("three"  " c " );
map.put("four"  " d " );

just call this method whenever you want to show the HashMap value

 private void ShowHashMapValue() {

        /**
         * get the Set Of keys from HashMap
         */
        Set setOfKeys = map.keySet();

/**
 * get the Iterator instance from Set
 */
        Iterator iterator = setOfKeys.iterator();

/**
 * Loop the iterator until we reach the last element of the HashMap
 */
        while (iterator.hasNext()) {
/**
 * next() method returns the next key from Iterator instance.
 * return type of next() method is Object so we need to do DownCasting to String
 */
            String key = (String) iterator.next();

/**
 * once we know the 'key', we can get the value from the HashMap
 * by calling get() method
 */
            String value = map.get(key);

            System.out.println("Key: " + key + ", Value: " + value);
        }
    } 

Making interface implementations async

Better solution is to introduce another interface for async operations. New interface must inherit from original interface.

Example:

interface IIO
{
    void DoOperation();
}

interface IIOAsync : IIO
{
    Task DoOperationAsync();
}


class ClsAsync : IIOAsync
{
    public void DoOperation()
    {
        DoOperationAsync().GetAwaiter().GetResult();
    }

    public async Task DoOperationAsync()
    {
        //just an async code demo
        await Task.Delay(1000);
    }
}


class Program
{
    static void Main(string[] args)
    {
        IIOAsync asAsync = new ClsAsync();
        IIO asSync = asAsync;

        Console.WriteLine(DateTime.Now.Second);

        asAsync.DoOperation();
        Console.WriteLine("After call to sync func using Async iface: {0}", 
            DateTime.Now.Second);

        asAsync.DoOperationAsync().GetAwaiter().GetResult();
        Console.WriteLine("After call to async func using Async iface: {0}", 
            DateTime.Now.Second);

        asSync.DoOperation();
        Console.WriteLine("After call to sync func using Sync iface: {0}", 
            DateTime.Now.Second);

        Console.ReadKey(true);
    }
}

P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.

What is the fastest way to transpose a matrix in C++?

Some details about transposing 4x4 square float (I will discuss 32-bit integer later) matrices with x86 hardware. It's helpful to start here in order to transpose larger square matrices such as 8x8 or 16x16.

_MM_TRANSPOSE4_PS(r0, r1, r2, r3) is implemented differently by different compilers. GCC and ICC (I have not checked Clang) use unpcklps, unpckhps, unpcklpd, unpckhpd whereas MSVC uses only shufps. We can actually combine these two approaches together like this.

t0 = _mm_unpacklo_ps(r0, r1);
t1 = _mm_unpackhi_ps(r0, r1);
t2 = _mm_unpacklo_ps(r2, r3);
t3 = _mm_unpackhi_ps(r2, r3);

r0 = _mm_shuffle_ps(t0,t2, 0x44);
r1 = _mm_shuffle_ps(t0,t2, 0xEE);
r2 = _mm_shuffle_ps(t1,t3, 0x44);
r3 = _mm_shuffle_ps(t1,t3, 0xEE);

One interesting observation is that two shuffles can be converted to one shuffle and two blends (SSE4.1) like this.

t0 = _mm_unpacklo_ps(r0, r1);
t1 = _mm_unpackhi_ps(r0, r1);
t2 = _mm_unpacklo_ps(r2, r3);
t3 = _mm_unpackhi_ps(r2, r3);

v  = _mm_shuffle_ps(t0,t2, 0x4E);
r0 = _mm_blend_ps(t0,v, 0xC);
r1 = _mm_blend_ps(t2,v, 0x3);
v  = _mm_shuffle_ps(t1,t3, 0x4E);
r2 = _mm_blend_ps(t1,v, 0xC);
r3 = _mm_blend_ps(t3,v, 0x3);

This effectively converted 4 shuffles into 2 shuffles and 4 blends. This uses 2 more instructions than the implementation of GCC, ICC, and MSVC. The advantage is that it reduces port pressure which may have a benefit in some circumstances. Currently all the shuffles and unpacks can go only to one particular port whereas the blends can go to either of two different ports.

I tried using 8 shuffles like MSVC and converting that into 4 shuffles + 8 blends but it did not work. I still had to use 4 unpacks.

I used this same technique for a 8x8 float transpose (see towards the end of that answer). https://stackoverflow.com/a/25627536/2542702. In that answer I still had to use 8 unpacks but I manged to convert the 8 shuffles into 4 shuffles and 8 blends.

For 32-bit integers there is nothing like shufps (except for 128-bit shuffles with AVX512) so it can only be implemented with unpacks which I don't think can be convert to blends (efficiently). With AVX512 vshufi32x4 acts effectively like shufps except for 128-bit lanes of 4 integers instead of 32-bit floats so this same technique might be possibly with vshufi32x4 in some cases. With Knights Landing shuffles are four times slower (throughput) than blends.

Check number of arguments passed to a Bash script

In case you want to be on the safe side, I recommend to use getopts.

Here is a small example:

    while getopts "x:c" opt; do
      case $opt in
        c)
          echo "-$opt was triggered, deploy to ci account" >&2
          DEPLOY_CI_ACCT="true"
          ;;
            x)
              echo "-$opt was triggered, Parameter: $OPTARG" >&2 
              CMD_TO_EXEC=${OPTARG}
              ;;
            \?)
              echo "Invalid option: -$OPTARG" >&2 
              Usage
              exit 1
              ;;
            :)
              echo "Option -$OPTARG requires an argument." >&2 
              Usage
              exit 1
              ;;
          esac
        done

see more details here for example http://wiki.bash-hackers.org/howto/getopts_tutorial

Mod in Java produces negative numbers

if b > 0:
    int mod = (mod = a % b) < 0 ? a + b : a;

Doesn't use the % operator twice.

Printf width specifier to maintain precision of floating-point value

I run a small experiment to verify that printing with DBL_DECIMAL_DIG does indeed exactly preserve the number's binary representation. It turned out that for the compilers and C libraries I tried, DBL_DECIMAL_DIG is indeed the number of digits required, and printing with even one digit less creates a significant problem.

#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

union {
    short s[4];
    double d;
} u;

void
test(int digits)
{
    int i, j;
    char buff[40];
    double d2;
    int n, num_equal, bin_equal;

    srand(17);
    n = num_equal = bin_equal = 0;
    for (i = 0; i < 1000000; i++) {
        for (j = 0; j < 4; j++)
            u.s[j] = (rand() << 8) ^ rand();
        if (isnan(u.d))
            continue;
        n++;
        sprintf(buff, "%.*g", digits, u.d);
        sscanf(buff, "%lg", &d2);
        if (u.d == d2)
            num_equal++;
        if (memcmp(&u.d, &d2, sizeof(double)) == 0)
            bin_equal++;
    }
    printf("Tested %d values with %d digits: %d found numericaly equal, %d found binary equal\n", n, digits, num_equal, bin_equal);
}

int
main()
{
    test(DBL_DECIMAL_DIG);
    test(DBL_DECIMAL_DIG - 1);
    return 0;
}

I run this with Microsoft's C compiler 19.00.24215.1 and gcc version 7.4.0 20170516 (Debian 6.3.0-18+deb9u1). Using one less decimal digit halves the number of numbers that compare exactly equal. (I also verified that rand() as used indeed produces about one million different numbers.) Here are the detailed results.

Microsoft C

Tested 999507 values with 17 digits: 999507 found numericaly equal, 999507 found binary equal
Tested 999507 values with 16 digits: 545389 found numericaly equal, 545389 found binary equal

GCC

Tested 999485 values with 17 digits: 999485 found numericaly equal, 999485 found binary equal
Tested 999485 values with 16 digits: 545402 found numericaly equal, 545402 found binary equal

How can I break from a try/catch block without throwing an exception in Java

You can always do it with a break from a loop construct or a labeled break as specified in aioobies answer.

public static void main(String[] args) {
    do {
        try {
            // code..
            if (condition)
                break;
            // more code...
        } catch (Exception e) {

        }
    } while (false);
}

Get the current file name in gulp.src()

If you want to use @OverZealous' answer (https://stackoverflow.com/a/21806974/1019307) in Typescript, you need to import instead of require:

import * as debug from 'gulp-debug';

...

    return gulp.src('./examples/*.html')
        .pipe(debug({title: 'example src:'}))
        .pipe(gulp.dest('./build'));

(I also added a title).

How to sum a variable by group

Several years later, just to add another simple base R solution that isn't present here for some reason- xtabs

xtabs(Frequency ~ Category, df)
# Category
# First Second  Third 
#    30      5     34 

Or if you want a data.frame back

as.data.frame(xtabs(Frequency ~ Category, df))
#   Category Freq
# 1    First   30
# 2   Second    5
# 3    Third   34

jQuery $.ajax(), pass success data into separate function

Works fine for me:

<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
    alert(data + "\t" + textStatus);
}

var test = function(str, cb) {
    var data = 'Input values';
    $.ajax({
        type: 'post',
        url: 'http://www.mydomain.com/ajaxscript',
        data: data,
        success: cb
    });
}
test('Hello, world', callback);
</script>

Cannot load properties file from resources directory

I use something like this to load properties file.

        final ResourceBundle bundle = ResourceBundle
                .getBundle("properties/errormessages");

        for (final Enumeration<String> keys = bundle.getKeys(); keys
                .hasMoreElements();) {
            final String key = keys.nextElement();
            final String value = bundle.getString(key);
            prop.put(key, value);
        }

How can I insert into a BLOB column from an insert statement in sqldeveloper?

Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:

insert into blob_fun values(1, hextoraw('453d7a34'));

453d7a34 is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.

printf with std::string?

Please don't use printf("%s", your_string.c_str());

Use cout << your_string; instead. Short, simple and typesafe. In fact, when you're writing C++, you generally want to avoid printf entirely -- it's a leftover from C that's rarely needed or useful in C++.

As to why you should use cout instead of printf, the reasons are numerous. Here's a sampling of a few of the most obvious:

  1. As the question shows, printf isn't type-safe. If the type you pass differs from that given in the conversion specifier, printf will try to use whatever it finds on the stack as if it were the specified type, giving undefined behavior. Some compilers can warn about this under some circumstances, but some compilers can't/won't at all, and none can under all circumstances.
  2. printf isn't extensible. You can only pass primitive types to it. The set of conversion specifiers it understands is hard-coded in its implementation, and there's no way for you to add more/others. Most well-written C++ should use these types primarily to implement types oriented toward the problem being solved.
  3. It makes decent formatting much more difficult. For an obvious example, when you're printing numbers for people to read, you typically want to insert thousands separators every few digits. The exact number of digits and the characters used as separators varies, but cout has that covered as well. For example:

    std::locale loc("");
    std::cout.imbue(loc);
    
    std::cout << 123456.78;
    

    The nameless locale (the "") picks a locale based on the user's configuration. Therefore, on my machine (configured for US English) this prints out as 123,456.78. For somebody who has their computer configured for (say) Germany, it would print out something like 123.456,78. For somebody with it configured for India, it would print out as 1,23,456.78 (and of course there are many others). With printf I get exactly one result: 123456.78. It is consistent, but it's consistently wrong for everybody everywhere. Essentially the only way to work around it is to do the formatting separately, then pass the result as a string to printf, because printf itself simply will not do the job correctly.

  4. Although they're quite compact, printf format strings can be quite unreadable. Even among C programmers who use printf virtually every day, I'd guess at least 99% would need to look things up to be sure what the # in %#x means, and how that differs from what the # in %#f means (and yes, they mean entirely different things).

How do I run a PowerShell script when the computer starts?

Prerequisite:

1. Start powershell with the "Run as Administrator" option

2. Enable running unsigned scripts with:

set-executionpolicy remotesigned

3. prepare your powershell script and know its path:

$path = "C:\Users\myname\myscript.ps1"

Steps:

1. setup a trigger, see also New-JobTrigger (PSScheduledJob) - PowerShell | Microsoft Docs

$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30

2. register a scheduled job, see also Register-ScheduledJob (PSScheduledJob) - PowerShell | Microsoft Docs

Register-ScheduledJob -Trigger $trigger -FilePath $path -Name MyScheduledJob

you can check it with Get-ScheduledJob -Name MyScheduledJob

3. Reboot Windows (restart /r) and check the result with:

Get-Job -name MyScheduledJob

see also Get-Job (Microsoft.PowerShell.Core) - PowerShell | Microsoft Docs

References:

  1. How to enable execution of PowerShell scripts? - Super User
  2. Use PowerShell to Create Job that Runs at Startup | Scripting Blog

deny directory listing with htaccess

Options -Indexes returns a 403 forbidden error for a protected directory. The same behaviour can be achived by using the following Redirect in htaccess :

RedirectMatch 403 ^/folder/?$ 

This will return a forbidden error for example.com/folder/ .

You can also use mod-rewrite to forbid a request for folder.

RewriteEngine on

RewriteRule ^folder/?$ - [F]

If your htaccess is in the folder that you are going to forbid , change RewriteRule's pattern from ^folder/?$ to ^$ .

How to center an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.

Now, add the style to the div class and use the text-align property with center as its value.

See the below example.

<style>
.myDivElement{
    text-align:center;
}
.myDivElement ul li{
   display:inline;

 }
</style>
<div class="myDivElement">
<ul>
    <li>Home</li>
    <li>About</li>
    <li>Gallery</li>
    <li>Contact</li>
</ul>
</div>

Here is the reference website Center Align Unordered List

Any way to clear python's IDLE window?

It seems it is impossible to do it without any external library.

An alternative way if you are using windows and don't want to open and close the shell everytime you want to clear it is by using windows command prompt.

  • Type python and hit enter to turn windows command prompt to python idle (make sure python is installed).

  • Type quit() and hit enter to turn it back to windows command prompt.

  • Type cls and hit enter to clear the command prompt/ windows shell.

Run batch file from Java code

Your code is fine, but the problem is inside the batch file.

You have to show the content of the bat file, your problem is in the paths inside the bat file.