Programs & Examples On #Zest

Zest: The Eclipse Visualization Toolkit, is a set of visualization components built for Eclipse. The entire Zest library has been developed in SWT / Draw2D and integrates seamlessly within Eclipse because of its recognized design.

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

Since unpaidMembers is a dictionary it always returns two values when called with .items() - (key, value). You may want to keep your data as a list of tuples [(name, email, lastname), (name, email, lastname)..].

How to automatically start a service when running a docker container?

First, there is a problem in your Dockerfile:

RUN service mysql restart && /tmp/setup.sh

Docker images do not save running processes. Therefore, your RUN command executes only during docker build phase and stops after the build is completed. Instead, you need to specify the command when the container is started using the CMD or ENTRYPOINT commands like below:

CMD mysql start

Secondly, the docker container needs a process (last command) to keep running, otherwise the container will exit/stop. Therefore, the normal service mysql start command cannot be used directly in the Dockerfile.

Solution

There are three typical ways to keep the process running:

  • Using service command and append non-end command after that like tail -F

    CMD service mysql start && tail -F /var/log/mysql/error.log
    

This is often preferred when you have a single service running as it makes the outputted log accessible to docker.

  • Or use foreground command to do this

    CMD /usr/bin/mysqld_safe
    

This works only if there is a script like mysqld_safe.

  • Or wrap your scripts into start.sh and put this in end

    CMD /start.sh
    

This is best if the command must perform a series of steps, again, /start.sh should stay running.

Note

For the beginner using supervisord is not recommended. Honestly, it is overkill. It is much better to use single service / single command for the container.

BTW: please check https://registry.hub.docker.com for existing mysql docker images for reference

Converting file size in bytes to human-readable string

Here is a prototype to convert a number to a readable string respecting the new international standards.

There are two ways to represent big numbers: You could either display them in multiples of 1000 = 10 3 (base 10) or 1024 = 2 10 (base 2). If you divide by 1000, you probably use the SI prefix names, if you divide by 1024, you probably use the IEC prefix names. The problem starts with dividing by 1024. Many applications use the SI prefix names for it and some use the IEC prefix names. The current situation is a mess. If you see SI prefix names you do not know whether the number is divided by 1000 or 1024

https://wiki.ubuntu.com/UnitsPolicy

http://en.wikipedia.org/wiki/Template:Quantities_of_bytes

Object.defineProperty(Number.prototype,'fileSize',{value:function(a,b,c,d){
 return (a=a?[1e3,'k','B']:[1024,'K','iB'],b=Math,c=b.log,
 d=c(this)/c(a[0])|0,this/b.pow(a[0],d)).toFixed(2)
 +' '+(d?(a[1]+'MGTPEZY')[--d]+a[2]:'Bytes');
},writable:false,enumerable:false});

This function contains no loop, and so it's probably faster than some other functions.

Usage:

IEC prefix

console.log((186457865).fileSize()); // default IEC (power 1024)
//177.82 MiB
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

SI prefix

console.log((186457865).fileSize(1)); //1,true for SI (power 1000)
//186.46 MB 
//kB,MB,GB,TB,PB,EB,ZB,YB

i set the IEC as default because i always used binary mode to calculate the size of a file... using the power of 1024


If you just want one of them in a short oneliner function:

SI

function fileSizeSI(a,b,c,d,e){
 return (b=Math,c=b.log,d=1e3,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'kMGTPEZY'[--e]+'B':'Bytes')
}
//kB,MB,GB,TB,PB,EB,ZB,YB

IEC

function fileSizeIEC(a,b,c,d,e){
 return (b=Math,c=b.log,d=1024,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'KMGTPEZY'[--e]+'iB':'Bytes')
}
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

Usage:

console.log(fileSizeIEC(7412834521));

if you have some questions about the functions just ask

Warning: Cannot modify header information - headers already sent by ERROR

Check something with echo, print() or printr() in the include file, header.php.

It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>. This could also make a problem.

How to Convert Int to Unsigned Byte and Back

The Integer.toString(size) call converts into the char representation of your integer, i.e. the char '5'. The ASCII representation of that character is the value 65.

You need to parse the string back to an integer value first, e.g. by using Integer.parseInt, to get back the original int value.

As a bottom line, for a signed/unsigned conversion, it is best to leave String out of the picture and use bit manipulation as @JB suggests.

Function pointer as a member of a C struct

Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?

PString * initializeString() {
    PString *str;
    str = (PString *) malloc(sizeof(PString));
    str->length = &length;
    return str;
}

How to declare a constant in Java

  1. You can use an enum type in Java 5 and onwards for the purpose you have described. It is type safe.
  2. A is an instance variable. (If it has the static modifier, then it becomes a static variable.) Constants just means the value doesn't change.
  3. Instance variables are data members belonging to the object and not the class. Instance variable = Instance field.

If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.

Java 5 and up enum type

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public String toString(){
    return this.color;
  }
}

If you wish to change the value of the enum you have created, provide a mutator method.

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public void setColor(String color){
    this.color = color;
  }

  public String toString(){
    return this.color;
  }
}

Example of accessing:

public static void main(String args[]){
  System.out.println(Color.RED.getColor());

  // or

  System.out.println(Color.GREEN);
}

How to call a method defined in an AngularJS directive?

Building on Oliver's answer - you might not always need to access a directive's inner methods, and in those cases you probably don't want to have to create a blank object and add a control attr to the directive just to prevent it from throwing an error (cannot set property 'takeTablet' of undefined).

You also might want to use the method in other places within the directive.

I would add a check to make sure scope.control exists, and set methods to it in a similar fashion to the revealing module pattern

app.directive('focusin', function factory() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div>A:{{control}}</div>',
    scope: {
      control: '='
    },
    link : function (scope, element, attrs) {
      var takenTablets = 0;
      var takeTablet = function() {
        takenTablets += 1;  
      }

      if (scope.control) {
        scope.control = {
          takeTablet: takeTablet
        };
      }
    }
  };
});

How to change a string into uppercase

To get upper case version of a string you can use str.upper:

s = 'sdsd'
s.upper()
#=> 'SDSD'

On the other hand string.ascii_uppercase is a string containing all ASCII letters in upper case:

import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

Remove credentials from Git

Answer for Mac Devices:

Go to

Applications/Utilities/Keychain Acccess

Search for git.credentials, and delete the git credentials for the desired URL.

Recyclerview inside ScrollView not scrolling smoothly

Try doing:

RecyclerView v = (RecyclerView) findViewById(...);
v.setNestedScrollingEnabled(false);

As an alternative, you can modify your layout using the support design library. I guess your current layout is something like:

<ScrollView >
   <LinearLayout >

       <View > <!-- upper content -->
       <RecyclerView > <!-- with custom layoutmanager -->

   </LinearLayout >
</ScrollView >

You can modify that to:

<CoordinatorLayout >

    <AppBarLayout >
        <CollapsingToolbarLayout >
             <!-- with your content, and layout_scrollFlags="scroll" -->
        </CollapsingToolbarLayout >
    </AppBarLayout >

    <RecyclerView > <!-- with standard layoutManager -->

</CoordinatorLayout >

However this is a longer road to take, and if you are OK with the custom linear layout manager, then just disable nested scrolling on the recycler view.

Edit (4/3/2016)

The v 23.2 release of the support libraries now includes a factory “wrap content” feature in all default LayoutManagers. I didn’t test it, but you should probably prefer it to that library you were using.

<ScrollView >
   <LinearLayout >

       <View > <!-- upper content -->
       <RecyclerView > <!-- with wrap_content -->

   </LinearLayout >
</ScrollView >

Add swipe to delete UITableViewCell

It's new feature in iOS11 and Swift 4.

Reference link :

Trailing Swipe :

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let delete = UIContextualAction(style: .destructive, title: "Delete") { (action, sourceView, completionHandler) in
        print("index path of delete: \(indexPath)")
        completionHandler(true)
    }

    let rename = UIContextualAction(style: .normal, title: "Edit") { (action, sourceView, completionHandler) in
        print("index path of edit: \(indexPath)")
        completionHandler(true)
    }
    let swipeActionConfig = UISwipeActionsConfiguration(actions: [rename, delete])
    swipeActionConfig.performsFirstActionWithFullSwipe = false
    return swipeActionConfig
}

enter image description here

Writing/outputting HTML strings unescaped

Complete example for using template functions in RazorEngine (for email generation, for example):

@model SomeModel
@{
    Func<PropertyChangeInfo, object> PropInfo =
        @<tr class="property">
            <td>
                @item.PropertyName                
            </td>
            <td class="value">
                <small class="old">@item.OldValue</small>
                <small class="new">@item.CurrentValue</small>                
            </td>
        </tr>;
}

<body>

@{ WriteLiteral(PropInfo(new PropertyChangeInfo("p1", @Model.Id, 2)).ToString()); }

</body>

How can I create a memory leak in Java?

I don't think anyone has said this yet: you can resurrect an object by overriding the finalize() method such that finalize() stores a reference of this somewhere. The garbage collector will only be called once on the object so after that the object will never destroyed.

How to decode jwt token in javascript without using a library?

you can use pure javascript atob() function to decode token into a string:

atob(token.split('.')[1]);

or parse directly it into a json object:

JSON.parse(atob(token.split('.')[1]));

read about atob() and btoa() built-in javascript functions Base64 encoding and decoding - Web APIs | MDN.

Remove redundant paths from $PATH variable

  1. Just echo $PATH
  2. copy details into a text editor
  3. remove unwanted entries
  4. PATH= # pass new list of entries

Java Minimum and Maximum values in Array

getMaxValue(array);
// get smallest number
getMinValue(array);

You are calling the methods but not using the returned values.

System.out.println(getMaxValue(array));
System.out.println(getMinValue(array)); 

Where are shared preferences stored?

Shared Preferences are the key/value pairs that we can store. They are internal type of storage which means we do not have to create an external database to store it. To see it go to, 1) Go to View in the menu bar. Select Tool Windows. 2) Click on Device File Explorer. 3) Device File Explorer opens up in the right hand side. 4) Find the data folder and click on it. 5) In the data folder, you can select another data folder. 6) Try to search for your package name in this data folder. Ex: com.example.com 7) Then Click on shared_prefs and open the .xml file.

Hope this helps!

Use string contains function in oracle SQL query

By lines I assume you mean rows in the table person. What you're looking for is:

select p.name
from   person p
where  p.name LIKE '%A%'; --contains the character 'A'

The above is case sensitive. For a case insensitive search, you can do:

select p.name
from   person p
where  UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'

For the special character, you can do:

select p.name
from   person p
where  p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)

The LIKE operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the % sign as it means match zero or more characters.

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

String joined = 
                Stream.of(isRead?"read":"", isFlagged?"flagged":"", isActionRequired?"action":"", isHide?"hide":"")
                      .filter(s -> s != null && !s.isEmpty())
                      .collect(Collectors.joining(","));

Vim for Windows - What do I type to save and exit from a file?

Use:

:wq!

The exclamation mark is used for overriding read-only mode.

How to implement __iter__(self) for a container object (Python)

