Programs & Examples On #Yaml

Use this tag for questions about the YAML data serialization format only, not for questions about programs (or examples) that happen to have their configuration in a YAML format. Questions about the CSS framework also called YAML should be tagged [yaml-css] instead.

How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

Removing all empty elements from a hash / YAML?

I know this thread is a bit old but I came up with a better solution which supports Multidimensional hashes. It uses delete_if? except its multidimensional and cleans out anything with a an empty value by default and if a block is passed it is passed down through it's children.

# Hash cleaner
class Hash
    def clean!
        self.delete_if do |key, val|
            if block_given?
                yield(key,val)
            else
                # Prepeare the tests
                test1 = val.nil?
                test2 = val === 0
                test3 = val === false
                test4 = val.empty? if val.respond_to?('empty?')
                test5 = val.strip.empty? if val.is_a?(String) && val.respond_to?('empty?')

                # Were any of the tests true
                test1 || test2 || test3 || test4 || test5
            end
        end

        self.each do |key, val|
            if self[key].is_a?(Hash) && self[key].respond_to?('clean!')
                if block_given?
                    self[key] = self[key].clean!(&Proc.new)
                else
                    self[key] = self[key].clean!
                end
            end
        end

        return self
    end
end

how to reference a YAML "setting" from elsewhere in the same YAML file?

In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:

const tampax = require('tampax');

