Programs & Examples On #Snoop

Snoop is the open source WPF spying utility. It allows you to spy/browse the visual tree of a running WPF application (without the need for a debugger) … and change properties ... amongst other things.

How do I use the new computeIfAbsent function?

Suppose you have the following code:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Test {
    public static void main(String[] s) {
        Map<String, Boolean> whoLetDogsOut = new ConcurrentHashMap<>();
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
    }
    static boolean f(String s) {
        System.out.println("creating a value for \""+s+'"');
        return s.isEmpty();
    }
}

Then you will see the message creating a value for "snoop" exactly once as on the second invocation of computeIfAbsent there is already a value for that key. The k in the lambda expression k -> f(k) is just a placeolder (parameter) for the key which the map will pass to your lambda for computing the value. So in the example the key is passed to the function invocation.

Alternatively you could write: whoLetDogsOut.computeIfAbsent("snoop", k -> k.isEmpty()); to achieve the same result without a helper method (but you won’t see the debugging output then). And even simpler, as it is a simple delegation to an existing method you could write: whoLetDogsOut.computeIfAbsent("snoop", String::isEmpty); This delegation does not need any parameters to be written.

To be closer to the example in your question, you could write it as whoLetDogsOut.computeIfAbsent("snoop", key -> tryToLetOut(key)); (it doesn’t matter whether you name the parameter k or key). Or write it as whoLetDogsOut.computeIfAbsent("snoop", MyClass::tryToLetOut); if tryToLetOut is static or whoLetDogsOut.computeIfAbsent("snoop", this::tryToLetOut); if tryToLetOut is an instance method.

WPF Binding to parent DataContext

I dont know about XamGrid but that's what i'll do with a standard wpf DataGrid:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Since the TextBlock and the TextBox specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.

How to encrypt String in Java

Here are some links you can read what Java supports

Encrypting/decrypting a data stream.

This example demonstrates how to encrypt (using a symmetric encryption algorithm such as AES, Blowfish, RC2, 3DES, etc) a large amount of data. The data is passed in chunks to one of the encrypt methods: EncryptBytes, EncryptString, EncryptBytesENC, or EncryptStringENC. (The method name indicates the type of input (string or byte array) and the return type (encoded string or byte array). The FirstChunk and LastChunk properties are used to indicate whether a chunk is the first, middle, or last in a stream to be encrypted. By default, both FirstChunk and LastChunk equal true -- meaning that the data passed is the entire amount.

JCERefGuide

Java Encryption Examples

How to convert an enum type variable to a string?

To extend James' answer, someone want some example code to support enum define with int value, I also have this requirement, so here is my way:

First one the is internal use macro, which is used by FOR_EACH:

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS_EXPAND_VALUE(r, data, elem)         \
    BOOST_PP_IF(                                                                \
        BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE(elem), 2),                           \
        BOOST_PP_TUPLE_ELEM(0, elem) = BOOST_PP_TUPLE_ELEM(1, elem),            \
        BOOST_PP_TUPLE_ELEM(0, elem) ),

And, here is the define macro:

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS(name, enumerators)                  \
    enum name {                                                                 \
        BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_WITH_STRING_CONVERSIONS_EXPAND_VALUE, \
                              0, enumerators) };

So when using it, you may like to write like this:

DEFINE_ENUM_WITH_STRING_CONVERSIONS(MyEnum,
    ((FIRST, 1))
    ((SECOND))
    ((MAX, SECOND)) )

which will expand to:

enum MyEnum
{
    FIRST = 1,
    SECOND,
    MAX = SECOND,
};

The basic idea is to define a SEQ, which every element is a TUPLE, so we can put addition value for enum member. In FOR_EACH loop, check the item TUPLE size, if the size is 2, expand the code to KEY = VALUE, else just keep the first element of TUPLE.

Because the input SEQ is actually TUPLEs, so if you want to define STRINGIZE functions, you may need to pre-process the input enumerators first, here is the macro to do the job:

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS_FIRST_ELEM(r, data, elem)           \
    BOOST_PP_TUPLE_ELEM(0, elem),

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS_FIRST_ELEM_SEQ(enumerators)         \
    BOOST_PP_SEQ_SUBSEQ(                                                        \
        BOOST_PP_TUPLE_TO_SEQ(                                                  \
            (BOOST_PP_SEQ_FOR_EACH(                                             \
                DEFINE_ENUM_WITH_STRING_CONVERSIONS_FIRST_ELEM, 0, enumerators) \
            )),                                                                 \
            0,                                                                  \
            BOOST_PP_SEQ_SIZE(enumerators))

The macro DEFINE_ENUM_WITH_STRING_CONVERSIONS_FIRST_ELEM_SEQ will only keep the first element in every TUPLE, and later convert to SEQ, now modify James' code, you will have the full power.

My implementation maybe not the simplest one, so if you do not find any clean code, mine for your reference.

Java: Get first item from a collection

You can do a casting. For example, if exists one method with this definition, and you know that this method is returning a List:

Collection<String> getStrings();

And after invoke it, you need the first element, you can do it like this:

List<String> listString = (List) getStrings();
String firstElement = (listString.isEmpty() ? null : listString.get(0));

Scroll to a div using jquery

First get the position of the div element upto which u want to scroll by jQuery position() method.
Example : var pos = $("div").position();
Then get the y cordinates (height) of that element with ".top" method.
Example : pos.top;
Then get the x cordinates of the that div element with ".left" method.
These methods are originated from CSS positioning.
Once we get x & y cordinates, then we can use javascript's scrollTo(); method.
This method scrolls the document upto specific height & width.
It takes two parameters as x & y cordinates. Syntax : window.scrollTo(x,y);
Then just pass the x & y cordinates of the DIV element in the scrollTo() function.
Refer the example below ↓ ↓

<!DOCTYPE HTML>
    <html>
    <head>
        <title>
            Scroll upto Div with jQuery.
        </title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#button1").click(function () {
                    var x = $("#element").position(); //gets the position of the div element...
                    window.scrollTo(x.left, x.top); //window.scrollTo() scrolls the page upto certain position....
                    //it takes 2 parameters : (x axis cordinate, y axis cordinate);
                });
            });
            </script>
    </head>
    <body>
        <button id="button1">
            Click here to scroll
        </button>

        <div id="element" style="position:absolute;top:200%;left:0%;background-color:orange;height:100px;width:200px;">
            The DIV element.
            </div>
        </body>
    </html>

catch specific HTTP error in python

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

Summarizing multiple columns with dplyr?

The dplyr package contains summarise_all for this aim:

library(dplyr)
# summarise_all was replaced with the summarise(acrosss(..)) syntax dplyr >=1.00
df %>% group_by(grp) %>% summarise(across(everything(), list(mean)))
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Alternatively, the purrrlyr package provides the same functionality:

library(purrrlyr)
df %>% slice_rows("grp") %>% dmap(mean)
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Also don't forget about data.table (use keyby to sort sort groups):

library(data.table)
setDT(df)[, lapply(.SD, mean), keyby = grp]
#>    grp        a        b        c        d
#> 1:   1 3.079412 2.979412 2.979412 2.914706
#> 2:   2 3.029126 3.038835 2.967638 2.873786
#> 3:   3 2.854701 2.948718 2.951567 3.062678

Let's try to compare performance.

library(dplyr)
library(purrrlyr)
library(data.table)
library(bench)
set.seed(123)
n <- 10000
df <- data.frame(
  a = sample(1:5, n, replace = TRUE), 
  b = sample(1:5, n, replace = TRUE), 
  c = sample(1:5, n, replace = TRUE), 
  d = sample(1:5, n, replace = TRUE), 
  grp = sample(1:3, n, replace = TRUE)
)
dt <- setDT(df)
mark(
  dplyr = df %>% group_by(grp) %>% summarise(across(everything(), list(mean))),
  purrrlyr = df %>% slice_rows("grp") %>% dmap(mean),
  data.table = dt[, lapply(.SD, mean), keyby = grp],
  check = FALSE
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 dplyr        2.81ms   2.85ms      328.        NA     17.3
#> 2 purrrlyr     7.96ms   8.04ms      123.        NA     24.5
#> 3 data.table 596.33µs 707.91µs     1409.        NA     10.3

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

@Controller
@RequestMapping(value = "/topic")
@Transactional

i solve this problem by adding @Transactional,i think this can make session open

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

Difference between staticmethod and classmethod

Instance Method:

+ Can modify object instance state

+ Can modify class state

Class Method:

- Can't modify object instance state

+ Can modify class state

Static Method:

- Can't modify object instance state

- Can't modify class state

class MyClass:
    ''' 
    Instance method has a mandatory first attribute self which represent the instance itself. 
    Instance method must be called by a instantiated instance.
    '''
    def method(self):
        return 'instance method called', self
    
    '''
    Class method has a mandatory first attribute cls which represent the class itself. 
    Class method can be called by an instance or by the class directly. 
    Its most common using scenario is to define a factory method.
    '''
    @classmethod
    def class_method(cls):
        return 'class method called', cls
    
    '''
    Static method doesn’t have any attributes of instances or the class. 
    It also can be called by an instance or by the class directly. 
    Its most common using scenario is to define some helper or utility functions which are closely relative to the class.
    '''
    @staticmethod
    def static_method():
        return 'static method called'


obj = MyClass()
print(obj.method())
print(obj.class_method()) # MyClass.class_method()
print(obj.static_method()) # MyClass.static_method()

output:

('instance method called', <__main__.MyClass object at 0x100fb3940>)
('class method called', <class '__main__.MyClass'>)
static method called

The instance method we actually had access to the object instance , right so this was an instance off a my class object whereas with the class method we have access to the class itself. But not to any of the objects, because the class method doesn't really care about an object existing. However you can both call a class method and static method on an object instance. This is going to work it doesn't really make a difference, so again when you call static method here it's going to work and it's going to know which method you want to call.

The Static methods are used to do some utility tasks, and class methods are used for factory methods. The factory methods can return class objects for different use cases.

And finally, a short example for better understanding:

class Student:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    @classmethod
    def get_from_string(cls, name_string: str):
        first_name, last_name = name_string.split()
        if Student.validate_name(first_name) and Student.validate_name(last_name):
            return cls(first_name, last_name)
        else:
            print('Invalid Names')

    @staticmethod
    def validate_name(name):
        return len(name) <= 10


stackoverflow_student = Student.get_from_string('Name Surname')
print(stackoverflow_student.first_name) # Name
print(stackoverflow_student.last_name) # Surname

How to change the CHARACTER SET (and COLLATION) throughout a database?

Adding to what David Whittaker posted, I have created a query that generates the complete table and columns alter statement that will convert each table. It may be a good idea to run

SET SESSION group_concat_max_len = 100000;

first to make sure your group concat doesn't go over the very small limit as seen here.

     SELECT a.table_name, concat('ALTER TABLE ', a.table_schema, '.', a.table_name, ' DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci, ',
        group_concat(distinct(concat(' MODIFY ',  column_name, ' ', column_type, ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ', if (is_nullable = 'NO', ' NOT', ''), ' NULL ',
        if (COLUMN_DEFAULT is not null, CONCAT(' DEFAULT \'', COLUMN_DEFAULT, '\''), ''), if (EXTRA != '', CONCAT(' ', EXTRA), '')))), ';') as alter_statement
    FROM information_schema.columns a
    INNER JOIN INFORMATION_SCHEMA.TABLES b ON a.TABLE_CATALOG = b.TABLE_CATALOG
        AND a.TABLE_SCHEMA = b.TABLE_SCHEMA
        AND a.TABLE_NAME = b.TABLE_NAME
        AND b.table_type != 'view'
    WHERE a.table_schema = ? and (collation_name = 'latin1_swedish_ci' or collation_name = 'utf8mb4_general_ci')
    GROUP BY table_name;

A difference here between the previous answer is it was using utf8 instead of ut8mb4 and using t1.data_type with t1.CHARACTER_MAXIMUM_LENGTH didn't work for enums. Also, my query excludes views since those will have to altered separately.

I simply used a Perl script to return all these alters as an array and iterated over them, fixed the columns that were too long (generally they were varchar(256) when the data generally only had 20 characters in them so that was an easy fix).

I found some data was corrupted when altering from latin1 -> utf8mb4. It appeared to be utf8 encoded latin1 characters in columns would get goofed in the conversion. I simply held data from the columns I knew was going to be an issue in memory from before and after the alter and compared them and generated update statements to fix the data.

Specifying ssh key in ansible playbook file

You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):