Another option is to inherit from the appropriate abstract base class from the `collections module as documented here.

In case the container is its own iterator, you can inherit from collections.Iterator. You only need to implement the next method then.

An example is:

>>> from collections import Iterator
>>> class MyContainer(Iterator):
...     def __init__(self, *data):
...         self.data = list(data)
...     def next(self):
...         if not self.data:
...             raise StopIteration
...         return self.data.pop()
...         
...     
... 
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
...     print i
...     
... 
4.0
3
two
1

While you are looking at the collections module, consider inheriting from Sequence, Mapping or another abstract base class if that is more appropriate. Here is an example for a Sequence subclass:

>>> from collections import Sequence
>>> class MyContainer(Sequence):
...     def __init__(self, *data):
...         self.data = list(data)
...     def __getitem__(self, index):
...         return self.data[index]
...     def __len__(self):
...         return len(self.data)
...         
...     
... 
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
...     print i
...     
... 
1
two
3
4.0

NB: Thanks to Glenn Maynard for drawing my attention to the need to clarify the difference between iterators on the one hand and containers that are iterables rather than iterators on the other.

How to make Visual Studio copy a DLL file to the output directory?

xcopy /y /d  "$(ProjectDir)External\*.dll" "$(TargetDir)"

You can also refer to a relative path, the next example will find the DLL in a folder located one level above the project folder. If you have multiple projects that use the DLL in a single solution, this places the source of the DLL in a common area reachable when you set any of them as the Startup Project.

xcopy /y /d  "$(ProjectDir)..\External\*.dll" "$(TargetDir)"

The /y option copies without confirmation. The /d option checks to see if a file exists in the target and if it does only copies if the source has a newer timestamp than the target.

I found that in at least newer versions of Visual Studio, such as VS2109, $(ProjDir) is undefined and had to use $(ProjectDir) instead.

Leaving out a target folder in xcopy should default to the output directory. That is important to understand reason $(OutDir) alone is not helpful.

$(OutDir), at least in recent versions of Visual Studio, is defined as a relative path to the output folder, such as bin/x86/Debug. Using it alone as the target will create a new set of folders starting from the project output folder. Ex: … bin/x86/Debug/bin/x86/Debug.

Combining it with the project folder should get you to the proper place. Ex: $(ProjectDir)$(OutDir).

However $(TargetDir) will provide the output directory in one step.

Microsoft's list of MSBuild macros for current and previous versions of Visual Studio

Loop in react-native

First of all, I recommend writing the item you want to render multiple times (in your case list of fields) as a separate component:

function Field() {
    return (
        <View>
            <View>
                <TextInput />
            </View>
            <View>
                <TextInput />
            </View>
            <View>
                <TextInput />
            </View>
        </View>
    );
}

Then, in your case, when rendering based on some number and not a list, I'd move the for loop outside of the render method for a more readable code:

renderFields() {
    const noGuest = this.state.guest;
    const fields = [];
    for (let i=0; i < noGuest; i++) {
        // Try avoiding the use of index as a key, it has to be unique!
        fields.push(
            <Field key={"guest_"+i} />
        );
    }
    return fields;
}

render () {
    return (
        <View>
            <View>
                <View><Text>No</Text></View>
                <View><Text>Name</Text></View>
                <View><Text>Preference</Text></View>
            </View>
            {this.renderFields()}
        </View>;
    )
}

However, there are many more ways to render looped content in react native. Most of the ways are covered in this article, so please check it out if you're interested in more details! The examples in article are from React, but everything applies to React Native as well!

Error: Cannot find module html

Install ejs if it is not.

npm install ejs

Then after just paste below two lines in your main file. (like app.js, main.js)

app.set('view engine', 'html');

app.engine('html', require('ejs').renderFile);

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

A simple solution is to convert base 64 to alphanumeric by discarding the non-alphanumeric characters.

This one uses random_bytes() for a cryptographically secure result.

function random_alphanumeric(int $length): string
{
    $result='';
    do
    {
        //Base 64 produces 4 characters for each 3 bytes, so most times this will give enough bytes in a single pass
        $bytes=random_bytes(($length+3-strlen($result))*2);
        //Discard non-alhpanumeric characters
        $result.=str_replace(['/','+','='],['','',''],base64_encode($bytes));
        //Keep adding characters until the string is long enough
        //Add a few extra because the last 2 or 3 characters of a base 64 string tend to be less diverse
    }while(strlen($result)<$length+3);
    return substr($result,0,$length);
}

Edit: I just revisited this because I need something a bit more flexible. Here is a solution that performs a bit better than the above and gives the option to specify any subset of the ASCII character set:

<?php
class RandomText
{
    protected
        $allowedChars,
        //Maximum index to use
        $allowedCount,
        //Index values will be taken from a pool of this size
        //It is a power of 2 to keep the distribution of values even
        $distributionSize,
        //This many characters will be generated for each output character
        $ratio;
    /**
     * @param string $allowedChars characters to choose from
     */
    public function __construct(string $allowedChars)
    {
        $this->allowedCount = strlen($allowedChars);
        if($this->allowedCount < 1 || $this->allowedCount > 256) throw new \Exception('At least 1 and no more than 256 allowed character(s) must be specified.');
        $this->allowedChars = $allowedChars;
        //Find the power of 2 equal or greater than the number of allowed characters
        $this->distributionSize = pow(2,ceil(log($this->allowedCount, 2)));
        //Generating random bytes is the expensive part of this algorithm
        //In most cases some will be wasted so it is helpful to produce some extras, but not too many
        //On average, this is how many characters needed to produce 1 character in the allowed set
        //50% of the time, more characters will be needed. My tests have shown this to perform well.
        $this->ratio = $this->distributionSize / $this->allowedCount;
    }

    /**
     * @param int $length string length of required result
     * @return string random text
     */
    public function get(int $length) : string
    {
        if($length < 1) throw new \Exception('$length must be >= 1.');
        $result = '';
        //Keep track of result length to prevent having to compute strlen()
        $l = 0;
        $indices = null;
        $i = null;
        do
        {
            //Bytes will be used to index the character set. Convert to integers.
            $indices = unpack('C*', random_bytes(ceil(($length - $l) * $this->ratio)));
            foreach($indices as $i)
            {
                //Reduce to the smallest range that gives an even distribution
                $i %= $this->distributionSize;
                //If the index is within the range of characters, add one char to the string
                if($i < $this->allowedCount)
                {
                    $l++;
                    $result .= $this->allowedChars[$i];
                }
                if($l >= $length) break;
            }
        }while($l < $length);
        return $result;
    }
}

psql: FATAL: role "postgres" does not exist

If you're using docker, make sure you're NOT using POSTGRES_USER=something_else, as this variable is used by the standard image to know the name of the PostgreSQL admin user (default as postgres).

In my case, I was using this variable with the intent to set another user to my specific database, but it ended up of course changing the main PostgreSQL user.

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result; 
}

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>
{
    SumRootN(10);
});

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
    Task t = new Task(() => SumRootN(10));
    t.Start();
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray()); 

First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

android - save image into gallery

Actually, you can save you picture at any place. If you want to save in a public space, so any other application can access, use this code:

storageDir = new File(
    Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    ), 
    getAlbumName()
);

The picture doesn't go to the album. To do this, you need to call a scan:

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

You can found more info at https://developer.android.com/training/camera/photobasics.html#TaskGallery

pandas: find percentile stats of a given column

You can use the pandas.DataFrame.quantile() function, as shown below.

import pandas as pd
import random

A = [ random.randint(0,100) for i in range(10) ]
B = [ random.randint(0,100) for i in range(10) ]

df = pd.DataFrame({ 'field_A': A, 'field_B': B })
df
#    field_A  field_B
# 0       90       72
# 1       63       84
# 2       11       74
# 3       61       66
# 4       78       80
# 5       67       75
# 6       89       47
# 7       12       22
# 8       43        5
# 9       30       64

df.field_A.mean()   # Same as df['field_A'].mean()
# 54.399999999999999

df.field_A.median() 
# 62.0

# You can call `quantile(i)` to get the i'th quantile,
# where `i` should be a fractional number.

df.field_A.quantile(0.1) # 10th percentile
# 11.9

df.field_A.quantile(0.5) # same as median
# 62.0

df.field_A.quantile(0.9) # 90th percentile
# 89.10000000000001

This declaration has no storage class or type specifier in C++

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

Char array declaration and initialization in C

Yes, this is a kind of inconsistency in the language.

The "=" in myarray = "abc"; is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc"; it's an initialization of the array. There's no way for "late initialization".

You should just remember this rule.

javascript - match string against the array of regular expressions

So we make a function that takes in a literal string, and the array we want to look through. it returns a new array with the matches found. We create a new regexp object inside this function and then execute a String.search on each element element in the array. If found, it pushes the string into a new array and returns.

// literal_string: a regex search, like /thisword/ig
// target_arr: the array you want to search /thisword/ig for.

function arr_grep(literal_string, target_arr) {
  var match_bin = [];
  // o_regex: a new regex object.
  var o_regex = new RegExp(literal_string);
  for (var i = 0; i < target_arr.length; i++) {
    //loop through array. regex search each element.
    var test = String(target_arr[i]).search(o_regex);
    if (test > -1) {
    // if found push the element@index into our matchbin.
    match_bin.push(target_arr[i]);
    }
  }
  return match_bin;
}

// arr_grep(/.*this_word.*/ig, someArray)

iPhone Navigation Bar Title text color

This works for me in Swift:

navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]

How to get the Android Emulator's IP address?

If you need to refer to your host computer's localhost, such as when you want the emulator client to contact a server running on the same host, use the alias 10.0.2.2 to refer to the host computer's loopback interface. From the emulator's perspective, localhost (127.0.0.1) refers to its own loopback interface.More details: http://developer.android.com/guide/faq/commontasks.html#localhostalias

How does the "view" method work in PyTorch?

weights.reshape(a, b) will return a new tensor with the same data as weights with size (a, b) as in it copies the data to another part of memory.

weights.resize_(a, b) returns the same tensor with a different shape. However, if the new shape results in fewer elements than the original tensor, some elements will be removed from the tensor (but not from memory). If the new shape results in more elements than the original tensor, new elements will be uninitialized in memory.

weights.view(a, b) will return a new tensor with the same data as weights with size (a, b)

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

Inline <style> tags vs. inline css properties

Style rules can be attached using:

  • External Files
  • In-page Style Tags
  • Inline Style Attribute

Generally, I prefer to use linked style sheets because they:

  • can be cached by browsers for performance; and
  • are a lot easier to maintain for a development perspective.

However, your question is asking specifically about the style tag versus inline styles. Prefer to use the style tag, in this case, because it:

  • provides a clear separation of markup from styling;
  • produces cleaner HTML markup; and
  • is more efficient with selectors to apply rules to multiple elements on a page improving management as well as making your page size smaller.

Inline elements only affect their respective element.

An important difference between the style tag and the inline attribute is specificity. Specificity determines when one style overrides another. Generally, inline styles have a higher specificity.

Read CSS: Specificity Wars for an entertaining look at this subject.

I hope that helps!

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

Right Click on Project -> Maven -> Update Project -> Select Force update of snapshot

Or

Navigate to project root folder and use following commands :

mvn clean install -U or mvn clean install --update-snapshots

Here -U will Forces a check for missing releases and updated snapshots on remote repositories

How do you overcome the HTML form nesting limitation?

In response to a question posted by Yar in a comment to his own answer, I present some JavaScript which will resize an iframe. For the case of a form button, it is safe to assume the iframe will be on the same domain. This is the code I use. You will have to alter the maths/constants for your own site:

function resizeIFrame(frame)
{
    try {
        innerDoc = ('contentDocument' in frame) ? frame.contentDocument : frame.contentWindow.document;
        if('style' in frame) {
            frame.style.width = Math.min(755, Math.ceil(innerDoc.body.scrollWidth)) + 'px';
            frame.style.height = Math.ceil(innerDoc.body.scrollHeight) + 'px';
        } else {
            frame.width = Math.ceil(innerDoc.body.scrollWidth);
            frame.height = Math.ceil(innerDoc.body.scrollHeight);
        }
    } catch(err) {
        window.status = err.message;
    }
}

Then call it like this:

<iframe ... frameborder="0" onload="if(window.parent && window.parent.resizeIFrame){window.parent.resizeIFrame(this);}"></iframe>

The ternary (conditional) operator in C

The fact that the ternary operator is an expression, not a statement, allows it to be used in macro expansions for function-like macros that are used as part of an expression. Const may not have been part of original C, but the macro pre-processor goes way back.

One place where I've seen it used is in an array package that used macros for bound-checked array accesses. The syntax for a checked reference was something like aref(arrayname, type, index), where arrayname was actually a pointer to a struct that included the array bounds and an unsigned char array for the data, type was the actual type of the data, and index was the index. The expansion of this was quite hairy (and I'm not going to do it from memory), but it used some ternary operators to do the bound checking.

You can't do this as a function call in C because of the need for polymorphism of the returned object. So a macro was needed to do the type casting in the expression. In C++ you could do this as a templated overloaded function call (probably for operator[]), but C doesn't have such features.

Edit: Here's the example I was talking about, from the Berkeley CAD array package (glu 1.4 edition). The documentation of the array_fetch usage is:

type
array_fetch(type, array, position)
typeof type;
array_t *array;
int position;

Fetch an element from an array. A runtime error occurs on an attempt to reference outside the bounds of the array. There is no type-checking that the value at the given position is actually of the type used when dereferencing the array.

and here is the macro defintion of array_fetch (note the use of the ternary operator and the comma sequencing operator to execute all the subexpressions with the right values in the right order as part of a single expression):

#define array_fetch(type, a, i)         \
(array_global_index = (i),              \
  (array_global_index >= (a)->num) ? array_abort((a),1) : 0,\
  *((type *) ((a)->space + array_global_index * (a)->obj_size)))

The expansion for array_insert ( which grows the array if necessary, like a C++ vector) is even hairier, involving multiple nested ternary operators.

Simple Deadlock Examples

One more simple deadlock example with two different resources and two thread waiting for each other to release resource. Directly from examples.oreilly.com/jenut/Deadlock.java

 public class Deadlock {
  public static void main(String[] args) {
    // These are the two resource objects we'll try to get locks for
    final Object resource1 = "resource1";
    final Object resource2 = "resource2";
    // Here's the first thread.  It tries to lock resource1 then resource2
    Thread t1 = new Thread() {
      public void run() {
        // Lock resource 1
        synchronized(resource1) {
          System.out.println("Thread 1: locked resource 1");

          // Pause for a bit, simulating some file I/O or something.  
          // Basically, we just want to give the other thread a chance to
          // run.  Threads and deadlock are asynchronous things, but we're
          // trying to force deadlock to happen here...
          try { Thread.sleep(50); } catch (InterruptedException e) {}

          // Now wait 'till we can get a lock on resource 2
          synchronized(resource2) {
            System.out.println("Thread 1: locked resource 2");
          }
        }
      }
    };

    // Here's the second thread.  It tries to lock resource2 then resource1
    Thread t2 = new Thread() {
      public void run() {
        // This thread locks resource 2 right away
        synchronized(resource2) {
          System.out.println("Thread 2: locked resource 2");

          // Then it pauses, for the same reason as the first thread does
          try { Thread.sleep(50); } catch (InterruptedException e) {}

          // Then it tries to lock resource1.  But wait!  Thread 1 locked
          // resource1, and won't release it 'till it gets a lock on
          // resource2.  This thread holds the lock on resource2, and won't
          // release it 'till it gets resource1.  We're at an impasse. Neither
          // thread can run, and the program freezes up.
          synchronized(resource1) {
            System.out.println("Thread 2: locked resource 1");
          }
        }
      }
    };

    // Start the two threads. If all goes as planned, deadlock will occur, 
    // and the program will never exit.
    t1.start(); 
    t2.start();
  }
}

Finding the direction of scrolling in a UIScrollView?

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {

    CGPoint targetPoint = *targetContentOffset;
    CGPoint currentPoint = scrollView.contentOffset;

    if (targetPoint.y > currentPoint.y) {
        NSLog(@"up");
    }
    else {
        NSLog(@"down");
    }
}

What is the optimal algorithm for the game 2048?

Algorithm

while(!game_over)
{
    for each possible move:
        evaluate next state

    choose the maximum evaluation
}

Evaluation

Evaluation =
    128 (Constant)
    + (Number of Spaces x 128)
    + Sum of faces adjacent to a space { (1/face) x 4096 }
    + Sum of other faces { log(face) x 4 }
    + (Number of possible next moves x 256)
    + (Number of aligned values x 2)

Evaluation Details

128 (Constant)

This is a constant, used as a base-line and for other uses like testing.

+ (Number of Spaces x 128)

More spaces makes the state more flexible, we multiply by 128 (which is the median) since a grid filled with 128 faces is an optimal impossible state.

+ Sum of faces adjacent to a space { (1/face) x 4096 }

Here we evaluate faces that have the possibility to getting to merge, by evaluating them backwardly, tile 2 become of value 2048, while tile 2048 is evaluated 2.

+ Sum of other faces { log(face) x 4 }

In here we still need to check for stacked values, but in a lesser way that doesn't interrupt the flexibility parameters, so we have the sum of { x in [4,44] }.

+ (Number of possible next moves x 256)

A state is more flexible if it has more freedom of possible transitions.

+ (Number of aligned values x 2)

This is a simplified check of the possibility of having merges within that state, without making a look-ahead.

Note: The constants can be tweaked..

How to check if variable's type matches Type stored in a variable

GetType() exists on every single framework type, because it is defined on the base object type. So, regardless of the type itself, you can use it to return the underlying Type

So, all you need to do is:

u.GetType() == t

How to get the size of a varchar[n] field in one SQL statement?

select column_name, data_type, character_maximum_length    
from INFORMATION_SCHEMA.COLUMNS
where table_name = 'Table1'

Can you remove elements from a std::list while iterating through it?

You want to do:

i= items.erase(i);

That will correctly update the iterator to point to the location after the iterator you removed.

How to detect internet speed in JavaScript?

I needed something similar, so I wrote https://github.com/beradrian/jsbandwidth. This is a rewrite of https://code.google.com/p/jsbandwidth/.

The idea is to make two calls through Ajax, one to download and the other to upload through POST.

It should work with both jQuery.ajax or Angular $http.

Accessing a property in a parent Component

There are different way:

export class Profile implements OnInit {
constructor(@Host() parent: App) {
  parent.userStatus ...
}
  • data-binding
export class Profile implements OnInit {
  @Input() userStatus:UserStatus;
  ...
}

<profile [userStatus]="userStatus">

Hidden property of a button in HTML

It also works without jQuery if you do the following changes:

  1. Add type="button" to the edit button in order not to trigger submission of the form.

  2. Change the name of your function from change() to anything else.

  3. Don't use hidden="hidden", use CSS instead: style="display: none;".

The following code works for me:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">

<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
    <img src="dba_images/textfield_key.png" alt=""/>
    Edit
</button>

<button type="submit" class="positive" name="save" id="save" style="display:none;">
    <img src="dba_images/apply2.png" alt=""/>
    Save
</button>

<button class="regular" name="change" id="change" style="display:none;">
    <img src="dba_images/textfield_key.png" alt=""/>
    change
</button>

    <button class="negative" name="cancel" id="cancel" style="display:none;">
        <img src="dba_images/cross.png" alt=""/>
        Cancel
    </button>
</div>
</form>
</body>
</html>

What does elementFormDefault do in XSD?

elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).

By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.

It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.

SVN how to resolve new tree conflicts when file is added on two branches

I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.

The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?

Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.

SQLAlchemy: What's the difference between flush() and commit()?

A Session object is basically an ongoing transaction of changes to a database (update, insert, delete). These operations aren't persisted to the database until they are committed (if your program aborts for some reason in mid-session transaction, any uncommitted changes within are lost).

The session object registers transaction operations with session.add(), but doesn't yet communicate them to the database until session.flush() is called.

session.flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction. The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is what session.commit() does).

session.commit() commits (persists) those changes to the database.

flush() is always called as part of a call to commit() (1).

When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds. By default, Session objects autoflush their operations, but this can be disabled.

Hopefully this example will make this clearer:

#---
s = Session()

s.add(Foo('A')) # The Foo('A') object has been added to the session.
                # It has not been committed to the database yet,
                #   but is returned as part of a query.
print 1, s.query(Foo).all()
s.commit()

#---
s2 = Session()
s2.autoflush = False

s2.add(Foo('B'))
print 2, s2.query(Foo).all() # The Foo('B') object is *not* returned
                             #   as part of this query because it hasn't
                             #   been flushed yet.
s2.flush()                   # Now, Foo('B') is in the same state as
                             #   Foo('A') was above.
print 3, s2.query(Foo).all() 
s2.rollback()                # Foo('B') has not been committed, and rolling
                             #   back the session's transaction removes it
                             #   from the session.
print 4, s2.query(Foo).all()

#---
Output:
1 [<Foo('A')>]
2 [<Foo('A')>]
3 [<Foo('A')>, <Foo('B')>]
4 [<Foo('A')>]

Iterate through a C++ Vector using a 'for' loop

The cleanest way of iterating through a vector is via iterators:

for (auto it = begin (vector); it != end (vector); ++it) {
    it->doSomething ();
}

or (equivalent to the above)

for (auto & element : vector) {
    element.doSomething ();
}

Prior to C++0x, you have to replace auto by the iterator type and use member functions instead of global functions begin and end.

This probably is what you have seen. Compared to the approach you mention, the advantage is that you do not heavily depend on the type of vector. If you change vector to a different "collection-type" class, your code will probably still work. You can, however, do something similar in Java as well. There is not much difference conceptually; C++, however, uses templates to implement this (as compared to generics in Java); hence the approach will work for all types for which begin and end functions are defined, even for non-class types such as static arrays. See here: How does the range-based for work for plain arrays?

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.

To install OpenSSL development package on Debian, Ubuntu or their derivatives:

$ sudo apt-get install libssl-dev

To install OpenSSL development package on Fedora, CentOS or RHEL:

$ sudo yum install openssl-devel 

Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :

dnf install openssl-devel

Your password does not satisfy the current policy requirements

NOTE: This might not be a secure solution. But if you are working on a test environment, just need a quick fix and doesn't even care about the security settings. This is a quick solution.

The same issue happened to me when I ran "mysql_secure_installation" and modified password security level to 'medium'.

I bypassed the error by running the followings:

mysql -h localhost -u root -p
mysql>uninstall plugin validate_password;

make sure you reinstall the plugin "validate_password" if necessary.

When to use .First and when to use .FirstOrDefault with LINQ?

Others have very well described the difference between First() and FirstOrDefault(). I want to take a further step in interpreting the semantics of these methods. In my opinion FirstOrDefault is being overused a lot. In the majority of the cases when you’re filtering data you would either expect to get back a collection of elements matching the logical condition or a single unique element by its unique identifier – such as a user, book, post etc... That’s why we can even get as far as saying that FirstOrDefault() is a code smell not because there is something wrong with it but because it’s being used way too often. This blog post explores the topic in details. IMO most of the times SingleOrDefault() is a much better alternative so watch out for this mistake and make sure you use the most appropriate method that clearly represents your contract and expectations.

How to set default vim colorscheme

Ubuntu 17.10 default doesn't have the ~/.vimrc file, we need create it and put the setting colorscheme color_scheme_name in it.

By the way, colorscheme desert is good scheme to choose.

Recommended website resolution (width and height)?

Forcing your user to scroll horizontally is a serious UI transgression. Unless you are specifically building a web site for a population with a known screen size, you are safest ensuring that your design works with screens as small as 800 pixels wide (about 8% of the web surfing population if memory serves me right). It is wise to make it adapt well to larger screens but not at the cost of the folks still surfing at 800x600.

Here's another thing to consider as well: not everyone runs their browser at full screen (I don't). So the idea that if is Ok to design for a specific (and large) "screen size" really doesn't work for a number of reasons.

Update on 12/15/2010: When I first answered this question, 800 pixels was an appropriate answer. However, at this point, I would recommend 1024 pixels wide (or 960 as someone else points out). Technology marches on...

Angularjs - ng-cloak/ng-show elements blink

I couldn't get any of these methods to work, so I eventually did the following. For the element you want initially hidden:

<div <!--...--> style="display: none;" ng-style="style">

Then in your controller, add this at or near the top:

$scope.style = { display: 'block' };

This way, the element is initially hidden, and only shows when the controller code has actually run.

You can tune the placement to your needs, perhaps adding some logic. In my case, I switch to a login path if not currently logged in, and didn't want my interface flickering beforehand, so I set $scope.style after the logged-in check.

how to select rows based on distinct values of A COLUMN only

if you dont wanna use DISTINCT use GROUP BY

 SELECT * FROM myTABLE GROUP BY EmailAddress

Adding ID's to google map markers

Why not use an cache that stores each marker object and references an ID?

var markerCache= {};
var idGen= 0;

function codeAddress(addr, contentStr){
    // create marker
    // store
    markerCache[idGen++]= marker;
}

Edit: of course this relies on a numeric index system that doesn't offer a length property like an array. You could of course prototype the Object object and create a length, etc for just such a thing. OTOH, generating a unique ID value (MD5, etc) of each address might be the way to go.

How to convert all tables from MyISAM into InnoDB?

It hasn't been mentioned yet, so I'll write it for posterity:

If you're migrating between DB servers (or have another reason you'd dump and reload your dta), you can just modify the output from mysqldump:

mysqldump --no-data DBNAME | sed 's/ENGINE=MyISAM/ENGINE=InnoDB/' > my_schema.sql;
mysqldump --no-create-info DBNAME > my_data.sql;

Then load it again:

mysql DBNAME < my_schema.sql && mysql DBNAME < my_data.sql

(Also, in my limited experience, this can be a much faster process than altering the tables ‘live’. It probably depends on the type of data and indexes.)

Extracting specific columns from a data frame

Using the dplyr package, if your data.frame is called df1:

library(dplyr)

df1 %>%
  select(A, B, E)

This can also be written without the %>% pipe as:

select(df1, A, B, E)

HTML form do some "action" when hit submit button

Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems

Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:

For this example you will need to create two pages. On the first page we will create a simple HTML form to collect some data. Here is an example:

<html>   
<head>
 <title>Test Page</title>
</head>   
<body>   
    <h2>Data Collection</h2><p>
    <form action="process.php" method="post">  
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="Name"/></td>
            </tr>   
            <tr>
                <td>Age:</td>
                <td><input type="text" name="Age"/></td>
            </tr>   
            <tr>
                <td colspan="2" align="center">
                <input type="submit"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

This page will send the Name and Age data to the page process.php. Now lets create process.php to use the data from the HTML form we made:

<?php   
    print "Your name is ". $Name;   
    print "<br />";   
    print "You are ". $Age . " years old";   
    print "<br />";   $old = 25 + $Age;
    print "In 25 years you will be " . $old . " years old";   
?>

As you may be aware, if you leave out the method="post" part of the form, the URL with show the data. For example if your name is Bill Jones and you are 35 years old, our process.php page will display as http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want, you can manually change the URL in this way and the output will change accordingly.

Additional JavaScript Example

This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.

Note: document.getElementById("fname").value gets the object with the ID tag that equals fname and then pulls it's value - which in this case is the text in the First Name textbox.

 <html>
    <head>
     <script type="text/javascript">
     function ExampleJS(){
        var jFirst = document.getElementById("fname").value;
        var jLast = document.getElementById("lname").value;
        alert("Your name is: " + jFirst + " " + jLast);
     }
     </script>

    </head>
    <body>
        <FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">

             First name: <input type="text" id="fname" name="firstname" /><br />
             Last name:  <input type="text" id="lname" name="lastname" /><br />
            <input name="Submit"  type="submit" value="Update" />
        </FORM>
    </body>
</html>

How to redirect DNS to different ports

Since I had troubles understanding this post here is a simple explanation for people like me. It is useful if:

  • You DO NOT need Load Balacing.
  • You DO NOT want to use nginx to do port forwarding.
  • You DO want to do PORT FORWARDING according to specific subdomains using SRV record.

Then here is what you need to do:

SRV records:

_minecraft._tcp.1.12          IN SRV    1 100 25567 1.12.<your-domain-name.com>.
_minecraft._tcp.1.13          IN SRV    1 100 25566 1.13.<your-domain-name.com>.

(I did not need a srv record for 1.14 since my 1.14 minecraft server was already on the 25565 port which is the default port of minecraft.)

And the A records:

1.12                          IN A      <your server IP>
1.13                          IN A      <your server IP>
1.14                          IN A      <your server IP>

Angular - ng: command not found

For MacOS

Sometimes the ng command does not get established as a link in /usr/local/bin. I fixed the problem by adding it manually:

ln -s /usr/local/Cellar/node/10.10.0/lib/node_modules/angular-cli/bin/ng /usr/local/bin/ng

Android SDK location

The question doesn't seem to require a programmatic solution, but my Google search brought me here anyway. Here's my C# attempt at detecting where the SDK is installed, based on the most common installation paths.

static string FindAndroidSDKPath()
{
    string uniqueFile = Path.Combine("platform-tools", "adb.exe"); // look for adb in Android folders
    string[] searchDirs =
    {
        // User/AppData/Local
        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
        // Program Files
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
        // Program Files (x86) (it's okay if we're on 32-bit, we check if this folder exists first)
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + " (x86)",
        // User/AppData/Roaming
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    };
    foreach (string searchDir in searchDirs)
    {
        string androidDir = Path.Combine(searchDir, "Android");
        if (Directory.Exists(androidDir))
        {
            string[] subDirs = Directory.GetDirectories(androidDir, "*sdk*", SearchOption.TopDirectoryOnly);
            foreach (string subDir in subDirs)
            {
                string path = Path.Combine(subDir, uniqueFile);
                if (File.Exists(path))
                {
                    // found unique file at DIR/Android
                    return subDir;
                }
            }
        }
    }
    // no luck finding SDK! :(
    return null;
}

I need this because I'm writing an extension to a C# program to work with Android Studio/Gradle. Hopefully someone else will find this approach useful.

How to center content in a bootstrap column?

If none of the above work (like in my case trying to center an input), I used Boostrap 4 offset:

<div class="row">
    <div class="col-6 offset-3">
        <input class="form-control" id="myInput" type="text" placeholder="Search..">
    </div>
</div>  

Correct way to remove plugin from Eclipse

I would like to propose my solution,that worked for me.

It's reverting Eclipse and its plugins versions, to the version just before the plugin was installed.

Regex to validate date format dd/mm/yyyy

The following expression is nice and easy to manipulate:

((((0[13578]|1[02])(\/|-|.)(0[1-9]|1[0-9]|2[0-9]|3[01]))|((0[469]|11)(\/|-|.)(0[1-9]|1[0-9]|2[0-9]|3[0]))|((02)((\/|-|.)(0[1-9]|1[0-9]|2[0-8]))))(\/|-|.)(19([6-9][0-9])|20(0[0-9]|1[0-4])))|((02)(\/|-|.)(29)(\/|-|.)(19(6[048]|7[26]|8[048]|9[26])|20(0[048]|1[26])))

It validates according to the MM/dd/YYYY format and allows for leap year support from 1960 to 2016. If you need the leap year support extended you need only manipulate this part of the expression:

(19(6[048]|7[26]|8[048]|9[26])|20(0[048]|1[26]))

Hope this helped you a lot

How to assign more memory to docker container

If you want to change the default container and you are using Virtualbox, you can do it via the commandline / CLI:

docker-machine stop
VBoxManage modifyvm default --cpus 2
VBoxManage modifyvm default --memory 4096
docker-machine start

How can I easily add storage to a VirtualBox machine with XP installed?

For Windows users there's an additional user friendly option: CloneVDI Tool by mpack. It's a GUI front-end to VBoxManage that makes things a little easier to work with.

http://forums.virtualbox.org/viewtopic.php?f=6&t=22422

As Alexander M. mentioned, you'll still have to use GParted, Partition Magic or a similar partition editor to grow your partition to the newly allocated physical drive. To do this just download the GParted iso, mount it as a bootable drive in the VirtualBox and boot from it.

http://gparted.sourceforge.net/download.php

How to URL encode a string in Ruby

I was originally trying to escape special characters in a file name only, not on the path, from a full URL string.

ERB::Util.url_encode didn't work for my use:

helper.send(:url_encode, "http://example.com/?a=\11\15")
# => "http%3A%2F%2Fexample.com%2F%3Fa%3D%09%0D"

Based on two answers in "Why is URI.escape() marked as obsolete and where is this REGEXP::UNSAFE constant?", it looks like URI::RFC2396_Parser#escape is better than using URI::Escape#escape. However, they both are behaving the same to me:

URI.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"
URI::Parser.new.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"

PHP: How to check if image file exists?

Here is the simplest way to check if a file exist:

if(is_file($filename)){
    return true; //the file exist
}else{
    return false; //the file does not exist
}

Is there an R function for finding the index of an element in a vector?

the function Position in funprog {base} also does the job. It allows you to pass an arbitrary function, and returns the first or last match.

Position(f, x, right = FALSE, nomatch = NA_integer)

Javascript window.open pass values using POST

Even though this question was long time ago, thanks all for the inputs that helping me out a similar problem. I also made a bit modification based on the others' answers here and making multiple inputs/valuables into a Single Object (json); and hope this helps someone.

js:

//example: params={id:'123',name:'foo'};

mapInput.name = "data";
mapInput.value = JSON.stringify(params); 

php:

$data=json_decode($_POST['data']); 

echo $data->id;
echo $data->name;

Get height of div with no height set in css

Also make sure the div is currently appended to the DOM and visible.

eloquent laravel: How to get a row count from a ->get()

Answer has been updated

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist);

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478

However as of now, the query builder always returns an array.

Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->get();
$wordCount = $wordlist->count();

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->count();

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

startForeground fail after upgrade to Android 8.1

Here is my solution

private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";

private void startForeground() {

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            getApplicationContext(), CHANNEL_ID);

    Notification notification;



        notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
                .setOngoing(true)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Send SMS gateway is running background")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setShowWhen(true)
                .build();

        NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);

        //All notifications should go through NotificationChannel on Android 26 & above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);

        }
        notificationManager.notify(NOTIFICATION_ID, notification);

    }

Hope it will help :)

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

Auto-indent spaces with C in vim?

These two commands should do it:

:set autoindent
:set cindent

For bonus points put them in a file named .vimrc located in your home directory on linux

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

Create or write/append in text file

Try this code:

function logErr($data){
  $logPath = __DIR__. "/../logs/logs.txt";
  $mode = (!file_exists($logPath)) ? 'w':'a';
  $logfile = fopen($logPath, $mode);
  fwrite($logfile, "\r\n". $data);
  fclose($logfile);
}

I always use it like this, and it works...

'console' is undefined error for Internet Explorer

I'm using fauxconsole; I modified the css a bit so that it looks nicer but works very well.

Get first and last day of month using threeten, LocalDate

Jon Skeets answer is right and has deserved my upvote, just adding this slightly different solution for completeness:

import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.with(lastDayOfMonth());

Illegal mix of collations MySQL Error

In general the best way is to Change the table collation. However I have an old application and are not really able to estimate the outcome whether this has side effects. Therefore I tried somehow to convert the string into some other format that solved the collation problem. What I found working is to do the string compare by converting the strings into a hexadecimal representation of it's characters. On the database this is done with HEX(column). For PHP you may use this function:

public static function strToHex($string)
{
    $hex = '';
    for ($i=0; $i<strlen($string); $i++){
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0'.$hexCode, -2);
    }
    return strToUpper($hex);
}

When doing the database query, your original UTF8 string must be converted first into an iso string (e.g. using utf8_decode() in PHP) before using it in the DB. Because of the collation type the database cannot have UTF8 characters inside so the comparism should work event though this changes the original string (converting UTF8 characters that are not existend in the ISO charset result in a ? or these are removed entirely). Just make sure that when you write data into the database, that you use the same UTF8 to ISO conversion.

How to delete files/subfolders in a specific directory at the command prompt in Windows

rmdir is my all time favorite command for the job. It works for deleting huge files and folders with subfolders. A backup is not created, so make sure that you have copied your files safely before running this command.

RMDIR "FOLDERNAME" /S /Q

This silently removes the folder and all files and subfolders.

How can I list the contents of a directory in Python?

The os module handles all that stuff.

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Availability: Unix, Windows.

Maven Java EE Configuration Marker with Java Server Faces 1.2

The m2e plugin generate project configuration every time when you update project (Maven->Update Project ... That action overrides facets setting configured manually in Eclipse. Therefore you have to configure it on pom level. By setting properties in pom file you can tell m2e plugin what to do.

Enable/Disable the JAX-RS/JPA/JSF Configurators at the pom.xml level The optional JAX-RS, JPA and JSF configurators can be enabled or disabled at a workspace level from Window > Preferences > Maven > Java EE Integration. Now, you can have a finer grain control on these configurators directly from your pom.xml properties :

Adding false in your pom properties section will disable the JAX-RS configurator Adding false in your pom properties section will disable the JPA configurator Adding false in your pom properties section will disable the JSF configurator The pom settings always override the workspace preferences. So if you have, for instance the JPA configurator disabled at the workspace level, using true will enable it on your project anyway. (http://wiki.eclipse.org/M2E-WTP/New_and_Noteworthy/1.0.0)

Set background image in CSS using jquery

Use :

 $(this).parent().css("background-image", "url(/images/r-srchbg_white.png) no-repeat;");

instead of

 $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat;");

More examples you cand see here

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

kiddailey I think was pretty close, however I would not disable ssl verification but rather rather just supply the local certificate:

In the Git config file

[http]
    sslCAinfo = /bin/curl-ca-bundle.crt

Or via command line:

git config --global http.sslCAinfo /bin/curl-ca-bundle.crt

How to "pretty" format JSON output in Ruby on Rails

Use the pretty_generate() function, built into later versions of JSON. For example:

require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)

Which gets you:

{
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}

Change Default branch in gitlab

In 8.0+ it looks like this was moved into the project. If you open your project and go to the gear icon on the right, then "Edit Project" you can set the default branch for the project.

What is a "method" in Python?

Sorry, but--in my opinion--RichieHindle is completely right about saying that method...

It's a function which is a member of a class.

Here is the example of a function that becomes the member of the class. Since then it behaves as a method of the class. Let's start with the empty class and the normal function with one argument:

>>> class C:
...     pass
...
>>> def func(self):
...     print 'func called'
...
>>> func('whatever')
func called

Now we add a member to the C class, which is the reference to the function. After that we can create the instance of the class and call its method as if it was defined inside the class:

>>> C.func = func
>>> o = C()
>>> o.func()
func called

We can use also the alternative way of calling the method:

>>> C.func(o)
func called

The o.func even manifests the same way as the class method:

>>> o.func
<bound method C.func of <__main__.C instance at 0x000000000229ACC8>>

And we can try the reversed approach. Let's define a class and steal its method as a function:

>>> class A:
...     def func(self):
...         print 'aaa'
...
>>> a = A()
>>> a.func
<bound method A.func of <__main__.A instance at 0x000000000229AD08>>
>>> a.func()
aaa

So far, it looks the same. Now the function stealing:

>>> afunc = A.func
>>> afunc(a)
aaa    

The truth is that the method does not accept 'whatever' argument:

>>> afunc('whatever')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method func() must be called with A instance as first 
  argument (got str instance instead)

IMHO, this is not the argument against method is a function that is a member of a class.

Later found the Alex Martelli's answer that basically says the same. Sorry if you consider it duplication :)

Android - running a method periodically using postDelayed() call

You can simplify the code like this.

In Java:

new Handler().postDelayed (() -> {
    //your code here
}, 1000);

In Kotlin:

Handler().postDelayed({
   //your code here
}, 1000)

How to make child divs always fit inside parent div?

If you want the child divs to fit the parent size, you should put a margin at least of the size of the child borders on the child divs (child.margin >= child.bordersize).

For this example, just remove the width:100%; and the height:100% in #one and remove the width:100% in #two. It should be something like this:

html, body {width:100%; height:100%; margin:0; padding:0;}    
.border {border:1px solid black;}   
.margin {margin:5px;}  
\#one {}   
\#two {height:50px;}    
\#three {width:100px; height:100%;}

What is %2C in a URL?

It's the ASCII keycode in hexadecimal for a comma (,).

You should use your language's URL encoding methods when placing strings in URLs.

You can see a handy list of characters with man ascii. It has this compact diagram available for mapping hexadecimal codes to the character:

   2 3 4 5 6 7       
 -------------      
0:   0 @ P ` p     
1: ! 1 A Q a q     
2: " 2 B R b r     
3: # 3 C S c s     
4: $ 4 D T d t     
5: % 5 E U e u     
6: & 6 F V f v     
7: ' 7 G W g w     
8: ( 8 H X h x     
9: ) 9 I Y i y     
A: * : J Z j z
B: + ; K [ k {
C: , < L \ l |
D: - = M ] m }
E: . > N ^ n ~
F: / ? O _ o DEL