const yamlString = `
dude:
  name: Arthur
weapon:
  favorite: Excalibur
  useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;

const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);

// output : "Arthur use Excalibur. The goal is to kill Mordred."

Editor's Note: poster is also the author of this package.

What's the best practice using a settings file in Python?

I Found this the most useful and easy to use https://wiki.python.org/moin/ConfigParserExamples

You just create a "myfile.ini" like:

[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True

[SectionTwo]
FavoriteColor=Green
[SectionThree]
FamilyName: Johnson

[Others]
Route: 66

And retrieve the data like:

>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("myfile.ini")
['c:\\tomorrow.ini']
>>> Config.sections()
['Others', 'SectionThree', 'SectionOne', 'SectionTwo']
>>> Config.options('SectionOne')
['Status', 'Name', 'Value', 'Age', 'Single']
>>> Config.get('SectionOne', 'Status')
'Single'

How can I include a YAML file inside another?

No, YAML does not include any kind of "import" or "include" statement.

Is it .yaml or .yml?

After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.

Long story short, the creator of YAML are saying .yaml, but personally I keep doing .yml. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml everywhere. I've been writing docker-compose.yml files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml...

So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...

How do I break a string in YAML over multiple lines?

For situations were the string might contain spaces or not, I prefer double quotes and line continuation with backslashes:

key: "String \
  with long c\
  ontent"

But note about the pitfall for the case that a continuation line begins with a space, it needs to be escaped (because it will be stripped away elsewhere):

key: "String\
  \ with lon\
  g content"

If the string contains line breaks, this needs to be written in C style \n.

See also this question.

Check if a list contains an item in Ansible

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions

How can I parse a YAML file from a Linux shell script?

yq is a lightweight and portable command-line YAML processor

The aim of the project is to be the jq or sed of yaml files.

(https://github.com/mikefarah/yq#readme)

As an example (stolen straight from the documentation), given a sample.yaml file of:

---
bob:
  item1:
    cats: bananas
  item2:
    cats: apples

then

yq r sample.yaml bob.*.cats

will output

- bananas
- apples

How to test that a registered variable is not empty?

- name: set pkg copy dir name
  set_fact:
    PKG_DIR: >-
      {% if ansible_os_family == "RedHat" %}centos/*.rpm
      {%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
      {%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
      {%- else %}{%- endif %}

Converting Swagger specification JSON to HTML documentation

There's a small Java program which generates docs (adoc or md) from a yaml file.

Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
        .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
        .withSwaggerMarkupLanguage(MarkupLanguage.ASCIIDOC)
        .withOutputLanguage(Language.DE)
        .build();

Swagger2MarkupConverter builder = Swagger2MarkupConverter.from(yamlFileAsString).withConfig(config).build();
return builder.toFileWithoutExtension(outFile);

Unfortunately it only supports OpenAPI 2.0 but not OpenAPI 3.0.

How can I parse a YAML file in Python

#!/usr/bin/env python

import sys
import yaml

def main(argv):

    with open(argv[0]) as stream:
        try:
            #print(yaml.load(stream))
            return 0
        except yaml.YAMLError as exc:
            print(exc)
            return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

How do I install the yaml package for Python?

Type in pip3 install yaml or like Connor pip3 install strictyaml

Correct MySQL configuration for Ruby on Rails Database.yml file

If you have multiple databases for testing and development this might help

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost

Mapping list in Yaml to list of objects in Spring Boot

  • You don't need constructors
  • You don't need to annotate inner classes
  • RefreshScope have some problems when using with @Configuration. Please see this github issue

Change your class like this:

@ConfigurationProperties(prefix = "available-payment-channels-list")
@Configuration
public class AvailableChannelsConfiguration {

    private String xyz;
    private List<ChannelConfiguration> channelConfigurations;

    // getters, setters

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;

        // getters, setters
    }

}

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How to escape indicator characters (i.e. : or - ) in YAML

Quotes, but I prefer them on the just the value:

url: "http://www.example.com/"

Putting them across the whole line looks like it might cause problems.

How do I set up the database.yml file in Rails?

The database.yml is a file that is created with new rails applications in /config and defines the database configurations that your application will use in different environments. Read this for details.

Example database.yml:

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: mysql
  encoding: utf8
  database: your_db
  username: root
  password: your_pass
  socket: /tmp/mysql.sock
  host: your_db_ip     #defaults to 127.0.0.1
  port: 3306           

How to parse/read a YAML file into a Python object?

Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file appropriately:

load_yaml_file = None

if not load_yaml_file:
    try:
        import yaml
        load_yaml_file = lambda fn: yaml.load(open(fn))
    except:
        pass

if not load_yaml_file:
    import commands, json
    if commands.getstatusoutput('ruby --version')[0] == 0:
        def load_yaml_file(fn):
            ruby = "puts YAML.load_file('%s').to_json" % fn
            j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
            return json.loads(j[1])

if not load_yaml_file:
    import os, sys
    print """
ERROR: %s requires ruby or python-yaml  to be installed.

apt-get install ruby

  OR

apt-get install python-yaml

  OR

Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
   apt-get install epel-release
   apt-get install python-pip
   apt-get install libyaml-cpp-dev
   python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
  https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
  Pip might not play by all the rules.
  Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
  https://stackoverflow.com/questions/46326059/
  https://stackoverflow.com/questions/36410756/
  https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
  https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.

""" % sys.argv[0]
    os._exit(4)


# test
import sys
print load_yaml_file(sys.argv[1])

What is the difference between YAML and JSON?

Sometimes you don't have to decide for one over the other.

In Go, for example, you can have both at the same time:

type Person struct {
    Name string `json:"name" yaml:"name"`
    Age int `json:"age" yaml:"age"`
}

How do you do block comments in YAML?

In .gitlab-ci.yml file following works::

To comment out a block (multiline): Select the whole block section > Ctrl K C

To uncomment already commented out block (multiline): Select the whole block section > Ctrl K U

How can I write data in YAML format in a file?

Link to the PyYAML documentation showing the difference for the default_flow_style parameter. To write it to a file in block mode (often more readable):

d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

produces:

A: a
B:
  C: c
  D: d
  E: e

What is the difference between .yaml and .yml extension?

As @David Heffeman indicates the recommendation is to use .yaml when possible, and the recommendation has been that way since September 2006.

That some projects use .yml is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).

The best way to approach this is to be rigorous when creating new files (i.e. use .yaml) and be permissive when accepting input (i.e. allow .yml when you encounter it), possible automatically upgrading/correcting these errors when possible.

The other recommendation I have is to document the argument(s) why you have to use .yml, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml has more pages than .yaml" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml extension instead of the correct .yaml, but I think you will be hard pressed to do so.

Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose used .yml, but in later versions started to use .yaml, although they still support .yml). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml instead of appveyor.yml for building the windows wheels of my YAML parser for Python).


On the other hand:

The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.

So it seems fitting that they also use a subset of the recommended extension.

Setting active profile and config location from command line in spring boot

-Dspring.profiles.active=staging -Dspring.config.location=C:\Config

is not correct.

should be:

--spring.profiles.active=staging --spring.config.location=C:\Config

How to set multiple commands in one yaml file with Kubernetes?

command: ["/bin/sh","-c"]
args: ["command one; command two && command three"]

Explanation: The command ["/bin/sh", "-c"] says "run a shell, and execute the following instructions". The args are then passed as commands to the shell. In shell scripting a semicolon separates commands, and && conditionally runs the following command if the first succeed. In the above example, it always runs command one followed by command two, and only runs command three if command two succeeded.

Alternative: In many cases, some of the commands you want to run are probably setting up the final command to run. In this case, building your own Dockerfile is the way to go. Look at the RUN directive in particular.

Use placeholders in yaml

I suppose https://get-ytt.io/ would be an acceptable solution to your problem

Expected block end YAML error

I would like to make this answer for meaningful, so the same kind of erroneous user can enjoy without feel any hassle.

Actually, i was getting the same error but for the different reason, in my case I didn't used any kind of quoted, still getting the same error like expected <block end>, but found BlockMappingStart.

I have solved it by fixing, the Alignment issue inside the same .yml file.

If we don't manage the proper 'tab-space(Keyboard key)' for maintaining successor or ancestor then we have to phase such kind of things.

Now i am doing well.

Using Docker-Compose, how to execute multiple commands

Alpine-based images actually seem to have no bash installed, but you can use sh or ash which link to /bin/busybox.

Example docker-compose.yml:

version: "3"
services:

  api:
    restart: unless-stopped
    command: ash -c "flask models init && flask run"

YAML Multi-Line Arrays

have you tried this?

-
  name: Jack
  age: 32
-
  name: Claudia
  age: 25

I get this: [{"name"=>"Jack", "age"=>32}, {"name"=>"Claudia", "age"=>25}] (I use the YAML Ruby class).

Use YAML with variables

I had this same question, and after a lot of research, it looks like it's not possible.

The answer from cgat is on the right track, but you can't actually concatenate references like that.

Here are things you can do with "variables" in YAML (which are officially called "node anchors" when you set them and "references" when you use them later):

Define a value and use an exact copy of it later:

default: &default_title This Post Has No Title
title: *default_title

{ or }

example_post: &example
  title: My mom likes roosters
  body: Seriously, she does. And I don't know when it started.
  date: 8/18/2012
first_post: *example
second_post:
  title: whatever, etc.

For more info, see this section of the wiki page about YAML: http://en.wikipedia.org/wiki/YAML#References

Define an object and use it with modifications later:

default: &DEFAULT
  URL:          stooges.com
  throw_pies?:  true  
  stooges:  &stooge_list
    larry:  first_stooge
    moe:    second_stooge
    curly:  third_stooge

development:
  <<: *DEFAULT
  URL:      stooges.local
  stooges: 
    shemp: fourth_stooge

test:
  <<: *DEFAULT
  URL:    test.stooges.qa
  stooges: 
    <<: *stooge_list
    shemp: fourth_stooge

This is taken directly from a great demo here: https://gist.github.com/bowsersenior/979804

YAML equivalent of array of objects in JSON

TL;DR

You want this:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Mappings

The YAML equivalent of a JSON object is a mapping, which looks like these:

# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2

Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:

# OK
   foo: 1
   bar: 2
# Parse error
   foo: 1
    bar: 2

Sequences

The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):

# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz

In a block sequence the -s must be in the same column.

JSON to YAML

Let's turn your JSON into YAML. Here's your JSON:

{"AAPL": [
  {
    "shares": -75.088,
    "date": "11/27/2015"
  },
  {
    "shares": 75.088,
    "date": "11/26/2015"
  },
]}

As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.

Starting from the inside out, we have objects that look like this:

{
  "shares": -75.088,
  "date": "11/27/2015"
}

The equivalent YAML mapping is:

shares: -75.088
date: 11/27/2015

We have two of these in an array (sequence):

- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Note how the -s line up and the first characters of the mapping keys line up.

Finally, this sequence is itself a value in a mapping with the key AAPL:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Parsing this and converting it back to JSON yields the expected result:

{
  "AAPL": [
    {
      "date": "11/27/2015", 
      "shares": -75.088
    }, 
    {
      "date": "11/26/2015", 
      "shares": 75.088
    }
  ]
}

You can see it (and edit it interactively) here.

Typescript empty object for a typed variable

Caveats

Here are two worthy caveats from the comments.

Either you want user to be of type User | {} or Partial<User>, or you need to redefine the User type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. – jcalz

I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property Username is left undefined, while the type annotation is saying it can't be undefined. – Ian Liu Rodrigues

Answer

One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.

type User = {
    Username: string;
    Email: string;
}

const user01 = {} as User;
const user02 = <User>{};

user01.Email = "[email protected]";

Here is a working example for you.

Here are type assertions working with suggestion.

java.lang.OutOfMemoryError: Java heap space in Maven

The chances are that the problem is in one of the unit tests that you've asked Maven to run.

As such, fiddling with the heap size is the wrong approach. Instead, you should be looking at the unit test that has caused the OOME, and trying to figure out if it is the fault of the unit test or the code that it is testing.

Start by looking at the stack trace. If there isn't one, run mvn ... test again with the -e option.

Android Room - simple select query - Cannot access database on the main thread

An elegant RxJava/Kotlin solution is to use Completable.fromCallable, which will give you an Observable which does not return a value, but can observed and subscribed on a different thread.

public Completable insert(Event event) {
    return Completable.fromCallable(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            return database.eventDao().insert(event)
        }
    }
}

Or in Kotlin:

fun insert(event: Event) : Completable = Completable.fromCallable {
    database.eventDao().insert(event)
}

You can the observe and subscribe as you would usually:

dataManager.insert(event)
    .subscribeOn(scheduler)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(...)

Make: how to continue after a command fails?

make -k (or --keep-going on gnumake) will do what you are asking for, I think.

You really ought to find the del or rm line that is failing and add a -f to it to keep that error from happening to others though.

Parsing domain from a URL

I'm adding this answer late since this is the answer that pops up most on Google...

You can use PHP to...

$url = "www.google.co.uk";
$host = parse_url($url, PHP_URL_HOST);
// $host == "www.google.co.uk"

to grab the host but not the private domain to which the host refers. (Example www.google.co.uk is the host, but google.co.uk is the private domain)

To grab the private domain, you must need know the list of public suffixes to which one can register a private domain. This list happens to be curated by Mozilla at https://publicsuffix.org/

The below code works when an array of public suffixes has been created already. Simply call

$domain = get_private_domain("www.google.co.uk");

with the remaining code...

// find some way to parse the above list of public suffix
// then add them to a PHP array
$suffix = [... all valid public suffix ...];

function get_public_suffix($host) {
  $parts = split("\.", $host);
  while (count($parts) > 0) {
    if (is_public_suffix(join(".", $parts)))
      return join(".", $parts);

    array_shift($parts);
  }

  return false;
}

function is_public_suffix($host) {
  global $suffix;
  return isset($suffix[$host]);
}

function get_private_domain($host) {
  $public = get_public_suffix($host);
  $public_parts = split("\.", $public);
  $all_parts = split("\.", $host);

  $private = [];

  for ($x = 0; $x < count($public_parts); ++$x) 
    $private[] = array_pop($all_parts);

  if (count($all_parts) > 0)
    $private[] = array_pop($all_parts);

  return join(".", array_reverse($private));
}

sqlplus statement from command line

Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).

I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:

sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF

How to update an object in a List<> in C#

You can do somthing like :

if (product != null) {
    var products = Repository.Products;
    var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
    Repository.Products[indexOf] = product;
    // or 
    Repository.Products[indexOf].prop = product.prop;
}

New lines inside paragraph in README.md

If you want to be a little bit fancier you can also create it as an html list to create something like bullets or numbers using ul or ol.

<ul>
<li>Line 1</li>
<li>Line 2</li>
</ul>

How to get all options of a select using jQuery?

$("input[type=checkbox][checked]").serializeArray();

Or:

$(".some_class[type=checkbox][checked]").serializeArray();

To see the results:

alert($("input[type=checkbox][checked]").serializeArray().toSource());

How do I use spaces in the Command Prompt?

Spaces in the Commend Prompt (in a VBA Shell command code line)

I had a very similar problem which ended up being a space in the command prompt when automating via VBA to get the contents from the command window into a text file. This Thread was one of many I caught along the way that didn’t quite get me the solution.

So this may help others with a similar problem: Since the syntax with quotes is always difficult to get right , I think showing some specific examples is always useful. The additional problem you get using the command prompt in VBA via the Shell thing, is that the code line often won’t error when something goes wrong: in fact a blink of the black commend window misleads into thinking something was done.

As example… say I have a Folder, with a text file in it like at

C:\Alans Folder\test1.txt ( https://imgur.com/FELSdB6 )

The space there in the folder name gives the problem.

Something like this would work, assuming the Folder, AlansFolder, exists

Sub ShellBlackCommandPromptWindowAutomatingCopyingWindowContent()
 Shell "cmd.exe /c ""ipconfig /all > C:\AlansFolder\test1.txt"""
End Sub

This won’t work. (It won’t error).

Sub ShellBlackCommandPromptWindowAutomatingCopyingWindowContent()
 Shell "cmd.exe /c ""ipconfig /all > C:\Alans Folder\test1.txt"""
End Sub

Including quote pairs around the path will make it work

Sub ShellBlackCommandPromptWindowAutomatingCopyingWindowContent()
 Shell "cmd.exe /c ""ipconfig /all > ""C:\Alans Folder\test1.txt"""""
End Sub

( By the way, if the text file does not exist, then it will be made).

With the benefit of hindsight, we can see that my solution does tie up approximately with some already given..

Converting that code line to a manual given command we would have

ipconfig /all > "C:\Alans Folder\test1.txt"

That seems to work

This works also

ipconfig /all > C:\AlansFolder\test1.txt

This doesn’t

ipconfig /all > C:\Alans Folder\test1.txt

This final form also works and ties up with the solution from sacra ….” You have to add quotation marks around each path and also enclose the whole command in quotation marks “ …..

cmd.exe /c "ipconfig /all > "C:\Alans Folder\test1.txt""

How to bundle vendor scripts separately and require them as needed with Webpack?

in my webpack.config.js (Version 1,2,3) file, I have

function isExternal(module) {
  var context = module.context;

  if (typeof context !== 'string') {
    return false;
  }

  return context.indexOf('node_modules') !== -1;
}

in my plugins array

plugins: [
  new CommonsChunkPlugin({
    name: 'vendors',
    minChunks: function(module) {
      return isExternal(module);
    }
  }),
  // Other plugins
]

Now I have a file that only adds 3rd party libs to one file as required.

If you want get more granular where you separate your vendors and entry point files:

plugins: [
  new CommonsChunkPlugin({
    name: 'common',
    minChunks: function(module, count) {
      return !isExternal(module) && count >= 2; // adjustable
    }
  }),
  new CommonsChunkPlugin({
    name: 'vendors',
    chunks: ['common'],
    // or if you have an key value object for your entries
    // chunks: Object.keys(entry).concat('common')
    minChunks: function(module) {
      return isExternal(module);
    }
  })
]

Note that the order of the plugins matters a lot.

Also, this is going to change in version 4. When that's official, I update this answer.

Update: indexOf search change for windows users

Define preprocessor macro through CMake?

To do this for a specific target, you can do the following:

target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)

You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.

Creating a procedure in mySql with parameters

Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.

DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;

In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.

How to call procedure? Well! its very easy, simply you can call procedure by hitting this command

$mysql> CAll getStudentInfo('pass_required_name');

enter image description here

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

Display SQL query results in php

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

Change your code to this :

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

Get request URL in JSP which is forwarded by Servlet

If you use RequestDispatcher.forward() to route the request from controller to the view, then request URI is exposed as a request attribute named javax.servlet.forward.request_uri. So, you can use

request.getAttribute("javax.servlet.forward.request_uri")

or

${requestScope['javax.servlet.forward.request_uri']}

How to remove square brackets from list in Python?

Yes, there are several ways to do it. For instance, you can convert the list to a string and then remove the first and last characters:

l = ['a', 2, 'c']
print str(l)[1:-1]
'a', 2, 'c'

If your list contains only strings and you want remove the quotes too then you can use the join method as has already been said.

How do multiple clients connect simultaneously to one port, say 80, on a server?

Important:

I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.

First remember below two rules:

  1. Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL} not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT} - Protocol is an important part of a socket's definition.

  2. OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.

Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP} and socket2{SRC-B, 100, DEST-X,80, TCP}. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.

To answer the original question of the post:

Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.

To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.

A bit more for completeness:

Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.

Server Types - single & multiple:

When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).

Suggested Books and rest of the two volumes if you can.

A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')

Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.

Can we import XML file into another XML file?

The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:

Per http://msdn.microsoft.com/en-us/library/aa302291.aspx

Why XInclude?

The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:

  • An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
  • An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
  • Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
  • Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.

The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.

Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.

Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:

<book xmlns:xi="http://www.w3.org/2001/XInclude">

  <title>The Wit and Wisdom of George W. Bush</title>

  <xi:include href="malapropisms.xml"/>

  <xi:include href="mispronunciations.xml"/>

  <xi:include href="madeupwords.xml"/>

</book>

UICollectionView current visible cell index

Swift 5:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    var visibleRect = CGRect()

    visibleRect.origin = collectionView.contentOffset
    visibleRect.size = collectionView.bounds.size

    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)

    guard let indexPath = collectionView.indexPathForItem(at: visiblePoint) else { return } 

    print(indexPath)
}

Working Answers Combined In Swift 2.2 :

 func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

        var visibleRect = CGRect()

        visibleRect.origin = self.collectionView.contentOffset
        visibleRect.size = self.collectionView.bounds.size

        let visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect))

        let visibleIndexPath: NSIndexPath = self.collectionView.indexPathForItemAtPoint(visiblePoint)

        guard let indexPath = visibleIndexPath else { return } 
        print(indexPath)

    }

Center a button in a Linear layout

You also can Try this Code:

<LinearLayout
            android:id="@+id/linear_layout"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:orientation="horizontal"
            android:weightSum="2.0"
            android:background="@drawable/anyBackground" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/img_mail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:background="@drawable/yourImage" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:layout_weight="1" >



<ImageView
            android:id="@+id/img_save"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:background="@drawable/yourImage" />
        </LinearLayout>
        </LinearLayout>

How to create an Array with AngularJS's ng-model

How to create an array of inputs with ng-model

Use the ng-repeat directive:

<ol>
  <li ng-repeat="n in [] | range:count">
    <input name="telephone-{{$index}}"
           ng-model="telephones[$index].value" >
  </li>
</ol>

The DEMO

_x000D_
_x000D_
angular.module("app",[])_x000D_
.controller("ctrl",function($scope){_x000D_
  $scope.count = 3;_x000D_
  $scope.telephones = [];_x000D_
})_x000D_
.filter("range",function() {_x000D_
  return (x,n) => Array.from({length:n},(x,index)=>(index));_x000D_
})
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>_x000D_
<body ng-app="app" ng-controller="ctrl">_x000D_
    <button>_x000D_
      Array length_x000D_
      <input type="number" ng-model="count" _x000D_
             ng-change="telephones.length=count">_x000D_
    </button>_x000D_
    <ol>_x000D_
      <li ng-repeat="n in [] | range:count">_x000D_
        <input name="telephone-{{$index}}"_x000D_
               ng-model="telephones[$index].value" >_x000D_
      </li>_x000D_
    </ol>  _x000D_
    {{telephones}}_x000D_
</body>
_x000D_
_x000D_
_x000D_

Pythonic way to return list of every nth item in a larger list

>>> lst = list(range(165))
>>> lst[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]

Note that this is around 100 times faster than looping and checking a modulus for each element:

$ python -m timeit -s "lst = list(range(1000))" "lst1 = [x for x in lst if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop
$ python -m timeit -s "lst = list(range(1000))" "lst1 = lst[0::10]"
100000 loops, best of 3: 4.02 usec per loop

How to set cookie in node js using express framework?

Not exactly answering your question, but I came across your question, while looking for an answer to an issue that I had. Maybe it will help somebody else.

My issue was that cookies were set in server response, but were not saved by the browser.

The server response came back with cookies set:

Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT 

This is how I solved it.

I used fetch in the client-side code. If you do not specify credentials: 'include' in the fetch options, cookies are neither sent to server nor saved by the browser, even though the server response sets cookies.

Example:

var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');

return fetch('/your/server_endpoint', {
    method: 'POST',
    mode: 'same-origin',
    redirect: 'follow',
    credentials: 'include', // Don't forget to specify this if you need cookies
    headers: headers,
    body: JSON.stringify({
        first_name: 'John',
        last_name: 'Doe'
    })
})

I hope this helps somebody.

How to change Tkinter Button state from disabled to normal?

I think a quick way to change the options of a widget is using the configure method.

In your case, it would look like this:

self.x.configure(state=NORMAL)

Difference between Activity Context and Application Context

I found this table super useful for deciding when to use different types of Contexts:

enter image description here

  1. An application CAN start an Activity from here, but it requires that a new task be created. This may fit specific use cases, but can create non-standard back stack behaviors in your application and is generally not recommended or considered good practice.
  2. This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application.
  3. Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.

Original article here.

GridView sorting: SortDirection always Ascending

In vb.net but very simple!

Protected Sub grTicketHistory_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grTicketHistory.Sorting

    Dim dt As DataTable = Session("historytable")
    If Session("SortDirection" & e.SortExpression) = "ASC" Then
        Session("SortDirection" & e.SortExpression) = "DESC"
    Else
        Session("SortDirection" & e.SortExpression) = "ASC"
    End If
    dt.DefaultView.Sort = e.SortExpression & " " & Session("SortDirection" & e.SortExpression)
    grTicketHistory.DataSource = dt
    grTicketHistory.DataBind()

End Sub

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

Python Unicode Encode Error

I wrote the following to fix the nuisance non-ascii quotes and force conversion to something usable.

unicodeToAsciiMap = {u'\u2019':"'", u'\u2018':"`", }