[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file =  <PATH TO KEY_FILE>

Hope this saves you some typing

How to use the CancellationToken property?

You have to pass the CancellationToken to the Task, which will periodically monitors the token to see whether cancellation is requested.

// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;  

// Task need to be cancelled with CancellationToken 
Task task = Task.Run(async () => {     
  while(!token.IsCancellationRequested) {
      Console.Write("*");         
      await Task.Delay(1000);
  }
}, token);

Console.WriteLine("Press enter to stop the task"); 
Console.ReadLine(); 
cancellationTokenSource.Cancel(); 

In this case, the operation will end when cancellation is requested and the Task will have a RanToCompletion state. If you want to be acknowledged that your task has been cancelled, you have to use ThrowIfCancellationRequested to throw an OperationCanceledException exception.

Task task = Task.Run(async () =>             
{                 
    while (!token.IsCancellationRequested) {
         Console.Write("*");                      
         await Task.Delay(1000);                
    }           
    token.ThrowIfCancellationRequested();               
}, token)
.ContinueWith(t =>
 {
      t.Exception?.Handle(e => true);
      Console.WriteLine("You have canceled the task");
 },TaskContinuationOptions.OnlyOnCanceled);  
 
Console.WriteLine("Press enter to stop the task");                 
Console.ReadLine();                 
cancellationTokenSource.Cancel();                 
task.Wait(); 

Hope this helps to understand better.

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

You can easily write the method to do that :

  public static String toCamelCase(final String init) {
    if (init == null)
        return null;

    final StringBuilder ret = new StringBuilder(init.length());

    for (final String word : init.split(" ")) {
        if (!word.isEmpty()) {
            ret.append(Character.toUpperCase(word.charAt(0)));
            ret.append(word.substring(1).toLowerCase());
        }
        if (!(ret.length() == init.length()))
            ret.append(" ");
    }

    return ret.toString();
}

How to write to file in Ruby?

The Ruby File class will give you the ins and outs of ::new and ::open but its parent, the IO class, gets into the depth of #read and #write.

How can I loop over entries in JSON?

Try this :

import urllib, urllib2, json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_object = json.load(response)
#print json_object['results']
if json_object['team'] == []:
    print 'No Data!'
else:
    for rows in json_object['team']:
        print 'Team ID:' + rows['team_id']
        print 'Team Name:' + rows['team_name']
        print 'Team URL:' + rows['team_icon_url']

mongo - couldn't connect to server 127.0.0.1:27017

This method only works if you want to repair your data files without preserving the original files

To find where you dbpath resides- vim /etc/mongodb.conf

check for option dbpath=

(I have dbpath=/var/lib/mongodb)

Default: /data/db/

Typical locations include: /srv/mongodb, /var/lib/mongodb or /opt/mongodb .

Replace the /var/lib/mongodb with your dbpath

sudo rm /var/lib/mongodb/mongod.lock
sudo mongod --dbpath /var/lib/mongodb/ --repair
sudo mongod --dbpath /var/lib/mongodb/ --journal

(Make sure that you leave you terminal running in which you have run above lines, dont press 'Ctrl+c' or quit it.) Type the command to start mongo now in another window.

Hope this works for you ! for those who want to repair your data files while preserving the original files mongo recover

How to retrieve the dimensions of a view?

Use getMeasuredWidth() and getMeasuredHeight() for your view.

Developer guide: View

CSS "and" and "or"

To select properties a AND b of a X element:

X[a][b]

To select properties a OR b of a X element:

X[a],X[b]

Match multiline text using regular expression

This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find() and matches() methods. find() succeeds if a match can be found anywhere in the target string, while matches() expects the regex to match the entire string.

Pattern p = Pattern.compile("xyz");

Matcher m = p.matcher("123xyzabc");
System.out.println(m.find());    // true
System.out.println(m.matches()); // false

Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true

Furthermore, MULTILINE doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^ and $.

Normally ^ matches the very beginning of the target string, and $ matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^ and $ to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.

So forget about what MULTILINE means and just remember what it does: changes the behavior of the ^ and $ anchors. DOTALL mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.

In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.

How to define static constant in a class in swift

Some might want certain class constants public while others private.

private keyword can be used to limit the scope of constants within the same swift file.

class MyClass {

struct Constants {

    static let testStr = "test"
    static let testStrLen = testStr.characters.count

    //testInt will not be accessable by other classes in different swift files
    private static let testInt = 1
}

func ownFunction()
{

    var newInt = Constants.testInt + 1

    print("Print testStr=\(Constants.testStr)")
}

}

Other classes will be able to access your class constants like below

class MyClass2
{

func accessOtherConstants()
{
    print("MyClass's testStr=\(MyClass.Constants.testStr)")
}

} 

Use a loop to plot n charts Python

Ok, so the easiest method to create several plots is this:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    # Show/save figure as desired.
    plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()

Note that you need to create a figure every time or pyplot will plot in the first one created.

If you want to create several data series all you need to do is:

import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')

You could automate it by having a list of colours like ['r','g','b','k'] and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.    
for i in range(len(x)):
    plt.plot(x[i],y[i],colours[i])
plt.show()

Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.

17 Dec 2019: added plt.show() and plt.figure() calls to clarify this part of the story.

C# - How to get Program Files (x86) on Windows 64 bit

The function below will return the x86 Program Files directory in all of these three Windows configurations:

  • 32 bit Windows
  • 32 bit program running on 64 bit Windows
  • 64 bit program running on 64 bit windows

 

static string ProgramFilesx86()
{
    if( 8 == IntPtr.Size 
        || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
    {
        return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
    }

    return Environment.GetEnvironmentVariable("ProgramFiles");
}

Fatal error: [] operator not supported for strings

You have probably defined $name, $date, $text or $date2 to be a string, like:

$name = 'String';

Then if you treat it like an array it will give that fatal error:

$name[] = 'new value'; // fatal error

To solve your problem just add the following code at the beginning of the loop:

$name = array();
$date = array();
$text = array();
$date2 = array();

This will reset their value to array and then you'll able to use them as arrays.

Horizontal list items

This fiddle shows how

http://jsfiddle.net/9th7X/

ul, li {
    display:inline
}

Great references on lists and css here:

http://alistapart.com/article/taminglists/

Passing variables through handlebars partial

Handlebars partials take a second parameter which becomes the context for the partial:

{{> person this}}

In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:

{{> person headline='Headline'}}

You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462 https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32

Merge or combine by rownames

Use match to return your desired vector, then cbind it to your matrix

cbind(t, z[, "symbol"][match(rownames(t), rownames(z))])

             [,1]         [,2]         [,3]         [,4]   
GO.ID        "GO:0002009" "GO:0030334" "GO:0015674" NA     
LEVEL        "8"          "6"          "7"          NA     
Annotated    "342"        "343"        "350"        NA     
Significant  "1"          "1"          "1"          NA     
Expected     "0.07"       "0.07"       "0.07"       NA     
resultFisher "0.679"      "0.065"      "0.065"      NA     
ILMN_1652464 "0"          "0"          "1"          "PLAC8"
ILMN_1651838 "0"          "0"          "0"          "RND1" 
ILMN_1711311 "1"          "1"          "0"          NA     
ILMN_1653026 "0"          "0"          "0"          "GRA"  

PS. Be warned that t is base R function that is used to transpose matrices. By creating a variable called t, it can lead to confusion in your downstream code.

How to INNER JOIN 3 tables using CodeIgniter

$this->db->select('*');    
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id', 'inner');
$this->db->join('table3', 'table1.id = table3.id', 'inner');
$this->db->where("table1", $id );
$query = $this->db->get();

Where you can specify which id should be viewed or select in specific table. You can also select which join portion either left, right, outer, inner, left outer, and right outer on the third parameter of join method.

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

Give all permissions to a user on a PostgreSQL database

In PostgreSQL 9.0+ you would do the following:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA MY_SCHEMA TO MY_GROUP;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA MY_SCHEMA TO MY_GROUP;

If you want to enable this for newly created relations too, then set the default permissions:

ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON TABLES TO MY_GROUP;
ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON SEQUENCES TO MY_GROUP;

However, seeing that you use 8.1 you have to code it yourself:

CREATE FUNCTION grant_all_in_schema (schname name, grant_to name) RETURNS integer AS $$
DECLARE
  rel RECORD;
BEGIN
  FOR rel IN
    SELECT c.relname
    FROM pg_class c
    JOIN pg_namespace s ON c.namespace = s.oid
    WHERE s.nspname = schname
  LOOP
    EXECUTE 'GRANT ALL PRIVILEGES ON ' || quote_ident(schname) || '.' || rel.relname || ' TO ' || quote_ident(grant_to);
  END LOOP;
  RETURN 1;
END; $$ LANGUAGE plpgsql STRICT;
REVOKE ALL ON FUNCTION grant_all_in_schema(name, name) FROM PUBLIC;

This will set the privileges on all relations: tables, views, indexes, sequences, etc. If you want to restrict that, filter on pg_class.relkind. See the pg_class docs for details.

You should run this function as superuser and as regular as your application requires. An option would be to package this in a cron job that executes every day or every hour.

Inserting HTML into a div

As alternative you can use insertAdjacentHTML - however I dig into and make some performance tests - (2019.09.13 Friday) MacOs High Sierra 10.13.6 on Chrome 76.0.3809 (64-bit), Safari 12.1.2 (13604.5.6), Firefox 69.0.0 (64-bit) ). The test F is only for reference - it is out of the question scope because we need to insert dynamically html - but in F I do it by 'hand' (in static way) - theoretically (as far I know) this should be the fastest way to insert new html elements.

enter image description here

SUMMARY

  • The A innerHTML = (do not confuse with +=) is fastest (Safari 48k operations per second, Firefox 43k op/sec, Chrome 23k op/sec) The A is ~31% slower than ideal solution F only chrome but on safari and firefox is faster (!)
  • The B innerHTML +=... is slowest on all browsers (Chrome 95 op/sec, Firefox 88 op/sec, Sfari 84 op/sec)
  • The D jQuery is second slow on all browsers (Safari 14 op/sec, Firefox 11k op/sec, Chrome 7k op/sec)
  • The reference solution F (theoretically fastest) is not fastest on firefox and safari (!!!) - which is surprising
  • The fastest browser was Safari

More info about why innerHTML = is much faster than innerHTML += is here. You can perform test on your machine/browser HERE

_x000D_
_x000D_
let html = "<div class='box'>Hello <span class='msg'>World</span> !!!</div>"_x000D_
_x000D_
function A() {    _x000D_
  container.innerHTML = `<div id="A_oiio">A: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function B() {    _x000D_
  container.innerHTML += `<div id="B_oiio">B: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function C() {    _x000D_
  container.insertAdjacentHTML('beforeend', `<div id="C_oiio">C: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function D() {    _x000D_
  $('#container').append(`<div id="D_oiio">D: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function E() {_x000D_
  let d = document.createElement("div");_x000D_
  d.innerHTML = `E: ${html}`;_x000D_
  d.id = 'E_oiio';_x000D_
  container.appendChild(d);_x000D_
}_x000D_
_x000D_
function F() {    _x000D_
  let dm = document.createElement("div");_x000D_
  dm.id = "F_oiio";_x000D_
  dm.appendChild(document.createTextNode("F: "));_x000D_
_x000D_
  let d = document.createElement("div");_x000D_
  d.classList.add('box');_x000D_
  d.appendChild(document.createTextNode("Hello "));_x000D_
  _x000D_
  let s = document.createElement("span");_x000D_
  s.classList.add('msg');_x000D_
  s.appendChild(document.createTextNode("World"));_x000D_
_x000D_
  d.appendChild(s);_x000D_
  d.appendChild(document.createTextNode(" !!!"));_x000D_
  dm.appendChild( d );_x000D_
  _x000D_
  container.appendChild(dm);_x000D_
}_x000D_
_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
.warr { color: red } .msg { color: blue } .box {display: inline}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="warr">This snippet only for show code used in test (in jsperf.com) - it not perform test itself. </div>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

How to use jQuery to get the current value of a file input field

Could you also do

$(input[type=file]).val()

integrating barcode scanner into php application?

I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.

Check if AJAX response data is empty/blank/null/undefined/0

//if(data="undefined"){

This is an assignment statement, not a comparison. Also, "undefined" is a string, it's a property. Checking it is like this: if (data === undefined) (no quotes, otherwise it's a string value)

If it's not defined, you may be returning an empty string. You could try checking for a falsy value like if (!data) as well

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

Naive question: Is it possible to somehow download GLIBC 2.15, put it in any folder (e.g. /tmp/myglibc) and then point to this path ONLY when executing something that needs this specific version of glibc?

Yes, it's possible.

Exists Angularjs code/naming conventions?

If you are a beginner, it is better you first go through some basic tutorials and after that learn about naming conventions. I have gone through the following to learn Angular, some of which are very effective.

Tutorials :

  1. http://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app
  2. http://viralpatel.net/blogs/angularjs-controller-tutorial/
  3. http://www.angularjstutorial.com/

Details of application structure and naming conventions can be found in a variety of places. I've gone through 100's of sites and I think these are among the best:

How can I convert a comma-separated string to an array?

Note that the following:

var a = "";
var x = new Array();
x = a.split(",");
alert(x.length);

will alert 1

Multi-select dropdown list in ASP.NET

I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.

Reading from stdin

From the man read:

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

Input parameters:

  • int fd file descriptor is an integer and not a file pointer. The file descriptor for stdin is 0

  • void *buf pointer to buffer to store characters read by the read function

  • size_t count maximum number of characters to read

So you can read character by character with the following code:

char buf[1];

while(read(0, buf, sizeof(buf))>0) {
   // read() here read from stdin charachter by character
   // the buf[0] contains the character got by read()
   ....
}

CSS performance relative to translateZ(0)

On mobile devices sending everything to the GPU will cause a memory overload and crash the application. I encountered this on an iPad app in Cordova. Best to only send the required items to the GPU, the divs that you're specifically moving around.

Better yet, use the 3d transitions transforms to do the animations like translateX(50px) as opposed to left:50px;

How to manually install a pypi module without pip/easy_install?

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contianed herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install

EDIT- thanks to kwatford (see first comment)

To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.

The docs say:

Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:

More details can be found here: http://docs.python.org/2.7/install/index.html

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

how to format date in Component of angular 5

You can find more information about the date pipe here, such as formats.

If you want to use it in your component, you can simply do

pipe = new DatePipe('en-US'); // Use your own locale

Now, you can simply use its transform method, which will be

const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');

How to access the first property of a Javascript object?

we can also do with this approch.

var example = {
  foo1: { /* stuff1 */},
  foo2: { /* stuff2 */},
  foo3: { /* stuff3 */}
}; 
Object.entries(example)[0][1];

Creating a Plot Window of a Particular Size

This will depend on the device you're using. If you're using a pdf device, you can do this:

pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )

You can then divide up the space in the pdf using the mfrow parameter like this:

par( mfrow = c(2,2) )

That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().

Other devices that might be useful include:

There's a list of all of the devices here.

Mocking HttpClient in unit tests

Since HttpClient use SendAsync method to perform all HTTP Requests, you can override SendAsync method and mock the HttpClient.

For that wrap creating HttpClient to a interface, something like below

public interface IServiceHelper
{
    HttpClient GetClient();
}

Then use above interface for dependency injection in your service, sample below

public class SampleService
{
    private readonly IServiceHelper serviceHelper;

    public SampleService(IServiceHelper serviceHelper)
    {
        this.serviceHelper = serviceHelper;
    }

    public async Task<HttpResponseMessage> Get(int dummyParam)
    {
        try
        {
            var dummyUrl = "http://www.dummyurl.com/api/controller/" + dummyParam;
            var client = serviceHelper.GetClient();
            HttpResponseMessage response = await client.GetAsync(dummyUrl);               

            return response;
        }
        catch (Exception)
        {
            // log.
            throw;
        }
    }
}

Now in unit test project create a helper class for mocking SendAsync. Here it is a FakeHttpResponseHandler class which is inheriting DelegatingHandler which will provide an option to override the SendAsync method. After overriding the SendAsync method need to setup a response for each HTTP Request which is calling SendAsync method, for that create a Dictionary with key as Uri and value as HttpResponseMessage so that whenever there is a HTTP Request and if the Uri matches SendAsync will return the configured HttpResponseMessage.

public class FakeHttpResponseHandler : DelegatingHandler
{
    private readonly IDictionary<Uri, HttpResponseMessage> fakeServiceResponse;
    private readonly JavaScriptSerializer javaScriptSerializer;
    public FakeHttpResponseHandler()
    {
        fakeServiceResponse =  new Dictionary<Uri, HttpResponseMessage>();
        javaScriptSerializer =  new JavaScriptSerializer();
    }

    /// <summary>
    /// Used for adding fake httpResponseMessage for the httpClient operation.
    /// </summary>
    /// <typeparam name="TQueryStringParameter"> query string parameter </typeparam>
    /// <param name="uri">Service end point URL.</param>
    /// <param name="httpResponseMessage"> Response expected when the service called.</param>
    public void AddFakeServiceResponse(Uri uri, HttpResponseMessage httpResponseMessage)
    {
        fakeServiceResponse.Remove(uri);
        fakeServiceResponse.Add(uri, httpResponseMessage);
    }

    /// <summary>
    /// Used for adding fake httpResponseMessage for the httpClient operation having query string parameter.
    /// </summary>
    /// <typeparam name="TQueryStringParameter"> query string parameter </typeparam>
    /// <param name="uri">Service end point URL.</param>
    /// <param name="httpResponseMessage"> Response expected when the service called.</param>
    /// <param name="requestParameter">Query string parameter.</param>
    public void AddFakeServiceResponse<TQueryStringParameter>(Uri uri, HttpResponseMessage httpResponseMessage, TQueryStringParameter requestParameter)
    {
        var serilizedQueryStringParameter = javaScriptSerializer.Serialize(requestParameter);
        var actualUri = new Uri(string.Concat(uri, serilizedQueryStringParameter));
        fakeServiceResponse.Remove(actualUri);
        fakeServiceResponse.Add(actualUri, httpResponseMessage);
    }

    // all method in HttpClient call use SendAsync method internally so we are overriding that method here.
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if(fakeServiceResponse.ContainsKey(request.RequestUri))
        {
            return Task.FromResult(fakeServiceResponse[request.RequestUri]);
        }

        return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            RequestMessage = request,
            Content = new StringContent("Not matching fake found")
        });
    }
}

Create a new implementation for IServiceHelper by mocking framework or like below. This FakeServiceHelper class we can use to inject the FakeHttpResponseHandler class so that whenever the HttpClient created by this class it will use FakeHttpResponseHandler class instead of the actual implementation.

public class FakeServiceHelper : IServiceHelper
{
    private readonly DelegatingHandler delegatingHandler;

    public FakeServiceHelper(DelegatingHandler delegatingHandler)
    {
        this.delegatingHandler = delegatingHandler;
    }

    public HttpClient GetClient()
    {
        return new HttpClient(delegatingHandler);
    }
}

And in test configure FakeHttpResponseHandler class by adding the Uri and expected HttpResponseMessage. The Uri should be the actual serviceendpoint Uri so that when the overridden SendAsync method is called from actual service implementation it will match the Uri in Dictionary and respond with the configured HttpResponseMessage. After configuring inject the FakeHttpResponseHandler object to the fake IServiceHelper implementation. Then inject the FakeServiceHelper class to the actual service which will make the actual service to use the override SendAsync method.

[TestClass]
public class SampleServiceTest
{
    private FakeHttpResponseHandler fakeHttpResponseHandler;

    [TestInitialize]
    public void Initialize()
    {
        fakeHttpResponseHandler = new FakeHttpResponseHandler();
    }