You can also quickly check a character's hexadecimal equivalent with:

$ echo -n , | xxd -p
2c

unix diff side-to-side results?

From man diff, you can use -y to do side-by-side.

-y, --side-by-side
       output in two columns

Hence, say:

diff -y /tmp/test1  /tmp/test2

Test

$ cat a                $ cat b
hello                  hello
my name                my name
is me                  is you

Let's compare them:

$ diff -y a b
hello                                                           hello
my name                                                         my name
is me                                                         | is you

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

Not directly related to the original question but this will be useful for someone. This error occurred to me with a simple two project structure. One project was handling some database operations with spring JDBC (say A) and the other did not have any JDBC operations at all(say B). But still, this error appeared while I was starting service B. Saying the datasource should be initialized properly.

As I figured out I had added this dependency to the parent pom of the two modules

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

This caused spring to initialize the JDBC dependencies for project B too. So, I moved it to project A's pom, everything was fine.

Hope this would help someone

anaconda/conda - install a specific package version

If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used

conda install [-y] package">=version"
conda install [-y] package'>=low_version, <=high_version'
conda install [-y] "package>=low_version, <high_version"

conda install -y torchvision">=0.3.0"
conda install  openpyxl'>=2.4.10,<=2.6.0'
conda install "openpyxl>=2.4.10,<3.0.0"