def unicodeToAscii(inStr):
    try:
        return str(inStr)
    except:
        pass
    outStr = ""
    for i in inStr:
        try:
            outStr = outStr + str(i)
        except:
            if unicodeToAsciiMap.has_key(i):
                outStr = outStr + unicodeToAsciiMap[i]
            else:
                try:
                    print "unicodeToAscii: add to map:", i, repr(i), "(encoded as _)"
                except:
                    print "unicodeToAscii: unknown code (encoded as _)", repr(i)
                outStr = outStr + "_"
    return outStr

remove all variables except functions

The posted setdiff answer is nice. I just thought I'd post this related function I wrote a while back. Its usefulness is up to the reader :-).

lstype<-function(type='closure'){ 
    inlist<-ls(.GlobalEnv)
    if (type=='function') type <-'closure'
    typelist<-sapply(sapply(inlist,get),typeof)
    return(names(typelist[typelist==type]))
}

Histogram Matplotlib

If you're willing to use pandas:

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

XPath OR operator for different nodes

If you want to select only one of two nodes with union operator, you can use this solution: (//bookstore/book/title | //bookstore/city/zipcode/title)[1]

Java switch statement multiple cases

Maybe not as elegant as some previous answers, but if you want to achieve switch cases with few large ranges, just combine ranges to a single case beforehand:

// make a switch variable so as not to change the original value
int switchVariable = variable;

//combine range 1-100 to one single case in switch
if(1 <= variable && variable <=100)
    switchVariable = 1;
switch (switchVariable) 
{ 
    case 0:
        break; 
    case 1:
        // range 1-100
        doSomething(); 
        break;
    case 101: 
        doSomethingElse(); 
        break;
    etc.
} 

Difference between Groovy Binary and Source release?

Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.

recyclerview No adapter attached; skipping layout

These Lines must be in OnCreate:

mmAdapter = new Adapter(msgList);
mrecyclerView.setAdapter(mmAdapter);

How do I check if a variable exists?

A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:

# Search for entry.
for x in y:
  if x == 3:
    found = x

# Work with found entry.
try:
  print('Found: {0}'.format(found))
except NameError:
  print('Not found')
else:
  # Handle rest of Found case here
  ...

Converting String To Float in C#

You can double.Parse("41.00027357629127");

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

How to print to stderr in Python?

If you want to exit a program because of a fatal error, use:

sys.exit("Your program caused a fatal error. ... description ...")

and import sys in the header.

How to create a HTTP server in Android?

You can try Restlet edition for android:

The source can be downloaded from Restlet website:

Show DialogFragment with animation growing from a point

To get a full-screen dialog with animation, write the following ...

Styles:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionModeBackground">?attr/colorPrimary</item>
    <item name="windowActionModeOverlay">true</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.NoActionBar.FullScreenDialog">
    <item name="android:windowAnimationStyle">@style/Animation.WindowSlideUpDown</item>
</style>

<style name="Animation.WindowSlideUpDown" parent="@android:style/Animation.Activity">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_down</item>
</style>

res/anim/slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:interpolator/accelerate_quad">

    <translate
        android:duration="@android:integer/config_shortAnimTime"
        android:fromYDelta="100%"
        android:toYDelta="0%"/>
</set>

res/anim/slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:interpolator/accelerate_quad">

    <translate
        android:duration="@android:integer/config_shortAnimTime"
        android:fromYDelta="0%"
        android:toYDelta="100%"/>
</set>

Java code:

public class MyDialog extends DialogFragment {

    @Override
    public int getTheme() {
        return R.style.AppTheme_NoActionBar_FullScreenDialog;
    }
}

private void showDialog() {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    Fragment previous = getSupportFragmentManager().findFragmentByTag(MyDialog.class.getName());
    if (previous != null) {
        fragmentTransaction.remove(previous);
    }
    fragmentTransaction.addToBackStack(null);

    MyDialog dialog = new MyDialog();
    dialog.show(fragmentTransaction, MyDialog.class.getName());
}

Create an empty data.frame

This question didn't specifically address my concerns (outlined here) but in case anyone wants to do this with a parameterized number of columns and no coercion:

> require(dplyr)
> dbNames <- c('a','b','c','d')
> emptyTableOut <- 
    data.frame(
        character(), 
        matrix(integer(), ncol = 3, nrow = 0), stringsAsFactors = FALSE
    ) %>% 
    setNames(nm = c(dbNames))
> glimpse(emptyTableOut)
Observations: 0
Variables: 4
$ a <chr> 
$ b <int> 
$ c <int> 
$ d <int>

As divibisan states on the linked question,

...the reason [coercion] occurs [when cbinding matrices and their constituent types] is that a matrix can only have a single data type. When you cbind 2 matrices, the result is still a matrix and so the variables are all coerced into a single type before converting to a data.frame

Resize font-size according to div size

I was looking for the same funcionality and found this answer. However, I wanted to give you guys a quick update. It's CSS3's vmin unit.

p, li
{
  font-size: 1.2vmin;
}

vmin means 'whichever is smaller between the 1% of the ViewPort's height and the 1% of the ViewPort's width'.

More info on SitePoint

git: fatal: Could not read from remote repository

I had a perfectly fine working git and suddenly I got that error when I tried to push to the master. As I found out, it was because the repository host had problems.

If you using GitHub or Bitbucket you can easily check the status at

https://status.github.com/messages or https://status.bitbucket.org/

enter image description here

Get Environment Variable from Docker Container

This command inspects docker stack processes' environment in the host :

pidof   dockerd containerd containerd-shim | tr ' ' '\n' \
      | xargs -L1 -I{} -- sudo xargs -a '/proc/{}/environ' -L1 -0

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){

}

and

public void doGet(HttpServletRequest req, HttpServletResponse resp){

}

One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

Python Library Path

You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:

import sys
sys.path.append('/home/user/python-libs')

Looping through JSON with node.js

Take a look at Traverse. It will recursively walk an object tree for you and at every node you have a number of different objects you can access - key of current node, value of current node, parent of current node, full key path of current node, etc. https://github.com/substack/js-traverse. I've used it to good effect on objects that I wanted to scrub circular references to and when I need to do a deep clone while transforming various data bits. Here's some code pulled form their samples to give you a flavor of what it can do.

var id = 54;
var callbacks = {};
var obj = { moo : function () {}, foo : [2,3,4, function () {}] };

var scrubbed = traverse(obj).map(function (x) {
    if (typeof x === 'function') {
        callbacks[id] = { id : id, f : x, path : this.path };
        this.update('[Function]');
        id++;
    }
});

console.dir(scrubbed);
console.dir(callbacks);

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Convert InputStream to JSONObject

The best solution in my opinion is to encapsulate the InputStream in a JSONTokener object. Something like this:

JSONObject jsonObject = new JSONObject(new JSONTokener(inputStream));

What do the return values of Comparable.compareTo mean in Java?

int x = thisObject.compareTo(anotherObject);

The compareTo() method returns an int with the following characteristics:

  • negative If thisObject < anotherObject
  • zero If thisObject == anotherObject
  • positive If thisObject > anotherObject

How do I use PHP namespaces with autoload?

I do something like this: See this GitHub Example

spl_autoload_register('AutoLoader');

function AutoLoader($className)
{
    $file = str_replace('\\',DIRECTORY_SEPARATOR,$className);

    require_once 'classes' . DIRECTORY_SEPARATOR . $file . '.php'; 
    //Make your own path, Might need to use Magics like ___DIR___
}

How to create standard Borderless buttons (like in the design guideline mentioned)?

For those who want to create borderless button programmatically for API's >= 8

ImageButton smsImgBtn = new ImageButton(this);
//Sets a drawable as the content of this button
smsImgBtn.setImageResource(R.drawable.message_icon);    
//Set to 0 to remove the background or for bordeless button
smsImgBtn.setBackgroundResource(0);

Calling @Html.Partial to display a partial view belonging to a different controller

As GvS said, but I also find it useful to use strongly typed views so that I can write something like

@Html.Partial(MVC.Student.Index(), model)

without magic strings.

Pass Multiple Parameters to jQuery ajax call

            data: JSON.stringify({ "objectnameOFcontroller": data, "Sel": $(th).val() }),

controller object name

mysql said: Cannot connect: invalid settings. xampp

it may be another mysqld instance running and stoped it with:

sudo service mysql stop

Worked for me.

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Close Xcode, rename the folder. Then make a new folder with the previous name. Run the project, stop the project. Delete the new folder, rename old folder and re-run.

My iPad Pro simulator is affected with this issue. Its something that makes me upset, so much hard work... hopefully Google works through bugs for the next SDK.

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

In my case, I don't have control over server setting, but I know it's expecting "application/json" for "Content-Type". I did this on the iOS client side:

manager.requestSerializer = [AFJSONRequestSerializer serializer];

refer to AFNetworking version 2 content-type error

Get the last day of the month in SQL

WinSQL: I wanted to return all records for last month:

where DATE01 between dateadd(month,-1,dateadd(day,1,dateadd(day,-day(today()),today()))) and dateadd(day,-day(today()),today())

This does the same thing:

where month(DATE01) = month(dateadd(month,-1,today())) and year(DATE01) = year(dateadd(month,-1,today()))

Chrome extension id - how to find it

As Alex Gray points out in a comment above, "all of the corresponding IDs are actually on the extensions page within the browser".

However, you must click the Developer Mode checkbox at top of Extensions page to see them.

Is it possible to forward-declare a function in Python?

Sometimes an algorithm is easiest to understand top-down, starting with the overall structure and drilling down into the details.

You can do so without forward declarations:

def main():
  make_omelet()
  eat()

def make_omelet():
  break_eggs()
  whisk()
  fry()

def break_eggs():
  for egg in carton:
    break(egg)

# ...

main()

How to view table contents in Mysql Workbench GUI?

Open a connection to your server first (SQL IDE) from the home screen. Then use the context menu in the schema tree to run a query that simply selects rows from the selected table. The LIMIT attached to that is to avoid reading too many rows by accident. This limit can be switched off (or adjusted) in the preferences dialog.

enter image description here

This quick way to select rows is however not very flexible. Normally you would run a query (File / New Query Tab) in the editor with additional conditions, like a sort order:

enter image description here

Can I use multiple versions of jQuery on the same page?

Taken from http://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page:

  • Original page loads his "jquery.versionX.js" -- $ and jQuery belong to versionX.
  • You call your "jquery.versionY.js" -- now $ and jQuery belong to versionY, plus _$ and _jQuery belong to versionX.
  • my_jQuery = jQuery.noConflict(true); -- now $ and jQuery belong to versionX, _$ and _jQuery are probably null, and my_jQuery is versionY.

Converting json results to a date

I use this:

function parseJsonDate(jsonDateString){
    return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}

Update 2018:

This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC on server and client.

  • 2018-07-31T11:56:48Z - ISO string can be parsed using new Date("2018-07-31T11:56:48Z") and obtained from a Date object using dateObject.toISOString()
  • 1533038208000 - milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date object using dateObject.getTime()

How to compare two date values with jQuery

var startDate = $('#start_date').val().replace(/-/g,'/');
var endDate = $('#end_date').val().replace(/-/g,'/');

if(startDate > endDate){
   // do your stuff here...
}

How to make the tab character 4 spaces instead of 8 spaces in nano?

For future viewers, there is a line in my /etc/nanorc file close to line 153 that says "set tabsize 8". The word might need to be tabsize instead of tabspace. After I replaced 8 with 4 and uncommented the line, it solved my problem.

Sending mail from Python using SMTP

You should make sure you format the date in the correct format - RFC2822.

Rolling or sliding window iterator?

def GetShiftingWindows(thelist, size):
    return [ thelist[x:x+size] for x in range( len(thelist) - size + 1 ) ]

>> a = [1, 2, 3, 4, 5]
>> GetShiftingWindows(a, 3)
[ [1, 2, 3], [2, 3, 4], [3, 4, 5] ]

WHERE statement after a UNION in SQL?

You probably need to wrap the UNION in a sub-SELECT and apply the WHERE clause afterward:

SELECT * FROM (
    SELECT * FROM Table1 WHERE Field1 = Value1
    UNION
    SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3

Basically, the UNION is looking for two complete SELECT statements to combine, and the WHERE clause is part of the SELECT statement.

It may make more sense to apply the outer WHERE clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

I was facing the same issue today what worked for is below down

For ANDROID STUDIO... Enable Instant Run

In File->Preferences->Build, Execution, Deployment->Instant Run-> Check Enable Instant run for hot swap...

Hope it helps

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

Subtract two variables in Bash

Try this Bash syntax instead of trying to use an external program expr:

count=$((FIRSTV-SECONDV))

BTW, the correct syntax of using expr is:

count=$(expr $FIRSTV - $SECONDV)

But keep in mind using expr is going to be slower than the internal Bash syntax I provided above.

How do I get the logfile from an Android device?

I hope this code will help someone. It took me 2 days to figure out how to log from device, and then filter it:

public File extractLogToFileAndWeb(){
        //set a file
        Date datum = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ITALY);
        String fullName = df.format(datum)+"appLog.log";
        File file = new File (Environment.getExternalStorageDirectory(), fullName);

        //clears a file
        if(file.exists()){
            file.delete();
        }


        //write log to file
        int pid = android.os.Process.myPid();
        try {
            String command = String.format("logcat -d -v threadtime *:*");        
            Process process = Runtime.getRuntime().exec(command);

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder result = new StringBuilder();
            String currentLine = null;

            while ((currentLine = reader.readLine()) != null) {
                   if (currentLine != null && currentLine.contains(String.valueOf(pid))) {
                       result.append(currentLine);
                       result.append("\n");
                    }
            }

            FileWriter out = new FileWriter(file);
            out.write(result.toString());
            out.close();

            //Runtime.getRuntime().exec("logcat -d -v time -f "+file.getAbsolutePath());
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
        }


        //clear the log
        try {
            Runtime.getRuntime().exec("logcat -c");
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
        }

        return file;
    }

as pointed by @mehdok

add the permission to the manifest for reading logs

<uses-permission android:name="android.permission.READ_LOGS" />

How to pass parameters to a Script tag?

Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.

Should I use the datetime or timestamp data type in MySQL?

+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+
|                                       TIMESTAMP                                       |                                 DATETIME                                 |
+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+
| TIMESTAMP requires 4 bytes.                                                           | DATETIME requires 8 bytes.                                               |
| Timestamp is the number of seconds that have elapsed since January 1, 1970 00:00 UTC. | DATETIME is a text displays 'YYYY-MM-DD HH:MM:SS' format.                |
| TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC.    | DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59' |
| TIMESTAMP during retrieval converted back to the current time zone.                   | DATETIME can not do this.                                                |
| TIMESTAMP is used mostly for metadata i.e. row created/modified and audit purpose.    | DATETIME is used mostly for user-data.                                   |
+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+

Pass Hidden parameters using response.sendRedirect()

Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.

RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);

The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue. Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.

Retrieving subfolders names in S3 bucket from boto3

S3 is an object storage, it doesn't have real directory structure. The "/" is rather cosmetic. One reason that people want to have a directory structure, because they can maintain/prune/add a tree to the application. For S3, you treat such structure as sort of index or search tag.

To manipulate object in S3, you need boto3.client or boto3.resource, e.g. To list all object

import boto3 
s3 = boto3.client("s3")
all_objects = s3.list_objects(Bucket = 'bucket-name') 

http://boto3.readthedocs.org/en/latest/reference/services/s3.html#S3.Client.list_objects

In fact, if the s3 object name is stored using '/' separator. The more recent version of list_objects (list_objects_v2) allows you to limit the response to keys that begin with the specified prefix.

To limit the items to items under certain sub-folders:

    import boto3 
    s3 = boto3.client("s3")
    response = s3.list_objects_v2(
            Bucket=BUCKET,
            Prefix ='DIR1/DIR2',
            MaxKeys=100 )

Documentation

Another option is using python os.path function to extract the folder prefix. Problem is that this will require listing objects from undesired directories.

import os
s3_key = 'first-level/1456753904534/part-00014'
filename = os.path.basename(s3_key) 
foldername = os.path.dirname(s3_key)

# if you are not using conventional delimiter like '#' 
s3_key = 'first-level#1456753904534#part-00014
filename = s3_key.split("#")[-1]

A reminder about boto3 : boto3.resource is a nice high level API. There are pros and cons using boto3.client vs boto3.resource. If you develop internal shared library, using boto3.resource will give you a blackbox layer over the resources used.

How to add shortcut keys for java code in eclipse

Type "Sysout" and then Ctrl+Space. It expands to

System.out.println();

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

I came researching the options that I would have to do this, however, I believe the method I use is the simplest:

SELECT COUNT(*), 
       DATEADD(dd, DATEDIFF(dd, 0, date_field),0) as dtgroup 
FROM TABLE 
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, date_field),0) 
ORDER BY dtgroup ASC;

Split a String into an array in Swift?

Or without closures you can do just this in Swift 2:

let fullName = "First Last"
let fullNameArr = fullName.characters.split(" ")
let firstName = String(fullNameArr[0])

How do I (or can I) SELECT DISTINCT on multiple columns?

SELECT DISTINCT a,b,c FROM t

is roughly equivalent to:

SELECT a,b,c FROM t GROUP BY a,b,c

It's a good idea to get used to the GROUP BY syntax, as it's more powerful.

For your query, I'd do it like this:

UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
    SELECT id
    FROM sales S
    INNER JOIN
    (
        SELECT saleprice, saledate
        FROM sales
        GROUP BY saleprice, saledate
        HAVING COUNT(*) = 1 
    ) T
    ON S.saleprice=T.saleprice AND s.saledate=T.saledate
 )

assembly to compare two numbers

First a CMP (comparison) instruction is called then one of the following:

jle - jump to line if less than or equal to
jge - jump to line if greater than or equal to

The lowest assembler works with is bytes, not bits (directly anyway). If you want to know about bit logic you'll need to take a look at circuit design.

convert a list of objects from one type to another using lambda expression

var target = origList.ConvertAll(x => (TargetType)x);

How to sort in-place using the merge sort algorithm?

I just tried in place merge algorithm for merge sort in JAVA by using the insertion sort algorithm, using following steps.
1) Two sorted arrays are available.
2) Compare the first values of each array; and place the smallest value into the first array.
3) Place the larger value into the second array by using insertion sort (traverse from left to right).
4) Then again compare the second value of first array and first value of second array, and do the same. But when swapping happens there is some clue on skip comparing the further items, but just swapping required.

I have made some optimization here; to keep lesser comparisons in insertion sort.
The only drawback i found with this solutions is it needs larger swapping of array elements in the second array.

e.g)

First___Array : 3, 7, 8, 9

Second Array : 1, 2, 4, 5

Then 7, 8, 9 makes the second array to swap(move left by one) all its elements by one each time to place himself in the last.

So the assumption here is swapping items is negligible compare to comparing of two items.

https://github.com/skanagavelu/algorithams/blob/master/src/sorting/MergeSort.java

package sorting;

import java.util.Arrays;

public class MergeSort {
    public static void main(String[] args) {
    int[] array = { 5, 6, 10, 3, 9, 2, 12, 1, 8, 7 };
    mergeSort(array, 0, array.length -1);
    System.out.println(Arrays.toString(array));

    int[] array1 = {4, 7, 2};
    System.out.println(Arrays.toString(array1));
    mergeSort(array1, 0, array1.length -1);
    System.out.println(Arrays.toString(array1));
    System.out.println("\n\n");

    int[] array2 = {4, 7, 9};
    System.out.println(Arrays.toString(array2));
    mergeSort(array2, 0, array2.length -1);
    System.out.println(Arrays.toString(array2));
    System.out.println("\n\n");

    int[] array3 = {4, 7, 5};
    System.out.println(Arrays.toString(array3));
    mergeSort(array3, 0, array3.length -1);
    System.out.println(Arrays.toString(array3));
    System.out.println("\n\n");

    int[] array4 = {7, 4, 2};
    System.out.println(Arrays.toString(array4));
    mergeSort(array4, 0, array4.length -1);
    System.out.println(Arrays.toString(array4));
    System.out.println("\n\n");

    int[] array5 = {7, 4, 9};
    System.out.println(Arrays.toString(array5));
    mergeSort(array5, 0, array5.length -1);
    System.out.println(Arrays.toString(array5));
    System.out.println("\n\n");

    int[] array6 = {7, 4, 5};
    System.out.println(Arrays.toString(array6));
    mergeSort(array6, 0, array6.length -1);
    System.out.println(Arrays.toString(array6));
    System.out.println("\n\n");

    //Handling array of size two
    int[] array7 = {7, 4};
    System.out.println(Arrays.toString(array7));
    mergeSort(array7, 0, array7.length -1);
    System.out.println(Arrays.toString(array7));
    System.out.println("\n\n");

    int input1[] = {1};
    int input2[] = {4,2};
    int input3[] = {6,2,9};
    int input4[] = {6,-1,10,4,11,14,19,12,18};
    System.out.println(Arrays.toString(input1));
    mergeSort(input1, 0, input1.length-1);
    System.out.println(Arrays.toString(input1));
    System.out.println("\n\n");

    System.out.println(Arrays.toString(input2));
    mergeSort(input2, 0, input2.length-1);
    System.out.println(Arrays.toString(input2));
    System.out.println("\n\n");

    System.out.println(Arrays.toString(input3));
    mergeSort(input3, 0, input3.length-1);
    System.out.println(Arrays.toString(input3));
    System.out.println("\n\n");

    System.out.println(Arrays.toString(input4));
    mergeSort(input4, 0, input4.length-1);
    System.out.println(Arrays.toString(input4));
    System.out.println("\n\n");
}

private static void mergeSort(int[] array, int p, int r) {
    //Both below mid finding is fine.
    int mid = (r - p)/2 + p;
    int mid1 = (r + p)/2;
    if(mid != mid1) {
        System.out.println(" Mid is mismatching:" + mid + "/" + mid1+ "  for p:"+p+"  r:"+r);
    }

    if(p < r) {
        mergeSort(array, p, mid);
        mergeSort(array, mid+1, r);
//      merge(array, p, mid, r);
        inPlaceMerge(array, p, mid, r);
        }
    }

//Regular merge
private static void merge(int[] array, int p, int mid, int r) {
    int lengthOfLeftArray = mid - p + 1; // This is important to add +1.
    int lengthOfRightArray = r - mid;

    int[] left = new int[lengthOfLeftArray];
    int[] right = new int[lengthOfRightArray];

    for(int i = p, j = 0; i <= mid; ){
        left[j++] = array[i++];
    }

    for(int i = mid + 1, j = 0; i <= r; ){
        right[j++] = array[i++];
    }

    int i = 0, j = 0;
    for(; i < left.length && j < right.length; ) {
        if(left[i] < right[j]){
            array[p++] = left[i++];
        } else {
            array[p++] = right[j++];
        }
    }
    while(j < right.length){
        array[p++] = right[j++];
    } 
    while(i < left.length){
        array[p++] = left[i++];
    }
}

//InPlaceMerge no extra array
private static void inPlaceMerge(int[] array, int p, int mid, int r) {
    int secondArrayStart = mid+1;
    int prevPlaced = mid+1;
    int q = mid+1;
    while(p < mid+1 && q <= r){
        boolean swapped = false;
        if(array[p] > array[q]) {
            swap(array, p, q);
            swapped = true;
        }   
        if(q != secondArrayStart && array[p] > array[secondArrayStart]) {
            swap(array, p, secondArrayStart);
            swapped = true;
        }
        //Check swapped value is in right place of second sorted array
        if(swapped && secondArrayStart+1 <= r && array[secondArrayStart+1] < array[secondArrayStart]) {
            prevPlaced = placeInOrder(array, secondArrayStart, prevPlaced);
        }
        p++;
        if(q < r) {     //q+1 <= r) {
            q++;
        }
    }
}

private static int placeInOrder(int[] array, int secondArrayStart, int prevPlaced) {
    int i = secondArrayStart;
    for(; i < array.length; i++) {
        //Simply swap till the prevPlaced position
        if(secondArrayStart < prevPlaced) {
            swap(array, secondArrayStart, secondArrayStart+1);
            secondArrayStart++;
            continue;
        }
        if(array[i] < array[secondArrayStart]) {
            swap(array, i, secondArrayStart);
            secondArrayStart++;
        } else if(i != secondArrayStart && array[i] > array[secondArrayStart]){
            break;
        }
    }
    return secondArrayStart;
}

private static void swap(int[] array, int m, int n){
    int temp = array[m];
    array[m] = array[n];
    array[n] = temp;
}
}

Set focus to field in dynamically loaded DIV

If

$("#header").focus();

is not working then is there another element on your page with the id of header?

Use firebug to run $("#header") and see what it returns.

Formatting doubles for output in C#

Another method, starting with the method:

double i = (10 * 0.69);
Console.Write(ToStringFull(i));       // Output 6.89999999999999946709294817
Console.Write(ToStringFull(-6.9)      // Output -6.90000000000000035527136788
Console.Write(ToStringFull(i - 6.9)); // Output -0.00000000000000088817841970012523233890533

A Drop-In Function...

public static string ToStringFull(double value)
{
    if (value == 0.0) return "0.0";
    if (double.IsNaN(value)) return "NaN";
    if (double.IsNegativeInfinity(value)) return "-Inf";
    if (double.IsPositiveInfinity(value)) return "+Inf";

    long bits = BitConverter.DoubleToInt64Bits(value);
    BigInteger mantissa = (bits & 0xfffffffffffffL) | 0x10000000000000L;
    int exp = (int)((bits >> 52) & 0x7ffL) - 1023;
    string sign = (value < 0) ? "-" : "";

    if (54 > exp)
    {
        double offset = (exp / 3.321928094887362358); //...or =Math.Log10(Math.Abs(value))
        BigInteger temp = mantissa * BigInteger.Pow(10, 26 - (int)offset) >> (52 - exp);
        string numberText = temp.ToString();
        int digitsNeeded = (int)((numberText[0] - '5') / 10.0 - offset);
        if (exp < 0)
            return sign + "0." + new string('0', digitsNeeded) + numberText;
        else
            return sign + numberText.Insert(1 - digitsNeeded, ".");
    }
    return sign + (mantissa >> (52 - exp)).ToString();
}

How it works

To solve this problem I used the BigInteger tools. Large values are simple as they just require left shifting the mantissa by the exponent. For small values we cannot just directly right shift as that would lose the precision bits. We must first give it some extra size by multiplying it by a 10^n and then do the right shifts. After that, we move over the decimal n places to the left. More text/code here.

Deleting rows with MySQL LEFT JOIN

Try this:

DELETE `deadline`
FROM `deadline`
INNER JOIN `job` ON `deadline`.`job_id` = `job`.`id`
WHERE `job`.`id` = 123

error: Unable to find vcvarsall.bat

Install Visual Studio 2015 Community Edition from https://www.visualstudio.com, then

for Python 3.4

set VS100COMNTOOLS=%VS140COMNTOOLS% && pip install XX

Vuejs: v-model array in multiple input

Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
  },_x000D_
  methods: {_x000D_
    addUser: function () {_x000D_
      this.users.push({ name: '',email:'' });_x000D_
    },_x000D_
    deleteUser: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.users.splice(index, 1);_x000D_
      if(index===0)_x000D_
      this.addUser()_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Add user</h1>_x000D_
  <div v-for="(user, index) in users">_x000D_
    <input v-model="user.name">_x000D_
    <input v-model="user.email">_x000D_
    <button @click="deleteUser(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addUser">_x000D_
    New User_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check if a Bash array contains a value

This could be worth investigating if you don't want to iterate:

#!/bin/bash
myarray=("one" "two" "three");
wanted="two"
if `echo ${myarray[@]/"$wanted"/"WAS_FOUND"} | grep -q "WAS_FOUND" ` ; then
 echo "Value was found"
fi
exit

Snippet adapted from: http://www.thegeekstuff.com/2010/06/bash-array-tutorial/ I think it is pretty clever.

EDIT: You could probably just do:

if `echo ${myarray[@]} | grep -q "$wanted"` ; then
echo "Value was found"
fi

But the latter only works if the array contains unique values. Looking for 1 in "143" will give false positive, methinks.

Convert text to columns in Excel using VBA

Try this

Sub Txt2Col()
    Dim rng As Range

    Set rng = [C7]
    Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))

    rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings

Update: button click event to act on another sheet

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim sh As Worksheet

    Set sh = Worksheets("Sheet2")
    With sh
        Set rng = .[C7]
        Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))

        rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,  _
        ConsecutiveDelimiter:=False, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=True, 
        Space:=False, 
        Other:=False, _
        FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
        TrailingMinusNumbers:=True
    End With
End Sub

Note the .'s (eg .Range) they refer to the With statement object

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

Get list of data-* attributes using javascript / jQuery

Have a look here:

If the browser also supports the HTML5 JavaScript API, you should be able to get the data with:

var attributes = element.dataset

or

var cat = element.dataset.cat

Oh, but I also read:

Unfortunately, the new dataset property has not yet been implemented in any browser, so in the meantime it’s best to use getAttribute and setAttribute as demonstrated earlier.

It is from May 2010.


If you use jQuery anyway, you might want to have a look at the customdata plugin. I have no experience with it though.

Styling text input caret

'Caret' is the word you are looking for. I do believe though, that it is part of the browsers design, and not within the grasp of css.

However, here is an interesting write up on simulating a caret change using Javascript and CSS http://www.dynamicdrive.com/forums/showthread.php?t=17450 It seems a bit hacky to me, but probably the only way to accomplish the task. The main point of the article is:

We will have a plain textarea somewhere in the screen out of the view of the viewer and when the user clicks on our "fake terminal" we will focus into the textarea and when the user starts typing we will simply append the data typed into the textarea to our "terminal" and that's that.

HERE is a demo in action


2018 update

There is a new css property caret-color which applies to the caret of an input or contenteditable area. The support is growing but not 100%, and this only affects color, not width or other types of appearance.

_x000D_
_x000D_
input{_x000D_
  caret-color: rgb(0, 200, 0);_x000D_
}
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Read all worksheets in an Excel workbook into an R list with data.frames

excel.link will do the job.

I actually found it easier to use compared to XLConnect (not that either package is that difficult to use). Learning curve for both was about 5 minutes.

As an aside, you can easily find all R packages that mention the word "Excel" by browsing to http://cran.r-project.org/web/packages/available_packages_by_name.html

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

It ignores the cached content when refreshing...

https://support.google.com/a/answer/3001912?hl=en

F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content

Should each and every table have a primary key?

Except for a few very rare cases (possibly a many-to-many relationship table, or a table you temporarily use for bulk-loading huge amounts of data), I would go with the saying:

If it doesn't have a primary key, it's not a table!

Marc

In SQL, is UPDATE always faster than DELETE+INSERT?

Keep in mind the actual fragmentation that occurs when DELETE+INSERT is issued opposed to a correctly implemented UPDATE will make great difference by time.

Thats why, for instance, REPLACE INTO that MySQL implements is discouraged as opposed to using the INSERT INTO ... ON DUPLICATE KEY UPDATE ... syntax.

JQuery .hasClass for multiple values in an if statement

For fun, I wrote a little jQuery add-on method that will check for any one of multiple class names:

$.fn.hasAnyClass = function() {
    for (var i = 0; i < arguments.length; i++) {
        if (this.hasClass(arguments[i])) {
            return true;
        }
    }
    return false;
}

Then, in your example, you could use this:

if ($('html').hasAnyClass('m320', 'm768')) {

// do stuff 

}

You can pass as many class names as you want.


Here's an enhanced version that also lets you pass multiple class names separated by a space:

$.fn.hasAnyClass = function() {
    for (var i = 0; i < arguments.length; i++) {
        var classes = arguments[i].split(" ");
        for (var j = 0; j < classes.length; j++) {
            if (this.hasClass(classes[j])) {
                return true;
            }
        }
    }
    return false;
}

if ($('html').hasAnyClass('m320 m768')) {
    // do stuff 
}

Working demo: http://jsfiddle.net/jfriend00/uvtSA/

I ran into a merge conflict. How can I abort the merge?

Comments suggest that git reset --merge is an alias for git merge --abort. It is worth noticing that git merge --abort is only equivalent to git reset --merge given that a MERGE_HEAD is present. This can be read in the git help for merge command.

git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.

After a failed merge, when there is no MERGE_HEAD, the failed merge can be undone with git reset --merge, but not necessarily with git merge --abort. They are not only old and new syntax for the same thing.

Personally, I find git reset --merge much more powerful for scenarios similar to the described one, and failed merges in general.

How can I set an SQL Server connection string?

You can use either Windows authentication, if your server is in the domain, or SQL Server authentication. Sa is a system administrator, the root account for SQL Server authentication. But it is a bad practice to use if for connecting to your clients.

You should create your own accounts, and use them to connect to your SQL Server instance. In each connection you set account login, its password and the default database, you want to connect to.

Div vertical scrollbar show

Have you tried overflow-y:auto ? It is not exactly what you want, as the scrollbar will appear only when needed.

How do I drag and drop files into an application?

You need to be aware of a gotcha. Any class that you pass around as the DataObject in the drag/drop operation has to be Serializable. So if you try and pass an object, and it is not working, ensure it can be serialized as that is almost certainly the problem. This has caught me out a couple of times!

How to margin the body of the page (html)?

Yeah a CSS primer will not hurt here so you can do two things: 1 - within the tags of your html you can open a style tag like this:

<style type="text/css">
  body {
   margin: 0px;
  }
  /*
   * this is the same as writing
   * body { margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px;}
   * I'm adding px here for clarity sake but the unit is not really needed if you have 0
   * look into em, pt and % for other unit types 
   * the rules are always clockwise: top, right, bottom, left
  */
</style>

2- the above though will only work on the page you have this code embeded, so if if you wanted to reuse this in 10 files, then you will have to copy it over on all 10 files, and if you wanted to make a change let's say have a margin of 5px instead, you would have to open all those files and make the edit. That's why using an external style sheet is a golden rule in front end coding. So save the body declaration in a separate file named style.css for example and from your add this to your html instead:

<link rel="stylesheet" type="text/css" href="style.css"/>

Now you can put this in the of all pages that will benefit from these styles and whenever needed to change them you will only need to do so in one place. Hope it helps. Cheers

Excel CSV. file with more than 1,048,576 rows of data

First you want to change the file format from csv to txt. That is simple to do, just edit the file name and change csv to txt. (Windows will give you warning about possibly corrupting the data, but it is fine, just click ok). Then make a copy of the txt file so that now you have two files both with 2 millions rows of data. Then open up the first txt file and delete the second million rows and save the file. Then open the second txt file and delete the first million rows and save the file. Now change the two files back to csv the same way you changed them to txt originally.

Include php files when they are in different folders

Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.

C# - insert values from file into two arrays

string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

Git merge without auto commit

When there is one commit only in the branch, I usually do

git merge branch_name --ff

How to include external Python code to use in other files?

Just write the "include" command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

Conversion of System.Array to List

in vb.net just do this

mylist.addrange(intsArray)

or

Dim mylist As New List(Of Integer)(intsArray)

Randomize a List<T>

You can achieve that be using this simple extension method

public static class IEnumerableExtensions
{

    public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
    {
        Random r = new Random();

        return target.OrderBy(x=>(r.Next()));
    }        
}

and you can use it by doing the following

// use this on any collection that implements IEnumerable!
// List, Array, HashSet, Collection, etc

List<string> myList = new List<string> { "hello", "random", "world", "foo", "bar", "bat", "baz" };

foreach (string s in myList.Randomize())
{
    Console.WriteLine(s);
}

How do I get countifs to select all non-blank cells in Excel?

If you are using multiple criteria, and want to count the number of non-blank cells in a particular column, you probably want to look at DCOUNTA.

e.g

  A   B   C   D  E   F   G
1 Dog Cat Cow    Dog Cat
2 x   1          x   1
3 x   2 
4 x   1   nb     Result:
5 x   2   nb     1

Formula in E5: =DCOUNTA(A1:C5,"Cow",E1:F2)

WorksheetFunction.CountA - not working post upgrade to Office 2010

This code works for me:

Sub test()
    Dim myRange As Range
    Dim NumRows As Integer

    Set myRange = Range("A:A")
    NumRows = Application.WorksheetFunction.CountA(myRange)

    MsgBox NumRows
End Sub

How to keep a Python script output window open?

Start the script from already open cmd window or at the end of script add something like this, in Python 2:

 raw_input("Press enter to exit ;)")

Or, in Python 3:

input("Press enter to exit ;)")

String variable interpolation Java

Just to add that there is also java.text.MessageFormat with the benefit of having numeric argument indexes.

Appending the 1st example from the documentation

int planet = 7;
String event = "a disturbance in the Force";

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
    planet, new Date(), event);

Result:

At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.

Convert Java object to XML string

To convert an Object to XML in Java

Customer.java

package com;

import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author ABsiddik
*/

@XmlRootElement
public class Customer {

int id;
String name;
int age;

String address;
ArrayList<String> mobileNo;


 public int getId() {
    return id;
}

@XmlAttribute
public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

@XmlElement
public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

@XmlElement
public void setAge(int age) {
    this.age = age;
}

public String getAddress() {
    return address;
}

@XmlElement
public void setAddress(String address) {
    this.address = address;
}

public ArrayList<String> getMobileNo() {
    return mobileNo;
}

@XmlElement
public void setMobileNo(ArrayList<String> mobileNo) {
    this.mobileNo = mobileNo;
}


}

ConvertObjToXML.java

package com;

import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