    [TestMethod]
    public async Task GetMethodShouldReturnFakeResponse()
    {
        Uri uri = new Uri("http://www.dummyurl.com/api/controller/");
        const int dummyParam = 123456;
        const string expectdBody = "Expected Response";

        var expectedHttpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(expectdBody)
        };

        fakeHttpResponseHandler.AddFakeServiceResponse(uri, expectedHttpResponseMessage, dummyParam);

        var fakeServiceHelper = new FakeServiceHelper(fakeHttpResponseHandler);

        var sut = new SampleService(fakeServiceHelper);

        var response = await sut.Get(dummyParam);

        var responseBody = await response.Content.ReadAsStringAsync();

        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        Assert.AreEqual(expectdBody, responseBody);
    }
}

GitHub Link : which is having sample implementation

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

It seems many indie developers like me are desperately looking for an answer to these questions for years. Strangely, even after 5 years this question was asked, it seems the answer to this question is still not clear.

As far as I can see, there is not any official statement in Google AdMob documentation or website about how a developer can safely answer these questions. It seems developers are left on their own in the mystery about answering some legally binding questions about the SDK.

In their support forums they can advice questioners to reach out to Apple Support:

Hi there,

I believe it would be best for you to reach out to Apple Support for your concern as it tackles with Apple Submission Guidelines rather than our SDK.

Regards, Joshua Lagonera Mobile Ads SDK Team

Or they can say that it is out of their scope of support:

Hello Robert,

On this forum, we deal with Mobile Ads SDK related technical concerns only. We would not be able to address you question as this is out of scope for our team.

Regards, Deepika Uragayala Mobile Ads SDK Team

The only answer I could find from a "Google person" is about the 4th question. It is not in the AdMob forum but in the "Tag Manager" forum but still related. It is like so:

Hi Jorn,