where option -y, --yes Do not ask for confirmation.

Here is a summary:

Format         Sample Specification     Results
Exact          qtconsole==4.5.1         4.5.1
Fuzzy          qtconsole=4.5            4.5.0, 4.5.1, ..., etc.
>=, >, <, <=  "qtconsole>=4.5"          4.5.0 or higher
               qtconsole"<4.6"          less than 4.6.0

OR            "qtconsole=4.5.1|4.5.2"   4.5.1, 4.5.2
AND           "qtconsole>=4.3.1,<4.6"   4.3.1 or higher but less than 4.6.0

Potion of the above information credit to Conda Cheat Sheet

Tested on conda 4.7.12

How to empty a list?

Another simple code you could use (depending on your situation) is:

index=len(list)-1

while index>=0:
    del list[index]
    index-=1

You have to start index at the length of the list and go backwards versus index at 0, forwards because that would end you up with index equal to the length of the list with it only being cut in half.

Also, be sure that the while line has a "greater than or equal to" sign. Omitting it will leave you with list[0] remaining.

LINQ to SQL - Left Outer Join with multiple join conditions

You need to introduce your join condition before calling DefaultIfEmpty(). I would just use extension method syntax:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value

Or you could use a subquery:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in (from f in fg
             where f.otherid == 17
             select f).DefaultIfEmpty()