/**
*
* @author ABsiddik
*/
public class ConvertObjToXML {

public static void main(String args[]) throws Exception
{
    ArrayList<String> numberList = new ArrayList<>();
    numberList.add("01942652579");
    numberList.add("01762752801");
    numberList.add("8800545");

    Customer c = new Customer();

    c.setId(23);
    c.setName("Abu Bakar Siddik");
    c.setAge(45);
    c.setAddress("Dhaka, Bangladesh");
    c.setMobileNo(numberList);

    File file = new File("C:\\Users\\NETIZEN-ONE\\Desktop \\customer.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(c, file);// this line create customer.xml file in specified path.

    StringWriter sw = new StringWriter();
    jaxbMarshaller.marshal(c, sw);
    String xmlString = sw.toString();

    System.out.println(xmlString);
}

}

Try with this example..

VBA check if file exists

I use this function to check for file existence:

Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it's a folder
    On Error Resume Next
    IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function

How to find largest objects in a SQL Server database?

You may also use the following code:

USE AdventureWork
GO
CREATE TABLE #GetLargest 
(
  table_name    sysname ,
  row_count     INT,
  reserved_size VARCHAR(50),
  data_size     VARCHAR(50),
  index_size    VARCHAR(50),
  unused_size   VARCHAR(50)
)

SET NOCOUNT ON

INSERT #GetLargest

EXEC sp_msforeachtable 'sp_spaceused ''?'''

SELECT 
  a.table_name,
  a.row_count,
  COUNT(*) AS col_count,
  a.data_size
  FROM #GetLargest a
     INNER JOIN information_schema.columns b
     ON a.table_name collate database_default
     = b.table_name collate database_default
       GROUP BY a.table_name, a.row_count, a.data_size
       ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESC

DROP TABLE #GetLargest

How to serialize SqlAlchemy result to JSON?

The built in serializer chokes with utf-8 cannot decode invalid start byte for some inputs. Instead, I went with:

def row_to_dict(row):
    temp = row.__dict__
    temp.pop('_sa_instance_state', None)
    return temp


def rows_to_list(rows):
    ret_rows = []
    for row in rows:
        ret_rows.append(row_to_dict(row))
    return ret_rows


@website_blueprint.route('/api/v1/some/endpoint', methods=['GET'])
def some_api():
    '''
    /some_endpoint
    '''
    rows = rows_to_list(SomeModel.query.all())
    response = app.response_class(
        response=jsonplus.dumps(rows),
        status=200,
        mimetype='application/json'
    )
    return response

How can I delete multiple lines in vi?

Sounds like you're entering the commands in command mode (aka. "Ex mode"). In that context :5d would remove line number 5, nothing else. For 5dd to work as intended -- that is, remove five consequent lines starting at the cursor -- enter it in normal mode and don't prefix the commands with :.

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

If the setTimeout function does not work for you either, then do the following:

//Create an iframe
iframe = $('body').append($('<iframe id="documentToPrint" name="documentToPrint" src="about:blank"/>'));
iframeElement = $('#documentToPrint')[0].contentWindow.document;

//Open the iframe
iframeElement.open();

//Write your content to the iframe
iframeElement.write($("yourContentId").html());

//This is the important bit.
//Wait for the iframe window to load, then print it.
$('#documentToPrint')[0].contentWindow.onload = function () {
    $('#print-document')[0].contentWindow.print();
    $('#print-document').remove();
};
iframeElement.close();

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

iOS: How to store username/password within an app?

There is a small bug in the above code (by the way Dave it was very helpful your post thank you)

In the part where we save the credentials it also needs the following code in order to work properly.

[self.keychainItem setObject:@"myCredentials" forKey:(__bridge id)(kSecAttrService)];

most probably is because the second time we try to (re-)sign in with the same credentials it finds them already assigned in the keychain items and the app crashes. with the above code it works like a charm.

Why emulator is very slow in Android Studio?

Google Launches Android Studio 2.0 With Improved Android Emulator And New Instant Run Feature

New Features in Android Studio 2.0 :

1.Instant Run: Faster Build & Deploy

You can quickly see your changes running on your device or emulator.
Enable Instant Run follow this steps:

1.open Settings/Preferences
2.go to Build, Execution, Deployment
3.Instant Run. Click on Enable Instant

Please see this video of Instant Run --> Instant Run

2.GPU Profiler

For developers who build graphics-intensive apps and games, the Studio now also includes a new GPU profiler. This will allow developers to see exactly what’s happening every time the screen draws a new image to trace performance issues.

click here for more details about the GPU Profiler tool

Getting Started Guide for Android Emulator Preview

For more detail about android 2.0 Biggest and best update of 2015 you can see very good article Author by @nuuneoi :

First Look at Android Emulator 2.0, the biggest and the best update yet in years

Ignore .classpath and .project from Git

Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore

Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore

Best Practices for Custom Helpers in Laravel 5

in dir bootstrap\autoload.php

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add

add this file

app\Helpers\function.php

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

React-Router open Link in new tab

To open an url in a new tab, you can use the Link tag as below:

<Link to="/yourRoute" target="_blank">
    Open YourRoute in a new tab
</Link>

It's nice to keep in mind that the <Link> element gets translated to an <a> element, and as per react-router-dom docs, you can pass any props you'd like to be on it such as title, id, className, etc.

Better way to represent array in java properties file

Use YAML files for properties, this supports properties as an array.

Quick glance about YAML:

A superset of JSON, it can do everything JSON can + more

  1. Simple to read
  2. Long properties into multiline values
  3. Supports comments
  4. Properties as Array
  5. YAML Validation

What does $_ mean in PowerShell?

$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3.0; Usage information found here) which represents the current item from the pipe.

PowerShell (v6.0) online documentation for automatic variables is here.

How to keep Docker container running after starting services?

If you are using a Dockerfile, try:

ENTRYPOINT ["tail", "-f", "/dev/null"]

(Obviously this is for dev purposes only, you shouldn't need to keep a container alive unless it's running a process eg. nginx...)

TypeError : Unhashable type

A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.

A list doesn't use a hash for indexing, so it isn't restricted to hashable items.

Redirect after Login on WordPress

// add the code to your theme function.php
//for logout redirection
add_action('wp_logout','auto_redirect_after_logout');
function auto_redirect_after_logout(){
wp_redirect( home_url() );
exit();
}
//for login redirection
add_action('wp_login','auto_redirect_after_login');
function auto_redirect_after_login(){
wp_redirect( home_url() );
exit();
`enter code here`}

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

Difference between add(), replace(), and addToBackStack()

Here is a picture that shows the difference between add() and replace()

enter image description here

So add() method keeps on adding fragments on top of the previous fragment in FragmentContainer.

While replace() methods clears all the previous Fragment from Containers and then add it in FragmentContainer.

What is addToBackStack

addtoBackStack method can be used with add() and replace methods. It serves a different purpose in Fragment API.

What is the purpose?

Fragment API unlike Activity API does not come with Back Button navigation by default. If you want to go back to the previous Fragment then the we use addToBackStack() method in Fragment. Let's understand both

Case 1:

getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.fragmentContainer, fragment, "TAG")
            .addToBackStack("TAG")
            .commit();

enter image description here

Case 2:

getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.fragmentContainer, fragment, "TAG")
            .commit();

enter image description here

What is the meaning of <> in mysql query?

<> is equal to != i.e, both are used to represent the NOT EQUAL operation. For instance, email <> '' and email != '' are same.

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

Simply put, you need to rewrite all of your database connections and queries.

You are using mysql_* functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.

A basic example of using PDO (without error handling):

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>

A basic example of using MySQLi (without error handling):

$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");

Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

How to use systemctl in Ubuntu 14.04

So you want to remove dangling images? Am I correct?

systemctl enable docker-container-cleanup.timer
systemctl start docker-container-cleanup.timer
systemctl enable docker-image-cleanup.timer 
systemctl start docker-image-cleanup.timer

https://github.com/larsks/docker-tools/tree/master/docker-maintenance-units

How to return the output of stored procedure into a variable in sql server

Use this code, Working properly

CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT

AS
Begin
 DECLARE @cnt int;
 DECLARE @status int =0;
 SET NOCOUNT OFF
 SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
 if(@cnt = 1)
   Begin
     return @status;
   End
 else
  Begin
   SET @status =1;
    return @status;
 End
END

Execute SP

DECLARE @statuss bit;
EXECUTE  [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;

How do I make a textbox that only accepts numbers?

you could use TextChanged/ Keypress event, use a regex to filter on numbers and take some action.

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

iOS: UIButton resize according to text length

To accomplish this using autolayout, try setting a variable width constraint:

Width Constraint

You may also need to adjust your Content Hugging Priority and Content Compression Resistance Priority to get the results you need.


UILabel is completely automatically self-sizing:

This UILabel is simply set to be centered on the screen (two constraints only, horizontal/vertical):

It changes widths totally automatically:

You do not need to set any width or height - it's totally automatic.

enter image description here

enter image description here

Notice the small yellow squares are simply attached ("spacing" of zero). They automatically move as the UILabel resizes.

Adding a ">=" constraint sets a minimum width for the UILabel:

enter image description here

StringStream in C#

Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter parameter?

The library provides a StringWriter: TextWriter but not a StringStream. I suppose you could create one by wrapping a MemoryStream, but is it really necessary?


After the Update:

void Main() 
{
  string myString;  // outside using

  using (MemoryStream stream = new MemoryStream ())
  {
     Print(stream);
     myString = Encoding.UTF8.GetString(stream.ToArray());
  }
  ... 

}

You may want to change UTF8 to ASCII, depending on the encoding used by Print().

PHP: HTTP or HTTPS?

You should be able to do this by checking the value of $_SERVER['HTTPS'] (it should only be set when using https).

See http://php.net/manual/en/reserved.variables.server.php.

Best way to stress test a website

For web service testing, soap rest or WCF (including WebHttpBinding), try out SOA Cleaner. Can be downloded from:http://xyrow.com. There is a free version, and it doesn't require any installation. It can also perform load tests.

How to change an Android app's name?

Old question but also now relative to Xamarin Android development:

As Xamarin allows for attributes to be used for adding items into the manifest, you may need to open your MainActivity.cs file and change the Label tag to your application's name:

MainActivity

Note: This attribute will override written android:label= tags in your manifest file as I found out whilst archiving the app ready for release so be sure to change this attribute too.

jQuery: how to trigger anchor link's click event

 window.open($('#myanchor').attr('href'));

               $('#myanchor')[0].click();

Javascript loop through object array?

for (let key in data) {
    let value = data[key];
    for (i = 0; i < value.length; i++) {
      console.log(value[i].msgFrom);
      console.log(value[i].msgBody);
    }
  }

Stopping a JavaScript function when a certain condition is met

use return for this

if(i==1) { 
    return; //stop the execution of function
}

//keep on going

Change Spinner dropdown icon

For this you can use .9 Patch Image and just simply set it in to background.

android:background="@drawable/spin"

Here i'll give you .9patch image. try with this.

enter image description here enter image description here

Right click on image and click Save Image as

set image name like this : anyname.9.png and hit save.

Enjoy.. Happy Coading. :)

How to use log levels in java

the different log levels are helpful for tools, whose can anaylse you log files. Normally a logfile contains lots of information. To avoid an information overload (or here an stackoverflow^^) you can use the log levels for grouping the information.

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

How can I write text on a HTML5 canvas element?

_x000D_
_x000D_
var canvas = document.getElementById("my-canvas");_x000D_
var context = canvas.getContext("2d");_x000D_
_x000D_
context.fillStyle = "blue";_x000D_
context.font = "bold 16px Arial";_x000D_
context.fillText("Zibri", (canvas.width / 2) - 17, (canvas.height / 2) + 8);
_x000D_
#my-canvas {_x000D_
  background: #FF0;_x000D_
}
_x000D_
<canvas id="my-canvas" width="200" height="120"></canvas>
_x000D_
_x000D_
_x000D_

SQL Server - How to lock a table until a stored procedure finishes

Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

If you want an empty string default then a preferred way is one of these (depending on your need):

$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);

If the url parameter something doesn't exist in the url then $_GET['something'] will return null

strval($_GET['something']) -> strval(null) -> ""

and your variable $value is set to an empty string.

  • trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
  • intval() if only numeric values are expected and the default is zero. intval(null) -> 0

Cases to consider:

...&something=value1&key2=value2 (typical)

...&key2=value2 (parameter missing from url $_GET will return null for it)

...&something=+++&key2=value (parameter is " ")

Why this is a preferred approach:

  • It fits neatly on one line and is clear what's going on.
  • It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
  • Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
  • It's compatible with older and newer php.

Update Strict mode may require something like this:

$str_value = strval(@$_GET['something']);
$trimmed_value = trim(@$_GET['something']);
$int_value = intval(@$_GET['somenumber']);

How to test an Internet connection with bash?

shortest way: fping 4.2.2.1 => "4.2.2.1 is alive"