Apple asks you about your use of IDFA when submitting your application (https://developer.apple.com/Library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html). For an app that doesn't display advertising, but includes the AdSupport framework for conversion attribution, you would select the appropriate checkbox(es). In respect to the Limit Ad Tracking stipulation, all of GTM's tags that utilize IDFA respect the limit ad tracking stipulations of the SDK.

Thanks,

Eric Burley Google Tag Manager.

Here is an Internet Archive link in case they remove this page.

Lastly, let me mention about AdMob's only statement I've seen about this issue (here is the Internet Archive link):

The Mobile Ads SDK for iOS utilizes Apple's advertising identifier (IDFA). The SDK uses IDFA under the guidelines laid out in the iOS developer program license agreement. You must ensure you are in compliance with the iOS developer program license agreement policies governing the use of this identifier.

In conclusion, it seems most developers using AdMob simply checks 1st and 4th checkmarks and submit their apps without being completely sure about what Google exactly does in its SDK and without any official information about it. I wish good luck to us all.

How do I remove a property from a JavaScript object?

The delete operator is used to remove properties from objects.

const obj = { foo: "bar" }
delete obj.foo
obj.hasOwnProperty("foo") // false

Note that, for arrays, this is not the same as removing an element. To remove an element from an array, use Array#splice or Array#pop. For example:

arr // [0, 1, 2, 3, 4]
arr.splice(3,1); // 3
arr // [0, 1, 2, 4]

Details

delete in JavaScript has a different function to that of the keyword in C and C++: it does not directly free memory. Instead, its sole purpose is to remove properties from objects.

For arrays, deleting a property corresponding to an index, creates a sparse array (ie. an array with a "hole" in it). Most browsers represent these missing array indices as "empty".

var array = [0, 1, 2, 3]
delete array[2] // [0, 1, empty, 3]

Note that delete does not relocate array[3] into array[2].

Different built-in functions in JavaScript handle sparse arrays differently.

  • for...in will skip the empty index completely.

  • A traditional for loop will return undefined for the value at the index.

  • Any method using Symbol.iterator will return undefined for the value at the index.

  • forEach, map and reduce will simply skip the missing index.

So, the delete operator should not be used for the common use-case of removing elements from an array. Arrays have a dedicated methods for removing elements and reallocating memory: Array#splice() and Array#pop.

Array#splice(start[, deleteCount[, item1[, item2[, ...]]]])

Array#splice mutates the array, and returns any removed indices. deleteCount elements are removed from index start, and item1, item2... itemN are inserted into the array from index start. If deleteCount is omitted then elements from startIndex are removed to the end of the array.

let a = [0,1,2,3,4]
a.splice(2,2) // returns the removed elements [2,3]
// ...and `a` is now [0,1,4]

There is also a similarly named, but different, function on Array.prototype: Array#slice.

Array#slice([begin[, end]])

Array#slice is non-destructive, and returns a new array containing the indicated indices from start to end. If end is left unspecified, it defaults to the end of the array. If end is positive, it specifies the zero-based non-inclusive index to stop at. If end is negative it, it specifies the index to stop at by counting back from the end of the array (eg. -1 will omit the final index). If end <= start, the result is an empty array.

let a = [0,1,2,3,4]
let slices = [
    a.slice(0,2),
    a.slice(2,2),
    a.slice(2,3),
    a.slice(2,5) ]

//   a           [0,1,2,3,4]
//   slices[0]   [0 1]- - -   
//   slices[1]    - - - - -
//   slices[2]    - -[3]- -
//   slices[3]    - -[2 4 5]

Array#pop

Array#pop removes the last element from an array, and returns that element. This operation changes the length of the array.

What is the difference between .*? and .* regular expressions?

On greedy vs non-greedy

Repetition in regex by default is greedy: they try to match as many reps as possible, and when this doesn't work and they have to backtrack, they try to match one fewer rep at a time, until a match of the whole pattern is found. As a result, when a match finally happens, a greedy repetition would match as many reps as possible.

The ? as a repetition quantifier changes this behavior into non-greedy, also called reluctant (in e.g. Java) (and sometimes "lazy"). In contrast, this repetition will first try to match as few reps as possible, and when this doesn't work and they have to backtrack, they start matching one more rept a time. As a result, when a match finally happens, a reluctant repetition would match as few reps as possible.

References


Example 1: From A to Z

Let's compare these two patterns: A.*Z and A.*?Z.

Given the following input:

eeeAiiZuuuuAoooZeeee

The patterns yield the following matches:

Let's first focus on what A.*Z does. When it matched the first A, the .*, being greedy, first tries to match as many . as possible.

eeeAiiZuuuuAoooZeeee
   \_______________/
    A.* matched, Z can't match

Since the Z doesn't match, the engine backtracks, and .* must then match one fewer .:

eeeAiiZuuuuAoooZeeee
   \______________/
    A.* matched, Z still can't match

This happens a few more times, until finally we come to this:

eeeAiiZuuuuAoooZeeee
   \__________/
    A.* matched, Z can now match

Now Z can match, so the overall pattern matches:

eeeAiiZuuuuAoooZeeee
   \___________/
    A.*Z matched

By contrast, the reluctant repetition in A.*?Z first matches as few . as possible, and then taking more . as necessary. This explains why it finds two matches in the input.

Here's a visual representation of what the two patterns matched:

eeeAiiZuuuuAoooZeeee
   \__/r   \___/r      r = reluctant
    \____g____/        g = greedy

Example: An alternative

In many applications, the two matches in the above input is what is desired, thus a reluctant .*? is used instead of the greedy .* to prevent overmatching. For this particular pattern, however, there is a better alternative, using negated character class.

The pattern A[^Z]*Z also finds the same two matches as the A.*?Z pattern for the above input (as seen on ideone.com). [^Z] is what is called a negated character class: it matches anything but Z.

The main difference between the two patterns is in performance: being more strict, the negated character class can only match one way for a given input. It doesn't matter if you use greedy or reluctant modifier for this pattern. In fact, in some flavors, you can do even better and use what is called possessive quantifier, which doesn't backtrack at all.

References


Example 2: From A to ZZ

This example should be illustrative: it shows how the greedy, reluctant, and negated character class patterns match differently given the same input.

eeAiiZooAuuZZeeeZZfff

These are the matches for the above input:

Here's a visual representation of what they matched:

         ___n
        /   \              n = negated character class
eeAiiZooAuuZZeeeZZfff      r = reluctant
  \_________/r   /         g = greedy
   \____________/g

Related topics

These are links to questions and answers on stackoverflow that cover some topics that may be of interest.

One greedy repetition can outgreed another

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

compile function -

  1. is called before the controller and link function.
  2. In compile function, you have the original template DOM so you can make changes on original DOM before AngularJS creates an instance of it and before a scope is created
  3. ng-repeat is perfect example - original syntax is template element, the repeated elements in HTML are instances
  4. There can be multiple element instances and only one template element
  5. Scope is not available yet
  6. Compile function can return function and object
  7. returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.
  8. returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

syntax

function compile(tElement, tAttrs, transclude) { ... }

controller

  1. called after the compile function
  2. scope is available here
  3. can be accessed by other directives (see require attribute)

pre - link

  1. The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.

  2. You can update the dom in the controller using angular.element but this is not recommended as the element is provided in the link function

  3. Pre-link function is used to implement logic that runs when angular js has already compiled the child elements but before any of the child element's post link have been called

post-link

  1. directive that only has link function, angular treats the function as a post link

  2. post will be executed after compile, controller and pre-link funciton, so that's why this is considered the safest and default place to add your directive logic

ToList()-- does it create a new list?

ToList will always create a new list, which will not reflect any subsequent changes to the collection.

However, it will reflect changes to the objects themselves (Unless they're mutable structs).

In other words, if you replace an object in the original list with a different object, the ToList will still contain the first object.
However, if you modify one of the objects in the original list, the ToList will still contain the same (modified) object.

./configure : /bin/sh^M : bad interpreter

You can use following command to fix

cat file_name.sh | tr -d '\r' > file_name.sh.new

Darkening an image with CSS (In any shape)

if you want only the background-image to be affected, you can use a linear gradient to do that, just like this:

  background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url(IMAGE_URL);

If you want it darker, make the alpha value higher, else you want it lighter, make alpha lower

js window.open then print()

As most of browsers has been updated, So print and close do not any more as It worked before. So you should add onafterprint event listener in order to close print window.

    var printWindow = window.open('https://stackoverflow.com/');
    printWindow.print();

    //Close window once print is finished
    printWindow.onafterprint = function(){
       printWindow.close()
    };

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

If the DLL and the .NET projects are in the same solution and you want to compile and run both every time, you can right click the properties of the .NET project, Build events, then add something like the following to Post-build event command line:

copy $(SolutionDir)Debug\MyOwn.dll .

It's basically a DOS line, and you can tweak based on where your DLL is being built to.

Java best way for string find and replace?

you can use pattern matcher as well, which will replace all in one shot.

Pattern keyPattern = Pattern.compile(key); Matcher matcher = keyPattern.matcher(str); String nerSrting = matcher.replaceAll(value);

WHERE clause on SQL Server "Text" data type

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

How to call a .NET Webservice from Android using KSOAP2?

How does your .NET Webservice look like?

I had the same effect using ksoap 2.3 from code.google.com. I followed the tutorial on The Code Project (which is great BTW.)

And everytime I used

    Integer result = (Integer)envelope.getResponse();

to get the result of a my webservice (regardless of the type, I tried Object, String, int) I ran into the org.ksoap2.serialization.SoapPrimitive exception.

I found a solution (workaround). The first thing I had to do was to remove the "SoapRpcMethod() attribute from my webservice methods.

    [SoapRpcMethod(), WebMethod]
    public Object GetInteger1(int i)
    {
        // android device will throw exception
        return 0;
    }

    [WebMethod]
    public Object GetInteger2(int i)
    {
        // android device will get the value
        return 0;
    }

Then I changed my Android code to:

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

However, I get a SoapPrimitive object, which has a "value" filed that is private. Luckily the value is passed through the toString() method, so I use Integer.parseInt(result.toString()) to get my value, which is enough for me, because I don't have any complex types that I need to get from my Web service.

Here is the full source:

private static final String SOAP_ACTION = "http://tempuri.org/GetInteger2";
private static final String METHOD_NAME = "GetInteger2";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:4711/Service1.asmx";

public int GetInteger2() throws IOException, XmlPullParserException {
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    PropertyInfo pi = new PropertyInfo();
    pi.setName("i");
    pi.setValue(123);
    request.addProperty(pi);

    SoapSerializationEnvelope envelope =
        new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);

    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
    androidHttpTransport.call(SOAP_ACTION, envelope);

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
    return Integer.parseInt(result.toString());
}

How to escape "&" in XML?

'&' --> '&amp;'

'<' --> '&lt;'

'>' --> '&gt;'

Execute JavaScript using Selenium WebDriver in C#

public static class Webdriver
{        
    public static void ExecuteJavaScript(string scripts)
    {
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        js.ExecuteScript(scripts);
    }

    public static T ExecuteJavaScript<T>(string scripts)
    {
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        return (T)js.ExecuteScript(scripts);
    }
}

In your code you can then do

string test = Webdriver.ExecuteJavaScript<string>(" return 'hello World'; ");
int test = Webdriver.ExecuteJavaScript<int>(" return 3; ");

Ansible: copy a directory content to another directory

the ansible doc is quite clear https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html for parameter src it says the following:

Local path to a file to copy to the remote server.
This can be absolute or relative.
If path is a directory, it is copied recursively. In this case, if path ends with "/", 
only inside contents of that directory are copied to destination. Otherwise, if it 
does not end with "/", the directory itself with all contents is copied. This behavior 
is similar to the rsync command line tool.

So what you need is skip the / at the end of your src path.

- name: copy html file
  copy: src=/home/vagrant/dist dest=/usr/share/nginx/html/

How to see the changes in a Git commit?

git show shows the changes made in the most recent commit.

Equivalent to git show HEAD.

git show HEAD~1 takes you back 1 commit.

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

Creating a LINQ select from multiple tables

If the anonymous type causes trouble for you, you can create a simple data class:

public class PermissionsAndPages
{
     public ObjectPermissions Permissions {get;set}
     public Pages Pages {get;set}
}

and then in your query:

select new PermissionsAndPages { Permissions = op, Page = pg };

Then you can pass this around:

return queryResult.SingleOrDefault(); // as PermissionsAndPages

Check if a number is int or float

Use isinstance.

>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True

So:

>>> if isinstance(x, int):
        print 'x is a int!'

x is a int!

_EDIT:_

As pointed out, in case of long integers, the above won't work. So you need to do:

>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False

How can I write these variables into one line of code in C#?

Give this a go:

string format = "{0} / {1} / {2} {3}";
string date = string.Format(format,mon.ToString(),da.ToString(),yer.ToString();
Console.WriteLine(date);

In fact, there's probably a way to format it automatically without even doing it yourself.

Check out http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

How do I get cURL to not show the progress bar?

I found that with curl 7.18.2 the download progress bar is not hidden with:

curl -s http://google.com > temp.html

but it is with:

curl -ss http://google.com > temp.html

Java "lambda expressions not supported at this language level"

Even after applying above defined project specific settings on IntelliJ as well as Eclipse, it was still failing for me !

what worked for me was addition of maven plugin with source and target with 1.8 setting in POM XML:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.0.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>com.abc.sparkcore.JavaWordCount</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>install</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
                    </configuration>   
     </execution>
            </executions>
        </plugin>
    </plugins>
</build> 

How to detect if numpy is installed

If you use eclipse, you simply type "import numpy" and eclipse will "complain" if doesn't find.

Java compiler level does not match the version of the installed Java project facet

I changed the configuration inside workspace/project/.setting/org.eclipse.wst.common.project.facet.core to :

installed facet="jst.web" version="2.5"
installed facet="jst.java" version="1.7"

Before changing config, remove project from IDE. This worked for me.

How to reverse a singly linked list using only two pointers?

To swap two variables without the use of a temporary variable,

a = a xor b
b = a xor b
a = a xor b

fastest way is to write it in one line

a = a ^ b ^ (b=a)

Similarly,

using two swaps

swap(a,b)
swap(b,c)

solution using xor

a = a^b^c
b = a^b^c
c = a^b^c
a = a^b^c

solution in one line

c = a ^ b ^ c ^ (a=b) ^ (b=c)
b = a ^ b ^ c ^ (c=a) ^ (a=b)
a = a ^ b ^ c ^ (b=c) ^ (c=a)

The same logic is used to reverse a linked list.

typedef struct List
{
 int info;
 struct List *next;
}List;


List* reverseList(List *head)
{
 p=head;
 q=p->next;
 p->next=NULL;
 while(q)
 {
    q = (List*) ((int)p ^ (int)q ^ (int)q->next ^ (int)(q->next=p) ^ (int)(p=q));
 }
 head = p;
 return head;
}  

notifyDataSetChanged example

You can use the runOnUiThread() method as follows. If you're not using a ListActivity, just adapt the code to get a reference to your ArrayAdapter.

final ArrayAdapter adapter = ((ArrayAdapter)getListAdapter());
runOnUiThread(new Runnable() {
    public void run() {
        adapter.notifyDataSetChanged();
    }
});

How to re-render flatlist?

If you are going to have a Button, you can update the data with a setState inside the onPress. SetState will then re-render your FlatList.

I need to round a float to two decimal places in Java

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118);
// 1.30

how to add picasso library in android studio

Add this to your dependencies in build.gradle:

enter image description here

dependencies {
 implementation 'com.squareup.picasso:picasso:2.71828'
  ...

The latest version can be found here

Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project

Take a look at your libraries folder, the library you just added should be in there.

enter image description here

Attempt to write a readonly database - Django w/ SELinux error

You have to add writing rights to the directory in which your sqlite database is stored. So running chmod 664 /srv/mysite should help.

This is a security risk, so better solution is to change the owner of your database to www-data:

chown www-data:www-data /srv/mysite
chown www-data:www-data /srv/mysite/DATABASE.sqlite

Nested classes' scope?

All explanations can be found in Python Documentation The Python Tutorial

For your first error <type 'exceptions.NameError'>: name 'outer_var' is not defined. The explanation is:

There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.

quoted from The Python Tutorial 9.4

For your second error <type 'exceptions.NameError'>: name 'OuterClass' is not defined

When a class definition is left normally (via the end), a class object is created.

quoted from The Python Tutorial 9.3.1

So when you try inner_var = Outerclass.outer_var, the Quterclass hasn't been created yet, that's why name 'OuterClass' is not defined

A more detailed but tedious explanation for your first error:

Although classes have access to enclosing functions’ scopes, though, they do not act as enclosing scopes to code nested within the class: Python searches enclosing functions for referenced names, but never any enclosing classes. That is, a class is a local scope and has access to enclosing local scopes, but it does not serve as an enclosing local scope to further nested code.

quoted from Learning.Python(5th).Mark.Lutz

Copy to Clipboard for all Browsers using javascript

This works on firefox 3.6.x and IE:

    function copyToClipboardCrossbrowser(s) {           
        s = document.getElementById(s).value;               

        if( window.clipboardData && clipboardData.setData )
        {
            clipboardData.setData("Text", s);
        }           
        else
        {
            // You have to sign the code to enable this or allow the action in about:config by changing
            //user_pref("signed.applets.codebase_principal_support", true);
            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

            var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;

            // create a transferable

            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;

            // specify the data we wish to handle. Plaintext in this case.
            trans.addDataFlavor('text/unicode');

            // To get the data from the transferable we need two new objects
            var str = new Object();
            var len = new Object();

            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

            str.data= s;        

            trans.setTransferData("text/unicode",str, str.data.length * 2);

            var clipid=Components.interfaces.nsIClipboard;              
            if (!clip) return false;
            clip.setData(trans,null,clipid.kGlobalClipboard);      
        }
    }

How can a windows service programmatically restart itself?

The problem with shelling out to a batch file or EXE is that a service may or may not have the permissions required to run the external app.

The cleanest way to do this that I have found is to use the OnStop() method, which is the entry point for the Service Control Manager. Then all your cleanup code will run, and you won't have any hanging sockets or other processes, assuming your stop code is doing its job.

To do this you need to set a flag before you terminate that tells the OnStop method to exit with an error code; then the SCM knows that the service needs to be restarted. Without this flag you won't be able to stop the service manually from the SCM. This also assumes you have set up the service to restart on an error.

Here's my stop code:

...

bool ABORT;

protected override void OnStop()
{
    Logger.log("Stopping service");
    WorkThreadRun = false;
    WorkThread.Join();
    Logger.stop();
    // if there was a problem, set an exit error code
    // so the service manager will restart this
    if(ABORT)Environment.Exit(1);
}

If the service runs into a problem and needs to restart, I launch a thread that stops the service from the SCM. This allows the service to clean up after itself:

...

if(NeedToRestart)
{
    ABORT = true;
    new Thread(RestartThread).Start();
}

void RestartThread()
{
    ServiceController sc = new ServiceController(ServiceName);
    try
    {
        sc.Stop();
    }
    catch (Exception) { }
}

Initializing array of structures

my_data is a struct with name as a field and data[] is arry of structs, you are initializing each index. read following:

5.20 Designated Initializers:

In a structure initializer, specify the name of a field to initialize with .fieldname =' before the element value. For example, given the following structure,

struct point { int x, y; };

the following initialization

struct point p = { .y = yvalue, .x = xvalue };

is equivalent to

struct point p = { xvalue, yvalue };

Another syntax which has the same meaning, obsolete since GCC 2.5, is fieldname:', as shown here:

struct point p = { y: yvalue, x: xvalue };

You can also write:

my_data data[] = {
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};

as:

my_data data[] = {
    [0] = { .name = "Peter" },
    [1] = { .name = "James" },
    [2] = { .name = "John" },
    [3] = { .name = "Mike" }
}; 

or:

my_data data[] = {
    [0].name = "Peter",
    [1].name = "James",
    [2].name = "John",
    [3].name = "Mike"
}; 

Second and third forms may be convenient as you don't need to write in order for example all of the above example are equivalent to:

my_data data[] = {
    [3].name = "Mike",
    [1].name = "James",
    [0].name = "Peter",
    [2].name = "John"
}; 

If you have multiple fields in your struct (for example, an int age), you can initialize all of them at once using the following:

my_data data[] = {
    [3].name = "Mike",
    [2].age = 40,
    [1].name = "James",
    [3].age = 23,
    [0].name = "Peter",
    [2].name = "John"
}; 

To understand array initialization read Strange initializer expression?

Additionally, you may also like to read @Shafik Yaghmour's answer for switch case: What is “…” in switch-case in C code

NGINX - No input file specified. - php Fast/CGI

If someone is still having trouble with it ... I solved it by correcting it this way:

Inside the site conf file (example: /etc/nginx/conf.d/SITEEXAMPLE.conf) I have the following line:

fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;

The error occurs because my site is NOT in the "/usr/share/nginx/html" folder but in the folder: /var/www/html/SITE/

So, change that part, leaving the code as below. Note: For those who use the site standard in /var/www/html/YOUR_SITE/

fastcgi_param  SCRIPT_FILENAME  /var/www/html/YOUR_SITE/$fastcgi_script_name;

How to find substring inside a string (or how to grep a variable)?

expr match "$LIST" '$SOURCE'

don't work because of this function search $SOURCE from begin of the string and return the position just after pattern $SOURCE if found else 0. So you must write another code:

expr match "$LIST" '.*'"$SOURCE" or expr "$LIST" : '.*'"$SOURCE"

The expression $SOURCE must be double quoted so as a parser may set substitution. Single quoted not substitute and the code above will search textual string $SOURCE from the beginning of the $LIST. If you need the beginning of the string subtract the length $SOURCE e.g ${#SOURCE}. You may write also

expr "$LIST" : ".*\($SOURCE\)"

This function just extract $SOURCE from $LIST and return it. You'll get empty string else. But they problem with double double quote. I don't know how it resolve without using additional variable. It's light solution. So you may write in C. There is ready function strstr. Don't use expr index, So is very attractive. But index search not substring and only first char.

Foreign keys in mongo?

Short answer: You should to use "weak references" between collections, using ObjectId properties:

References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models.

https://docs.mongodb.com/manual/core/data-modeling-introduction/#references

This will of course not check any referential integrity. You need to handle "dead links" on your side (application level).

Parsing JSON in Excel VBA

UPDATE 3 (Sep 24 '17)

Check VBA-JSON-parser on GitHub for the latest version and examples. Import JSON.bas module into the VBA project for JSON processing.

UPDATE 2 (Oct 1 '16)

However if you do want to parse JSON on 64-bit Office with ScriptControl, then this answer may help you to get ScriptControl to work on 64-bit.

UPDATE (Oct 26 '15)

Note that a ScriptControl-based approachs makes the system vulnerable in some cases, since they allows a direct access to the drives (and other stuff) for the malicious JS code via ActiveX's. Let's suppose you are parsing web server response JSON, like JsonString = "{a:(function(){(new ActiveXObject('Scripting.FileSystemObject')).CreateTextFile('C:\\Test.txt')})()}". After evaluating it you'll find new created file C:\Test.txt. So JSON parsing with ScriptControl ActiveX is not a good idea.

Trying to avoid that, I've created JSON parser based on RegEx's. Objects {} are represented by dictionaries, that makes possible to use dictionary's properties and methods: .Count, .Exists(), .Item(), .Items, .Keys. Arrays [] are the conventional zero-based VB arrays, so UBound() shows the number of elements. Here is the code with some usage examples:

Option Explicit

Sub JsonTest()
    Dim strJsonString As String
    Dim varJson As Variant
    Dim strState As String
    Dim varItem As Variant

    ' parse JSON string to object
    ' root element can be the object {} or the array []
    strJsonString = "{""a"":[{}, 0, ""value"", [{""stuff"":""content""}]], b:null}"
    ParseJson strJsonString, varJson, strState

    ' checking the structure step by step
    Select Case False ' if any of the checks is False, the sequence is interrupted
        Case IsObject(varJson) ' if root JSON element is object {},
        Case varJson.Exists("a") ' having property a,
        Case IsArray(varJson("a")) ' which is array,
        Case UBound(varJson("a")) >= 3 ' having not less than 4 elements,
        Case IsArray(varJson("a")(3)) ' where forth element is array,
        Case UBound(varJson("a")(3)) = 0 ' having the only element,
        Case IsObject(varJson("a")(3)(0)) ' which is object,
        Case varJson("a")(3)(0).Exists("stuff") ' having property stuff,
        Case Else
            MsgBox "Check the structure step by step" & vbCrLf & varJson("a")(3)(0)("stuff") ' then show the value of the last one property.
    End Select

    ' direct access to the property if sure of structure
    MsgBox "Direct access to the property" & vbCrLf & varJson.Item("a")(3)(0).Item("stuff") ' content

    ' traversing each element in array
    For Each varItem In varJson("a")
        ' show the structure of the element
        MsgBox "The structure of the element:" & vbCrLf & BeautifyJson(varItem)
    Next

    ' show the full structure starting from root element
    MsgBox "The full structure starting from root element:" & vbCrLf & BeautifyJson(varJson)

End Sub

Sub BeautifyTest()
    ' put sourse JSON string to "desktop\source.json" file
    ' processed JSON will be saved to "desktop\result.json" file
    Dim strDesktop As String
    Dim strJsonString As String
    Dim varJson As Variant
    Dim strState As String
    Dim strResult As String
    Dim lngIndent As Long

    strDesktop = CreateObject("WScript.Shell").SpecialFolders.Item("Desktop")
    strJsonString = ReadTextFile(strDesktop & "\source.json", -2)
    ParseJson strJsonString, varJson, strState
    If strState <> "Error" Then
        strResult = BeautifyJson(varJson)
        WriteTextFile strResult, strDesktop & "\result.json", -1
    End If
    CreateObject("WScript.Shell").PopUp strState, 1, , 64
End Sub

Sub ParseJson(ByVal strContent As String, varJson As Variant, strState As String)
    ' strContent - source JSON string
    ' varJson - created object or array to be returned as result
    ' strState - Object|Array|Error depending on processing to be returned as state
    Dim objTokens As Object
    Dim objRegEx As Object
    Dim bMatched As Boolean

    Set objTokens = CreateObject("Scripting.Dictionary")
    Set objRegEx = CreateObject("VBScript.RegExp")
    With objRegEx
        ' specification http://www.json.org/
        .Global = True
        .MultiLine = True
        .IgnoreCase = True
        .Pattern = """(?:\\""|[^""])*""(?=\s*(?:,|\:|\]|\}))"
        Tokenize objTokens, objRegEx, strContent, bMatched, "str"
        .Pattern = "(?:[+-])?(?:\d+\.\d*|\.\d+|\d+)e(?:[+-])?\d+(?=\s*(?:,|\]|\}))"
        Tokenize objTokens, objRegEx, strContent, bMatched, "num"
        .Pattern = "(?:[+-])?(?:\d+\.\d*|\.\d+|\d+)(?=\s*(?:,|\]|\}))"
        Tokenize objTokens, objRegEx, strContent, bMatched, "num"
        .Pattern = "\b(?:true|false|null)(?=\s*(?:,|\]|\}))"
        Tokenize objTokens, objRegEx, strContent, bMatched, "cst"
        .Pattern = "\b[A-Za-z_]\w*(?=\s*\:)" ' unspecified name without quotes
        Tokenize objTokens, objRegEx, strContent, bMatched, "nam"
        .Pattern = "\s"
        strContent = .Replace(strContent, "")
        .MultiLine = False
        Do
            bMatched = False
            .Pattern = "<\d+(?:str|nam)>\:<\d+(?:str|num|obj|arr|cst)>"
            Tokenize objTokens, objRegEx, strContent, bMatched, "prp"
            .Pattern = "\{(?:<\d+prp>(?:,<\d+prp>)*)?\}"
            Tokenize objTokens, objRegEx, strContent, bMatched, "obj"
            .Pattern = "\[(?:<\d+(?:str|num|obj|arr|cst)>(?:,<\d+(?:str|num|obj|arr|cst)>)*)?\]"
            Tokenize objTokens, objRegEx, strContent, bMatched, "arr"
        Loop While bMatched
        .Pattern = "^<\d+(?:obj|arr)>$" ' unspecified top level array
        If Not (.Test(strContent) And objTokens.Exists(strContent)) Then
            varJson = Null
            strState = "Error"
        Else
            Retrieve objTokens, objRegEx, strContent, varJson
            strState = IIf(IsObject(varJson), "Object", "Array")
        End If
    End With
End Sub

Sub Tokenize(objTokens, objRegEx, strContent, bMatched, strType)
    Dim strKey As String
    Dim strRes As String
    Dim lngCopyIndex As Long
    Dim objMatch As Object

    strRes = ""
    lngCopyIndex = 1
    With objRegEx
        For Each objMatch In .Execute(strContent)
            strKey = "<" & objTokens.Count & strType & ">"
            bMatched = True
            With objMatch
                objTokens(strKey) = .Value
                strRes = strRes & Mid(strContent, lngCopyIndex, .FirstIndex - lngCopyIndex + 1) & strKey
                lngCopyIndex = .FirstIndex + .Length + 1
            End With
        Next
        strContent = strRes & Mid(strContent, lngCopyIndex, Len(strContent) - lngCopyIndex + 1)
    End With
End Sub

Sub Retrieve(objTokens, objRegEx, strTokenKey, varTransfer)
    Dim strContent As String
    Dim strType As String
    Dim objMatches As Object
    Dim objMatch As Object
    Dim strName As String
    Dim varValue As Variant
    Dim objArrayElts As Object

    strType = Left(Right(strTokenKey, 4), 3)
    strContent = objTokens(strTokenKey)
    With objRegEx
        .Global = True
        Select Case strType
            Case "obj"
                .Pattern = "<\d+\w{3}>"
                Set objMatches = .Execute(strContent)
                Set varTransfer = CreateObject("Scripting.Dictionary")
                For Each objMatch In objMatches
                    Retrieve objTokens, objRegEx, objMatch.Value, varTransfer
                Next
            Case "prp"
                .Pattern = "<\d+\w{3}>"
                Set objMatches = .Execute(strContent)

                Retrieve objTokens, objRegEx, objMatches(0).Value, strName
                Retrieve objTokens, objRegEx, objMatches(1).Value, varValue
                If IsObject(varValue) Then
                    Set varTransfer(strName) = varValue
                Else
                    varTransfer(strName) = varValue
                End If
            Case "arr"
                .Pattern = "<\d+\w{3}>"
                Set objMatches = .Execute(strContent)
                Set objArrayElts = CreateObject("Scripting.Dictionary")
                For Each objMatch In objMatches
                    Retrieve objTokens, objRegEx, objMatch.Value, varValue
                    If IsObject(varValue) Then
                        Set objArrayElts(objArrayElts.Count) = varValue
                    Else
                        objArrayElts(objArrayElts.Count) = varValue
                    End If
                    varTransfer = objArrayElts.Items
                Next
            Case "nam"
                varTransfer = strContent
            Case "str"
                varTransfer = Mid(strContent, 2, Len(strContent) - 2)
                varTransfer = Replace(varTransfer, "\""", """")
                varTransfer = Replace(varTransfer, "\\", "\")
                varTransfer = Replace(varTransfer, "\/", "/")
                varTransfer = Replace(varTransfer, "\b", Chr(8))
                varTransfer = Replace(varTransfer, "\f", Chr(12))
                varTransfer = Replace(varTransfer, "\n", vbLf)
                varTransfer = Replace(varTransfer, "\r", vbCr)
                varTransfer = Replace(varTransfer, "\t", vbTab)
                .Global = False
                .Pattern = "\\u[0-9a-fA-F]{4}"
                Do While .Test(varTransfer)
                    varTransfer = .Replace(varTransfer, ChrW(("&H" & Right(.Execute(varTransfer)(0).Value, 4)) * 1))
                Loop
            Case "num"
                varTransfer = Evaluate(strContent)
            Case "cst"
                Select Case LCase(strContent)
                    Case "true"
                        varTransfer = True
                    Case "false"
                        varTransfer = False
                    Case "null"
                        varTransfer = Null
                End Select
        End Select
    End With
End Sub

Function BeautifyJson(varJson As Variant) As String
    Dim strResult As String
    Dim lngIndent As Long
    BeautifyJson = ""
    lngIndent = 0
    BeautyTraverse BeautifyJson, lngIndent, varJson, vbTab, 1
End Function

Sub BeautyTraverse(strResult As String, lngIndent As Long, varElement As Variant, strIndent As String, lngStep As Long)
    Dim arrKeys() As Variant
    Dim lngIndex As Long
    Dim strTemp As String

    Select Case VarType(varElement)
        Case vbObject
            If varElement.Count = 0 Then
                strResult = strResult & "{}"
            Else
                strResult = strResult & "{" & vbCrLf
                lngIndent = lngIndent + lngStep
                arrKeys = varElement.Keys
                For lngIndex = 0 To UBound(arrKeys)
                    strResult = strResult & String(lngIndent, strIndent) & """" & arrKeys(lngIndex) & """" & ": "
                    BeautyTraverse strResult, lngIndent, varElement(arrKeys(lngIndex)), strIndent, lngStep
                    If Not (lngIndex = UBound(arrKeys)) Then strResult = strResult & ","
                    strResult = strResult & vbCrLf
                Next
                lngIndent = lngIndent - lngStep
                strResult = strResult & String(lngIndent, strIndent) & "}"
            End If
        Case Is >= vbArray
            If UBound(varElement) = -1 Then
                strResult = strResult & "[]"
            Else
                strResult = strResult & "[" & vbCrLf
                lngIndent = lngIndent + lngStep
                For lngIndex = 0 To UBound(varElement)
                    strResult = strResult & String(lngIndent, strIndent)
                    BeautyTraverse strResult, lngIndent, varElement(lngIndex), strIndent, lngStep
                    If Not (lngIndex = UBound(varElement)) Then strResult = strResult & ","
                    strResult = strResult & vbCrLf
                Next
                lngIndent = lngIndent - lngStep
                strResult = strResult & String(lngIndent, strIndent) & "]"
            End If
        Case vbInteger, vbLong, vbSingle, vbDouble
            strResult = strResult & varElement
        Case vbNull
            strResult = strResult & "Null"
        Case vbBoolean
            strResult = strResult & IIf(varElement, "True", "False")
        Case Else
            strTemp = Replace(varElement, "\""", """")
            strTemp = Replace(strTemp, "\", "\\")
            strTemp = Replace(strTemp, "/", "\/")
            strTemp = Replace(strTemp, Chr(8), "\b")
            strTemp = Replace(strTemp, Chr(12), "\f")
            strTemp = Replace(strTemp, vbLf, "\n")
            strTemp = Replace(strTemp, vbCr, "\r")
            strTemp = Replace(strTemp, vbTab, "\t")
            strResult = strResult & """" & strTemp & """"
    End Select

End Sub

Function ReadTextFile(strPath As String, lngFormat As Long) As String
    ' lngFormat -2 - System default, -1 - Unicode, 0 - ASCII
    With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 1, False, lngFormat)
        ReadTextFile = ""
        If Not .AtEndOfStream Then ReadTextFile = .ReadAll
        .Close
    End With
End Function

Sub WriteTextFile(strContent As String, strPath As String, lngFormat As Long)
    With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 2, True, lngFormat)
        .Write (strContent)
        .Close
    End With
End Sub

One more opportunity of this JSON RegEx parser is that it works on 64-bit Office, where ScriptControl isn't available.

INITIAL (May 27 '15)

Here is one more method to parse JSON in VBA, based on ScriptControl ActiveX, without external libraries:

Sub JsonTest()

    Dim Dict, Temp, Text, Keys, Items

    ' Converting JSON string to appropriate nested dictionaries structure
    ' Dictionaries have numeric keys for JSON Arrays, and string keys for JSON Objects
    ' Returns Nothing in case of any JSON syntax issues
    Set Dict = GetJsonDict("{a:[[{stuff:'result'}]], b:''}")
    ' You can use For Each ... Next and For ... Next loops through keys and items
    Keys = Dict.Keys
    Items = Dict.Items

    ' Referring directly to the necessary property if sure, without any checks
    MsgBox Dict("a")(0)(0)("stuff")

    ' Auxiliary DrillDown() function
    ' Drilling down the structure, sequentially checking if each level exists
    Select Case False
    Case DrillDown(Dict, "a", Temp, "")
    Case DrillDown(Temp, 0, Temp, "")
    Case DrillDown(Temp, 0, Temp, "")
    Case DrillDown(Temp, "stuff", "", Text)
    Case Else
        ' Structure is consistent, requested value found
        MsgBox Text
    End Select

End Sub

Function GetJsonDict(JsonString As String)
    With CreateObject("ScriptControl")
        .Language = "JScript"
        .ExecuteStatement "function gettype(sample) {return {}.toString.call(sample).slice(8, -1)}"
        .ExecuteStatement "function evaljson(json, er) {try {var sample = eval('(' + json + ')'); var type = gettype(sample); if(type != 'Array' && type != 'Object') {return er;} else {return getdict(sample);}} catch(e) {return er;}}"
        .ExecuteStatement "function getdict(sample) {var type = gettype(sample); if(type != 'Array' && type != 'Object') return sample; var dict = new ActiveXObject('Scripting.Dictionary'); if(type == 'Array') {for(var key = 0; key < sample.length; key++) {dict.add(key, getdict(sample[key]));}} else {for(var key in sample) {dict.add(key, getdict(sample[key]));}} return dict;}"
        Set GetJsonDict = .Run("evaljson", JsonString, Nothing)
    End With
End Function

Function DrillDown(Source, Prop, Target, Value)
    Select Case False
    Case TypeName(Source) = "Dictionary"
    Case Source.exists(Prop)
    Case Else
        Select Case True
        Case TypeName(Source(Prop)) = "Dictionary"
            Set Target = Source(Prop)
            Value = Empty
        Case IsObject(Source(Prop))
            Set Value = Source(Prop)
            Set Target = Nothing
        Case Else
            Value = Source(Prop)
            Set Target = Nothing
        End Select
        DrillDown = True
        Exit Function
    End Select
    DrillDown = False
End Function

Finding the id of a parent div using Jquery

You could use event delegation on the parent div. Or use the closest method to find the parent of the button.

The easiest of the two is probably the closest.

var id = $("button").closest("div").prop("id");

How to Make Laravel Eloquent "IN" Query?

Here is how you do in Eloquent

$users = User::whereIn('id', array(1, 2, 3))->get();

And if you are using Query builder then :

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

"replace" function examples

Here's two simple examples

> x <- letters[1:4]
> replace(x, 3, 'Z') #replacing 'c' by 'Z'
[1] "a" "b" "Z" "d"
> 
> y <- 1:10
> replace(y, c(4,5), c(20,30)) # replacing 4th and 5th elements by 20 and 30
 [1]  1  2  3 20 30  6  7  8  9 10

Convert string to number and add one

The parseInt solution is the best way to go as it is clear what is happening.

For completeness it is worth mentioning that this can also be done with the + operator

$('.load_more').live("click",function() { //When user clicks
  var newcurrentpageTemp = +$(this).attr("id") + 1; //Get the id from the hyperlink
  alert(newcurrentpageTemp);
  dosomething();
});

An established connection was aborted by the software in your host machine

I encountered this issue on my Windows 7 64-bit development machine when running Android Studio 2.1.x and Android Studio 2.2.x side-by-side.

I had deployed an application via the 2.2.x instance the previous day and had left that IDE running. The next day I deployed a different application from the 2.1.x IDE and this is when I encountered the issue.

Shutting down both IDEs and then restarting the 2.1.x IDE resolved the issue for me.

Node.js/Express.js App Only Works on Port 3000

Try this

$ PORT=8080 node app.js

GIT commit as different user without email / or only email

It is all dependent on how you commit.

For example:

git commit -am "Some message"

will use your ~\.gitconfig username. In other words, if you open that file you should see a line that looks like this:

[user]
    email = [email protected]

That would be the email you want to change. If your doing a pull request through Bitbucket or Github etc. you would be whoever you're logged in as.

How do I change Eclipse to use spaces instead of tabs?

In eclipse mars (EE) on Mac OS X, the only way I could find this in the preferences was to open the Preference dialog and type Formatter, then select Java->Code Style->Formatter.

Java->Code Style has no access to Formatter!

How can I parse a String to BigDecimal?

Try this

// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);

// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);

If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)

Also keep in mind that decimalFormat.parse can throw a ParseException so you need to handle it (with try/catch) or throw it and let another part of your program handle it

Using port number in Windows host file

Using netsh with connectaddress=127.0.0.1 did not work for me.

Despite looking everywhere on the internet I could not find the solution which solved this for me, which was to use connectaddress=127.x.x.x (i.e. any 127. ipv4 address, just not 127.0.0.1) as this appears to link back to localhost just the same but without the restriction, so that the loopback works in netsh.

docker mounting volumes on host

If you came here because you were looking for a simple way to browse any VOLUME:

  1. Find out the name of the volume with docker volume list
  2. Shut down all running containers to which this volume is attached to
  3. Run docker run -it --rm --mount source=[NAME OF VOLUME],target=/volume busybox
  4. A shell will open. cd /volume to enter the volume.

Iterator Loop vs index loop

By writing your client code in terms of iterators you abstract away the container completely.

Consider this code:

class ExpressionParser // some generic arbitrary expression parser
{
public:
    template<typename It>
    void parse(It begin, const It end)
    {
        using namespace std;
        using namespace std::placeholders;
        for_each(begin, end, 
            bind(&ExpressionParser::process_next, this, _1);
    }
    // process next char in a stream (defined elsewhere)
    void process_next(char c);
};

client code:

ExpressionParser p;

std::string expression("SUM(A) FOR A in [1, 2, 3, 4]");
p.parse(expression.begin(), expression.end());

std::istringstream file("expression.txt");
p.parse(std::istringstream<char>(file), std::istringstream<char>());

char expr[] = "[12a^2 + 13a - 5] with a=108";
p.parse(std::begin(expr), std::end(expr));

Edit: Consider your original code example, implemented with :

using namespace std;

vector<int> myIntVector;
// Add some elements to myIntVector
myIntVector.push_back(1);
myIntVector.push_back(4);
myIntVector.push_back(8);

copy(myIntVector.begin(), myIntVector.end(), 
    std::ostream_iterator<int>(cout, " "));

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

What is the best way to auto-generate INSERT statements for a SQL Server table?

why not just backup the data before your work with it, then restore when you want it to be refreshed?

if you must generate inserts try: http://vyaskn.tripod.com/code.htm#inserts

Good tool for testing socket connections?

Another tool is tcpmon. This is a java open-source tool to monitor a TCP connection. It's not directly a test server. It is placed in-between a client and a server but allow to see what is going through the "tube" and also to change what is going through.

How to urlencode data for curl command?

Direct link to awk version : http://www.shelldorado.com/scripts/cmds/urlencode
I used it for years and it works like a charm

:
##########################################################################
# Title      :  urlencode - encode URL data
# Author     :  Heiner Steven ([email protected])
# Date       :  2000-03-15
# Requires   :  awk
# Categories :  File Conversion, WWW, CGI
# SCCS-Id.   :  @(#) urlencode  1.4 06/10/29
##########################################################################
# Description
#   Encode data according to
#       RFC 1738: "Uniform Resource Locators (URL)" and
#       RFC 1866: "Hypertext Markup Language - 2.0" (HTML)
#
#   This encoding is used i.e. for the MIME type
#   "application/x-www-form-urlencoded"
#
# Notes
#    o  The default behaviour is not to encode the line endings. This
#   may not be what was intended, because the result will be
#   multiple lines of output (which cannot be used in an URL or a
#   HTTP "POST" request). If the desired output should be one
#   line, use the "-l" option.
#
#    o  The "-l" option assumes, that the end-of-line is denoted by
#   the character LF (ASCII 10). This is not true for Windows or
#   Mac systems, where the end of a line is denoted by the two
#   characters CR LF (ASCII 13 10).
#   We use this for symmetry; data processed in the following way:
#       cat | urlencode -l | urldecode -l
#   should (and will) result in the original data
#
#    o  Large lines (or binary files) will break many AWK
#       implementations. If you get the message
#       awk: record `...' too long
#        record number xxx
#   consider using GNU AWK (gawk).
#
#    o  urlencode will always terminate it's output with an EOL
#       character
#
# Thanks to Stefan Brozinski for pointing out a bug related to non-standard
# locales.
#
# See also
#   urldecode
##########################################################################

PN=`basename "$0"`          # Program name
VER='1.4'

: ${AWK=awk}

Usage () {
    echo >&2 "$PN - encode URL data, $VER
usage: $PN [-l] [file ...]
    -l:  encode line endings (result will be one line of output)

The default is to encode each input line on its own."
    exit 1
}

Msg () {
    for MsgLine
    do echo "$PN: $MsgLine" >&2
    done
}

Fatal () { Msg "$@"; exit 1; }

set -- `getopt hl "$@" 2>/dev/null` || Usage
[ $# -lt 1 ] && Usage           # "getopt" detected an error

EncodeEOL=no
while [ $# -gt 0 ]
do
    case "$1" in
        -l) EncodeEOL=yes;;
    --) shift; break;;
    -h) Usage;;
    -*) Usage;;
    *)  break;;         # First file name
    esac
    shift
done

LANG=C  export LANG
$AWK '
    BEGIN {
    # We assume an awk implementation that is just plain dumb.
    # We will convert an character to its ASCII value with the
    # table ord[], and produce two-digit hexadecimal output
    # without the printf("%02X") feature.

    EOL = "%0A"     # "end of line" string (encoded)
    split ("1 2 3 4 5 6 7 8 9 A B C D E F", hextab, " ")
    hextab [0] = 0
    for ( i=1; i<=255; ++i ) ord [ sprintf ("%c", i) "" ] = i + 0
    if ("'"$EncodeEOL"'" == "yes") EncodeEOL = 1; else EncodeEOL = 0
    }
    {
    encoded = ""
    for ( i=1; i<=length ($0); ++i ) {
        c = substr ($0, i, 1)
        if ( c ~ /[a-zA-Z0-9.-]/ ) {
        encoded = encoded c     # safe character
        } else if ( c == " " ) {
        encoded = encoded "+"   # special handling
        } else {
        # unsafe character, encode it as a two-digit hex-number
        lo = ord [c] % 16
        hi = int (ord [c] / 16);
        encoded = encoded "%" hextab [hi] hextab [lo]
        }
    }
    if ( EncodeEOL ) {
        printf ("%s", encoded EOL)
    } else {
        print encoded
    }
    }
    END {
        #if ( EncodeEOL ) print ""
    }
' "$@"

Get the contents of a table row with a button click

The object of the exercise is to find the row that contains the information. When we get there, we can easily extract the required information.

Answer

$(".use-address").click(function() {
    var $item = $(this).closest("tr")   // Finds the closest row <tr> 
                       .find(".nr")     // Gets a descendent with class="nr"
                       .text();         // Retrieves the text within <td>

    $("#resultas").append($item);       // Outputs the answer
});

VIEW DEMO

Now let's focus on some frequently asked questions in such situations.

How to find the closest row?

Using .closest():

var $row = $(this).closest("tr");

Using .parent():

You can also move up the DOM tree using .parent() method. This is just an alternative that is sometimes used together with .prev() and .next().

var $row = $(this).parent()             // Moves up from <button> to <td>
                  .parent();            // Moves up from <td> to <tr>

Getting all table cell <td> values

So we have our $row and we would like to output table cell text:

var $row = $(this).closest("tr"),       // Finds the closest row <tr> 
    $tds = $row.find("td");             // Finds all children <td> elements

$.each($tds, function() {               // Visits every single <td> element
    console.log($(this).text());        // Prints out the text within the <td>
});

VIEW DEMO

Getting a specific <td> value

Similar to the previous one, however we can specify the index of the child <td> element.

var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element

$.each($tds, function() {                // Visits every single <td> element
    console.log($(this).text());         // Prints out the text within the <td>
});

VIEW DEMO

Useful methods

  • .closest() - get the first element that matches the selector
  • .parent() - get the parent of each element in the current set of matched elements
  • .parents() - get the ancestors of each element in the current set of matched elements
  • .children() - get the children of each element in the set of matched elements
  • .siblings() - get the siblings of each element in the set of matched elements
  • .find() - get the descendants of each element in the current set of matched elements
  • .next() - get the immediately following sibling of each element in the set of matched elements
  • .prev() - get the immediately preceding sibling of each element in the set of matched elements

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

All of the above did not work for me, but a rebuild of the rpm database, with the following command, did:

sudo rpm --rebuilddb

Thanks all for the help.

scroll up and down a div on button click using jquery

You can use this simple plugin to add scrollUp and scrollDown to your jQuery

https://github.com/phpust/JQueryScrollDetector

Copy a file in a sane, safe and efficient way

Qt has a method for copying files:

#include <QFile>
QFile::copy("originalFile.example","copiedFile.example");

Note that to use this you have to install Qt (instructions here) and include it in your project (if you're using Windows and you're not an administrator, you can download Qt here instead). Also see this answer.

Angularjs loading screen on ajax request

If you are using Restangular (which is awesome) you can create an animation during api calls. Here is my solution. Add a response interceptor and a request interceptor that sends out a rootscope broadcast. Then create a directive to listen for that response and request.:

         angular.module('mean.system')
  .factory('myRestangular',['Restangular','$rootScope', function(Restangular,$rootScope) {
    return Restangular.withConfig(function(RestangularConfigurer) {
      RestangularConfigurer.setBaseUrl('http://localhost:3000/api');
      RestangularConfigurer.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
        var extractedData;
        // .. to look for getList operations
        if (operation === 'getList') {
          // .. and handle the data and meta data
          extractedData = data.data;
          extractedData.meta = data.meta;
        } else {
          extractedData = data.data;
        }
        $rootScope.$broadcast('apiResponse');
        return extractedData;
      });
      RestangularConfigurer.setRequestInterceptor(function (elem, operation) {
        if (operation === 'remove') {
          return null;
        }
        return (elem && angular.isObject(elem.data)) ? elem : {data: elem};
      });
      RestangularConfigurer.setRestangularFields({
        id: '_id'
      });
      RestangularConfigurer.addRequestInterceptor(function(element, operation, what, url) {
        $rootScope.$broadcast('apiRequest');
        return element;
      });
    });
  }]);

Here is the directive:

        angular.module('mean.system')
  .directive('smartLoadingIndicator', function($rootScope) {
    return {
      restrict: 'AE',
      template: '<div ng-show="isAPICalling"><p><i class="fa fa-gear fa-4x fa-spin"></i>&nbsp;Loading</p></div>',
      replace: true,
      link: function(scope, elem, attrs) {
        scope.isAPICalling = false;

        $rootScope.$on('apiRequest', function() {
          scope.isAPICalling = true;
        });
        $rootScope.$on('apiResponse', function() {
          scope.isAPICalling = false;
        });
      }
    };
  })
;

How do I pipe a subprocess call to a text file?

If you want to write the output to a file you can use the stdout-argument of subprocess.call.

It takes None, subprocess.PIPE, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.

You need to open a file with something like open and pass the object or file descriptor integer to call:

f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=f)

I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.

Can't check signature: public key not found

There is a similar problem.it is a tomcat digital signature.

$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc apache-tomcat-9.0.16-windows- 
x64.zip
gpg: Signature made 2019?02? 5?  0:32:50
gpg:                using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Can't check signature: No public key

but then I use the RSA key it provided to receive the public key to verify.

$ gpg --receive-keys A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: key 10C01C5A2F6059E7: 38 signatures not checked due to missing keys
gpg: key 10C01C5A2F6059E7: public key "Mark E D Thomas <[email protected]>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1

Then successfully.

$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc
gpg: assuming signed data in 'apache-tomcat-9.0.16-windows-x64.zip'
gpg: Signature made 2019?02? 5?  0:32:50
gpg:                using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Good signature from "Mark E D Thomas <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: A9C5 DF4D 22E9 9998 D987  5A51 10C0 1C5A 2F60 59E7

Visual Studio Code open tab in new window

When I want to split the screens I usually do one of the following:

  1. open new window with: Ctrl+Shift+N
    and after that I drag the current file I want to the new window.
  2. on the File explorer - I hit Ctrl+Enter on the file I want - and then this file and the other file open together in the same screen but in split mode, so you can see the two files together. If the screen is wide enough this is not a bad solution at all that you can get used to.

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

CSS text-overflow: ellipsis; not working?

I have been having this problem and I wanted a solution that could easily work with dynamic widths. The solution use css grid. This is how the code looks like:

// css 
.parent{
      display: grid; 
      grid-template-columns: auto 1fr;
}      
.dynamic-width-child{
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
}
.fixed-width-child{
      white-space: nowrap;
}

.

// html
<div class="parent">
  <div class="dynamic-width-child">
    iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii asdfhlhlafh;lshd;flhsd;lhfaaaaaaaaaaaaaaaaaaaa
  </div>
  <div class="fixed-width-child">Why?-Zed</div>

Differences between key, superkey, minimal superkey, candidate key and primary key

Super Key : Super key is a set of one or more attributes whose values identify tuple in the relation uniquely.

Candidate Key : Candidate key can be defined as a minimal subset of super key. In some cases , candidate key can not alone since there is alone one attribute is the minimal subset. Example,

Employee(id, ssn, name, addrress)

Here Candidate key is (id, ssn) because we can easily identify the tuple using either id or ssn . Althrough, minimal subset of super key is either id or ssn. but both of them can be considered as candidate key.

Primary Key : Primary key is a one of the candidate key.

Example : Student(Id, Name, Dept, Result)

Here

Super Key : {Id, Id+Name, Id+Name+Dept} because super key is set of attributes .

Candidate Key : Id because Id alone is the minimal subset of super key.

Primary Key : Id because Id is one of the candidate key

How to Iterate over a Set/HashSet without an Iterator?

You can use an enhanced for loop:

Set<String> set = new HashSet<String>();

//populate set

for (String s : set) {
    System.out.println(s);
}

Or with Java 8:

set.forEach(System.out::println);

What is Domain Driven Design?

I believe the following pdf will give you the bigger picture. Domain Driven Design by Eric Evans

NOTE: Think of a project you can work on, apply the little things you understood and see best practices. It will help you to grow your ability to the micro service architecture design approach too.

Why do we need boxing and unboxing in C#?

In general, you typically will want to avoid boxing your value types.

However, there are rare occurances where this is useful. If you need to target the 1.1 framework, for example, you will not have access to the generic collections. Any use of the collections in .NET 1.1 would require treating your value type as a System.Object, which causes boxing/unboxing.

There are still cases for this to be useful in .NET 2.0+. Any time you want to take advantage of the fact that all types, including value types, can be treated as an object directly, you may need to use boxing/unboxing. This can be handy at times, since it allows you to save any type in a collection (by using object instead of T in a generic collection), but in general, it is better to avoid this, as you're losing type safety. The one case where boxing frequently occurs, though, is when you're using Reflection - many of the calls in reflection will require boxing/unboxing when working with value types, since the type is not known in advance.

OSError - Errno 13 Permission denied

Just close the file in case it is opened in the background. The error disappears by itself

How to pass a null variable to a SQL Stored Procedure from C#.net code

Use DBNull.Value Better still, make your stored procedure parameters have defaults of NULL. Or use a Nullable<DateTime> parameter if the parameter will sometimes be a valid DateTime object

Using classes with the Arduino

On this page, the Arduino sketch defines a couple of Structs (plus a couple of methods) which are then called in the setup loop and main loop. Simple enough to interpret, even for a barely-literate programmer like me.

Singleton: How should it be used

But when I need something like a Singleton, I often end up using a Schwarz Counter to instantiate it.

How to model type-safe enum types?

A slightly less verbose way of declaring named enumerations:

object WeekDay extends Enumeration("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") {
  type WeekDay = Value
  val Sun, Mon, Tue, Wed, Thu, Fri, Sat = Value
}

WeekDay.valueOf("Wed") // returns Some(Wed)
WeekDay.Fri.toString   // returns Fri

Of course the problem here is that you will need to keep the ordering of the names and vals in sync which is easier to do if name and val are declared on the same line.

Adding image inside table cell in HTML

This worked for me:-

 <!DOCTYPE html> 
  <html>
  <head>
<title>CAR APPLICATION</title>
 </head>
 <body>
<center>
    <h1>CAR APPLICATION</h1>
</center>

<table border="5" bordercolor="red" align="center">
    <tr>
        <th colspan="3">ABCD</th> 
    </tr>
    <tr>
        <th>Name</th>
        <th>Origin</th>
        <th>Photo</th>
    </tr>
    <tr>
        <td>Bugatti Veyron Super Sport</th>
        <td>Molsheim, Alsace, France</th>
                <!-- considering it is on the same folder that .html file -->
        <td><img src=".\A.jpeg" alt="" border=3 height=100 width=300></img></th>
    </tr>
    <tr>
        <td>SSC Ultimate Aero TT  TopSpeed</th>
        <td>United States</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
    <tr>
        <td>Koenigsegg CCX</th>
        <td>Ängelholm, Sweden</th>
        <td border=4 height=100 width=300>Photo1</th>
    </tr>
    <tr>
        <td>Saleen S7</th>
        <td>Irvine, California, United States</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
    <tr>
        <td> McLaren F1</th>
        <td>Surrey, England</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
    <tr>
        <td>Ferrari Enzo</th>
        <td>Maranello, Italy</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
    <tr>
        <td> Pagani Zonda F Clubsport</th>
        <td>Modena, Italy</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
</table>
  </body>
  <html>

Getting path of captured image in Android using camera intent

Here I updated the sample code in Kotlin. Please note on Nougat and above version Uri.fromFile(file) is not working and it crashes the app for that need to implement FileProvider which is safest way to send files from intent. For implementing this refer this answer or this article

private fun takePhotoFromCamera() {
        val isDeviceSupportCamera: Boolean = this.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
        if (isDeviceSupportCamera) {
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS + "/attachments")!!.path,
                        System.currentTimeMillis().toString() + ".jpg")
//            fileUri = Uri.fromFile(file)
                fileUri = FileProvider.getUriForFile(this, this.applicationContext.packageName + ".provider", file!!)
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
                    takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                }
                startActivityForResult(takePictureIntent, Constants.REQUEST_CODE_IMAGE_CAPTURE)
            }

        } else {
            Toast.makeText(this, this.getString(R.string.camera_not_supported), Toast.LENGTH_SHORT).show()
        }
    }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
             if(requestCode == Constants.REQUEST_CODE_IMAGE_CAPTURE) {
                realPath = file?.path
                 //do what ever you want to do
            }
    }
}

CSS text-transform capitalize on all caps

If the data is coming from a database, as in my case, you can lower it before sending it to a select list/drop down list. Shame you can't do it in CSS.

Jmeter - get current date and time

JMeter is using java SimpleDateFormat

For UTC with timezone use this

${__time(yyyy-MM-dd'T'hh:mm:ssX)}

Importing two classes with same name. How to handle?

I just had the same problem, what I did, I arranged the library order in sequence, for example there were java.lang.NullPointerException and javacard.lang.NullPointerException. I made the first one as default library and if you needed to use the other you can explicitly specify the full qualified class name.

What are Bearer Tokens and token_type in OAuth 2?

token_type is a parameter in Access Token generate call to Authorization server, which essentially represents how an access_token will be generated and presented for resource access calls. You provide token_type in the access token generation call to an authorization server.

If you choose Bearer (default on most implementation), an access_token is generated and sent back to you. Bearer can be simply understood as "give access to the bearer of this token." One valid token and no question asked. On the other hand, if you choose Mac and sign_type (default hmac-sha-1 on most implementation), the access token is generated and kept as secret in Key Manager as an attribute, and an encrypted secret is sent back as access_token.

Yes, you can use your own implementation of token_type, but that might not make much sense as developers will need to follow your process rather than standard implementations of OAuth.

Getting Current time to display in Label. VB.net

Use Date.Now instead of DateTime.Now

TCPDF ERROR: Some data has already been output, can't send PDF file

This problem is when apache/php show errors.

This data(html) destroy pdf output.

You must off display errors in php.ini.

How to display (print) vector in Matlab?

To print a vector which possibly has complex numbers-

fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

Delete the following files from the directory:

\wamp\bin\mysql\mysql5.6.17\ib_logfile0
\wamp\bin\mysql\mysql5.6.17\ib_logfile1
\wamp\bin\mysql\mysql5.6.17\ibdata1

This solved my problem.

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.

What I finally end up doing was replacing the single quote ' with it code &#39; using a regex after the stringify() method call the following way:

var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "&#39;");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.

Django DateField default options

This should do the trick:

models.DateTimeField(_("Date"), auto_now_add = True)

How to stretch a table over multiple pages

You should \usepackage{longtable}.

Convert JSON array to an HTML table in jQuery

If you accept using another jQuery dependent tool, I would recommend using Tabulator. Then you will not need to write HTML or any other DOM generating code, while maintaining great flexibility regarding the formatting and processing of the table data.

enter image description here

For another working example using Node, you can look at the MMM-Tabulator demo project.

How do I access command line arguments in Python?

Python tutorial explains it:

import sys

print(sys.argv)

More specifically, if you run python example.py one two three:

>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']

How to provide a mysql database connection in single file in nodejs

I think that you should use a connection pool instead of share a single connection. A connection pool would provide a much better performance, as you can check here.

As stated in the library documentation, it occurs because the MySQL protocol is sequential (this means that you need multiple connections to execute queries in parallel).

Connection Pool Docs

How to initialize a variable of date type in java?

tl;dr

Use Instant, replacement for java.util.Date.

Instant.now()  // Capture current moment as seen in UTC.

If you must have a Date, convert.

java.util.Date.from( Instant.now() ) 

java.time

The java.util.Date & .Calendar classes have been supplanted by the java.time framework built into Java 8 and later. The new classes are a tremendous improvement, inspired by the successful Joda-Time library.

The java.time classes tend to use static factory methods rather than constructors for instantiating objects.

To get the current moment in UTC time zone:

Instant instant = Instant.now();

To get the current moment in a particular time zone:

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );

If you must have a java.util.Date for use with other classes not yet updated for the java.time types, convert from Instant.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to create a fix size list in python?

You can do it using array module. array module is part of python standard library:

from array import array
from itertools import repeat

a = array("i", repeat(0, 10))
# or
a = array("i", [0]*10)

repeat function repeats 0 value 10 times. It's more memory efficient than [0]*10, since it doesn't allocate memory, but repeats returning the same number x number of times.

How to delete a folder with files using Java

Guava 21+ to the rescue. Use only if there are no symlinks pointing out of the directory to delete.

com.google.common.io.MoreFiles.deleteRecursively(
      file.toPath(),
      RecursiveDeleteOption.ALLOW_INSECURE
) ;

(This question is well-indexed by Google, so other people usig Guava might be happy to find this answer, even if it is redundant with other answers elsewhere.)

Android Studio rendering problems

I had the same problem, current update, but rendering failed because I need to update.

Try changing the update version you are on. The default is Stable, but there are 3 more options, Canary being the newest and potentially least stable. I chose to check for updates from the Dev Channel, which is a little more stable than Canary build. It fixed the problem and seems to work fine.

To change the version, Check for Updates, then click the Updates link on the popup that says you already have the latest version.

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

For an alternative cryptography library, have a look at Bouncy Castle. It has AES and a lot of added functionality. It's a liberal open source library. You will have to use the lightweight, proprietary Bouncy Castle API for this to work though.

Sending GET request with Authentication headers using restTemplate

A simple solution would be to configure static http headers needed for all calls in the bean configuration of the RestTemplate:

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate getRestTemplate(@Value("${did-service.bearer-token}") String bearerToken) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add((request, body, clientHttpRequestExecution) -> {
            HttpHeaders headers = request.getHeaders();
            if (!headers.containsKey("Authorization")) {
                String token = bearerToken.toLowerCase().startsWith("bearer") ? bearerToken : "Bearer " + bearerToken;
                request.getHeaders().add("Authorization", token);
            }
            return clientHttpRequestExecution.execute(request, body);
        });
        return restTemplate;
    }
}

A Space between Inline-Block List Items

Solution:

ul {
    font-size: 0;
}

ul li {
    font-size: 14px;
    display: inline-block;
}

You must set parent font size to 0

What is the main purpose of setTag() getTag() methods of View?

We can use setTag() and getTag() to set and get custom objects as per our requirement. The setTag() method takes an argument of type Object, and getTag() returns an Object.

For example,

Person p = new Person();
p.setName("Ramkailash");
p.setId(2000001);
button1.setTag(p);

Char Comparison in C

In C the char type has a numeric value so the > operator will work just fine for example

#include <stdio.h>
main() {

    char a='z';

    char b='h';

    if ( a > b ) {
        printf("%c greater than %c\n",a,b);
    }
}

CSS override rules and specificity

The important needs to be inside the ;

td.rule2 div {     background-color: #ffff00 !important; } 

in fact i believe this should override it

td.rule2 { background-color: #ffff00 !important; } 

How to append in a json file in Python?

Assuming you have a test.json file with the following content:

{"67790": {"1": {"kwh": 319.4}}}

Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

import json

a_dict = {'new_key': 'new_value'}

with open('test.json') as f:
    data = json.load(f)

data.update(a_dict)

with open('test.json', 'w') as f:
    json.dump(data, f)

Then, in test.json, you'll have:

{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}

Hope this is what you wanted.

document.getElementById().value and document.getElementById().checked not working for IE

Have a look at jQuery, a cross-browser library that will make your life a lot easier.

var msg = 'abc';
$('#msg').val(msg);
$('#sp_100').attr('checked', 'checked');

Rails 4: how to use $(document).ready() with turbo-links

I found my functions doubled when using a function for ready and turbolinks:load so I used,

var ready = function() {
  // you code goes here
}

if (Turbolinks.supported == false) {
  $(document).on('ready', ready);
};
if (Turbolinks.supported == true) {
  $(document).on('turbolinks:load', ready);
};

That way your functions don't double if turbolinks is supported!

Open Jquery modal dialog on click event

May be helpful... :)

$(document).ready(function() {
    $('#buutonId').on('click', function() {
        $('#modalId').modal('open');
    });
});

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In my view page:

<p:dataTable  ...>
<p:column>
<p:commandLink actionListener="#{inquirySOController.viewDetail}" 
               process="@this" update=":mainform:dialog_content"
           oncomplete="dlg2.show()">
    <h:graphicImage library="images" name="view.png"/>
    <f:param name="trxNo" value="#{item.map['trxNo']}"/>
</p:commandLink>
</p:column>
</p:dataTable>

backing bean

 public void viewDetail(ActionEvent e) {

    String trxNo = getFacesContext().getRequestParameterMap().get("trxNo");

    for (DTO item : list) {
        if (item.get("trxNo").toString().equals(trxNo)) {
            System.out.println(trxNo);
            setSelectedItem(item);
            break;
        }
    }
}

How can I remove the string "\n" from within a Ruby string?

When you want to remove a string, rather than replace it you can use String#delete (or its mutator equivalent String#delete!), e.g.:

x = "foo\nfoo"
x.delete!("\n")

x now equals "foofoo"

In this specific case String#delete is more readable than gsub since you are not actually replacing the string with anything.

Wait until all jQuery Ajax requests are done?

javascript is event-based, so you should never wait, rather set hooks/callbacks

You can probably just use the success/complete methods of jquery.ajax

Or you could use .ajaxComplete :

$('.log').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxComplete handler.');
    //and you can do whatever other processing here, including calling another function...
  }
});

though youy should post a pseudocode of how your(s) ajax request(s) is(are) called to be more precise...

How to center a (background) image within a div?

This works for me :

<style>
   .WidgetBody
        {   
            background: #F0F0F0;
            background-image:url('images/mini-loader.gif');
            background-position: 50% 50%;            
            background-repeat:no-repeat;            
        }
</style>        

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

This will work, Try this -

<input id="textField1" onfocus="this.select()" onmouseup="return false" /> 

Works in Safari/IE 9 and Chrome, I did not get a chance to test in Firefox though.

How to get all Windows service names starting with a common word?

Using PowerShell, you can use the following

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name

This will show a list off all services which displayname starts with "NATION-".

You can also directly stop or start the services;

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service

or simply

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service

Count number of occurences for each unique value

You can try also a tidyverse

library(tidyverse) 
dummyData %>% 
    as.tibble() %>% 
    count(value)
# A tibble: 2 x 2
  value     n
  <dbl> <int>
1     1    25
2     2    75

Good tutorial for using HTML5 History API (Pushstate?)

For a great tutorial the Mozilla Developer Network page on this functionality is all you'll need: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

Unfortunately, the HTML5 History API is implemented differently in all the HTML5 browsers (making it inconsistent and buggy) and has no fallback for HTML4 browsers. Fortunately, History.js provides cross-compatibility for the HTML5 browsers (ensuring all the HTML5 browsers work as expected) and optionally provides a hash-fallback for HTML4 browsers (including maintained support for data, titles, pushState and replaceState functionality).

You can read more about History.js here: https://github.com/browserstate/history.js

For an article about Hashbangs VS Hashes VS HTML5 History API, see here: https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling

What is the best way to merge mp3 files?

The time problem has to do with the ID3 headers of the MP3 files, which is something your method isn't taking into account as the entire file is copied.

Do you have a language of choice that you want to use or doesn't it matter? That will affect what libraries are available that support the operations you want.

Difference between "managed" and "unmanaged"

Managed Code

Managed code is what Visual Basic .NET and C# compilers create. It runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. So, think of it as, "My code is managed by the CLR."

Visual Basic and C# can only produce managed code, so, if you're writing an application in one of those languages you are writing an application managed by the CLR. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it's optional.

Unmanaged Code

Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.

No free memory management or anything else the CLR provides.

Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

Mixing the two

Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application. This blurs the line between the two and complicates the definition, but it's worth mentioning just so you know that you can still have memory leaks if, for example, you're using a third party library with some badly written unmanaged code.

Here's an example I found by googling:

#using <mscorlib.dll>
using namespace System;

#include "stdio.h"

void ManagedFunction()
{
    printf("Hello, I'm managed in this section\n");
}

#pragma unmanaged
UnmanagedFunction()
{
    printf("Hello, I am unmanaged through the wonder of IJW!\n");
    ManagedFunction();
}

#pragma managed
int main()
{
    UnmanagedFunction();
    return 0;
}

Excel VBA Run-time Error '32809' - Trying to Understand it

I exported the VBA Module - resaved the file, then imported the module again and all is well

How to determine the number of days in a month in SQL Server?

I upvoted Mehrdad, but this works as well. :)

CREATE function dbo.IsLeapYear
(
    @TestYear int
)
RETURNS bit
AS
BEGIN
    declare @Result bit
    set @Result = 
    cast(
        case when ((@TestYear % 4 = 0) and (@testYear % 100 != 0)) or (@TestYear % 400 = 0)
        then 1
        else 0
        end
    as bit )
    return @Result
END
GO

CREATE FUNCTION dbo.GetDaysInMonth
(
    @TestDT datetime
)
RETURNS INT
AS
BEGIN

    DECLARE @Result int 
    DECLARE @MonthNo int

    Set @MonthNo = datepart(m,@TestDT)

    Set @Result = 
    case @MonthNo
        when  1 then 31
        when  2 then 
            case 
                when dbo.IsLeapYear(datepart(yyyy,@TestDT)) = 0
                then 28
                else 29
            end
        when  3 then 31
        when  4 then 30
        when  5 then 31
        when  6 then 30
        when  7 then 31
        when  8 then 31
        when  9 then 30 
        when 10 then 31
        when 11 then 30 
        when 12 then 31
    end

    RETURN @Result
END
GO

To Test

declare @testDT datetime;

set @testDT = '2404-feb-15';

select dbo.GetDaysInMonth(@testDT)

What is the difference between XML and XSD?

XML versus XSD

XML defines the syntax of elements and attributes for structuring data in a well-formed document.

XSD (aka XML Schema), like DTD before, powers the eXtensibility in XML by enabling the user to define the vocabulary and grammar of the elements and attributes in a valid XML document.

How to change screen resolution of Raspberry Pi

TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the

resolution 82   1920x1080   60Hz    1080p

hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1

How to ALTER multiple columns at once in SQL Server

We can alter multiple columns in a single query like this:

ALTER TABLE `tblcommodityOHLC`
    CHANGE COLUMN `updated_on` `updated_on` DATETIME NULL DEFAULT NULL AFTER `updated_by`,
    CHANGE COLUMN `delivery_datetime` `delivery_datetime` DATETIME NULL DEFAULT CURRENT_TIMESTAMP AFTER `delivery_status`;

Just give the queries as comma separated.

Correct Way to Load Assembly, Find Class and Call Run() Method

I'm doing exactly what you're looking for in my rules engine, which uses CS-Script for dynamically compiling, loading, and running C#. It should be easily translatable into what you're looking for, and I'll give an example. First, the code (stripped-down):

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using CSScriptLibrary;

namespace RulesEngine
{
    /// <summary>
    /// Make sure <typeparamref name="T"/> is an interface, not just any type of class.
    /// 
    /// Should be enforced by the compiler, but just in case it's not, here's your warning.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RulesEngine<T> where T : class
    {
        public RulesEngine(string rulesScriptFileName, string classToInstantiate)
            : this()
        {
            if (rulesScriptFileName == null) throw new ArgumentNullException("rulesScriptFileName");
            if (classToInstantiate == null) throw new ArgumentNullException("classToInstantiate");

            if (!File.Exists(rulesScriptFileName))
            {
                throw new FileNotFoundException("Unable to find rules script", rulesScriptFileName);
            }

            RulesScriptFileName = rulesScriptFileName;
            ClassToInstantiate = classToInstantiate;

            LoadRules();
        }

        public T @Interface;

        public string RulesScriptFileName { get; private set; }
        public string ClassToInstantiate { get; private set; }
        public DateTime RulesLastModified { get; private set; }

        private RulesEngine()
        {
            @Interface = null;
        }

        private void LoadRules()
        {
            if (!File.Exists(RulesScriptFileName))
            {
                throw new FileNotFoundException("Unable to find rules script", RulesScriptFileName);
            }

            FileInfo file = new FileInfo(RulesScriptFileName);

            DateTime lastModified = file.LastWriteTime;

            if (lastModified == RulesLastModified)
            {
                // No need to load the same rules twice.
                return;
            }

            string rulesScript = File.ReadAllText(RulesScriptFileName);

            Assembly compiledAssembly = CSScript.LoadCode(rulesScript, null, true);

            @Interface = compiledAssembly.CreateInstance(ClassToInstantiate).AlignToInterface<T>();

            RulesLastModified = lastModified;
        }
    }
}

This will take an interface of type T, compile a .cs file into an assembly, instantiate a class of a given type, and align that instantiated class to the T interface. Basically, you just have to make sure the instantiated class implements that interface. I use properties to setup and access everything, like so:

private RulesEngine<IRulesEngine> rulesEngine;

public RulesEngine<IRulesEngine> RulesEngine
{
    get
    {
        if (null == rulesEngine)
        {
            string rulesPath = Path.Combine(Application.StartupPath, "Rules.cs");

            rulesEngine = new RulesEngine<IRulesEngine>(rulesPath, typeof(Rules).FullName);
        }

        return rulesEngine;
    }
}

public IRulesEngine RulesEngineInterface
{
    get { return RulesEngine.Interface; }
}

For your example, you want to call Run(), so I'd make an interface that defines the Run() method, like this:

public interface ITestRunner
{
    void Run();
}

Then make a class that implements it, like this:

public class TestRunner : ITestRunner
{
    public void Run()
    {
        // implementation goes here
    }
}

Change the name of RulesEngine to something like TestHarness, and set your properties:

private TestHarness<ITestRunner> testHarness;

public TestHarness<ITestRunner> TestHarness
{
    get
    {
        if (null == testHarness)
        {
            string sourcePath = Path.Combine(Application.StartupPath, "TestRunner.cs");

            testHarness = new TestHarness<ITestRunner>(sourcePath , typeof(TestRunner).FullName);
        }

        return testHarness;
    }
}

public ITestRunner TestHarnessInterface
{
    get { return TestHarness.Interface; }
}

Then, anywhere you want to call it, you can just run:

ITestRunner testRunner = TestHarnessInterface;

if (null != testRunner)
{
    testRunner.Run();
}

It would probably work great for a plugin system, but my code as-is is limited to loading and running one file, since all of our rules are in one C# source file. I would think it'd be pretty easy to modify it to just pass in the type/source file for each one you wanted to run, though. You'd just have to move the code from the getter into a method that took those two parameters.

Also, use your IRunnable in place of ITestRunner.

Creating random colour in Java?

A one-liner for random RGB values:

new Color((int)(Math.random() * 0x1000000))

Adding :default => true to boolean in existing Rails column

change_column :things, :price_1, :integer, default: 123, null: false

Seems to be best way to add a default to an existing column that doesn't have null: false already.

Otherwise:

change_column :things, :price_1, :integer, default: 123

Some research I did on this:

https://gist.github.com/Dorian/417b9a0e1a4e09a558c39345d50c8c3b

Use superscripts in R axis labels

@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -

plot(rnorm(30), xlab = expression('4'^th*'moment'))

getActivity() returns null in Fragment function

PJL is right. I have used his suggestion and this is what i have done:

  1. defined global variables for fragment:

    private final Object attachingActivityLock = new Object();

    private boolean syncVariable = false;

  2. implemented

@Override
public void onAttach(Activity activity) {
  super.onAttach(activity);
  synchronized (attachingActivityLock) {
      syncVariable = true;
      attachingActivityLock.notifyAll();
  }
}

3 . I wrapped up my function, where I need to call getActivity(), in thread, because if it would run on main thread, i would block the thread with the step 4. and onAttach() would never be called.

    Thread processImage = new Thread(new Runnable() {

        @Override
        public void run() {
            processImage();
        }
    });
    processImage.start();

4 . in my function where I need to call getActivity(), I use this (before the call getActivity())

    synchronized (attachingActivityLock) {
        while(!syncVariable){
            try {
                attachingActivityLock.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

If you have some UI updates, remember to run them on UI thread. I need to update ImgeView so I did:

image.post(new Runnable() {

    @Override
    public void run() {
        image.setImageBitmap(imageToShow);
    }
});

How can I use Helvetica Neue Condensed Bold in CSS?

In case anyone is still looking for Helvetica Neue Condensed Bold, you essentially have two options.

  1. fonts.com: License the real font as a webfont from fonts.com. Free (with a badge), $10/month for 250k pageviews and $100/month for 2.5M pageviews. You can download the font to your desktop with the most expensive plan (but if you're on a Mac you already have it).
  2. myfonts.com / fontspring.com: Buy a pretty close alternative like Nimbus Sans Novus D from MyFont ($160 for unlimited pageviews), or Franklin Gothic FS Demi Condensed, from fontspring.com (about $21.95, flat one time fee with unlimited pageviews). In both cases you also get to download the font for your desktop so you can use it in Photoshop for comps.

A very cheap compromise is to buy Franklin from fontspring and then use "HelveticaNeue-CondensedBold" as the preferred font in your CSS.

h2 {"HelveticaNeue-CondensedBold", "FranklinGothicFSDemiCondensed", Arial, sans-serif;}

Then if a Mac user loads your site they see Helvetica Neue, but if they're on another platform they see Franklin.

UPDATE: I discovered a much closer match to Helvetica Neue Condensed Bold is Nimbus Sans Novus D Condensed bold. In fact, it is also derived from Helvetica. You can get it at MyFonts.com for $20 (desktop) and $20 (web, 10k pageviews). Web with unlimited pageviews is $160. I have used this font throughout (i.e. NOT exploiting the Mac's built in "NimbusSansNovusDBoldCondensed" at all) because it leads to a design that is more uniform across browsers. Built in HN and Nimbus Sans are very similar in all respects but point size. Nimbus needs a few extra points to get an identical size match.

Regex - Does not contain certain Characters

^[^<>]+$

The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

What is __stdcall?

The answers so far have covered the details, but if you don't intend to drop down to assembly, then all you have to know is that both the caller and the callee must use the same calling convention, otherwise you'll get bugs that are hard to find.

How do I get the full path to a Perl script that is executing?

Have you tried:

$ENV{'SCRIPT_NAME'}

or

use FindBin '$Bin';
print "The script is located in $Bin.\n";

It really depends on how it's being called and if it's CGI or being run from a normal shell, etc.

Image size (Python, OpenCV)

from this tutorial: https://www.tutorialkart.com/opencv/python/opencv-python-get-image-size/

import cv2

# read image
img = cv2.imread('/home/ubuntu/Walnut.jpg', cv2.IMREAD_UNCHANGED)

# get dimensions of image
dimensions = img.shape

# height, width, number of channels in image

height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]

from this other tutorial: https://www.pyimagesearch.com/2018/07/19/opencv-tutorial-a-guide-to-learn-opencv/

image = cv2.imread("jp.png")

(h, w, d) = image.shape

Please double check things before posting answers.

Is it a good practice to place C++ definitions in header files?

I think your co-worker is right as long as he does not enter in the process to write executable code in the header. The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.

By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.

Aligning two divs side-by-side

The HTML code is for three div align side by side and can be used for two also by some changes

<div id="wrapper">
  <div id="first">first</div>
  <div id="second">second</div>
  <div id="third">third</div>
</div>

The CSS will be

#wrapper {
  display:table;
  width:100%;
}
#row {
  display:table-row;
}
#first {
  display:table-cell;
  background-color:red;
  width:33%;
}
#second {
  display:table-cell;
  background-color:blue;
  width:33%;
}
#third {
  display:table-cell;
  background-color:#bada55;
  width:34%;
}

This code will workup towards responsive layout as it will resize the

<div> 

according to device width. Even one can silent anyone

<div>

as

<!--<div id="third">third</div> --> 

and can use rest two for two

<div> 

side by side.

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

I think we should sent in this format

var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});

Its already mentioned in Pass array to mvc Action via AJAX

It worked for me

Is there a “not in” operator in JavaScript for checking object properties?

Two quick possibilities:

if(!('foo' in myObj)) { ... }

or

if(myObj['foo'] === undefined) { ... }

Comments in .gitignore?

Do git help gitignore

You will get the help page with following line:

A line starting with # serves as a comment.

PowerShell The term is not recognized as cmdlet function script file or operable program

For the benefit of searchers, there is another way you can produce this error message - by missing the $ off the script block name when calling it.

e.g. I had a script block like so:

$qa = {
    param($question, $answer)
    Write-Host "Question = $question, Answer = $answer"
}

I tried calling it using:

&qa -question "Do you like powershell?" -answer "Yes!"

But that errored. The correct way was:

&$qa -question "Do you like powershell?" -answer "Yes!"

PHP Get name of current directory

getcwd();

or

dirname(__FILE__);

or (PHP5)

basename(__DIR__) 

http://php.net/manual/en/function.getcwd.php

http://php.net/manual/en/function.dirname.php

You can use basename() to get the trailing part of the path :)

In your case, I'd say you are most likely looking to use getcwd(), dirname(__FILE__) is more useful when you have a file that needs to include another library and is included in another library.

Eg:

main.php
libs/common.php
libs/images/editor.php

In your common.php you need to use functions in editor.php, so you use

common.php:

require_once dirname(__FILE__) . '/images/editor.php';

main.php:

require_once libs/common.php

That way when common.php is require'd in main.php, the call of require_once in common.php will correctly includes editor.php in images/editor.php instead of trying to look in current directory where main.php is run.

Validating input using java.util.Scanner

If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here: http://java.sun.com/developer/technicalArticles/releases/1.4regex/

Otherwise, to parse an int from a string, try Integer.parseInt(string). If the string is not a number, you will get an exception. Otherise you can then perform your checks on that value to make sure it is not negative.

String input;
int number;
try
{
    number = Integer.parseInt(input);
    if(number > 0)
    {
        System.out.println("You positive number is " + number);
    }
} catch (NumberFormatException ex)
{
     System.out.println("That is not a positive number!");
}

To get a character-only string, you would probably be better of looping over each character checking for digits, using for instance Character.isLetter(char).

String input
for(int i = 0; i<input.length(); i++)
{
   if(!Character.isLetter(input.charAt(i)))
   {
      System.out.println("This string does not contain only letters!");
      break;
   }
}

Good luck!

Import an existing git project into GitLab?

rake gitlab:import:repos might be a more suitable method for mass importing:

  • copy the bare repository under repos_path (/home/git/repositories/group/repo.git). Directory name must end in .git and be under a group or user namespace.
  • run bundle exec rake gitlab:import:repos

The owner will the first admin, and a group will get created if not already existent.

See also: How to import an existing bare git repository into Gitlab?

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

There's a bit of confusion in your question:

  • a Date datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE into a Date.
  • When you want to display a date, either on screen or to send it to another system via a character API (XML, file...), you use the TO_CHAR function. In Oracle, a Date has no format: it is a point in time.
  • Reciprocally, you would use TO_TIMESTAMP_TZ to convert a VARCHAR2 to a TIMESTAMP, but this won't convert a Date to a TIMESTAMP.
  • You use FROM_TZ to add the time zone information to a TIMESTAMP (or a Date).
  • In Oracle, CST is a time zone but CDT is not. CDT is a daylight saving information.
  • To complicate things further, CST/CDT (-05:00) and CST/CST (-06:00) will have different values obviously, but the time zone CST will inherit the daylight saving information depending upon the date by default.

So your conversion may not be as simple as it looks.

Assuming that you want to convert a Date d that you know is valid at time zone CST/CST to the equivalent at time zone CST/CDT, you would use:

SQL> SELECT from_tz(d, '-06:00') initial_ts,
  2         from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
  3    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  4                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  5            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00

My default timestamp format has been used here. I can specify a format explicitely:

SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
  2         to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
  3                 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
  4    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  5                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  6            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00      2012-10-09 02:10:21 -05:00

What is the purpose of a plus symbol before a variable?

Operator + is a unary operator which converts value to number. Below I prepared a table with corresponding results of using this operator for different values.

+-----------------------------+-----------+
| Value                       | + (Value) |
+-----------------------------+-----------+
| 1                           | 1         |
| '-1'                        | -1        |
| '3.14'                      | 3.14      |
| '3'                         | 3         |
| '0xAA'                      | 170       |
| true                        | 1         |
| false                       | 0         |
| null                        | 0         |
| 'Infinity'                  | Infinity  |
| 'infinity'                  | NaN       |
| '10a'                       | NaN       |
| undefined                   | Nan       |
| ['Apple']                   | Nan       |
| function(val){ return val } | NaN       |
+-----------------------------+-----------+

Operator + returns value for objects which have implemented method valueOf.

let something = {
    valueOf: function () {
        return 25;
    }
};

console.log(+something);

Adding line break in C# Code behind page

Strings are immutable, so using

public string GenerateString()
{
    return
        "abc" +
        "def";
}

will slow you performance - each of those values is a string literal which must be concatenated at runtime - bad news if you reuse the method/property/whatever alot...

Store your string literals in resources is a good idea...

public string GenerateString()
{
    return Resources.MyString;
}

That way it is localisable and the code is tidy (although performance is pretty terrible).

Chart.js v2 - hiding grid lines

If you want to hide gridlines but want to show yAxes, you can set:

yAxes: [{...
         gridLines: {
                        drawBorder: true,
                        display: false
                    }
       }]

Fastest way to write huge data in text file Java

You might try removing the BufferedWriter and just using the FileWriter directly. On a modern system there's a good chance you're just writing to the drive's cache memory anyway.

It takes me in the range of 4-5 seconds to write 175MB (4 million strings) -- this is on a dual-core 2.4GHz Dell running Windows XP with an 80GB, 7200-RPM Hitachi disk.

Can you isolate how much of the time is record retrieval and how much is file writing?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

public class FileWritingPerfTest {
    

private static final int ITERATIONS = 5;
private static final double MEG = (Math.pow(1024, 2));
private static final int RECORD_COUNT = 4000000;
private static final String RECORD = "Help I am trapped in a fortune cookie factory\n";
private static final int RECSIZE = RECORD.getBytes().length;

public static void main(String[] args) throws Exception {
    List<String> records = new ArrayList<String>(RECORD_COUNT);
    int size = 0;
    for (int i = 0; i < RECORD_COUNT; i++) {
        records.add(RECORD);
        size += RECSIZE;
    }
    System.out.println(records.size() + " 'records'");
    System.out.println(size / MEG + " MB");
    
    for (int i = 0; i < ITERATIONS; i++) {
        System.out.println("\nIteration " + i);
        
        writeRaw(records);
        writeBuffered(records, 8192);
        writeBuffered(records, (int) MEG);
        writeBuffered(records, 4 * (int) MEG);
    }
}

private static void writeRaw(List<String> records) throws IOException {
    File file = File.createTempFile("foo", ".txt");
    try {
        FileWriter writer = new FileWriter(file);
        System.out.print("Writing raw... ");
        write(records, writer);
    } finally {
        // comment this out if you want to inspect the files afterward
        file.delete();
    }
}

private static void writeBuffered(List<String> records, int bufSize) throws IOException {
    File file = File.createTempFile("foo", ".txt");
    try {
        FileWriter writer = new FileWriter(file);
        BufferedWriter bufferedWriter = new BufferedWriter(writer, bufSize);
    
        System.out.print("Writing buffered (buffer size: " + bufSize + ")... ");
        write(records, bufferedWriter);
    } finally {
        // comment this out if you want to inspect the files afterward
        file.delete();
    }
}

private static void write(List<String> records, Writer writer) throws IOException {
    long start = System.currentTimeMillis();
    for (String record: records) {
        writer.write(record);
    }
    // writer.flush(); // close() should take care of this
    writer.close(); 
    long end = System.currentTimeMillis();
    System.out.println((end - start) / 1000f + " seconds");
}
}

'Field required a bean of type that could not be found.' error spring restful API using mongodb

I also had the same error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field repository in com.kalsym.next.gen.campaign.controller.CampaignController required a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' that could not be found.


Action:

Consider defining a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' in your configuration.de here

And my packages were constructed in the same way as mentioned in the accepted answer. I fixed my issue by adding EnableMongoRepositories annotation in the main class like this:

@SpringBootApplication
@EnableMongoRepositories(basePackageClasses = CustomerRepository.class)
public class CampaignAPI {

    public static void main(String[] args) {
        SpringApplication.run(CampaignAPI.class, args);
    }
}

If you need to add multiple don't forget the curly braces:

@EnableMongoRepositories(basePackageClasses
    = {
        MSASMSRepository.class, APartyMappingRepository.class
    })

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

You could use find along with the -exec flag in a single command line to do the job

find . -name "*.zip" -exec unzip {} \;

Show/hide widgets in Flutter programmatically

UPDATE: Since this answer was written, Visibility was introduced and provides the best solution to this problem.


You can use Opacity with an opacity: of 0.0 to draw make an element hidden but still occupy space.

To make it not occupy space, replace it with an empty Container().

EDIT: To wrap it in an Opacity object, do the following:

            new Opacity(opacity: 0.0, child: new Padding(
              padding: const EdgeInsets.only(
                left: 16.0,
              ),
              child: new Icon(pencil, color: CupertinoColors.activeBlue),
            ))

Google Developers quick tutorial on Opacity: https://youtu.be/9hltevOHQBw

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

Android translate animation - permanently move View to new position using AnimationListener

This is what worked for me perfectly:-

// slide the view from its current position to below itself
public void slideUp(final View view, final View llDomestic){

    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",0f);
    animation.setDuration(100);
    llDomestic.setVisibility(View.GONE);
    animation.start();

}

// slide the view from below itself to the current position
public void slideDown(View view,View llDomestic){
    llDomestic.setVisibility(View.VISIBLE);
    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",   0f);
    animation.setDuration(100);
    animation.start();
}

llDomestic : The view which you want to hide. view: The view which you want to move down or up.

PHP - Indirect modification of overloaded property

This is occurring due to how PHP treats overloaded properties in that they are not modifiable or passed by reference.

See the manual for more information regarding overloading.

To work around this problem you can either use a __set function or create a createObject method.

Below is a __get and __set that provides a workaround to a similar situation to yours, you can simply modify the __set to suite your needs.

Note the __get never actually returns a variable. and rather once you have set a variable in your object it no longer is overloaded.

/**
 * Get a variable in the event.
 *
 * @param  mixed  $key  Variable name.
 *
 * @return  mixed|null
 */
public function __get($key)
{
    throw new \LogicException(sprintf(
        "Call to undefined event property %s",
        $key
    ));
}

/**
 * Set a variable in the event.
 *
 * @param  string  $key  Name of variable
 *
 * @param  mixed  $value  Value to variable
 *
 * @return  boolean  True
 */
public function __set($key, $value)
{
    if (stripos($key, '_') === 0 && isset($this->$key)) {
        throw new \LogicException(sprintf(
            "%s is a read-only event property", 
            $key
        ));
    }
    $this->$key = $value;
    return true;
}

Which will allow for:

$object = new obj();
$object->a = array();
$object->a[] = "b";
$object->v = new obj();
$object->v->a = "b";

Convert iterator to pointer?

If your function really takes vector<int> * (a pointer to vector), then you should pass &foo since that will be a pointer to the vector. Obviously that will not simply solve your problem, but you cannot directly convert an iterator to a vector, since the memory at the address of the iterator will not directly address a valid vector.

You can construct a new vector by calling the vector constructor:

template <class InputIterator> vector(InputIterator, InputIterator)

This constructs a new vector by copying the elements between the two iterators. You would use it roughly like this:

bar(std::vector<int>(foo.begin()+1, foo.end());

Twitter Bootstrap 3, vertically center content

You can use display:inline-block instead of float and vertical-align:middle with this CSS:

.col-lg-4, .col-lg-8 {
    float:none;
    display:inline-block;
    vertical-align:middle;
    margin-right:-4px;
}

The demo http://bootply.com/94402