where p.companyid == 100
select f.value

Passing a String by Reference in Java?

String is a special class in Java. It is Thread Safe which means "Once a String instance is created, the content of the String instance will never changed ".

Here is what is going on for

 zText += "foo";

First, Java compiler will get the value of zText String instance, then create a new String instance whose value is zText appending "foo". So you know why the instance that zText point to does not changed. It is totally a new instance. In fact, even String "foo" is a new String instance. So, for this statement, Java will create two String instance, one is "foo", another is the value of zText append "foo". The rule is simple: The value of String instance will never be changed.

For method fillString, you can use a StringBuffer as parameter, or you can change it like this:

String fillString(String zText) {
    return zText += "foo";
}

How to prevent scrollbar from repositioning web page?

I tried to fix likely the same issue which caused by twitter bootstrap .modal-open class applied to body. The solution html {overflow-y: scroll} doesn't help. One possible solution I found is to add {width: 100%; width: 100vw} to the html element.

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

Python: converting a list of dictionaries to json

response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
response_json = json.dumps(response_json)
response_json = json.loads(response_json)

How do I debug Node.js applications?

Visual Studio Code will be my choice for debugging. No overhead of installing any tools or npm install stuff. Just set the starting point of your app in package.json and VSCode will automatically create a configuration file inside your solution. It's build on Electron, on which editors like Atom are built.

VS Code gives similar debugging experience as you might have had in other IDEs like VS, Eclipse, etc.

enter image description here enter image description here

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

If anyone is getting this error after a Phpmyadmin export, using the custom options and adding the "drop tables" statements cleared this right up.

How to drop a PostgreSQL database if there are active connections to it?

On Windows, You can open the Task Manager -> Services, find the "postgresql" process, and restart it. When service will running again the database can be removed.

restarting the "postgresql" process

Getting all documents from one collection in Firestore

if you want include Id

async getMarkers() {
  const events = await firebase.firestore().collection('events')
  events.get().then((querySnapshot) => {
      const tempDoc = querySnapshot.docs.map((doc) => {
        return { id: doc.id, ...doc.data() }
      })
      console.log(tempDoc)
    })
}

Same way with array

async getMarkers() {
  const events = await firebase.firestore().collection('events')
  events.get().then((querySnapshot) => {
      const tempDoc = []
      querySnapshot.forEach((doc) => {
         tempDoc.push({ id: doc.id, ...doc.data() })
      })
      console.log(tempDoc)
   })
 }

Restrict SQL Server Login access to only one database

this is to topup to what was selected as the correct answer. It has one missing step that when not done, the user will still be able to access the rest of the database. First, do as @DineshDB suggested

  1. Connect to your SQL server instance using management studio
   2. Goto Security -> Logins -> (RIGHT CLICK) New Login
   3. fill in user details
   4. Under User Mapping, select the databases you want the user to be able to access and configure

the missing step is below:

5. Under user mapping, ensure that "sysadmin" is NOT CHECKED and select "db_owner" as the role for the new user.

And thats it.

Binding ConverterParameter

The ConverterParameter property can not be bound because it is not a dependency property.

Since Binding is not derived from DependencyObject none of its properties can be dependency properties. As a consequence, a Binding can never be the target object of another Binding.

There is however an alternative solution. You could use a MultiBinding with a multi-value converter instead of a normal Binding:

<Style TargetType="FrameworkElement">
    <Setter Property="Visibility">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource AccessLevelToVisibilityConverter}">
                <Binding Path="Tag" RelativeSource="{RelativeSource Mode=FindAncestor,
                                                     AncestorType=UserControl}"/>
                <Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>
</Style>

The multi-value converter gets an array of source values as input:

public class AccessLevelToVisibilityConverter : IMultiValueConverter
{
    public object Convert(
        object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.All(v => (v is bool && (bool)v))
            ? Visibility.Visible
            : Visibility.Hidden;
    }