i prefer this as it's faster and less verbose output than ping, downside is you will have to install it.

you can use any public dns rather than a specific website.

fping -q google.com && echo "do something because you're connected!"

-q returns an exit code, so i'm just showing an example of running something you're online.

to install on mac: brew install fping; on ubuntu: sudo apt-get install fping

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

Add context path to Spring Boot application

We can set it using WebServerFactoryCustomizer. This can be added directly in the spring boot main method class which starts up the Spring ApplicationContext.

@Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
      webServerFactoryCustomizer() {
        return factory -> factory.setContextPath("/demo");
}

Split string in Lua?

A lot of these answers only accept single-character separators, or don't deal with edge cases well (e.g. empty separators), so I thought I would provide a more definitive solution.

Here are two functions, gsplit and split, adapted from the code in the Scribunto MediaWiki extension, which is used on wikis like Wikipedia. The code is licenced under the GPL v2. I have changed the variable names and added comments to make the code a bit easier to understand, and I have also changed the code to use regular Lua string patterns instead of Scribunto's patterns for Unicode strings. The original code has test cases here.

-- gsplit: iterate over substrings in a string separated by a pattern
-- 
-- Parameters:
-- text (string)    - the string to iterate over
-- pattern (string) - the separator pattern
-- plain (boolean)  - if true (or truthy), pattern is interpreted as a plain
--                    string, not a Lua pattern
-- 
-- Returns: iterator
--
-- Usage:
-- for substr in gsplit(text, pattern, plain) do
--   doSomething(substr)
-- end
local function gsplit(text, pattern, plain)
  local splitStart, length = 1, #text
  return function ()
    if splitStart then
      local sepStart, sepEnd = string.find(text, pattern, splitStart, plain)
      local ret
      if not sepStart then
        ret = string.sub(text, splitStart)
        splitStart = nil
      elseif sepEnd < sepStart then
        -- Empty separator!
        ret = string.sub(text, splitStart, sepStart)
        if sepStart < length then
          splitStart = sepStart + 1
        else
          splitStart = nil
        end
      else
        ret = sepStart > splitStart and string.sub(text, splitStart, sepStart - 1) or ''
        splitStart = sepEnd + 1
      end
      return ret
    end
  end
end

-- split: split a string into substrings separated by a pattern.
-- 
-- Parameters:
-- text (string)    - the string to iterate over
-- pattern (string) - the separator pattern
-- plain (boolean)  - if true (or truthy), pattern is interpreted as a plain
--                    string, not a Lua pattern
-- 
-- Returns: table (a sequence table containing the substrings)
local function split(text, pattern, plain)
  local ret = {}
  for match in gsplit(text, pattern, plain) do
    table.insert(ret, match)
  end
  return ret
end

Some examples of the split function in use:

local function printSequence(t)
  print(unpack(t))
end

printSequence(split('foo, bar,baz', ',%s*'))       -- foo     bar     baz
printSequence(split('foo, bar,baz', ',%s*', true)) -- foo, bar,baz
printSequence(split('foo', ''))                    -- f       o       o

how to reset <input type = "file">

The reseting input file is on very single

$('input[type=file]').val(null);

If you bind reset the file in change other field of the form, or load form with ajax.

This example is applicable

selector for example is $('input[type=text]') or any element of the form

event click, change, or any event

$('body').delegate('event', 'selector', function(){
     $('input[type=file]').val(null) ;
});

How to use onBlur event on Angular2?

HTML

<input name="email" placeholder="Email"  (blur)="$event.target.value=removeSpaces($event.target.value)" value="">

TS

removeSpaces(string) {
 let splitStr = string.split(' ').join('');
  return splitStr;
}

Fill remaining vertical space - only CSS

All you need is a bit of improved markup. Wrap the second within the first and it will render under.

<div id="wrapper">
    <div id="first">
        Here comes the first content
        <div id="second">I will render below the first content</div>
    </div>
</div>

Demo

How to disassemble a memory range with GDB?

This isn't the direct answer to your question, but since you seem to just want to disassemble the binary, perhaps you could just use objdump:

objdump -d program

This should give you its dissassembly. You can add -S if you want it source-annotated.

Execute a PHP script from another PHP script

You can invoke a PHP script manually from the command line

hello.php
<?php
 echo 'hello world!';
?>

Command line:
php hello.php

Output:
hello world!

See the documentation: http://php.net/manual/en/features.commandline.php


EDIT OP edited the question to add a critical detail: the script is to be executed by another script.

There are a couple of approaches. First and easiest, you could simply include the file. When you include a file, the code within is "executed" (actually, interpreted). Any code that is not within a function or class body will be processed immediately. Take a look at the documentation for include (docs) and/or require (docs) (note: include_once and require_once are related, but different in an important way. Check out the documents to understand the difference) Your code would look like this:

 include('hello.php');
 /* output
 hello world!
 */

Second and slightly more complex is to use shell_exec (docs). With shell_exec, you will call the php binary and pass the desired script as the argument. Your code would look like this:

$output = shell_exec('php hello.php');
echo "<pre>$output</pre>";
/* output
hello world!
*/

Finally, and most complex, you could use the CURL library to call the file as though it were requested via a browser. Check out the CURL library documentation here: http://us2.php.net/manual/en/ref.curl.php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myDomain.com/hello.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)

$output = curl_exec($ch);
curl_close($ch);
echo "<pre>$output</pre>";
/* output
hello world!
*/

Documentation for functions used

Convert Mat to Array/Vector in OpenCV

byte * matToBytes(Mat image)
{
   int size = image.total() * image.elemSize();
   byte * bytes = new byte[size];  //delete[] later
   std::memcpy(bytes,image.data,size * sizeof(byte));
}

python catch exception and continue try block

one way you could handle this is with a generator. Instead of calling the function, yield it; then whatever is consuming the generator can send the result of calling it back into the generator, or a sentinel if the generator failed: The trampoline that accomplishes the above might look like so:

def consume_exceptions(gen):
    action = next(gen)
    while True:
        try:
            result = action()
        except Exception:
            # if the action fails, send a sentinel
            result = None

        try:
            action = gen.send(result)
        except StopIteration:
            # if the generator is all used up, result is the return value.
            return result

a generator that would be compatible with this would look like this:

def do_smth1():
    1 / 0

def do_smth2():
    print "YAY"

def do_many_things():
    a = yield do_smth1
    b = yield do_smth2
    yield "Done"
>>> consume_exceptions(do_many_things())
YAY

Note that do_many_things() does not call do_smth*, it just yields them, and consume_exceptions calls them on its behalf

Find package name for Android apps to use Intent to launch Market app from web

This is quite a difficult situation, you can get the package name from the apk file, but i assume you want to do it automatically.

AndroLib has the package names for lots of apps but you would have to parse it as there is no API that i could find. Theres a dev section that may have some tools to help you.

Good Luck

All ASP.NET Web API controllers return 404

I have dozens of installations of my app with different clients which all worked fine and then this one just always returned 404 on all api calls. It turns out that when I created the application pool in IIS for this client it defaulted to .net framework 2.0 instead of 4.0 and I missed it. This caused the 404 error. Seems to me this should have been a 500 error. Very misleading Microsoft!

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.

  1. Remove the update on your component that is not working
  2. Put a temporary component with a bogus update within the component you were trying to update
  3. hit the page, the servlet exception error will tell you the correct client Id you need to reference.
  4. Remove bogus component and put correct clientId in the original update

Here is code example as my words may not describe it best.

<p:tabView id="tabs">
    <p:tab id="search" title="Search">                        
        <h:form id="insTable">
            <p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
                <p:column>
                    <p:commandLink id="select"

Remove the failing update within this component

 oncomplete="dlg.show()">
                        <f:setPropertyActionListener value="#{lndInstrument}" 
                                        target="#{instrumentBean.selectedInstrument}" />
                        <h:outputText value="#{lndInstrument.name}" />
                    </p:commandLink>                                    
                </p:column>
            </p:dataTable>
            <p:dialog id="dlg" modal="true" widgetVar="dlg">
                <h:panelGrid id="display">

Add a component within the component of the id you are trying to update using an update that will fail

   <p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>

                    <h:outputText value="Name:" />
                    <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
                </h:panelGrid>
            </p:dialog>                            
        </h:form>
    </p:tab>
</p:tabView>

Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton

So the correct clientId to use would then be the bold plus the id of the target container (display in this case)

tabs:insTable:display

Extract subset of key-value pairs from Python dictionary object?

A bit of speed comparison for all mentioned methods:

UPDATED on 2020.07.13 (thx to @user3780389): ONLY for keys from bigdict.

 IPython 5.5.0 -- An enhanced Interactive Python.
Python 2.7.18 (default, Aug  8 2019, 00:00:00) 
[GCC 7.3.1 20180303 (Red Hat 7.3.1-5)] on linux2
import numpy.random as nprnd
  ...: keys = nprnd.randint(100000, size=10000)
  ...: bigdict = dict([(_, nprnd.rand()) for _ in range(100000)])
  ...: 
  ...: %timeit {key:bigdict[key] for key in keys}
  ...: %timeit dict((key, bigdict[key]) for key in keys)
  ...: %timeit dict(map(lambda k: (k, bigdict[k]), keys))
  ...: %timeit {key:bigdict[key] for key in set(keys) & set(bigdict.keys())}
  ...: %timeit dict(filter(lambda i:i[0] in keys, bigdict.items()))
  ...: %timeit {key:value for key, value in bigdict.items() if key in keys}
100 loops, best of 3: 2.36 ms per loop
100 loops, best of 3: 2.87 ms per loop
100 loops, best of 3: 3.65 ms per loop
100 loops, best of 3: 7.14 ms per loop
1 loop, best of 3: 577 ms per loop
1 loop, best of 3: 563 ms per loop

As it was expected: dictionary comprehensions are the best option.

Difference between acceptance test and functional test?

In my world, we use the terms as follows:

functional testing: This is a verification activity; did we build a correctly working product? Does the software meet the business requirements?

For this type of testing we have test cases that cover all the possible scenarios we can think of, even if that scenario is unlikely to exist "in the real world". When doing this type of testing, we aim for maximum code coverage. We use any test environment we can grab at the time, it doesn't have to be "production" caliber, so long as it's usable.

acceptance testing: This is a validation activity; did we build the right thing? Is this what the customer really needs?

This is usually done in cooperation with the customer, or by an internal customer proxy (product owner). For this type of testing we use test cases that cover the typical scenarios under which we expect the software to be used. This test must be conducted in a "production-like" environment, on hardware that is the same as, or close to, what a customer will use. This is when we test our "ilities":

  • Reliability, Availability: Validated via a stress test.

  • Scalability: Validated via a load test.

  • Usability: Validated via an inspection and demonstration to the customer. Is the UI configured to their liking? Did we put the customer branding in all the right places? Do we have all the fields/screens they asked for?

  • Security (aka, Securability, just to fit in): Validated via demonstration. Sometimes a customer will hire an outside firm to do a security audit and/or intrusion testing.

  • Maintainability: Validated via demonstration of how we will deliver software updates/patches.

  • Configurability: Validated via demonstration of how the customer can modify the system to suit their needs.

This is by no means standard, and I don't think there is a "standard" definition, as the conflicting answers here demonstrate. The most important thing for your organization is that you define these terms precisely, and stick to them.

How do I change the hover over color for a hover over table in Bootstrap?

.table-hover tbody tr:hover td {
    background: #ffffff;
}

How to create a numpy array of arbitrary length strings?

You can do so by creating an array of dtype=object. If you try to assign a long string to a normal numpy array, it truncates the string:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'], 
      dtype='|S6')

But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)

Indeed, because it's an array of objects, you can assign any kind of python object to the array:

>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)

However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:

>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop

Kubernetes service external ip pending

If it is your private k8s cluster, MetalLB would be a better fit. Below are the steps.

Step 1: Install MetalLB in your cluster

kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.3/manifests/namespace.yaml
kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.3/manifests/metallb.yaml
# On first install only
kubectl create secret generic -n metallb-system memberlist --from-literal=secretkey="$(openssl rand -base64 128)"

Step 2: Configure it by using a configmap

apiVersion: v1
kind: ConfigMap
metadata:
  namespace: metallb-system
  name: config
data:
  config: |
    address-pools:
    - name: default
      protocol: layer2
      addresses:
      - 172.42.42.100-172.42.42.105 #Update this with your Nodes IP range 

Step 3: Create your service to get an external IP (would be a private IP though).

FYR:

Before MetalLB installation: enter image description here

After MetalLB installation: enter image description here

enter image description here

Xcode process launch failed: Security

"If you get this, the app has installed on your device. You have to tap the icon. It will ask you if you really want to run it. Say “yes” and then Build & Run again."

To add to that, this only holds true the moment you get the error, if you click OK, then tap on the app. It will do nothing. Scratched my head on that for 30 odd minutes, searching for alternative ways to address the problem.