    public object[] ConvertBack(
        object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

How do I install the yaml package for Python?

pip install PyYAML

If libyaml is not found or compiled PyYAML can do without it on Mavericks.

How to Set Opacity (Alpha) for View in Android

I've run into this problem with ICS/JB because the default buttons for the Holo theme consist of images that are slightly transparent. For a background this is especially noticeable.

Gingerbread vs. ICS+:

Gingerbread ICS

Copying over all of the drawable states and images for each resolution and making the transparent images solid is a pain, so I've opted for a dirtier solution: wrap the button in a holder that has a white background. Here's a crude XML drawable (ButtonHolder) which does exactly that:

Your XML file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              style="@style/Content">
  <RelativeLayout style="@style/ButtonHolder">
      <Button android:id="@+id/myButton"
              style="@style/Button"
              android:text="@string/proceed"/>
    </RelativeLayout>
</LinearLayout>

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
    </shape>
  </item>

</layer-list>

styles.xml

.
.
.      
  <style name="ButtonHolder">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:background">@drawable/buttonholder</item>
  </style>

  <style name="Button" parent="@android:style/Widget.Button">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:textStyle">bold</item>
  </style>
.
.
.

However, this results in a white border because the Holo button images include margins to account for the pressed space:

Too much white Too much white pressed

So the solution is to give the white background a margin (4dp worked for me) and rounded corners (2dp) to completely hide the white yet make the button solid:

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

  <item>
    <shape android:shape="rectangle">
      <solid android:color="@android:color/transparent"/>
    </shape>
  </item>

  <item android:top="4dp" android:bottom="4dp" android:left="4dp" android:right="4dp">
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
      <corners android:radius="2dp" />
    </shape>
  </item>

</layer-list>

The final result looks like this:

No white No white pressed

You should target this style for v14+, and tweak or exclude it for Gingerbread/Honeycomb because their native button image sizes are different from ICS and JB's (e.g. this exact style behind a Gingerbread button results in a small bit of white below the button).

JS jQuery - check if value is in array

The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects. we can create a prototype for this purpose

Array.prototype.has_element = function(element) {
    return $.inArray( element, this) !== -1;
};

And then use it like this

var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false

See the Demo below

_x000D_
_x000D_
Array.prototype.has_element = function(element) {_x000D_
  return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Reading output of a command into an array in Bash

You can use

my_array=( $(<command>) )

to store the output of command <command> into the array my_array.

You can access the length of that array using

my_array_length=${#my_array[@]}

Now the length is stored in my_array_length.

Hive cast string to date dd-MM-yyyy

Let's say you have a column 'birth_day' in your table which is in string format, you should use the following query to filter using birth_day

date_Format(birth_day, 'yyyy-MM-dd')

You can use it in a query in the following way

select * from yourtable
where 
date_Format(birth_day, 'yyyy-MM-dd') = '2019-04-16';

Go To Definition: "Cannot navigate to the symbol under the caret."

I also faced with the same problem and "Find all references" for selected class has solved this issue.

Changing the interval of SetInterval while it's running

(function variableInterval() {
    //whatever needs to be done
    interval *= 2; //deal with your interval
    setTimeout(variableInterval, interval);
    //whatever needs to be done
})();

can't get any shorter

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I solved this issue after changing the "Gradle Version" and "Android Plugin version".

You just goto "File>>Project Structure>>Project>>" and make changes here. I have worked a combination of versions from another working project of mine and added to the Project where I was getting this problem.

How can I get Docker Linux container information from within the container itself?

This will get the full container id from within a container:

cat /proc/self/cgroup | grep "cpu:/" | sed 's/\([0-9]\):cpu:\/docker\///g'

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

A useful function to determine if an arbitrary permission has been blocked from requesting (in Kotlin):

private fun isPermissionBlockedFromAsking(activity: Activity, permission: String): Boolean {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED
            && !activity.shouldShowRequestPermissionRationale(permission)
            && PreferenceManager.getDefaultSharedPreferences(activity).getBoolean(permission, false)
    }
    return false
}

Use of this requires setting a shared preference boolean with the name of your desired permission (e.g. android.Manifest.permission.READ_PHONE_STATE) to true when you first request a permission.


Explanation:

Build.VERSION.SDK_INT >= Build.VERSION_CODES.M as some of the code may only be run on API level 23+.

ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED to check we don't already have the permission.

!activity.shouldShowRequestPermissionRationale(permission) to check whether the user has denied the app asking again. Due to quirks of this function, the following line is also required.

PreferenceManager.getDefaultSharedPreferences(activity).getBoolean(permission, false) this is used (along with setting the value to true on first permission request) to distinguish between the "Never asked" and "Never ask again" states, as the previous line doesn't return this information.

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

clear site data in your browser. and it will be fixed. sometimes when you run proxies, vpns or some other programs this error happens.

How to check if file already exists in the folder

Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"

Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.

If System.IO.File.Exists(SavePath) Then
   'The file exists
Else
    'the file doesn't exist
End If

Better way to remove specific characters from a Perl string

You could use the tr instead:

       $p =~ tr/fo//d;

will delete every f and every o from $p. In your case it should be:

       $p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d

See Perl's tr documentation.

tr/SEARCHLIST/REPLACEMENTLIST/cdsr

Transliterates all occurrences of the characters found (or not found if the /c modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.

[…]

If the /d modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.

getting error while updating Composer

Your error message is pretty explicit about what is going wrong:

laravel/framework v5.2.9 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.

Do you have mbstring installed on your server and is it enabled?

You can install mbstring as part of the libapache2-mod-php5 package:

sudo apt-get install libapache2-mod-php5

Or standalone with:

sudo apt-get install php-mbstring

Installing it will also enable it, however you can also enable it by editing your php.ini file and remove the ; that is commenting it out if it is already installed.

If this is on your local machine, then follow the appropriate steps to install this on your environment.

How to delete or add column in SQLITE?

ALTER TABLE SQLite

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

You can:

  1. create new table as the one you are trying to change,
  2. copy all data,
  3. drop old table,
  4. rename the new one.

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

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

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

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

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

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

Privacy keys with example description: cheatsheet

Source

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

Source

And add privacy keys like this:

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

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

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

Update 2019:

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

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

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

Copying a HashMap in Java

What you assign one object to another, all you're doing is copying the reference to the object, not the contents of it. What you need to do is take your object B and manually copy the contents of object A into it.

If you do this often, you might consider implementing a clone() method on the class that will create a new object of the same type, and copy all of it's contents into the new object.

How can I generate a 6 digit unique number?

Among the answers given here before this one, the one by "Yes Barry" is the most appropriate one.

random_int(100000, 999999)

Note that here we use random_int, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_bytes was also introduced in PHP 7 and likewise uses a cryptographic random generator.

Many other solutions for random value generation, including those involving time(), microtime(), uniqid(), rand(), mt_rand(), str_shuffle(), and array_rand(), are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.

The code above generates a string of 6 decimal digits. If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int or random_bytes rather than rand(), mt_rand(), str_shuffle(), etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question, and see also: generating a random code in php?

I also list other things to keep in mind when generating unique identifiers, especially random ones.

Difference between "on-heap" and "off-heap"

Not 100%; however, it sounds like the heap is an object or set of allocated space (on RAM) that is built into the functionality of the code either Java itself or more likely functionality from ehcache itself, and the off-heap Ram is there own system as well; however, it sounds like this is one magnitude slower as it is not as organized, meaning it may not use a heap (meaning one long set of space of ram), and instead uses different address spaces likely making it slightly less efficient.

Then of course the next tier lower is hard-drive space itself.

I don't use ehcache, so you may not want to trust me, but that what is what I gathered from their documentation.

Auto Scale TextView Text to Fit within Bounds

You can use the android.text.StaticLayout class for this. That's what TextView uses internally.

Substring in excel

What about using Replace all? Just replace All on bracket to space. And comma to space. And I think you can achieve it.

What's the fastest way to delete a large folder in Windows?

and to delete a lot of folders, you could also create a batch file with the command spdenne posted.

1) make a text file that has the following contents replacing the folder names in quotes with your folder names:

rmdir /s /q "My Apps"  
rmdir /s /q "My Documents"  
rmdir /s /q "My Pictures"  
rmdir /s /q "My Work Files"

2) save the batch file with a .bat extension (for example deletefiles.bat)
3) open a command prompt (Start > Run > Cmd) and execute the batch file. you can do this like so from the command prompt (substituting X for your drive letter):

X:  
deletefiles.bat

Change package name for Android in React Native

I use the react-native-rename* npm package. Install it via

npm install react-native-rename -g

Then, from the root of your React Native project, execute the following:

react-native-rename "MyApp" -b com.mycompany.myapp

Python time measure function

First and foremost, I highly suggest using a profiler or atleast use timeit.

However if you wanted to write your own timing method strictly to learn, here is somewhere to get started using a decorator.

Python 2:

def timing(f):
    def wrap(*args):
        time1 = time.time()
        ret = f(*args)
        time2 = time.time()
        print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
        return ret
    return wrap

And the usage is very simple, just use the @timing decorator:

@timing
def do_work():
  #code

Python 3:

def timing(f):
    def wrap(*args, **kwargs):
        time1 = time.time()
        ret = f(*args, **kwargs)
        time2 = time.time()
        print('{:s} function took {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0))

        return ret
    return wrap

Note I'm calling f.func_name to get the function name as a string(in Python 2), or f.__name__ in Python 3.

When to use Task.Delay, when to use Thread.Sleep?

if the current thread is killed and you use Thread.Sleep and it is executing then you might get a ThreadAbortException. With Task.Delay you can always provide a cancellation token and gracefully kill it. Thats one reason I would choose Task.Delay. see http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx

I also agree efficiency is not paramount in this case.

How to debug ORA-01775: looping chain of synonyms?

We had the same ORA-01775 error but in our case, the schema user was missing some 'grant select' on a couple of the public synonyms.

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

Tkinter: How to use threads to preventing main event loop from "freezing"

I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.

Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!

Here's class TkRepeatingTask and BackgroundTask:

import threading

class TkRepeatingTask():

    def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
        self.__tk_   = tkRoot
        self.__func_ = taskFuncPointer        
        self.__freq_ = freqencyMillis
        self.__isRunning_ = False

    def isRunning( self ) : return self.__isRunning_ 

    def start( self ) : 
        self.__isRunning_ = True
        self.__onTimer()

    def stop( self ) : self.__isRunning_ = False

    def __onTimer( self ): 
        if self.__isRunning_ :
            self.__func_() 
            self.__tk_.after( self.__freq_, self.__onTimer )

class BackgroundTask():

    def __init__( self, taskFuncPointer ):
        self.__taskFuncPointer_ = taskFuncPointer
        self.__workerThread_ = None
        self.__isRunning_ = False

    def taskFuncPointer( self ) : return self.__taskFuncPointer_

    def isRunning( self ) : 
        return self.__isRunning_ and self.__workerThread_.isAlive()

    def start( self ): 
        if not self.__isRunning_ :
            self.__isRunning_ = True
            self.__workerThread_ = self.WorkerThread( self )
            self.__workerThread_.start()

    def stop( self ) : self.__isRunning_ = False

    class WorkerThread( threading.Thread ):
        def __init__( self, bgTask ):      
            threading.Thread.__init__( self )
            self.__bgTask_ = bgTask

        def run( self ):
            try :
                self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
            except Exception as e: print repr(e)
            self.__bgTask_.stop()

Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:

def tkThreadingTest():

    from tkinter import Tk, Label, Button, StringVar
    from time import sleep

    class UnitTestGUI:

        def __init__( self, master ):
            self.master = master
            master.title( "Threading Test" )

            self.testButton = Button( 
                self.master, text="Blocking", command=self.myLongProcess )
            self.testButton.pack()

            self.threadedButton = Button( 
                self.master, text="Threaded", command=self.onThreadedClicked )
            self.threadedButton.pack()

            self.cancelButton = Button( 
                self.master, text="Stop", command=self.onStopClicked )
            self.cancelButton.pack()

            self.statusLabelVar = StringVar()
            self.statusLabel = Label( master, textvariable=self.statusLabelVar )
            self.statusLabel.pack()

            self.clickMeButton = Button( 
                self.master, text="Click Me", command=self.onClickMeClicked )
            self.clickMeButton.pack()

            self.clickCountLabelVar = StringVar()            
            self.clickCountLabel = Label( master,  textvariable=self.clickCountLabelVar )
            self.clickCountLabel.pack()

            self.threadedButton = Button( 
                self.master, text="Timer", command=self.onTimerClicked )
            self.threadedButton.pack()

            self.timerCountLabelVar = StringVar()            
            self.timerCountLabel = Label( master,  textvariable=self.timerCountLabelVar )
            self.timerCountLabel.pack()

            self.timerCounter_=0

            self.clickCounter_=0

            self.bgTask = BackgroundTask( self.myLongProcess )

            self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )

        def close( self ) :
            print "close"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass            
            self.master.quit()

        def onThreadedClicked( self ):
            print "onThreadedClicked"
            try: self.bgTask.start()
            except: pass

        def onTimerClicked( self ) :
            print "onTimerClicked"
            self.timer.start()

        def onStopClicked( self ) :
            print "onStopClicked"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass                        

        def onClickMeClicked( self ):
            print "onClickMeClicked"
            self.clickCounter_+=1
            self.clickCountLabelVar.set( str(self.clickCounter_) )

        def onTimer( self ) :
            print "onTimer"
            self.timerCounter_+=1
            self.timerCountLabelVar.set( str(self.timerCounter_) )

        def myLongProcess( self, isRunningFunc=None ) :
            print "starting myLongProcess"
            for i in range( 1, 10 ):
                try:
                    if not isRunningFunc() :
                        self.onMyLongProcessUpdate( "Stopped!" )
                        return
                except : pass   
                self.onMyLongProcessUpdate( i )
                sleep( 1.5 ) # simulate doing work
            self.onMyLongProcessUpdate( "Done!" )                

        def onMyLongProcessUpdate( self, status ) :
            print "Process Update: %s" % (status,)
            self.statusLabelVar.set( str(status) )

    root = Tk()    
    gui = UnitTestGUI( root )
    root.protocol( "WM_DELETE_WINDOW", gui.close )
    root.mainloop()

if __name__ == "__main__": 
    tkThreadingTest()

Two import points I'll stress about BackgroundTask:

1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.

2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!

How do I attach events to dynamic HTML elements with jQuery?

After jQuery 1.7 the preferred methods are .on() and .off()

Sean's answer shows an example.

Now Deprecated:

Use the jQuery functions .live() and .die(). Available in jQuery 1.3.x

From the docs:

To display each paragraph's text in an alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Also, the livequery plugin does this and has support for more events.

Listing available com ports with Python

one line solution with pySerial package.

python -m serial.tools.list_ports

How to Convert Boolean to String

The function var_export returns a string representation of a variable, so you could do this:

var_export($res, true);

The second argument tells the function to return the string instead of echoing it.

How to deal with floating point number precision in JavaScript?

The result you've got is correct and fairly consistent across floating point implementations in different languages, processors and operating systems - the only thing that changes is the level of the inaccuracy when the float is actually a double (or higher).

0.1 in binary floating points is like 1/3 in decimal (i.e. 0.3333333333333... forever), there's just no accurate way to handle it.

If you're dealing with floats always expect small rounding errors, so you'll also always have to round the displayed result to something sensible. In return you get very very fast and powerful arithmetic because all the computations are in the native binary of the processor.

Most of the time the solution is not to switch to fixed-point arithmetic, mainly because it's much slower and 99% of the time you just don't need the accuracy. If you're dealing with stuff that does need that level of accuracy (for instance financial transactions) Javascript probably isn't the best tool to use anyway (as you've want to enforce the fixed-point types a static language is probably better).

You're looking for the elegant solution then I'm afraid this is it: floats are quick but have small rounding errors - always round to something sensible when displaying their results.

End of File (EOF) in C

That's a lot of questions.

  1. Why EOF is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"

  2. any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF is 0 when it's FALSE, meaning getchar() returned EOF.

  3. in order to emulate EOF when reading from stdin press Ctrl+D

tmux status bar configuration

I have been playing about with tmux today, trying to customised a little here and there, managed to get battery info displaying on the status right with a ruby script.

Copy the ruby script from http://natedickson.com/blog/2013/04/30/battery-status-in-tmux/ and save it as:

 battinfo.rb in ~/bin

To make it executable make sure to run:

chmod +x ~/bin/battinfo.rb

edit your ~/.tmux.config and include this line

set -g status-right "#[fg=colour155]#(pmset -g batt | ~/bin/battinfo.rb) | #[fg=colour45]%d %b %R"

How to get mouse position in jQuery without mouse-events?

I don't believe there's a way to query the mouse position, but you can use a mousemove handler that just stores the information away, so you can query the stored information.

jQuery(function($) {
    var currentMousePos = { x: -1, y: -1 };
    $(document).mousemove(function(event) {
        currentMousePos.x = event.pageX;
        currentMousePos.y = event.pageY;
    });

    // ELSEWHERE, your code that needs to know the mouse position without an event
    if (currentMousePos.x < 10) {
        // ....
    }
});

But almost all code, other than setTimeout code and such, runs in response to an event, and most events provide the mouse position. So your code that needs to know where the mouse is probably already has access to that information...

Java random numbers using a seed

Several of the examples here create a new Random instance, but this is unnecessary. There is also no reason to use synchronized as one solution does. Instead, take advantage of the methods on the ThreadLocalRandom class:

double randomGenerator() {
    return ThreadLocalRandom.current().nextDouble(0.5);
}

Forcing label to flow inline with input that they label

Put the input in the label, and ditch the for attribute

<label>
  label1:
  <input type="text" id="id1" name="whatever" />
</label>

But of course, what if you want to style the text? Just use a span.

<label id="id1">
  <span>label1:</span>
  <input type="text" name="whatever" />
</label>

How to convert HTML to PDF using iTextSharp

As of 2018, there is also iText7 (A next iteration of old iTextSharp library) and its HTML to PDF package available: itext7.pdfhtml

Usage is straightforward:

HtmlConverter.ConvertToPdf(
    new FileInfo(@"Path\to\Html\File.html"),
    new FileInfo(@"Path\to\Pdf\File.pdf")
);

Method has many more overloads.

Update: iText* family of products has dual licensing model: free for open source, paid for commercial use.

SQL QUERY replace NULL value in a row with a value from the previous known value

Here is the Oracle solution (10g or higher). It uses the analytic function last_value() with the ignore nulls option, which substitutes the last non-null value for the column.

SQL> select *
  2  from mytable
  3  order by id
  4  /

        ID    SOMECOL
---------- ----------
         1          3
         2
         3          5
         4
         5
         6          2

6 rows selected.

SQL> select id
  2         , last_value(somecol ignore nulls) over (order by id) somecol
  3  from mytable
  4  /

        ID    SOMECOL
---------- ----------
         1          3
         2          3
         3          5
         4          5
         5          5
         6          2

6 rows selected.

SQL>

How to debug Apache mod_rewrite

There's the htaccess tester.

It shows which conditions were tested for a certain URL, which ones met the criteria and which rules got executed.

It seems to have some glitches, though.

Disable autocomplete via CSS

CSS does not have this ability. You would need to use client-side scripting.

Pass a PHP string to a JavaScript variable (and escape newlines)

You could try

<script type="text/javascript">
    myvar = unescape('<?=rawurlencode($myvar)?>');
</script>

How to delete a folder with files using Java

In JDK 7 you could use Files.walkFileTree() and Files.deleteIfExists() to delete a tree of files. (Sample: http://fahdshariff.blogspot.ru/2011/08/java-7-deleting-directory-by-walking.html)

In JDK 6 one possible way is to use FileUtils.deleteQuietly from Apache Commons which will remove a file, a directory, or a directory with files and sub-directories.

add class with JavaScript

I like to use a custom "foreach" function of sorts for these kinds of things:

function Each( objs, func )
{
    if ( objs.length ) for ( var i = 0, ol = objs.length, v = objs[ 0 ]; i < ol && func( v, i ) !== false; v = objs[ ++i ] );
    else for ( var p in objs ) if ( func( objs[ p ], p ) === false ) break;
}

(Can't remember where I found the above function, but it has been quite useful.)

Then after fetching your objects (to elements in this example) just do

Each( elements, function( element )
{
    element.addEventListener( "mouseover", function()
    {
        element.classList.add( "active" );
        //element.setAttribute( "class", "active" );
        element.setAttribute( "src", "newsource" );
    });

    // Remove class and new src after "mouseover" ends, if you wish.
    element.addEventListener( "mouseout", function()
    {
        element.classList.remove( "active" );
        element.setAttribute( "src", "originalsource" );
    });
});

classList is a simple way for handling elements' classes. Just needs a shim for a few browsers. If you must use setAttribute you must remember that whatever is set with it will overwrite the previous values.

EDIT: Forgot to mention that you need to use attachEvent instead of addEventListener on some IE versions. Test with if ( document.addEventListener ) {...}.

How to printf "unsigned long" in C?

The correct specifier for unsigned long is %lu.

If you are not getting the exact value you are expecting then there may be some problems in your code.

Please copy your code here. Then maybe someone can tell you better what the problem is.

Read file As String

Reworked the method set originating from -> the accepted answer

@JaredRummler An answer to your comment:

Read file As String

Won't this add an extra new line at the end of the string?

To prevent having a newline added at the end you can use a Boolean value set during the first loop as you will in the code example Boolean firstLine

public static String convertStreamToString(InputStream is) throws IOException {
   // http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    Boolean firstLine = true;
    while ((line = reader.readLine()) != null) {
        if(firstLine){
            sb.append(line);
            firstLine = false;
        } else {
            sb.append("\n").append(line);
        }
    }
    reader.close();
    return sb.toString();
}

public static String getStringFromFile (String filePath) throws IOException {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();
    return ret;
}

How to use filesaver.js

Just as example from github, it works. https://github.com/eligrey/FileSaver.js

<script src="FileSaver.js"></script>
<script type="text/javascript">
    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    saveAs(blob, "hello world.txt");
</script>

How to Replace dot (.) in a string in Java

Use Apache Commons Lang:

String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);

or with standalone JDK:

String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);

How to set the thumbnail image on HTML5 video?

Display Your Video First Frame as Thumbnail:

Add preload="metadata" to your video tag and the second of the first frame #t=0.5 to your video source:

_x000D_
_x000D_
<video width="400" controls="controls" preload="metadata">_x000D_
  <source src="https://www.w3schools.com/html/mov_bbb.mp4#t=0.5" type="video/mp4">_x000D_
</video>
_x000D_
_x000D_
_x000D_

Pass a PHP array to a JavaScript function

Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.

drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))

This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here

$employee = array(
 "employee_id" => 10011,
   "Name" => "Nathan",
   "Skills" =>
    array(
           "analyzing",
           "documentation" =>
            array(
              "desktop",
                "mobile"
             )
        )
);

Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.

{
    "employee_id": 10011,
    "Name": "Nathan",
    "Skills": {
        "0": "analyzing",
        "documentation": [
            "desktop",
            "mobile"
        ]
    }
}

On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.