Executing <script> elements inserted with .innerHTML

Just do:

document.body.innerHTML = document.body.innerHTML + '<img src="../images/loaded.gif" alt="" onload="alert(\'test\');this.parentNode.removeChild(this);" />';

How to disable/enable select field using jQuery?

Your select doesn't have an ID, only a name. You'll need to modify your selector:

$("#pizza").on("click", function(){
  $("select[name='pizza_kind']").prop("disabled", !this.checked);
});

Demo: http://jsbin.com/imokuj/2/edit

Hide/encrypt password in bash file to stop accidentally seeing it

There's a more convenient way to store passwords in a script but you will have to encrypt and obfuscate the script so that it cannot be read. In order to successfully encrypt and obfuscate a shell script and actually have that script be executable, try copying and pasting it here:

http://www.kinglazy.com/shell-script-encryption-kinglazy-shieldx.htm

On the above page, all you have to do is submit your script and give the script a proper name, then hit the download button. A zip file will be generated for you. Right click on the download link and copy the URL you're provided. Then, go to your UNIX box and perform the following steps.

Installation:

1. wget link-to-the-zip-file
2. unzip the-newly-downloaded-zip-file
3. cd /tmp/KingLazySHIELD
4. ./install.sh /var/tmp/KINGLAZY/SHIELDX-(your-script-name) /home/(your-username) -force

What the above install command will do for you is:

  1. Install the encrypted version of your script in the directory /var/tmp/KINGLAZY/SHIELDX-(your-script-name).
  2. It'll place a link to this encrypted script in whichever directory you specify in replacement of /home/(your-username) - that way, it allows you to easily access the script without having to type the absolute path.
  3. Ensures NO ONE can modify the script - Any attempts to modify the encrypted script will render it inoperable...until those attempts are stopped or removed. It can even be configured to notify you whenever someone tries to do anything with the script other than run it...i.e. hacking or modification attempts.
  4. Ensures absolutely NO ONE can make copies of it. No one can copy your script to a secluded location and try to screw around with it to see how it works. All copies of the script must be links to the original location which you specified during install (step 4).

NOTE:

This does not work for interactive scripts that prompts and waits on the user for a response. The values that are expected from the user should be hard-coded into the script. The encryption ensures no one can actually see those values so you need not worry about that.

RELATION:

The solution provided in this post answers your problem in the sense that it encrypts the actual script containing the password that you wanted to have encrypted. You get to leave the password as is (unencrypted) but the script that the password is in is so deeply obfuscated and encrypted that you can rest assured no one will be able to see it. And if attempts are made to try to pry into the script, you will receive email notifications about them.

String Comparison in Java

Below Algo "compare two strings lexicographically"

  1. Input two strings string 1 and string 2.

  2. for (int i = 0; i < str1.length() && i < str2.length(); i ++)

    (Loop through each character of both strings comparing them until one of the string terminates):

    a. If unicode value of both the characters is same then continue;

    b. If unicode value of character of string 1 and unicode value of string 2 is different then return (str1[i]-str2[i])

  3. if length of string 1 is less than string2

    return str2[str1.length()]

    else

    return str1[str2.length()]

    // This method compares two strings lexicographically

    public static int compareCustom(String s1, String s2) {
        for (int i = 0; i < s1.length() && i< s2.length(); i++) {
            if(s1.charAt(i) == s2.charAt(i)){
                //System.out.println("Equal");
                continue;
            }
            else{
                return s1.charAt(i) - s2.charAt(i);
            }   
        }
        if(s1.length()<s2.length()){
            return s2.length() - s1.length();
        }
        else if(s1.length()>s2.length()){
            return s1.length()-s2.length();
        }
        else{
            return 0;
        }
    }
    

if two String are equal it will return 0 otherwise return Negative or positive value

Source : - Source

sorting and paging with gridview asp.net

More simple way...:

    Dim dt As DataTable = DirectCast(GridView1.DataSource, DataTable)
    Dim dv As New DataView(dt)

    If GridView1.Attributes("dir") = SortDirection.Ascending Then
        dv.Sort = e.SortExpression & " DESC" 
        GridView1.Attributes("dir") = SortDirection.Descending

    Else
        GridView1.Attributes("dir") = SortDirection.Ascending
        dv.Sort = e.SortExpression & " ASC"

    End If

    GridView1.DataSource = dv
    GridView1.DataBind()

How do you format code in Visual Studio Code (VSCode)

The code formatting is available in Visual Studio Code through the following shortcuts:

  • On Windows Shift + Alt + F
  • On Mac Shift + Option + F
  • On Linux Ctrl + Shift + I

Alternatively, you can find the shortcut, as well as other shortcuts, through the 'Command Palette' provided in the editor with Ctrl +Shift+ P (or Command + Shift + P on Mac), and then searching for format document.

For unsaved snippets

  1. Open command palette (Win: F1 or Ctrt+Shift+P)

  2. Find 'Change Language Model'

  3. Select language e.g. json. By now syntax should be highlighted.

  4. Format document (e.g. Open Command Palette -> 'Format Document')

Unformat

  1. Select text
  2. Command Palette -> Join Lines

'Show the pics'

enter image description here enter image description here

How to disable EditText in Android

The below code disables the EditText in android

editText.setEnabled(false);

How do I pause my shell script for a second before continuing?

read -r -p "Wait 5 seconds or press any key to continue immediately" -t 5 -n 1 -s

To continue when you press any one button

for more info check read manpage ref 1, ref 2

In CSS what is the difference between "." and "#" when declaring a set of styles?

.class targets the following element:

<div class="class"></div>

#class targets the following element:

<div id="class"></div>

Note that the id MUST be unique throughout the document, whilst any number of elements may share a class.

Select rows with same id but different value in another column

This is an old question yet I find that I also need a solution for this from time to time. The previous answers are all good and works well, I just personally prefer using CTE, for example:

DECLARE @T TABLE (ARIDNR INT, LIEFNR varchar(5)) --table variable for loading sample data
INSERT INTO @T (ARIDNR, LIEFNR) VALUES (1,'A'),(2,'A'),(3,'A'),(1,'B'),(2,'B'); --add your sample data to it
WITH duplicates AS --the CTE portion to find the duplicates
(
    SELECT ARIDNR FROM @T GROUP BY ARIDNR HAVING COUNT(*) > 1
)
SELECT t.* FROM @T t --shows results from main table
INNER JOIN duplicates d on t.ARIDNR = d.ARIDNR --where the main table can be joined to the duplicates CTE

Yields the following results:

1|A
1|B
2|B
2|A

Proper way to assert type of variable in Python

You might want to try this example for version 2.6 of Python.

def my_print(text, begin, end):
    "Print text in UPPER between 'begin' and 'end' in lower."
    for obj in (text, begin, end):
        assert isinstance(obj, str), 'Argument of wrong type!'
    print begin.lower() + text.upper() + end.lower()

However, have you considered letting the function fail naturally instead?

Pretty printing XML in Python

As of Python 3.9 (still a release candidate as of 12 Aug 2020), there is a new xml.etree.ElementTree.indent() function for pretty-printing XML trees.

Sample usage:

import xml.etree.ElementTree as ET

element = ET.XML("<html><body>text</body></html>")
ET.indent(element)
print(ET.tostring(element, encoding='unicode'))

The upside is that it does not require any additional libraries. For more information check https://bugs.python.org/issue14465 and https://github.com/python/cpython/pull/15200

Unstaged changes left after git reset --hard

Another cause for this might be case-insensitive file systems. If you have multiple folders in your repo on the same level whose names only differ by case, you will get hit by this. Browse the source repository using its web interface (e.g. GitHub or VSTS) to make sure.

For more information: https://stackoverflow.com/a/2016426/67824

How can I get current location from user in iOS

iOS 11.x Swift 4.0 Info.plist needs these two properties

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We're watching you</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Watch Out</string>

And this code ... making sure of course your a CLLocationManagerDelegate

let locationManager = CLLocationManager()

// MARK location Manager delegate code + more

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .notDetermined:
        print("User still thinking")
    case .denied:
        print("User hates you")
    case .authorizedWhenInUse:
            locationManager.stopUpdatingLocation()
    case .authorizedAlways:
            locationManager.startUpdatingLocation()
    case .restricted:
        print("User dislikes you")
    }

And of course this code too which you can put in viewDidLoad().

locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestLocation()

And these two for the requestLocation to get you going, aka save you having to get out of your seat :)

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print(locations)
}

onKeyDown event not working on divs in React

You're missing the binding of the method in the constructor. This is how React suggests that you do it:

class Whatever {
  constructor() {
    super();
    this.onKeyPressed = this.onKeyPressed.bind(this);
  }

  onKeyPressed(e) {
    // your code ...
  }

  render() {
    return (<div onKeyDown={this.onKeyPressed} />);
  }
}

There are other ways of doing this, but this will be the most efficient at runtime.

Reading output of a command into an array in Bash

The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *, ?, [...].

To get the output of a command in an array, with one line per element, there are essentially 3 ways:

  1. With Bash=4 use mapfile—it's the most efficient:

    mapfile -t my_array < <( my_command )
    
  2. Otherwise, a loop reading the output (slower, but safe):

    my_array=()
    while IFS= read -r line; do
        my_array+=( "$line" )
    done < <( my_command )
    
  3. As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:

    IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
    

    Please make sure you use exactly this form, i.e., make sure you have the following:

    • IFS=$'\n' on the same line as the read statement: this will only set the environment variable IFS for the read statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read to break the stream at the EOL character \n.
    • -r: this is important. It tells read to not interpret the backslashes as escape sequences.
    • -d '': please note the space between the -d option and its argument ''. If you don't leave a space here, the '' will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read to stop reading at the nil byte. Some people write it as -d $'\0', but it is not really necessary. -d '' is better.
    • -a my_array tells read to populate the array my_array while reading the stream.
    • You must use the printf '\0' statement after my_command, so that read returns 0; it's actually not a big deal if you don't (you'll just get an return code 1, which is okay if you don't use set -e – which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf '', which doesn't output anything. printf '\0' prints a null byte, needed by read to happily stop reading there (remember the -d '' option?).

If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.

If you want to use read, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]} in the example I gave).

Note that mapfile provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile and the options -C and -c therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).


Now I'm going to tell you why the following method:

my_array=( $( my_command) )

is broken when there are spaces:

$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!

Then some people will then recommend using IFS=$'\n' to fix it:

$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!

But now let's use another command, with globs:

$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?

That's because I have a file called t in the current directory… and this filename is matched by the glob [three four]… at this point some people would recommend using set -f to disable globbing: but look at it: you have to change IFS and use set -f to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.

$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'

here we're working with the shell!

Visual Studio Community 2015 expiration date

You can use "RunasDate" to solve this.

PHP - iterate on string characters

// Unicode Codepoint Escape Syntax in PHP 7.0
$str = "cat!\u{1F431}";

// IIFE (Immediately Invoked Function Expression) in PHP 7.0
$gen = (function(string $str) {
    for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) {
        yield mb_substr($str, $i, 1);
    }
})($str);

var_dump(
    true === $gen instanceof Traversable,
    // PHP 7.1
    true === is_iterable($gen)
);

foreach ($gen as $char) {
    echo $char, PHP_EOL;
}

SQL Server error on update command - "A severe error occurred on the current command"

A different scenario but the same error: I got this error when I was trying to insert records into a temporary table using a stored procedure. It turned out there was a parameter mismatch. I was trying to insert a BIGINT into an INT.

Credit goes to Vicky Harp: http://vickyharp.com/2012/03/troubleshooting-a-severe-error-occurred-on-the-current-command/

The mysqli extension is missing. Please check your PHP configuration

I simply copied my php_myslqli.dll file from ert folder back to php folder, and it worked for me after restarting my Apache and MySQL from the control Panel

How do I select last 5 rows in a table without sorting?

Well, the "last five rows" are actually the last five rows depending on your clustered index. Your clustered index, by definition, is the way that he rows are ordered. So you really can't get the "last five rows" without some order. You can, however, get the last five rows as it pertains to the clustered index.

SELECT TOP 5 * FROM MyTable
ORDER BY MyCLusteredIndexColumn1, MyCLusteredIndexColumnq, ..., MyCLusteredIndexColumnN DESC

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

Its should work for all version of eclipse even in Spring tool suit(STS). Here is the steps

Go to the URl Follow The link to download or click the bellow link to direct download Click Here to download

Download JD-Eclipse. Download and unzip the JD-Eclipse Update Site,

Launch Eclipse,

Click on "Help > Install New Software...",

Click on button "Add..." to add an new repository,

Enter "JD-Eclipse Update Site" and select the local site directory,

enter image description here

Select extracted folder and give any name. I have given JDA. and click ok.

enter image description here

Check "Java Decompiler Eclipse Plug-in",

enter image description here

Next, next, next... and restart Eclipse.