$.ajax({
        type: 'POST',
        headers: {
            "cache-control": "no-cache"
        },
        url: "employee.php",
        async: false,
        cache: false,
        data: {
            employee_id: 10011
        },
        success: function (jsonString) {
            var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
    });

Is there a job scheduler library for node.js?

agenda is a Lightweight job scheduling for node. This will help you.

How do I get the color from a hexadecimal color code using .NET?

The three variants below give exactly the same color. The last one has the benefit of being highlighted in the Visual Studio 2010 IDE (maybe it's ReSharper that's doing it) with proper color.

var cc1 = System.Drawing.ColorTranslator.FromHtml("#479DEE");

var cc2 = System.Drawing.Color.FromArgb(0x479DEE);

var cc3 = System.Drawing.Color.FromArgb(0x47, 0x9D, 0xEE);

Expected block end YAML error

In my case, the error occured when I tried to pass a variable which was looking like a bytes-object (b"xxxx") but was actually a string.

You can convert the string to a real bytes object like this:

foo.strip('b"').replace("\\n", "\n").encode()

Child element click event trigger the parent click event

I faced the same problem and solve it by this method. html :

<div id="parentDiv">
   <div id="childDiv">
     AAA
   </div>
    BBBB
</div>

JS:

$(document).ready(function(){
 $("#parentDiv").click(function(e){
   if(e.target.id=="childDiv"){
     childEvent();
   } else {
     parentEvent();
   }
 });
});

function childEvent(){
    alert("child event");
}

function parentEvent(){
    alert("paren event");
}

Why is String immutable in Java?

If HELLO is your String then you can't change HELLO to HILLO. This property is called immutability property.

You can have multiple pointer String variable to point HELLO String.

But if HELLO is char Array then you can change HELLO to HILLO. Eg,

char[] charArr = 'HELLO';
char[1] = 'I'; //you can do this

Answer:

Programming languages have immutable data variables so that it can be used as keys in key, value pair. String variables are used as keys/indices, so they are immutable.

How to get URL of current page in PHP

$_SERVER['REQUEST_URI']

For more details on what info is available in the $_SERVER array, see the PHP manual page for it.

If you also need the query string (the bit after the ? in a URL), that part is in this variable:

$_SERVER['QUERY_STRING']

Can I serve multiple clients using just Flask app.run() as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of app.run() with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as app.run(threaded=True)

Space between border and content? / Border distance from content?

Just wrap another div around it, which has the border and the padding you want.

SyntaxError: non-default argument follows default argument

You can't have a non-keyword argument after a keyword argument.

Make sure you re-arrange your function arguments like so:

def a(len1,til,hgt=len1,col=0):
    system('mode con cols='+len1,'lines='+hgt)
    system('title',til)
    system('color',col)

a(64,"hi",25,"0b")

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

If you want to avoid the mem cost of using the exec command, I believe you can do better with xargs. I think the following is a more efficient alternative to

find foo -type f ! -name '*Music*' -exec cp {} bar \; # new proc for each exec



find . -maxdepth 1 -name '*Music*' -prune -o -print0 | xargs -0 -i cp {} dest/

Insert 2 million rows into SQL Server quickly

Re the solution for SqlBulkCopy:

I used the StreamReader to convert and process the text file. The result was a list of my object.

I created a class than takes Datatable or a List<T> and a Buffer size (CommitBatchSize). It will convert the list to a data table using an extension (in the second class).

It works very fast. On my PC, I am able to insert more than 10 million complicated records in less than 10 seconds.

Here is the class:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{

public class BulkUploadToSql<T>
{
    public IList<T> InternalStore { get; set; }
    public string TableName { get; set; }
    public int CommitBatchSize { get; set; }=1000;
    public string ConnectionString { get; set; }

    public void Commit()
    {
        if (InternalStore.Count>0)
        {
            DataTable dt;
            int numberOfPages = (InternalStore.Count / CommitBatchSize)  + (InternalStore.Count % CommitBatchSize == 0 ? 0 : 1);
            for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
                {
                    dt= InternalStore.Skip(pageIndex * CommitBatchSize).Take(CommitBatchSize).ToDataTable();
                BulkInsert(dt);
                }
        } 
    }

    public void BulkInsert(DataTable dt)
    {
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            // make sure to enable triggers
            // more on triggers in next post
            SqlBulkCopy bulkCopy =
                new SqlBulkCopy
                (
                connection,
                SqlBulkCopyOptions.TableLock |
                SqlBulkCopyOptions.FireTriggers |
                SqlBulkCopyOptions.UseInternalTransaction,
                null
                );

            // set the destination table name
            bulkCopy.DestinationTableName = TableName;
            connection.Open();

            // write the data in the "dataTable"
            bulkCopy.WriteToServer(dt);
            connection.Close();
        }
        // reset
        //this.dataTable.Clear();
    }

}

public static class BulkUploadToSqlHelper
{
    public static DataTable ToDataTable<T>(this IEnumerable<T> data)
    {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
}

}

Here is an example when I want to insert a List of my custom object List<PuckDetection> (ListDetections):

var objBulk = new BulkUploadToSql<PuckDetection>()
{
        InternalStore = ListDetections,
        TableName= "PuckDetections",
        CommitBatchSize=1000,
        ConnectionString="ENTER YOU CONNECTION STRING"
};
objBulk.Commit();

The BulkInsert class can be modified to add column mapping if required. Example you have an Identity key as first column.(this assuming that the column names in the datatable are the same as the database)

//ADD COLUMN MAPPING
foreach (DataColumn col in dt.Columns)
{
        bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

How are booleans formatted in Strings in Python?

>>> print "%r, %r" % (True, False)
True, False

This is not specific to boolean values - %r calls the __repr__ method on the argument. %s (for str) should also work.

How to drop all tables from the database with manage.py CLI in Django?

The command ./manage.py sqlclear or ./manage.py sqlflush seems to clear the table and not delete them, however if you want to delete the complete database try this : manage.py flush.

Warning: this will delete your database completely and you will lose all your data, so if that not important go ahead and try it.

Create numpy matrix filled with NaNs

You rarely need loops for vector operations in numpy. You can create an uninitialized array and assign to all entries at once:

>>> a = numpy.empty((3,3,))
>>> a[:] = numpy.nan
>>> a
array([[ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN]])

I have timed the alternatives a[:] = numpy.nan here and a.fill(numpy.nan) as posted by Blaenk:

$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a.fill(np.nan)"
10000 loops, best of 3: 54.3 usec per loop
$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a[:] = np.nan" 
10000 loops, best of 3: 88.8 usec per loop

The timings show a preference for ndarray.fill(..) as the faster alternative. OTOH, I like numpy's convenience implementation where you can assign values to whole slices at the time, the code's intention is very clear.

Note that ndarray.fill performs its operation in-place, so numpy.empty((3,3,)).fill(numpy.nan) will instead return None.

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

You are using the wrong parameters name, try:

if($_POST){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['text'];

//send email
    mail("[email protected]", "51 Deep comment from" .$email, $message);
}

How do I install cURL on Windows?

You may find XAMPP at http://www.apachefriends.org/en/xampp.html

http://www.apachefriends.org/en/xampp-windows.html explains XMAPP for Windows.

Yes, there are 3 php.ini files after installation, one is for php4, one is for php5, and one is for apache. Please modify them accordingly.

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

How to get last 7 days data from current datetime to last 7 days in sql server

This worked for me!!

SELECT * FROM `users` where `created_at` BETWEEN CURDATE()-7 AND CURDATE()

If (Array.Length == 0)

check if the array is null first so you would avoid a null pointer exception

logic in any language: if array is null or is empty :do ....

How to invoke function from external .c file in C?

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

How do I read from parameters.yml in a controller in symfony2?

In Symfony 2.6 and older versions, to get a parameter in a controller - you should get the container first, and then - the needed parameter.

$this->container->getParameter('api_user');

This documentation chapter explains it.

While $this->get() method in a controller will load a service (doc)

In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:

$this->getParameter('api_user');

Convert NSData to String?

I believe your "P" as the dataWithBytes param

NSData *keydata = [NSData dataWithBytes:P length:len];

should be "buf"

NSData *keydata = [NSData dataWithBytes:buf length:len];

since i2d_PrivateKey puts the pointer to the output buffer p at the end of the buffer and waiting for further input, and buf is still pointing to the beginning of your buffer.

The following code works for me where pkey is a pointer to an EVP_PKEY:

unsigned char *buf, *pp;
int len = i2d_PrivateKey(pkey, NULL);
buf = OPENSSL_malloc(len); 
pp = buf;
i2d_PrivateKey(pkey, &pp);

NSData* pkeyData = [NSData dataWithBytes:(const void *)buf length:len];
DLog(@"Private key in hex (%d): %@", len, pkeyData);

You can use an online converter to convert your binary data into base 64 (http://tomeko.net/online_tools/hex_to_base64.php?lang=en) and compare it to the private key in your cert file after using the following command and checking the output of mypkey.pem:

openssl pkcs12 -in myCert.p12 -nocerts -nodes -out mypkey.pem

I referenced your question and this EVP function site for my answer.

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

It sounds like the Xml may not be well formed. If that is the case, then you will not be able to cast it as Xml and given that, you are limited in how much text you can return in Management Studio. However, you could break up the text into smaller chunks like so:

With Tally As
    (
        Select ROW_NUMBER() OVER ( ORDER BY s1.object_id ) - 1 As Num
        From sys.sysobjects As s1
            Cross Join sys.sysobjects As s2
    )
Select Substring(T1.textCol, T2.Num * 8000 + 1, 8000)
From Table As T1
    Cross Join Tally As T2
Where T2.Num <= Ceiling(Len(T1.textCol) / 8000)
Order By T2.Num

You would then need to manually combine them again.

EDIT

It sounds like there are some characters in the text data that the Xml parser does not like. You could try converting those values to entities and then try the Convert(xml, data) trick. So something like:

Update Table
Set Data = Replace(Cast(Data As varchar(max)),'<','&lt;')

(I needed to cast to varchar(max) because the replace function will not work on text columns. There should not be any reason you couldn't convert those text columns to varchar(max).)

How to insert 1000 rows at a time

You can of course use a loop, or you can insert them in a single statement, e.g.

Insert into db
(names,email,password) 
Values
('abc','def','mypassword')
,('ghi','jkl','mypassword2')
,('mno','pqr','mypassword3')

It really depends where you're getting your data from.

If you use a loop, wrapping it in a transaction will make it a bit faster.

UPDATE

What if i want to insert unique names?

If you want to insert unique names, then you need to generate data with unique names. One way to do this is to use Visual Studio to generate test data.

Short circuit Array.forEach like calling break

Found this solution on another site. You can wrap the forEach in a try / catch scenario.

if(typeof StopIteration == "undefined") {
 StopIteration = new Error("StopIteration");
}

try {
  [1,2,3].forEach(function(el){
    alert(el);
    if(el === 1) throw StopIteration;
  });
} catch(error) { if(error != StopIteration) throw error; }

More details here: http://dean.edwards.name/weblog/2006/07/enum/

install apt-get on linux Red Hat server

wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm

rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm

maybe some URL is broken,please research it. Enjoy~~

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Set the path of the root folder and after run the below command

ex : cd C:\Users\maha\Documents\gradle\gs-gradle-master\initial

Is <img> element block level or inline level?

Whenever you insert an image it just takes the width that the image has originally. You can add any other html element next to it and you will see that it will allow it. That makes image an "inline" element.

How do I change the default application icon in Java?

You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:

Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))

Do not forget to import:

import java.awt.Toolkit;

in the source code!

Selecting/excluding sets of columns in pandas

Here's how to create a copy of a DataFrame excluding a list of columns:

df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
df2 = df.drop(['B', 'D'], axis=1)

But be careful! You mention views in your question, suggesting that if you changed df, you'd want df2 to change too. (Like a view would in a database.)

This method doesn't achieve that:

>>> df.loc[0, 'A'] = 999 # Change the first value in df
>>> df.head(1)
     A         B         C         D
0  999 -0.742688 -1.980673 -0.920133
>>> df2.head(1) # df2 is unchanged. It's not a view, it's a copy!
          A         C
0  0.251262 -1.980673

Note also that this is also true of @piggybox's method. (Although that method is nice and slick and Pythonic. I'm not doing it down!!)

For more on views vs. copies see this SO answer and this part of the Pandas docs which that answer refers to.

SQL search multiple values in same field

Yes, you can use SQL IN operator to search multiple absolute values:

SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );

If you want to use LIKE you will need to use OR instead:

SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';

Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.