Programs & Examples On #Vt100

The VT100 is a video terminal that was made by Digital Equipment Corporation (DEC). Its detailed attributes became the de facto standard for terminal emulators to emulate.

How to send a correct authorization header for basic authentication

Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding and http://en.wikipedia.org/wiki/Basic_access_authentication , here is how to do Basic auth with a header instead of putting the username and password in the URL. Note that this still doesn't hide the username or password from anyone with access to the network or this JS code (e.g. a user executing it in a browser):

$.ajax({
  type: 'POST',
  url: http://theappurl.com/api/v1/method/,
  data: {},
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(unescape(encodeURIComponent(YOUR_USERNAME + ':' + YOUR_PASSWORD))))
  }
});

MySQL limit from descending order

Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:

select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc

Embed HTML5 YouTube video without iframe?

Here is a example of embedding without an iFrame:

_x000D_
_x000D_
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
  <embed
    src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
    wmode="transparent"
    type="video/mp4"
    width="100%" height="100%"
    allow="autoplay; encrypted-media; picture-in-picture"
    allowfullscreen
    title="Keyboard Cat"
  >
</div>
_x000D_
_x000D_
_x000D_

compare to regular iframe "embed" code from YouTube:

_x000D_
_x000D_
<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen>
</iframe>
_x000D_
_x000D_
_x000D_

and as far as HTML5 goes, use <object> tag like so (corrected):

_x000D_
_x000D_
<object
  style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
  data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
_x000D_
_x000D_

Short description of the scoping rules?

The Python name resolution only knows the following kinds of scope:

  1. builtins scope which provides the Builtin Functions, such as print, int, or zip,
  2. module global scope which is always the top-level of the current module,
  3. three user-defined scopes that can be nested into each other, namely
    1. function closure scope, from any enclosing def block, lambda expression or comprehension.
    2. function local scope, inside a def block, lambda expression or comprehension,
    3. class scope, inside a class block.

Notably, other constructs such as if, for, or with statements do not have their own scope.

The scoping TLDR: The lookup of a name begins at the scope in which the name is used, then any enclosing scopes (excluding class scopes), to the module globals, and finally the builtins – the first match in this search order is used. The assignment to a scope is by default to the current scope – the special forms nonlocal and global must be used to assign to a name from an outer scope.

Finally, comprehensions and generator expressions as well as := asignment expressions have one special rule when combined.


Nested Scopes and Name Resolution

These different scopes build a hierarchy, with builtins then global always forming the base, and closures, locals and class scope being nested as lexically defined. That is, only the nesting in the source code matters, not for example the call stack.

print("builtins are available without definition")

some_global = "1"  # global variables are at module scope

def outer_function():
    some_closure = "3.1"  # locals and closure are defined the same, at function scope
    some_local = "3.2"    # a variable becomes a closure if a nested scope uses it

    class InnerClass:
         some_classvar = "3.3"   # class variables exist *only* at class scope

         def nested_function(self):
             some_local = "3.2"   # locals can replace outer names
             print(some_closure)  # closures are always readable
    return InnerClass

Even though class creates a scope and may have nested classes, functions and comprehensions, the names of the class scope are not visible to enclosed scopes. This creates the following hierarchy:

? builtins           [print, ...]
??? globals            [some_global]
  ??? outer_function     [some_local, some_closure]
    ??? InnerClass         [some_classvar]
    ??? inner_function     [some_local]

Name resolution always starts at the current scope in which a name is accessed, then goes up the hierarchy until a match is found. For example, looking up some_local inside outer_function and inner_function starts at the respective function - and immediately finds the some_local defined in outer_function and inner_function, respectively. When a name is not local, it is fetched from the nearest enclosing scope that defines it – looking up some_closure and print inside inner_function searches until outer_function and builtins, respectively.


Scope Declarations and Name Binding

By default, a name belongs to any scope in which it is bound to a value. Binding the same name again in an inner scope creates a new variable with the same name - for example, some_local exists separately in both outer_function and inner_function. As far as scoping is concerned, binding includes any statement that sets the value of a name – assignment statements, but also the iteration variable of a for loop, or the name of a with context manager. Notably, del also counts as name binding.

When a name must refer to an outer variable and be bound in an inner scope, the name must be declared as not local. Separate declarations exists for the different kinds of enclosing scopes: nonlocal always refers to the nearest closure, and global always refers to a global name. Notably, nonlocal never refers to a global name and global ignores all closures of the same name. There is no declaration to refer to the builtin scope.


some_global = "1"

def outer_function():
    some_closure = "3.2"
    some_global = "this is ignored by a nested global declaration"
    
    def inner_function():
        global some_global     # declare variable from global scope
        nonlocal some_closure  # declare variable from enclosing scope
        message = " bound by an inner scope"
        some_global = some_global + message
        some_closure = some_closure + message
    return inner_function

Of note is that function local and nonlocal are resolved at compile time. A nonlocal name must exist in some outer scope. In contrast, a global name can be defined dynamically and may be added or removed from the global scope at any time.


Comprehensions and Assignment Expressions

The scoping rules of list, set and dict comprehensions and generator expressions are almost the same as for functions. Likewise, the scoping rules for assignment expressions are almost the same as for regular name binding.

The scope of comprehensions and generator expressions is of the same kind as function scope. All names bound in the scope, namely the iteration variables, are locals or closures to the comprehensions/generator and nested scopes. All names, including iterables, are resolved using name resolution as applicable inside functions.

some_global = "global"

def outer_function():
    some_closure = "closure"
    return [            # new function-like scope started by comprehension
        comp_local      # names resolved using regular name resolution
        for comp_local  # iteration targets are local
        in "iterable"
        if comp_local in some_global and comp_local in some_global
    ]

An := assignment expression works on the nearest function, class or global scope. Notably, if the target of an assignment expression has been declared nonlocal or global in the nearest scope, the assignment expression honors this like a regular assignment.

print(some_global := "global")

def outer_function():
    print(some_closure := "closure")

However, an assignment expression inside a comprehension/generator works on the nearest enclosing scope of the comprehension/generator, not the scope of the comprehension/generator itself. When several comprehensions/generators are nested, the nearest function or global scope is used. Since the comprehension/generator scope can read closures and global variables, the assignment variable is readable in the comprehension as well. Assigning from a comprehension to a class scope is not valid.

print(some_global := "global")

def outer_function():
    print(some_closure := "closure")
    steps = [
        # v write to variable in containing scope
        (some_closure := some_closure + comp_local)
        #                 ^ read from variable in containing scope
        for comp_local in some_global
    ]
    return some_closure, steps

While the iteration variable is local to the comprehension in which it is bound, the target of the assignment expression does not create a local variable and is read from the outer scope:

? builtins           [print, ...]
??? globals            [some_global]
  ??? outer_function     [some_closure]
    ??? <listcomp>         [comp_local]

How to read values from the querystring with ASP.NET Core?

I have a better solution for this problem,

  • request is a member of abstract class ControllerBase
  • GetSearchParams() is an extension method created in bellow helper class.

var searchparams = await Request.GetSearchParams();

I have created a static class with few extension methods

public static class HttpRequestExtension
{
  public static async Task<SearchParams> GetSearchParams(this HttpRequest request)
        {
            var parameters = await request.TupledParameters();

            try
            {
                for (var i = 0; i < parameters.Count; i++)
                {
                    if (parameters[i].Item1 == "_count" && parameters[i].Item2 == "0")
                    {
                        parameters[i] = new Tuple<string, string>("_summary", "count");
                    }
                }
                var searchCommand = SearchParams.FromUriParamList(parameters);
                return searchCommand;
            }
            catch (FormatException formatException)
            {
                throw new FhirException(formatException.Message, OperationOutcome.IssueType.Invalid, OperationOutcome.IssueSeverity.Fatal, HttpStatusCode.BadRequest);
            }
        }



public static async Task<List<Tuple<string, string>>> TupledParameters(this HttpRequest request)
{
        var list = new List<Tuple<string, string>>();


        var query = request.Query;
        foreach (var pair in query)
        {
            list.Add(new Tuple<string, string>(pair.Key, pair.Value));
        }

        if (!request.HasFormContentType)
        {
            return list;
        }
        var getContent = await request.ReadFormAsync();

        if (getContent == null)
        {
            return list;
        }
        foreach (var key in getContent.Keys)
        {
            if (!getContent.TryGetValue(key, out StringValues values))
            {
                continue;
            }
            foreach (var value in values)
            {
                list.Add(new Tuple<string, string>(key, value));
            }
        }
        return list;
    }
}

in this way you can easily access all your search parameters. I hope this will help many developers :)

Ruby send JSON request

The net/http api can be tough to use.

require "net/http"

uri = URI.parse(uri)

Net::HTTP.new(uri.host, uri.port).start do |client|
  request                 = Net::HTTP::Post.new(uri.path)
  request.body            = "{}"
  request["Content-Type"] = "application/json"
  client.request(request)
end

Remove all files in a directory

This will get all files in a directory and remove them.

import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
dir = os.path.join(BASE_DIR, "foldername")

for root, dirs, files in os.walk(dir):
  for file in files:
    path = os.path.join(dir, file)
    os.remove(path)

ant build.xml file doesn't exist

may be you can specify where the buildfile is located and then invoke desired action.

Eg: ant -file {BuildfileLocation/build.xml} -v

Detect and exclude outliers in Pandas data frame

a full example with data and 2 groups follows:

Imports:

from StringIO import StringIO
import pandas as pd
#pandas config
pd.set_option('display.max_rows', 20)

Data example with 2 groups: G1:Group 1. G2: Group 2:

TESTDATA = StringIO("""G1;G2;Value
1;A;1.6
1;A;5.1
1;A;7.1
1;A;8.1

1;B;21.1
1;B;22.1
1;B;24.1
1;B;30.6

2;A;40.6
2;A;51.1
2;A;52.1
2;A;60.6

2;B;80.1
2;B;70.6
2;B;90.6
2;B;85.1
""")

Read text data to pandas dataframe:

df = pd.read_csv(TESTDATA, sep=";")

Define the outliers using standard deviations

stds = 1.0
outliers = df[['G1', 'G2', 'Value']].groupby(['G1','G2']).transform(
           lambda group: (group - group.mean()).abs().div(group.std())) > stds

Define filtered data values and the outliers:

dfv = df[outliers.Value == False]
dfo = df[outliers.Value == True]

Print the result:

print '\n'*5, 'All values with decimal 1 are non-outliers. In the other hand, all values with 6 in the decimal are.'
print '\nDef DATA:\n%s\n\nFiltred Values with %s stds:\n%s\n\nOutliers:\n%s' %(df, stds, dfv, dfo)

CSS: fixed position on x-axis but not y?

Updated the script to check the start position:

function float_horizontal_scroll(id) {
var el = jQuery(id);
var isLeft = el.css('left') !== 'auto';
var start =((isLeft ? el.css('left') : el.css('right')).replace("px", ""));
jQuery(window).scroll(function () {
    var leftScroll = jQuery(this).scrollLeft();
    if (isLeft)
        el.css({ 'left': (start + leftScroll) + 'px' });
    else
        el.css({ 'right': (start - leftScroll) + 'px' });
});

}

How can you get the build/version number of your Android application?

private String GetAppVersion() {
    try {
        PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        return _info.versionName;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return "";
    }
}

private int GetVersionCode() {
    try {
        PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        return _info.versionCode;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return -1;
    }
}

What are the lengths of Location Coordinates, latitude and longitude?

Latitude maximum in total is: 9 (12.3456789), longitude 10 (123.4567890), they both have maximum 7 decimals chars (At least is what i can find in Google Maps),

For example, both columns in Rails and Postgresql looks something like this:

t.decimal :latitude, precision: 9, scale: 7
t.decimal :longitude, precision: 10, scale: 7

Smooth GPS data

This might come a little late...

I wrote this KalmanLocationManager for Android, which wraps the two most common location providers, Network and GPS, kalman-filters the data, and delivers updates to a LocationListener (like the two 'real' providers).

I use it mostly to "interpolate" between readings - to receive updates (position predictions) every 100 millis for instance (instead of the maximum gps rate of one second), which gives me a better frame rate when animating my position.

Actually, it uses three kalman filters, on for each dimension: latitude, longitude and altitude. They're independent, anyway.

This makes the matrix math much easier: instead of using one 6x6 state transition matrix, I use 3 different 2x2 matrices. Actually in the code, I don't use matrices at all. Solved all equations and all values are primitives (double).

The source code is working, and there's a demo activity. Sorry for the lack of javadoc in some places, I'll catch up.

C++ Fatal Error LNK1120: 1 unresolved externals

In my particular case, this error error was happening because the file which I've added wasn't referenced at .vcproj file.

Setting ANDROID_HOME enviromental variable on Mac OS X

To set ANDROID_HOME, variable, you need to know how you installed android dev setup.

If you don't know you can check if the following paths exist in your machine. Add the following to .bashrc, .zshrc, or .profile depending on what you use

If you installed with homebrew,

export ANDROID_HOME=/usr/local/opt/android-sdk

Check if this path exists:

If you installed android studio following the website,

export ANDROID_HOME=~/Library/Android/sdk

Finally add it to path:

export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

If you're too lazy to open an editor do this:

echo "export ANDROID_HOME=~/Library/Android/sdk" >> ~/.bashrc
echo "export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools" >> ~/.bashrc

Why does ++[[]][+[]]+[+[]] return the string "10"?

Step by steps of that, + turn value to a number and if you add to an empty array +[]...as it's empty and is equal to 0, it will

So from there, now look into your code, it's ++[[]][+[]]+[+[]]...

And there is plus between them ++[[]][+[]] + [+[]]

So these [+[]] will return [0] as they have an empty array which gets converted to 0 inside the other array...

So as imagine, the first value is a 2-dimensional array with one array inside... so [[]][+[]] will be equal to [[]][0] which will return []...

And at the end ++ convert it and increase it to 1...

So you can imagine, 1 + "0" will be "10"...

Why does return the string “10”?

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

Found other similar question, but not the answer.

It would have been interesting to know, where you have found this question.

As far as I can remember and according com.jcraft.jsch.JSchException: Auth cancel try to add to method .addIdentity() a passphrase. You can use "" in case you generated a keyfile without one. Another source of error is the fingerprint string. If it doesn't match you will get an authentication failure either (depends from on the target server).

And at last here my working source code - after I could solve the ugly administration tasks:

public void connect(String host, int port, 
                    String user, String pwd,
                    String privateKey, String fingerPrint,
                    String passPhrase
                  ) throws JSchException{
    JSch jsch = new JSch();

    String absoluteFilePathPrivatekey = "./";
    File tmpFileObject = new File(privateKey);
    if (tmpFileObject.exists() && tmpFileObject.isFile())
    {
      absoluteFilePathPrivatekey = tmpFileObject.getAbsolutePath();
    }

    jsch.addIdentity(absoluteFilePathPrivatekey, passPhrase);
    session = jsch.getSession(user, host, port);

    //Password and fingerprint will be given via UserInfo interface.
    UserInfo ui = new UserInfoImpl(pwd, fingerPrint);
    session.setUserInfo(ui);

    session.connect();

    Channel channel = session.openChannel("sftp");
    channel.connect();
    c = (ChannelSftp) channel;
}

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

While not elegant, works for me in certain situations.

Controller

if (RedirectToPage)
    return PartialView("JavascriptRedirect", new JavascriptRedirectModel("http://www.google.com"));
else
   ... return regular ajax partialview

Model

    public JavascriptRedirectModel(string location)
    {
        Location = location;
    }

    public string Location { get; set; }

/Views/Shared/JavascriptRedirect.cshtml

@model Models.Shared.JavascriptRedirectModel

<script type="text/javascript">
    window.location = '@Model.Location';
</script>

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

how to calculate binary search complexity

It doesn't half search time, that wouldn't make it log(n). It decreases it logarithmicly. Think about this for a moment. If you had 128 entries in a table and had to search linearly for your value, it would probably take around 64 entries on average to find your value. That's n/2 or linear time. With a binary search, you eliminate 1/2 the possible entries each iteration, such that at most it would only take 7 compares to find your value (log base 2 of 128 is 7 or 2 to the 7 power is 128.) This is the power of binary search.

Set active tab style with AngularJS

I can't remember where I found this method, but it's pretty simple and works well.

HTML:

<nav role="navigation">
    <ul>
        <li ui-sref-active="selected" class="inactive"><a ui-sref="tab-01">Tab 01</a></li> 
        <li ui-sref-active="selected" class="inactive"><a ui-sref="tab-02">Tab 02</a></li>
    </ul>
</nav>

CSS:

  .selected {
    background-color: $white;
    color: $light-blue;
    text-decoration: none;
    border-color: $light-grey;
  } 

python for increment inner loop

In python, for loops iterate over iterables, instead of incrementing a counter, so you have a couple choices. Using a skip flag like Artsiom recommended is one way to do it. Another option is to make a generator from your range and manually advance it by discarding an element using next().

iGen = (i for i in range(0, 6))
for i in iGen:
    print i
    if not i % 2:
        iGen.next()

But this isn't quite complete because next() might throw a StopIteration if it reaches the end of the range, so you have to add some logic to detect that and break out of the outer loop if that happens.

In the end, I'd probably go with aw4ully's solution with the while loops.

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

In my case I have a kubernetes cluster with nginx ingress controller and nginx+php-fpm to handle drupal instance.

I notice this issue on one of my page, where my pictures was not loaded in chrome. After investigation I discovered that modsecurity module enabled in my nginx ingress somehow produce this issue. Not fully know why, but after disabling it, all pages are loaded fine.

Best Regards.

Checking from shell script if a directory contains files

I would go for find:

if [ -z "$(find $dir -maxdepth 1 -type f)" ]; then
    echo "$dir has NO files"
else
    echo "$dir has files"

This checks the output of looking for just files in the directory, without going through the subdirectories. Then it checks the output using the -z option taken from man test:

   -z STRING
          the length of STRING is zero

See some outcomes:

$ mkdir aaa
$ dir="aaa"

Empty dir:

$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
empty

Just dirs in it:

$ mkdir aaa/bbb
$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
empty

A file in the directory:

$ touch aaa/myfile
$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
$ rm aaa/myfile 

A file in a subdirectory:

$ touch aaa/bbb/another_file
$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
empty

Autoplay an audio with HTML5 embed tag while the player is invisible

"Sensitive" era

Modern browsers today seem to block (by default) these autoplay features. They are somewhat treated as pop-ops. Very intrusive. So yeah, users now have the complete control on when the sounds are played. [1,2,3]

HTML5 era

<audio controls autoplay loop hidden>
    <source src="audio.mp3" type="audio/mpeg">
</audio>

Early days of HTML

<embed src="audio.mp3" style="visibility:hidden" />

References

  1. Jer Noble, New <video> Policies for iOS, WebKit, link
  2. Allow or block media autoplay in Firefox, FireFox Help, link
  3. Mounir Lamouri, Unified autoplay, Chromium Blog, link
  4. Embedded content, World Wide Web Consortium, link

CSS: Auto resize div to fit container width

CSS auto-fit container between float:left & float:right divs solved my problem, thanks for your comments.

#left
{
    width:200px;
    float:left;
    background-color:antiquewhite;
    margin-left:10px;
}
#content
{
    overflow:hidden;
    margin-left:10px;
    background-color:AppWorkspace;
}

How do I find where JDK is installed on my windows machine?

#!/bin/bash

if [[ $(which ${JAVA_HOME}/bin/java) ]]; then
    exe="${JAVA_HOME}/bin/java"
elif [[ $(which java) ]]; then
    exe="java"
else 
    echo "Java environment is not detected."
    exit 1
fi

${exe} -version

For windows:

@echo off
if "%JAVA_HOME%" == "" goto nojavahome

echo Using JAVA_HOME            :   %JAVA_HOME%

"%JAVA_HOME%/bin/java.exe" -version
goto exit

:nojavahome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program.
goto exit

:exit

This link might help to explain how to find java executable from bash: http://srcode.org/2014/05/07/detect-java-executable/

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The only difference is that CHARACTER VARYING is more human friendly than VARCHAR

How to change the default encoding to UTF-8 for Apache?

In httpd.conf add (or change if it's already there):

AddDefaultCharset utf-8

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

i faced this issue where i was using SQL it is different from MYSQL the solution was puting in this format: =date('m-d-y h:m:s'); rather than =date('y-m-d h:m:s');

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

find difference between two text files with one item per line

With GNU sed:

sed 's#[^^]#[&]#g;s#\^#\\^#g;s#^#/^#;s#$#$/d#' file1 | sed -f- file2

How it works:

The first sed produces an output like this:

/^[d][s][f]$/d
/^[s][d][f][s][d]$/d
/^[d][s][f][s][d][f]$/d

Then it is used as a sed script by the second sed.

Uncaught TypeError: (intermediate value)(...) is not a function

To make semicolon rules simple

Every line that begins with a (, [, `, or any operator (/, +, - are the only valid ones), must begin with a semicolon.

func()
;[0].concat(myarr).forEach(func)
;(myarr).forEach(func)
;`hello`.forEach(func)
;/hello/.exec(str)
;+0
;-0

This prevents a

func()[0].concat(myarr).forEach(func)(myarr).forEach(func)`hello`.forEach(func)/hello/.forEach(func)+0-0

monstrocity.

Additional Note

To mention what will happen: brackets will index, parentheses will be treated as function parameters. The backtick would transform into a tagged template, and regex or explicitly signed integers will turn into operators. Of course, you can just add a semicolon to the end of every line. It's good to keep mind though when you're quickly prototyping and are dropping your semicolons.

Also, adding semicolons to the end of every line won't help you with the following, so keep in mind statements like

return // Will automatically insert semicolon, and return undefined.
    (1+2);
i // Adds a semicolon
   ++ // But, if you really intended i++ here, your codebase needs help.

The above case will happen to return/continue/break/++/--. Any linter will catch this with dead-code or ++/-- syntax error (++/-- will never realistically happen).

Finally, if you want file concatenation to work, make sure each file ends with a semicolon. If you're using a bundler program (recommended), it should do this automatically.

Printing reverse of any String without using any predefined function?

public class ReverseString {

public static void main(String [] args) {

    String s = "reverse string" ;
    String b = "";

            for (int i = 0; i < s.length(); i++ ){
                 b= b + s.substring(s.length()-1-i, s.length()-i);

                 }

             System.out.println(b);
}

ReactJS: Maximum update depth exceeded error

Forget about the react first:
This is not related to react and let us understand the basic concepts of Java Script. For Example you have written following function in java script (name is A).

function a() {

};

Q.1) How to call the function that we have defined?
Ans: a();

Q.2) How to pass reference of function so that we can call it latter?
Ans: let fun = a;

Now coming to your question, you have used paranthesis with function name, mean that function will be called when following statement will be render.

_x000D_
_x000D_
<td><span onClick={this.toggle()}>Details</span></td>
_x000D_
_x000D_
_x000D_

Then How to correct it?
Simple!! Just remove parenthesis. By this way you have given the reference of that function to onClick event. It will call back your function only when your component is clicked.

_x000D_
_x000D_
 <td><span onClick={this.toggle}>Details</span></td>
_x000D_
_x000D_
_x000D_

One suggestion releated to react:
Avoid using inline function as suggested by someone in answers, it may cause performance issue. Avoid following code, It will create instance of same function again and again whenever function will be called (lamda statement creates new instance every time).
Note: and no need to pass event (e) explicitly to the function. you can access it with in the function without passing it.

_x000D_
_x000D_
{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}
_x000D_
_x000D_
_x000D_

https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578

.NET console application as Windows service

You need to seperate the functionality into a class or classes and launch that via one of two stubs. The console stub or service stub.

As its plain to see, when running windows, the myriad services that make up the infrastructure do not (and can't directly) present console windows to the user. The service needs to communicate with the user in a non graphical way: via the SCM; in the event log, to some log file etc. The service will also need to communicate with windows via the SCM, otherwise it will get shutdown.

It would obviously be acceptable to have some console app that can communicate with the service but the service needs to run independently without a requirement for GUI interaction.

The Console stub can very useful for debugging service behaviour but should not be used in a "productionized" environment which, after all, is the purpose of creating a service.

I haven't read it fully but this article seems to pint in the right direction.

How to enable core dump in my Linux C++ program

You can do it this way inside a program:

#include <sys/resource.h>

// core dumps may be disallowed by parent of this process; change that
struct rlimit core_limits;
core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
setrlimit(RLIMIT_CORE, &core_limits);

In Python, how do I index a list with another list?

I wasn't happy with any of these approaches, so I came up with a Flexlist class that allows for flexible indexing, either by integer, slice or index-list:

class Flexlist(list):
    def __getitem__(self, keys):
        if isinstance(keys, (int, slice)): return list.__getitem__(self, keys)
        return [self[k] for k in keys]

Which, for your example, you would use as:

L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
Idx = [0, 3, 7]
T = L[ Idx ]

print(T)  # ['a', 'd', 'h']

How to loop through an array of objects in swift

Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for in loop.

if let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] 
{
    for object in photos {
        let url = object.url
    }
}

There's also guard let else instead of if let if you prefer having the result available in scope:

guard let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] else 
{
    // break or return
}
// now 'photos' is available outside the guard
for object in photos {
    let url = object.url
}

Multiple arguments to function called by pthread_create()?

struct arg_struct *args = (struct arg_struct *)args;

--> this assignment is wrong, I mean the variable argument should be used in this context. Cheers!!!

Item frequency count in Python

Can't you just use count?

words = 'the quick brown fox jumps over the lazy gray dog'
words.count('z')
#output: 1

How to set a ripple effect on textview or imageview on Android?

Please refer below answer for ripple effect.

ripple on Textview or view :

android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackgroundBorderless"

ripple on Button or Imageview :

android:foreground="?android:attr/selectableItemBackgroundBorderless"

CentOS 64 bit bad ELF interpreter

Try

$ yum provides ld-linux.so.2
$ yum update
$ yum install glibc.i686 libfreetype.so.6 libfontconfig.so.1 libstdc++.so.6

Hope this clears out.

How to obtain the last index of a list?

You can use the list length. The last index will be the length of the list minus one.

len(list1)-1 == 3

How to convert all tables from MyISAM into InnoDB?

Try this shell script

DBENGINE='InnoDB' ;
DBUSER='your_db_user' ;
DBNAME='your_db_name' ;
DBHOST='your_db_host'
DBPASS='your_db_pass' ;
mysqldump --add-drop-table -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME > mtest.sql; mysql -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME -Nse "SHOW TABLES;" | while read TABLE ; do mysql -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME -Nse "ALTER TABLE $TABLE ENGINE=$DBENGINE;" ; done

Is it possible that one domain name has multiple corresponding IP addresses?

Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.

Android update activity UI from service

for me the simplest solution was to send a broadcast, in the activity oncreate i registered and defined the broadcast like this (updateUIReciver is defined as a class instance) :

 IntentFilter filter = new IntentFilter();

 filter.addAction("com.hello.action"); 

 updateUIReciver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                //UI update here

            }
        };
 registerReceiver(updateUIReciver,filter);

And from the service you send the intent like this:

Intent local = new Intent();

local.setAction("com.hello.action");

this.sendBroadcast(local);

don't forget to unregister the recover in the activity on destroy :

unregisterReceiver(updateUIReciver);

Removing duplicates from a SQL query (not just "use distinct")

Your question is kind of confusing; do you want to show only one row per user, or do you want to show a row per picture but suppress repeating values in the U.NAME field? I think you want the second; if not there are plenty of answers for the first.

Whether to display repeating values is display logic, which SQL wasn't really designed for. You can use a cursor in a loop to process the results row-by-row, but you will lose a lot of performance. If you have a "smart" frontend language like a .NET language or Java, whatever construction you put this data into can be cheaply manipulated to suppress repeating values before finally displaying it in the UI.

If you're using Microsoft SQL Server, and the transformation HAS to be done at the data layer, you may consider using a CTE (Computed Table Expression) to hold the initial query, then select values from each row of the CTE based on whether the columns in the previous row hold the same data. It'll be more performant than the cursor, but it'll be kinda messy either way. Observe:

USING CTE (Row, Name, PicID)
AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY U.NAME, P.PIC_ID),
       U.NAME, P.PIC_ID
    FROM USERS U
        INNER JOIN POSTINGS P1
            ON U.EMAIL_ID = P1.EMAIL_ID
        INNER JOIN PICTURES P
            ON P1.PIC_ID = P.PIC_ID
    WHERE P.CAPTION LIKE '%car%'
    ORDER BY U.NAME, P.PIC_ID 
)
SELECT
    CASE WHEN current.Name == previous.Name THEN '' ELSE current.Name END,
    current.PicID
FROM CTE current
LEFT OUTER JOIN CTE previous
   ON current.Row = previous.Row + 1
ORDER BY current.Row

The above sample is TSQL-specific; it is not guaranteed to work in any other DBPL like PL/SQL, but I think most of the enterprise-level SQL engines have something similar.

Shorter syntax for casting from a List<X> to a List<Y>?

The direct cast var ListOfY = (List<Y>)ListOfX is not possible because it would require co/contravariance of the List<T> type, and that just can't be guaranteed in every case. Please read on to see the solutions to this casting problem.

While it seems normal to be able to write code like this:

List<Animal> animals = (List<Animal>) mammalList;

because we can guarantee that every mammal will be an animal, this is obviously a mistake:

List<Mammal> mammals = (List<Mammal>) animalList;

since not every animal is a mammal.

However, using C# 3 and above, you can use

IEnumerable<Animal> animals = mammalList.Cast<Animal>();

that eases the casting a little. This is syntactically equivalent to your one-by-one adding code, as it uses an explicit cast to cast each Mammal in the list to an Animal, and will fail if the cast is not successfull.

If you like more control over the casting / conversion process, you could use the ConvertAll method of the List<T> class, which can use a supplied expression to convert the items. It has the added benifit that it returns a List, instead of IEnumerable, so no .ToList() is necessary.

List<object> o = new List<object>();
o.Add("one");
o.Add("two");
o.Add(3);

IEnumerable<string> s1 = o.Cast<string>(); //fails on the 3rd item
List<string> s2 = o.ConvertAll(x => x.ToString()); //succeeds

Can’t delete docker image with dependent child images

Force deleting a list of images (exclude version 10, for example)

docker images | grep version | grep -v version10 > images.txt && for img in $( awk -F" " '{print $3}' /root/images.txt ) ; do docker rmi -f $img; done

How do I list all tables in a schema in Oracle SQL?

select * from cat;

it will show all tables in your schema cat synonym of user_catalog

What is a "slug" in Django?

It is a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL.

Python Script to convert Image into Byte array

Use bytearray:

with open("img.png", "rb") as image:
  f = image.read()
  b = bytearray(f)
  print b[0]

You can also have a look at struct which can do many conversions of that kind.

Replacing few values in a pandas dataframe column with another value

Replace

DataFrame object has powerful and flexible replace method:

DataFrame.replace(
        to_replace=None,
        value=None,
        inplace=False,
        limit=None,
        regex=False, 
        method='pad',
        axis=None)

Note, if you need to make changes in place, use inplace boolean argument for replace method:

Inplace

inplace: boolean, default False If True, in place. Note: this will modify any other views on this object (e.g. a column form a DataFrame). Returns the caller if this is True.

Snippet

df['BrandName'].replace(
    to_replace=['ABC', 'AB'],
    value='A',
    inplace=True
)

how to get multiple checkbox value using jquery

Also you can use $('input[name="selector[]"]').serialize();. It returns URL encoded string like: "selector%5B%5D=1&selector%5B%5D=3"

How to make a pure css based dropdown menu?

View code online on: WebCrafts.org

HTML code:

<body id="body">
<div id="navigation">
    <h2>
        Pure CSS Drop-down Menu
    </h2>
  <div id="nav" class="nav">
    <ul>
        <li><a href="#">Menu1</a></li>
        <li>
            <a href="#">Menu2</a>
          <ul>
                <li><a href="#">Sub-Menu1</a></li>
                <li>
                    <a href="#">Sub-Menu2</a>
                  <ul>
                        <li><a href="#">Demo1</a></li>
                      <li><a href="#">Demo2</a></li>
                    </ul>
                </li>
                <li><a href="#">Sub-Menu3</a></li>
                <li><a href="#">Sub-Menu4</a></li>
            </ul>
        </li>
        <li><a href="#">Menu3</a></li>
        <li><a href="#">Menu4</a></li>
    </ul>
  </div>
</div>
</body>

Css code:

body{
    background-color:#111;
}

#navigation{
    text-align:center;
}
#navigation h2{
    color:#DDD;
}

.nav{
    display:inline-block;
    z-index:5;
    font-weight:bold;
}
.nav ul{
    width:auto;
    list-style:none;
}

.nav ul li{
    display:inline-block;
}

.nav ul li a{
    text-decoration:none;
    text-align:center;
    color:#222;
    display:block;
    width:120px;
    line-height:30px;
    background-color:gray;
}

.nav ul li a:hover{
    background-color:#EEC;   
}
.nav ul li ul{
    margin-top:0px;
    padding-left:0px;
    position:absolute;
    display:none;
}

.nav ul li:hover ul{
    display:block;
}

.nav ul li ul li{
    display:block;
}

.nav ul li ul li ul{
    margin-left:100%;
    margin-top:-30px;
    visibility:hidden;
}

.nav ul li ul li:hover ul{
    margin-left:100%;
    visibility:visible;
}

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

MySQL: update a field only if condition is met

found the solution with AND condition:

  $trainstrength = "UPDATE user_character SET strength_trains = strength_trains + 1, trained_strength = trained_strength +1, character_gold = character_gold - $gold_to_next_strength WHERE ID = $currentUser AND character_gold > $gold_to_next_strength";

Required maven dependencies for Apache POI to work

ooxml for dealing the .xlsx files and the ooxml refers to the xml, hence we will be needed to refer the below three dependedncies in the pom.xml for the

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>3.9</version>
</dependency>
<dependency>
   <groupId>xml-apis</groupId>
   <artifactId>xml-apis</artifactId>
   <version>1.4.01</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.9</version>
   <exclusions>
     <exclusion>
       <artifactId>xml-apis</artifactId>
       <groupId>xml-apis</groupId>
     </exclusion>       
   </exclusions>
</dependency>

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

How to insert an object in an ArrayList at a specific position

To insert value into ArrayList at particular index, use:

public void add(int index, E element)

This method will shift the subsequent elements of the list. but you can not guarantee the List will remain sorted as the new Object you insert may sit on the wrong position according to the sorting order.


To replace the element at the specified position, use:

public E set(int index, E element)

This method replaces the element at the specified position in the list with the specified element, and returns the element previously at the specified position.

How to test REST API using Chrome's extension "Advanced Rest Client"

in the header section you have to write

Authorization: Basic aG9sY67890vbGNpbQ==

where string after basic is the 64bit encoding value of your username:password. php example of getting the header values is: echo "Authorization: Basic " . base64_encode("myUser:myPassword");

n.b: I assumed your authentication method as basic. which can be different as well.

JavaScript data grid for millions of rows

I kind of fail to see the point, for jqGrid you can use the virtual scrolling functionality:

http://www.trirand.net/aspnetmvc/grid/performancevirtualscrolling

but then again, millions of rows with filtering can be done:

http://www.trirand.net/aspnetmvc/grid/performancelinq

I really fail to see the point of "as if there are no pages" though, I mean... there is no way to display 1,000,000 rows at once in the browser - this is 10MB of HTML raw, I kind of fail to see why users would not want to see the pages.

Anyway...

How to use JavaScript with Selenium WebDriver Java

Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver. Please correct me if I'm wrong.

The WebDriverJs is actually "just" another WebDriver language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now). This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.

If you want to run JavaScript code in Java WebDriver, do this instead:

WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
    ((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
    throw new IllegalStateException("This driver does not support JavaScript!");
}

I like to do this, also:

WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
    js = (JavascriptExecutor)driver;
} // else throw...

// later on...
js.executeScript("return document.getElementById('someId');");

You can find more documentation on this here, in the documenation, or, preferably, in the JavaDocs of JavascriptExecutor.

The executeScript() takes function calls and raw JS, too. You can return a value from it and you can pass lots of complicated arguments to it, some random examples:

  1. // returns the right WebElement
    // it's the same as driver.findElement(By.id("someId"))
    js.executeScript("return document.getElementById('someId');");
    
  2. // draws a border around WebElement
    WebElement element = driver.findElement(By.anything("tada"));
    js.executeScript("arguments[0].style.border='3px solid red'", element);
    
  3. // changes all input elements on the page to radio buttons
    js.executeScript(
            "var inputs = document.getElementsByTagName('input');" +
            "for(var i = 0; i < inputs.length; i++) { " +
            "    inputs[i].type = 'radio';" +
            "}" );
    

How to save a spark DataFrame as csv on disk?

Apache Spark does not support native CSV output on disk.

You have four available solutions though:

  1. You can convert your Dataframe into an RDD :

    def convertToReadableString(r : Row) = ???
    df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
    

    This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)

    What I usually do if I want to append all the partitions into a big CSV is

    cat filePath/part* > mycsvfile.csv
    

    Some will use coalesce(1,false) to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.

    Note that df.rdd will return an RDD[Row].

  2. With Spark <2, you can use databricks spark-csv library:

    • Spark 1.4+:

      df.write.format("com.databricks.spark.csv").save(filepath)
      
    • Spark 1.3:

      df.save(filepath,"com.databricks.spark.csv")
      
  3. With Spark 2.x the spark-csv package is not needed as it's included in Spark.

    df.write.format("csv").save(filepath)
    
  4. You can convert to local Pandas data frame and use to_csv method (PySpark only).

Note: Solutions 1, 2 and 3 will result in CSV format files (part-*) generated by the underlying Hadoop API that Spark calls when you invoke save. You will have one part- file per partition.

Can't connect to local MySQL server through socket homebrew

In my case, the culprit was found in the logfiles:

$ tail /usr/local/var/mysql/<hostname>.lan.err
2019-09-19  7:32:21 0 [ERROR] InnoDB: redo log file './ib_logfile0' exists. Creating system tablespace with existing redo log files is not recommended. Please delete all redo log files before creating new system tablespace.
2019-09-19  7:32:21 0 [ERROR] InnoDB: Database creation was aborted with error Generic error. You may need to delete the ibdata1 file before trying to start up again.

So I renamed ib_logfile0 to get rid of the error (I had to do the same with ib_logfile1 afterwards).

mv /usr/local/var/mysql/ib_logfile0 /usr/local/var/mysql/ib_logfile0_bak
mv /usr/local/var/mysql/ib_logfile1 /usr/local/var/mysql/ib_logfile1_bak
brew services restart mariadb

Static Block in Java

It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.

It is also possible to write non-static initializers, which look even stranger:

public class Foo {
    {
        // This code will be executed before every constructor
        // but after the call to super()
    }

    Foo() {

    }
}

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

jQuery - find table row containing table cell containing specific text

You can use filter() to do that:

var tableRow = $("td").filter(function() {
    return $(this).text() == "foo";
}).closest("tr");

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

First please check in module.ts file that in @NgModule all properties are only one time. If any of are more than one time then also this error come. Because I had also occur this error but in module.ts file entryComponents property were two time that's why I was getting this error. I resolved this error by removing one time entryComponents from @NgModule. So, I recommend that first you check it properly.

Why use multiple columns as primary keys (composite primary key)

We create composite primary keys to guarantee the uniqueness column values which compose a single record. It is a constraint which helps prevent insertion of data which should not be duplicated.

i.e: If all student Ids and birth certificate numbers are uniquely assigned to a single person. Then it would be a good idea to make the primary key for a person a composition of student id and birth certificate number because it would prevent you from accidentally inserting two people who have different student ids and the same birth certificate.

How can I loop over entries in JSON?

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']

jquery - is not a function error

I solved it by renaming my function.

Changed

function editForm(value)

to

function editTheForm(value)

Works perfectly.

chart.js load totally new data

You need to clean old data. No need to re initialize:

for (i in myChartLine.datasets[0].points)
    myChartLine.removeData();

Why does npm install say I have unmet dependencies?

npm install will install all the packages from npm-shrinkwrap.json, but might ignore packages in package.json, if they're not preset in the former.

If you're project has a npm-shrinkwrap.json, make sure you run npm shrinkwrap to regenerate it, each time you add add/remove/change package.json.

How can I make git accept a self signed certificate?

I use a windows machine and this article helped me. Basically I opened ca-bundle.crt in notepad and added chain certificates in it (all of them). This issue usually happens for company networks where we have middle men sitting between system and git repo. We need to export all of the certs in cert chain except leaf cert in base 64 format and add all of them to ca-bundle.crt and then configure git for this modified crt file.

Change IPython/Jupyter notebook working directory

If you are using ipython in linux, then follow the steps:
!cd /directory_name/
You can try all the commands which work in you linux terminal.
!vi file_name.py

Just specify the exclamation(!) symbol before your linux commands.

How to count string occurrence in string?

You can use match to define such function:

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}

Convert char* to string C++

There seems to be a few details left out of your explanation, but I will do my best...

If these are NUL-terminated strings or the memory is pre-zeroed, you can just iterate down the length of the memory segment until you hit a NUL (0) character or the maximum length (whichever comes first). Use the string constructor, passing the buffer and the size determined in the previous step.

string retrieveString( char* buf, int max ) {

    size_t len = 0;
    while( (len < max) && (buf[ len ] != '\0') ) {
        len++;
    }

    return string( buf, len );

}

If the above is not the case, I'm not sure how you determine where a string ends.

How can I throw CHECKED exceptions from inside Java 8 streams?

If you use Spring Framework you can use ReflectionUtils.rethrowRuntimeException(ex) described here https://docs.spring.io/spring/docs/5.2.8.RELEASE/javadoc-api/org/springframework/util/ReflectionUtils.html#rethrowRuntimeException-java.lang.Throwable- The beauty of this util method is that it re-throws exactly same exception but of Runtime type, so your catch block that expects exception of checked type will still catch it as intended.

How do you echo a 4-digit Unicode character in Bash?

Sorry for reviving this old question. But when using bash there is a very easy approach to create Unicode codepoints from plain ASCII input, which even does not fork at all:

unicode() { local -n a="$1"; local c; printf -vc '\\U%08x' "$2"; printf -va "$c"; }
unicodes() { local a c; for a; do printf -vc '\\U%08x' "$a"; printf "$c"; done; };

Use it as follows to define certain codepoints

unicode crossbones 0x2620
echo "$crossbones"

or to dump the first 65536 unicode codepoints to stdout (takes less than 2s on my machine. The additional space is to prevent certain characters to flow into each other due to shell's monospace font):

for a in {0..65535}; do unicodes "$a"; printf ' '; done

or to tell a little very typical parent's story (this needs Unicode 2010):

unicodes 0x1F6BC 32 43 32 0x1F62D 32 32 43 32 0x1F37C 32 61 32 0x263A 32 32 43 32 0x1F4A9 10

Explanation:

  • printf '\UXXXXXXXX' prints out any Unicode character
  • printf '\\U%08x' number prints \UXXXXXXXX with the number converted to Hex, this then is fed to another printf to actually print out the Unicode character
  • printf recognizes octal (0oct), hex (0xHEX) and decimal (0 or numbers starting with 1 to 9) as numbers, so you can choose whichever representation fits best
  • printf -v var .. gathers the output of printf into a variable, without fork (which tremendously speeds up things)
  • local variable is there to not pollute the global namespace
  • local -n var=other aliases var to other, such that assignment to var alters other. One interesting part here is, that var is part of the local namespace, while other is part of the global namespace.
    • Please note that there is no such thing as local or global namespace in bash. Variables are kept in the environment, and such are always global. Local just puts away the current value and restores it when the function is left again. Other functions called from within the function with local will still see the "local" value. This is a fundamentally different concept than all the normal scoping rules found in other languages (and what bash does is very powerful but can lead to errors if you are a programmer who is not aware of that).

Check if a Windows service exists and delete in PowerShell

One could use Where-Object

if ((Get-Service | Where-Object {$_.Name -eq $serviceName}).length -eq 1) { "Service Exists" }

Get HTML code from website in C#

I am using AngleSharp and have been very satisfied with it.

Here is a simple example how to fetch a page:

var config = Configuration.Default.WithDefaultLoader();
var document = await BrowsingContext.New(config).OpenAsync("https://www.google.com");

And now you have a web page in document variable. Then you can easily access it by LINQ or other methods. For example if you want to get a string value from a HTML table:

var someStringValue = document.All.Where(m =>
        m.LocalName == "td" &&
        m.HasAttribute("class") &&
        m.GetAttribute("class").Contains("pid-1-bid")
    ).ElementAt(0).TextContent.ToString();

To use CSS selectors please see AngleSharp examples.

char *array and char array[]

No. Actually it's the "same" as

char array[] = {'O', 'n', 'e', ..... 'i','c','\0');

Every character is a separate element, with an additional \0 character as a string terminator.

I quoted "same", because there are some differences between char * array and char array[]. If you want to read more, take a look at C: differences between char pointer and array

capture div into image using html2canvas

You can get the screenshot of a division and save it easily just using the below snippet. Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.

 html2canvas(document.getElementsByClassName("image-div")[0], {
  useCORS: true,
}).then(function (canvas) {
  var imageURL = canvas.toDataURL("image/png");
  let a = document.createElement("a");
  a.href = imageURL;
  a.download = imageURL;
  a.click();
});

How to Copy Text to Clip Board in Android?

As a handy kotlin extension:

fun Context.copyToClipboard(text: CharSequence){
    val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clip = ClipData.newPlainText("label",text)
    clipboard.setPrimaryClip(clip)
}

Update:

If you using ContextCompat you should use:

ContextCompat.getSystemService(this, ClipboardManager::class.java)

How can I dismiss the on screen keyboard?

For Flutter 1.17.3 (stable channel as of June 2020), use

FocusManager.instance.primaryFocus.unfocus();

How to hide html source & disable right click and text copy?

This code is used for disable the right click events and keyboard short cuts.

Just try with this code

_x000D_
_x000D_
document.onkeydown = function(e) {_x000D_
    if(e.keyCode == 123) {_x000D_
     return false;_x000D_
    }_x000D_
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)){_x000D_
     return false;_x000D_
    }_x000D_
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)){_x000D_
     return false;_x000D_
    }_x000D_
    if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)){_x000D_
     return false;_x000D_
    }_x000D_
_x000D_
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)){_x000D_
     return false;_x000D_
    }      _x000D_
 }
_x000D_
_x000D_
_x000D_

Force index use in Oracle

There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.

Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.

begin 
   DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
                                 , INDNAME=>IndexName);
end;

For table.

begin 
   DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
                                 , TABNAME=>TableName);
end;

In extreme cases, you can try setting up the statistics on your own.

Parsing JSON object in PHP using json_decode

You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.

ld.exe: cannot open output file ... : Permission denied

The Best solution is go to console in eclipse IDE and click the red button to terminate the program. You will see the your program is running and output can be seen there. :) !!

Angular EXCEPTION: No provider for Http

>= Angular 4.3

for the introduced HttpClientModule

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule, // if used
    HttpClientModule,
    JsonpModule // if used
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Angular2 >= RC.5

Import HttpModule to the module where you use it (here for example the AppModule:

import { HttpModule } from '@angular/http';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule, // if used
    HttpModule,
    JsonpModule // if used
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Importing the HttpModule is quite similar to adding HTTP_PROVIDERS in previous version.

Linq on DataTable: select specific column into datatable, not whole table

LINQ is very effective and easy to use on Lists rather than DataTable. I can see the above answers have a loop(for, foreach), which I will not prefer.

So the best thing to select a perticular column from a DataTable is just use a DataView to filter the column and use it as you want.

Find it here how to do this.

DataView dtView = new DataView(dtYourDataTable);
DataTable dtTableWithOneColumn= dtView .ToTable(true, "ColumnA");

Now the DataTable dtTableWithOneColumn contains only one column(ColumnA).

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

Within Notepad select File > Save As...

File name: ".whatever you want" (with the leading dot)

You can do it in Explorer (in Windows 7) by adding a period at the end of the filename:

.whatever you want.

Windows will automatically remove the trailing dot when you validate.

postgresql sequence nextval in schema

SELECT last_value, increment_by from "other_schema".id_seq;

for adding a seq to a column where the schema is not public try this.

nextval('"other_schema".id_seq'::regclass)

How can I set the Secure flag on an ASP.NET Session Cookie?

secure - This attribute tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS. This will help protect the cookie from being passed over unencrypted requests. If the application can be accessed over both HTTP and HTTPS, then there is the potential that the cookie can be sent in clear text.

ImportError: No module named requests

I have installed python2.7 and python3.6

Open Command Line to ~/.bash_profile I find that #Setting PATH for Python 3.6 , So I change the path to PATH="/usr/local/Cellar/python/2.7.13/bin:${PATH}" , (please make sure your python2.7's path) ,then save. It works for me.

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

Convert integer to hexadecimal and back again

Use:

int myInt = 2934;
string myHex = myInt.ToString("X");  // Gives you hexadecimal
int myNewInt = Convert.ToInt32(myHex, 16);  // Back to int again.

See How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide) for more information and examples.

What's the difference between unit, functional, acceptance, and integration tests?

Depending on where you look, you'll get slightly different answers. I've read about the subject a lot, and here's my distillation; again, these are slightly wooly and others may disagree.

Unit Tests

Tests the smallest unit of functionality, typically a method/function (e.g. given a class with a particular state, calling x method on the class should cause y to happen). Unit tests should be focussed on one particular feature (e.g., calling the pop method when the stack is empty should throw an InvalidOperationException). Everything it touches should be done in memory; this means that the test code and the code under test shouldn't:

  • Call out into (non-trivial) collaborators
  • Access the network
  • Hit a database
  • Use the file system
  • Spin up a thread
  • etc.

Any kind of dependency that is slow / hard to understand / initialise / manipulate should be stubbed/mocked/whatevered using the appropriate techniques so you can focus on what the unit of code is doing, not what its dependencies do.

In short, unit tests are as simple as possible, easy to debug, reliable (due to reduced external factors), fast to execute and help to prove that the smallest building blocks of your program function as intended before they're put together. The caveat is that, although you can prove they work perfectly in isolation, the units of code may blow up when combined which brings us to ...

Integration Tests

Integration tests build on unit tests by combining the units of code and testing that the resulting combination functions correctly. This can be either the innards of one system, or combining multiple systems together to do something useful. Also, another thing that differentiates integration tests from unit tests is the environment. Integration tests can and will use threads, access the database or do whatever is required to ensure that all of the code and the different environment changes will work correctly.

If you've built some serialization code and unit tested its innards without touching the disk, how do you know that it'll work when you are loading and saving to disk? Maybe you forgot to flush and dispose filestreams. Maybe your file permissions are incorrect and you've tested the innards using in memory streams. The only way to find out for sure is to test it 'for real' using an environment that is closest to production.

The main advantage is that they will find bugs that unit tests can't such as wiring bugs (e.g. an instance of class A unexpectedly receives a null instance of B) and environment bugs (it runs fine on my single-CPU machine, but my colleague's 4 core machine can't pass the tests). The main disadvantage is that integration tests touch more code, are less reliable, failures are harder to diagnose and the tests are harder to maintain.

Also, integration tests don't necessarily prove that a complete feature works. The user may not care about the internal details of my programs, but I do!

Functional Tests

Functional tests check a particular feature for correctness by comparing the results for a given input against the specification. Functional tests don't concern themselves with intermediate results or side-effects, just the result (they don't care that after doing x, object y has state z). They are written to test part of the specification such as, "calling function Square(x) with the argument of 2 returns 4".

Acceptance Tests

Acceptance testing seems to be split into two types:

Standard acceptance testing involves performing tests on the full system (e.g. using your web page via a web browser) to see whether the application's functionality satisfies the specification. E.g. "clicking a zoom icon should enlarge the document view by 25%." There is no real continuum of results, just a pass or fail outcome.

The advantage is that the tests are described in plain English and ensures the software, as a whole, is feature complete. The disadvantage is that you've moved another level up the testing pyramid. Acceptance tests touch mountains of code, so tracking down a failure can be tricky.

Also, in agile software development, user acceptance testing involves creating tests to mirror the user stories created by/for the software's customer during development. If the tests pass, it means the software should meet the customer's requirements and the stories can be considered complete. An acceptance test suite is basically an executable specification written in a domain specific language that describes the tests in the language used by the users of the system.

Conclusion

They're all complementary. Sometimes it's advantageous to focus on one type or to eschew them entirely. The main difference for me is that some of the tests look at things from a programmer's perspective, whereas others use a customer/end user focus.

When do I use the PHP constant "PHP_EOL"?

I just experienced this issue when outputting to a Windows client. Sure, PHP_EOL is for server side, but most content output from php is for windows clients. So I have to place my findings here for the next person.

A) echo 'My Text' . PHP_EOL; // Bad because this just outputs \n and most versions of windows notepad display this on a single line, and most windows accounting software can't import this type of end of line character.

B) echo 'My Text \r\n'; //Bad because single quoted php strings do not interpret \r\n

C) echo "My Text \r\n"; // Yay it works! Looks correct in notepad, and works when importing the file to other windows software such as windows accounting and windows manufacturing software.

Check if a list contains an item in Ansible

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested

Using IF ELSE in Oracle

IF is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.

In SQL, you can use a CASE statement in the query itself

SELECT DISTINCT a.item, 
                (CASE WHEN b.salesman = 'VIKKIE'
                      THEN 'ICKY'
                      ELSE b.salesman
                  END), 
                NVL(a.manufacturer,'Not Set') Manufacturer
  FROM inv_items a, 
       arv_sales b
 WHERE  a.co = '100'
   AND a.co = b.co
   AND A.ITEM_KEY = b.item_key   
   AND a.item LIKE 'BX%'
   AND b.salesman in ('01','15')
   AND trans_date BETWEEN to_date('010113','mmddrr')
                      and to_date('011713','mmddrr')
ORDER BY a.item

Since you aren't doing any aggregation, you don't want a GROUP BY in your query. Are you really sure that you need the DISTINCT? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.

jsonify a SQLAlchemy result set in Flask

For a flat query (no joins) you can do this

@app.route('/results/')
def results():
    data = Table.query.all()
    result = [d.__dict__ for d in data]
    return jsonify(result=result)

and if you only want to return certain columns from the database you can do this

@app.route('/results/')
def results():
    cols = ['id', 'url', 'shipping']
    data = Table.query.all()
    result = [{col: getattr(d, col) for col in cols} for d in data]
    return jsonify(result=result)

What is the difference between And and AndAlso in VB.NET?

If Bool1 And Bool2 Then

Evaluates both Bool1 and Bool2

If Bool1 AndAlso Bool2 Then

Evaluates Bool2 if and only if Bool1 is true.

Replace multiple whitespaces with single whitespace in JavaScript string

You can augment String to implement these behaviors as methods, as in:

String.prototype.killWhiteSpace = function() {
    return this.replace(/\s/g, '');
};

String.prototype.reduceWhiteSpace = function() {
    return this.replace(/\s+/g, ' ');
};

This now enables you to use the following elegant forms to produce the strings you want:

"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra        whitespaces".reduceWhiteSpace();

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

It worked for me with version 3.0.0-M1.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M1</version>
</plugin>

You might need to run it with sudo.

How to make a smooth image rotation in Android?

If you are using a set Animation like me you should add the interpolation inside the set tag:

<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">

 <rotate
    android:duration="5000"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:startOffset="0"
    android:toDegrees="360" />

 <alpha
    android:duration="200"
    android:fromAlpha="0.7"
    android:repeatCount="infinite"
    android:repeatMode="reverse"
    android:toAlpha="1.0" />

</set>

That Worked for me.

Java: Why is the Date constructor deprecated, and what do I use instead?

new GregorianCalendar(1985, Calendar.JANUARY, 1).getTime();

(the pre-Java-8 way)

How can I open Windows Explorer to a certain directory from within a WPF app?

This should work:

Process.Start(@"<directory goes here>")

Or if you'd like a method to run programs/open files and/or folders:

private void StartProcess(string path)
{
    ProcessStartInfo StartInformation = new ProcessStartInfo();

    StartInformation.FileName = path;

    Process process = Process.Start(StartInformation);

    process.EnableRaisingEvents = true;
}

And then call the method and in the parenthesis put either the directory of the file and/or folder there or the name of the application. Hope this helped!

How to test Spring Data repositories?

tl;dr

To make it short - there's no way to unit test Spring Data JPA repositories reasonably for a simple reason: it's way to cumbersome to mock all the parts of the JPA API we invoke to bootstrap the repositories. Unit tests don't make too much sense here anyway, as you're usually not writing any implementation code yourself (see the below paragraph on custom implementations) so that integration testing is the most reasonable approach.

Details

We do quite a lot of upfront validation and setup to make sure you can only bootstrap an app that has no invalid derived queries etc.

  • We create and cache CriteriaQuery instances for derived queries to make sure the query methods do not contain any typos. This requires working with the Criteria API as well as the meta.model.
  • We verify manually defined queries by asking the EntityManager to create a Query instance for those (which effectively triggers query syntax validation).
  • We inspect the Metamodel for meta-data about the domain types handled to prepare is-new checks etc.

All stuff that you'd probably defer in a hand-written repository which might cause the application to break at runtime (due to invalid queries etc.).

If you think about it, there's no code you write for your repositories, so there's no need to write any unittests. There's simply no need to as you can rely on our test base to catch basic bugs (if you still happen to run into one, feel free to raise a ticket). However, there's definitely need for integration tests to test two aspects of your persistence layer as they are the aspects that related to your domain:

  • entity mappings
  • query semantics (syntax is verified on each bootstrap attempt anyway).

Integration tests

This is usually done by using an in-memory database and test cases that bootstrap a Spring ApplicationContext usually through the test context framework (as you already do), pre-populate the database (by inserting object instances through the EntityManager or repo, or via a plain SQL file) and then execute the query methods to verify the outcome of them.

Testing custom implementations

Custom implementation parts of the repository are written in a way that they don't have to know about Spring Data JPA. They are plain Spring beans that get an EntityManager injected. You might of course wanna try to mock the interactions with it but to be honest, unit-testing the JPA has not been a too pleasant experience for us as well as it works with quite a lot of indirections (EntityManager -> CriteriaBuilder, CriteriaQuery etc.) so that you end up with mocks returning mocks and so on.

Preloading @font-face fonts?

Via Google's webfontloader

var fontDownloadCount = 0;
WebFont.load({
    custom: {
        families: ['fontfamily1', 'fontfamily2']
    },
    fontinactive: function() {
        fontDownloadCount++;
        if (fontDownloadCount == 2) {
            // all fonts have been loaded and now you can do what you want
        }
    }
});

Passing environment-dependent variables in webpack

You can directly use the EnvironmentPlugin available in webpack to have access to any environment variable during the transpilation.

You just have to declare the plugin in your webpack.config.js file:

var webpack = require('webpack');

module.exports = {
    /* ... */
    plugins = [
        new webpack.EnvironmentPlugin(['NODE_ENV'])
    ]
};

Note that you must declare explicitly the name of the environment variables you want to use.

Combine two columns and add into one new column

Generally, I agree with @kgrittn's advice. Go for it.

But to address your basic question about concat(): The new function concat() is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.

If you can rule out null values, the good old (SQL standard) concatenation operator || is still the best choice, and @luis' answer is just fine:

SELECT col_a || col_b;

If either of your columns can be null, the result would be null in that case. You could defend with COALESCE:

SELECT COALESCE(col_a, '') || COALESCE(col_b, '');

But that get tedious quickly with more arguments. That's where concat() comes in, which never returns null, not even if all arguments are null. Per documentation:

NULL arguments are ignored.

SELECT concat(col_a, col_b);

The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string '', but one might want null instead (at least I would). One possible way:

SELECT CASE
          WHEN col_a IS NULL THEN col_b
          WHEN col_b IS NULL THEN col_a
          ELSE col_a || col_b
       END;

This gets more complex with more columns quickly. Again, use concat() but add a check for the special condition:

SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
            ELSE concat(col_a, col_b) END;

How does this work?
(col_a, col_b) is shorthand notation for a row type expression ROW (col_a, col_b). And a row type is only null if all columns are null. Detailed explanation:

Also, use concat_ws() to add separators between elements (ws for "with separator").


An expression like the one in Kevin's answer:

SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;

is tedious to prepare for null values in PostgreSQL 8.3 (without concat()). One way (of many):

SELECT COALESCE(
         CASE
            WHEN $1.zipcode IS NULL THEN $1.city
            WHEN $1.city    IS NULL THEN $1.zipcode
            ELSE $1.zipcode || ' - ' || $1.city
         END, '')
       || COALESCE(', ' || $1.state, '');

Function volatility is only STABLE

concat() and concat_ws() are STABLE functions, not IMMUTABLE because they can invoke datatype output functions (like timestamptz_out) that depend on locale settings.
Explanation by Tom Lane.

This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE function wrapper. Example here:

How to get the number of columns from a JDBC ResultSet?

PreparedStatement ps=con.prepareStatement("select * from stud");

ResultSet rs=ps.executeQuery();

ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("columns: "+rsmd.getColumnCount());  
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));  
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)); 

What is the meaning of "POSIX"?

The most important things POSIX 7 defines

  1. C API

    Greatly extends ANSI C with things like:

    • more file operations: mkdir, dirname, symlink, readlink, link (hardlinks), poll(), stat, sync, nftw()
    • process and threads: fork, execl, wait, pipe, semaphors sem_*, shared memory (shm_*), kill, scheduling parameters (nice, sched_*), sleep, mkfifo, setpgid()
    • networking: socket()
    • memory management: mmap, mlock, mprotect, madvise, brk()
    • utilities: regular expressions (reg*)

    Those APIs also determine underlying system concepts on which they depend, e.g. fork requires a concept of a process.

    Many Linux system calls exist to implement a specific POSIX C API function and make Linux compliant, e.g. sys_write, sys_read, ... Many of those syscalls also have Linux-specific extensions however.

    Major Linux desktop implementation: glibc, which in many cases just provides a shallow wrapper to system calls.

  2. CLI utilities

    E.g.: cd, ls, echo, ...

    Many utilities are direct shell front ends for a corresponding C API function, e.g. mkdir.

    Major Linux desktop implementation: GNU Coreutils for the small ones, separate GNU projects for the big ones: sed, grep, awk, ... Some CLI utilities are implemented by Bash as built-ins.

  3. Shell language

    E.g., a=b; echo "$a"

    Major Linux desktop implementation: GNU Bash.

  4. Environment variables

    E.g.: HOME, PATH.

    PATH search semantics are specified, including how slashes prevent PATH search.

  5. Program exit status

    ANSI C says 0 or EXIT_SUCCESS for success, EXIT_FAILURE for failure, and leaves the rest implementation defined.

    POSIX adds:

  6. Regular expression

    There are two types: BRE (Basic) and ERE (Extended). Basic is deprecated and only kept to not break APIs.

    Those are implemented by C API functions, and used throughout CLI utilities, e.g. grep accepts BREs by default, and EREs with -E.

    E.g.: echo 'a.1' | grep -E 'a.[[:digit:]]'

    Major Linux implementation: glibc implements the functions under regex.h which programs like grep can use as backend.

  7. Directory structure

    E.g.: /dev/null, /tmp

    The Linux FHS greatly extends POSIX.

  8. Filenames

    • / is the path separator
    • NUL cannot be used
    • . is cwd, .. parent
    • portable filenames
      • use at most max 14 chars and 256 for the full path
      • can only contain: a-zA-Z0-9._-

    See also: what is posix compliance for filesystem?

  9. Command line utility API conventions

    Not mandatory, used by POSIX, but almost nowhere else, notably not in GNU. But true, it is too restrictive, e.g. single letter flags only (e.g. -a), no double hyphen long versions (e.g. --all).

    A few widely used conventions:

    • - means stdin where a file is expected
    • -- terminates flags, e.g. ls -- -l to list a directory named -l

    See also: Are there standards for Linux command line switches and arguments?

  10. "POSIX ACLs" (Access Control Lists), e.g. as used as backend for setfacl.

    This was withdrawn but it was implemented in several OSes, including in Linux with setxattr.

Who conforms to POSIX?

Many systems follow POSIX closely, but few are actually certified by the Open Group which maintains the standard. Notable certified ones include:

  • OS X (Apple) X stands for both 10 and UNIX. Was the first Apple POSIX system, released circa 2001. See also: Is OSX a POSIX OS?
  • AIX (IBM)
  • HP-UX (HP)
  • Solaris (Oracle)

Most Linux distros are very compliant, but not certified because they don't want to pay the compliance check. Inspur's K-UX and Huawei's EulerOS are two certified examples.

The official list of certified systems be found at: https://www.opengroup.org/openbrand/register/ and also at the wiki page.

Windows

Windows implemented POSIX on some of its professional distributions.

Since it was an optional feature, programmers could not rely on it for most end user applications.

Support was deprecated in Windows 8:

In 2016 a new official Linux-like API called "Windows Subsystem for Linux" was announced. It includes Linux system calls, ELF running, parts of the /proc filesystem, Bash, GCC, (TODO likely glibc?), apt-get and more: https://channel9.msdn.com/Events/Build/2016/P488 so I believe that it will allow Windows to run much, if not all, of POSIX. However, it is focused on developers / deployment instead of end users. In particular, there were no plans to allow access to the Windows GUI.

Historical overview of the official Microsoft POSIX compatibility: http://brianreiter.org/2010/08/24/the-sad-history-of-the-microsoft-posix-subsystem/

Cygwin is a well known GPL third-party project for that "provides substantial POSIX API functionality" for Windows, but requires that you "rebuild your application from source if you want it to run on Windows". MSYS2 is a related project that seems to add more functionality on top of Cygwin.

Android

Android has its own C library (Bionic) which does not fully support POSIX as of Android O: Is Android POSIX-compatible?

Bonus level

The Linux Standard Base further extends POSIX.

Use the non-frames indexes, they are much more readable and searchable: http://pubs.opengroup.org/onlinepubs/9699919799/nfindex.html

Get a full zipped version of the HTML pages for grepping: Where is the list of the POSIX C API functions?

How to check if an array value exists?

To check if the index is defined: isset($something['say'])

How to exit from ForEach-Object in PowerShell

If you insist on using ForEach-Object, then I would suggest adding a "break condition" like this:

$Break = $False;

1,2,3,4 | Where-Object { $Break -Eq $False } | ForEach-Object {

    $Break = $_ -Eq 3;

    Write-Host "Current number is $_";
}

The above code must output 1,2,3 and then skip (break before) 4. Expected output:

Current number is 1
Current number is 2
Current number is 3

How to split a comma-separated value to columns

This worked for me

CREATE FUNCTION [dbo].[SplitString](
    @delimited NVARCHAR(MAX),
    @delimiter NVARCHAR(100)
) RETURNS @t TABLE ( val NVARCHAR(MAX))
AS
BEGIN
    DECLARE @xml XML
    SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'
    INSERT INTO @t(val)
    SELECT  r.value('.','varchar(MAX)') as item
    FROM  @xml.nodes('/t') as records(r)
    RETURN
END

design a stack such that getMinimum( ) should be O(1)

I think only push operation suffers, is enough. My implementation includes a stack of nodes. Each node contain the data item and also the minimum on that moment. This minimum is updated each time a push operation is done.

Here are some points for understanding:

  • I implemented the stack using Linked List.

  • A pointer top always points to the last pushed item. When there is no item in that stack top is NULL.

  • When an item is pushed a new node is allocated which has a next pointer that points to the previous stack and top is updated to point to this new node.

Only difference with normal stack implementation is that during push it updates a member min for the new node.

Please have a look at code which is implemented in C++ for demonstration purpose.

/*
 *  Implementation of Stack that can give minimum in O(1) time all the time
 *  This solution uses same data structure for minimum variable, it could be implemented using pointers but that will be more space consuming
 */

#include <iostream>
using namespace std;

typedef struct stackLLNodeType stackLLNode;

struct stackLLNodeType {
    int item;
    int min;
    stackLLNode *next;
};

class DynamicStack {
private:
    int stackSize;
    stackLLNode *top;

public:
    DynamicStack();
    ~DynamicStack();
    void push(int x);
    int pop();
    int getMin();
    int size() { return stackSize; }
};

void pushOperation(DynamicStack& p_stackObj, int item);
void popOperation(DynamicStack& p_stackObj);

int main () {
    DynamicStack stackObj;

    pushOperation(stackObj, 3);
    pushOperation(stackObj, 1);
    pushOperation(stackObj, 2);
    popOperation(stackObj);
    popOperation(stackObj);
    popOperation(stackObj);
    popOperation(stackObj);
    pushOperation(stackObj, 4);
    pushOperation(stackObj, 7);
    pushOperation(stackObj, 6);
    popOperation(stackObj);
    popOperation(stackObj);
    popOperation(stackObj);
    popOperation(stackObj);

    return 0;
}

DynamicStack::DynamicStack() {
    // initialization
    stackSize = 0;
    top = NULL;
}

DynamicStack::~DynamicStack() {
    stackLLNode* tmp;
    // chain memory deallocation to avoid memory leak
    while (top) {
        tmp = top;
        top = top->next;
        delete tmp;
    }
}

void DynamicStack::push(int x) {
    // allocate memory for new node assign to top
    if (top==NULL) {
        top = new stackLLNode;
        top->item = x;
        top->next = NULL;
        top->min = top->item;
    }
    else {
        // allocation of memory
        stackLLNode *tmp = new stackLLNode;
        // assign the new item
        tmp->item = x;
        tmp->next = top;

        // store the minimum so that it does not get lost after pop operation of later minimum
        if (x < top->min)
            tmp->min = x;
        else
            tmp->min = top->min;

        // update top to new node
        top = tmp;
    }
    stackSize++;
}

int DynamicStack::pop() {
    // check if stack is empty
    if (top == NULL)
        return -1;

    stackLLNode* tmp = top;
    int curItem = top->item;
    top = top->next;
    delete tmp;
    stackSize--;
    return curItem;
}

int DynamicStack::getMin() {
    if (top == NULL)
        return -1;
    return top->min;
}
void pushOperation(DynamicStack& p_stackObj, int item) {
    cout<<"Just pushed: "<<item<<endl;
    p_stackObj.push(item);
    cout<<"Current stack min: "<<p_stackObj.getMin()<<endl;
    cout<<"Current stack size: "<<p_stackObj.size()<<endl<<endl;
}

void popOperation(DynamicStack& p_stackObj) {
    int popItem = -1;
    if ((popItem = p_stackObj.pop()) == -1 )
        cout<<"Cannot pop. Stack is empty."<<endl;
    else {
        cout<<"Just popped: "<<popItem<<endl;
        if (p_stackObj.getMin() == -1)
            cout<<"No minimum. Stack is empty."<<endl;
        else
            cout<<"Current stack min: "<<p_stackObj.getMin()<<endl;
        cout<<"Current stack size: "<<p_stackObj.size()<<endl<<endl;
    }
}

And the output of the program looks like this:

Just pushed: 3
Current stack min: 3
Current stack size: 1

Just pushed: 1
Current stack min: 1
Current stack size: 2

Just pushed: 2
Current stack min: 1
Current stack size: 3

Just popped: 2
Current stack min: 1
Current stack size: 2

Just popped: 1
Current stack min: 3
Current stack size: 1

Just popped: 3
No minimum. Stack is empty.
Current stack size: 0

Cannot pop. Stack is empty.
Just pushed: 4
Current stack min: 4
Current stack size: 1

Just pushed: 7
Current stack min: 4
Current stack size: 2

Just pushed: 6
Current stack min: 4
Current stack size: 3

Just popped: 6
Current stack min: 4
Current stack size: 2

Just popped: 7
Current stack min: 4
Current stack size: 1

Just popped: 4
No minimum. Stack is empty.
Current stack size: 0

Cannot pop. Stack is empty.

python - checking odd/even numbers and changing outputs on number size

def main():
    n = float(input('odd:'))
    while n % 2 == 0:
        #if n % 2 == 1: No need for these lines as if it were true the while loop would not have been entered.
            #break not required as the while condition will break loop
        n = float(input('odd:'))


    for i in range(int((n+1)/2)):
        print(' '*i+'*'*int((n-2*i))+' '*i)

main()

#1st part ensures that it is an odd number that was entered.2nd part does the printing of triangular

Toggle button using two image on different state

Do this:

<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   <!--check.xml-->
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

create check.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>

Excel Formula to SUMIF date falls in particular month

Try this instead:

  =SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))

It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.

Here's how the formula works.

  1. MONTH($A$2:$A$6) creates an array of numeric values of the month for the dates in A2:A6, that is,
    {1, 1, 1, 2, 2}.
  2. Then the comparison {1, 1, 1, 2, 2}= 1 produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}, which comprises the condition for the IF statement.
  3. The IF statement then returns an array of values, with {430, 96, 400.. for the values of the sum ranges where the month value equals 1 and ..0,0} where the month value does not equal 1.
  4. That array {430, 96, 400, 0, 0} is then summed to get the answer you are looking for.

This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.

It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)--also works.

Heads up: This does not work in Google Spreadsheets

best way to get folder and file list in Javascript

In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS") out to make it even faster):

var _getAllFilesFromFolder = function(dir) {

    var filesystem = require("fs");
    var results = [];

    filesystem.readdirSync(dir).forEach(function(file) {

        file = dir+'/'+file;
        var stat = filesystem.statSync(file);

        if (stat && stat.isDirectory()) {
            results = results.concat(_getAllFilesFromFolder(file))
        } else results.push(file);

    });

    return results;

};

usage is clear:

_getAllFilesFromFolder(__dirname + "folder");

In jQuery, how do I select an element by its name attribute?

This worked for me..

HTML:

<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>

Jquery:


    $(".radioClass").each(function() {
        if($(this).is(':checked'))
        alert($(this).val());
    });

Hope it helps..

What are the date formats available in SimpleDateFormat class?

Date and time formats are well described below

SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns

There could be n Number of formats you can possibly make. ex - dd/MM/yyyy or YYYY-'W'ww-u or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.

  • G - Era designator (AD)
  • y - Year (1996; 96)
  • Y - Week Year (2009; 09)
  • M - Month in year (July; Jul; 07)
  • w - Week in year (27)
  • W - Week in month (2)
  • D - Day in year (189)
  • d - Day in month (10)
  • F - Day of week in month (2)
  • E - Day name in week (Tuesday; Tue)
  • u - Day number of week (1 = Monday, ..., 7 = Sunday)
  • a - AM/PM marker
  • H - Hour in day (0-23)
  • k - Hour in day (1-24)
  • K - Hour in am/pm (0-11)
  • h - Hour in am/pm (1-12)
  • m - Minute in hour (30)
  • s - Second in minute (55)
  • S - Millisecond (978)
  • z - General time zone (Pacific Standard Time; PST; GMT-08:00)
  • Z - RFC 822 time zone (-0800)
  • X - ISO 8601 time zone (-08; -0800; -08:00)

To parse:

2000-01-23T04:56:07.000+0000

Use: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

How to revert a merge commit that's already pushed to remote branch?

As Ryan mentioned, git revert could make merging difficult down the road, so git revert may not be what you want. I found that using the git reset --hard <commit-hash-prior-to-merge> command to be more useful here.

Once you have done the hard reset part, you can then force push to the remote branch, i.e. git push -f <remote-name> <remote-branch-name>, where <remote-name> is often named origin. From that point you can re-merge if you'd like.

Using scp to copy a file to Amazon EC2 instance?

second directory is your target destination, don't use server name there. In other words, you don't need to mention machine name for the machine you're currently in.

scp -i /path/to/your/.pemkey -r /copy/from/path user@server:/copy/to/path

-r if it's a directory.

Regular expression for excluding special characters

I would just white list the characters.

^[a-zA-Z0-9äöüÄÖÜ]*$

Building a black list is equally simple with regex but you might need to add much more characters - there are a lot of Chinese symbols in unicode ... ;)

^[^<>%$]*$

The expression [^(many characters here)] just matches any character that is not listed.

How to change text color and console color in code::blocks?

You should define the function textcolor before. Because textcolor is not a standard function in C.

void textcolor(unsigned short color) {
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon,color);
}

Gradle - Could not find or load main class

For Netbeans 11 users, this works for me:

apply plugin: 'java'
apply plugin: 'application'

// This comes out to package + '.' + mainClassName
mainClassName = 'com.hello.JavaApplication1'

Here generally is my tree:

C:\...\NETBEANSPROJECTS\JAVAAPPLICATION1
¦   build.gradle
+---src
¦   +---main
¦   ¦   +---java
¦   ¦       +---com
¦   ¦           +---hello
¦   ¦                   JavaApplication1.java
¦   ¦
¦   +---test
¦       +---java
+---test

How to make a class property?

Here's how I would do this:

class ClassPropertyDescriptor(object):

    def __init__(self, fget, fset=None):
        self.fget = fget
        self.fset = fset

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        return self.fget.__get__(obj, klass)()

    def __set__(self, obj, value):
        if not self.fset:
            raise AttributeError("can't set attribute")
        type_ = type(obj)
        return self.fset.__get__(obj, type_)(value)

    def setter(self, func):
        if not isinstance(func, (classmethod, staticmethod)):
            func = classmethod(func)
        self.fset = func
        return self

def classproperty(func):
    if not isinstance(func, (classmethod, staticmethod)):
        func = classmethod(func)

    return ClassPropertyDescriptor(func)


class Bar(object):

    _bar = 1

    @classproperty
    def bar(cls):
        return cls._bar

    @bar.setter
    def bar(cls, value):
        cls._bar = value


# test instance instantiation
foo = Bar()
assert foo.bar == 1

baz = Bar()
assert baz.bar == 1

# test static variable
baz.bar = 5
assert foo.bar == 5

# test setting variable on the class
Bar.bar = 50
assert baz.bar == 50
assert foo.bar == 50

The setter didn't work at the time we call Bar.bar, because we are calling TypeOfBar.bar.__set__, which is not Bar.bar.__set__.

Adding a metaclass definition solves this:

class ClassPropertyMetaClass(type):
    def __setattr__(self, key, value):
        if key in self.__dict__:
            obj = self.__dict__.get(key)
        if obj and type(obj) is ClassPropertyDescriptor:
            return obj.__set__(self, value)

        return super(ClassPropertyMetaClass, self).__setattr__(key, value)

# and update class define:
#     class Bar(object):
#        __metaclass__ = ClassPropertyMetaClass
#        _bar = 1

# and update ClassPropertyDescriptor.__set__
#    def __set__(self, obj, value):
#       if not self.fset:
#           raise AttributeError("can't set attribute")
#       if inspect.isclass(obj):
#           type_ = obj
#           obj = None
#       else:
#           type_ = type(obj)
#       return self.fset.__get__(obj, type_)(value)

Now all will be fine.

How to show and update echo on same line

This is vary useful please try it and change as required.

#!/bin/bash
for load in $(seq 1 100); do
    echo -ne "$load % downloded ...\r"
    sleep 1
done
echo "100"
echo "Loaded ..."

Running Python in PowerShell?

Using CMD you can run your python scripts as long as the installed python is added to the path with the following line:

C: \ Python27;

The (27) is example referring to version 2.7, add as per your version.

Path to system path:

Control Panel => System and Security => System => Advanced Settings => Advanced => Environment Variables.

Under "User Variables," append the PATH variable to the path of the Python installation directory (As above).

Once this is done, you can open a CMD where your scripts are saved, or manually navigate through the CMD.

To run the script enter:

C: \ User \ X \ MyScripts> python ScriptName.py

jQuery click event not working in mobile browsers

You can use jQuery Mobile vclick event:

Normalized event for handling touchend or mouse click events on touch devices.

$(document).ready(function(){
   $('.publications').vclick(function() {
       $('#filter_wrapper').show();
   });
 });

PostgreSQL visual interface similar to phpMyAdmin?

Azure Data Studio with Postgres addin is the tool of choice to manage postgres databases for me. Check it out. https://docs.microsoft.com/en-us/sql/azure-data-studio/quickstart-postgres?view=sql-server-ver15

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The general approach to write to any stream (not only MemoryStream) is to use BinaryWriter:

static void Write(Stream s, Byte[] bytes)
{
    using (var writer = new BinaryWriter(s))
    {
        writer.Write(bytes);
    }
}

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

About J Hardiman's answer, how about:

SELECT empName, projIDs=
  REPLACE(
    REPLACE(
      (SELECT REPLACE(projID, ' ', '-somebody-puts-microsoft-out-of-his-misery-please-') AS [data()] FROM project_members WHERE empName=a.empName FOR XML PATH('')), 
      ' ', 
      ' / '), 
    '-somebody-puts-microsoft-out-of-his-misery-please-',
    ' ') 
  FROM project_members a WHERE empName IS NOT NULL GROUP BY empName

By the way, is the use of "Surname" a typo or am i not understanding a concept here?

Anyway, thanks a lot guys cuz it saved me quite some time :)

How to merge every two lines into one from the command line?

Here is my solution in bash:

while read line1; do read line2; echo "$line1, $line2"; done < data.txt

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

What is the target platform of your application? I think you should set the platform to x86, do not set it to Any CPU.

Access a global variable in a PHP function

For many years I have always used this format:

<?php
    $data = "Hello";

    function sayHello(){
        echo $GLOBALS["data"];
    }

    sayHello();
?>

I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.

Object reference not set to an instance of an object.

The correct way in .NET 4.0 is:

if (String.IsNullOrWhiteSpace(strSearch))

The String.IsNullOrWhiteSpace method used above is equivalent to:

if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0) 
// String.Empty is the same as ""

Reference for IsNullOrWhiteSpace method

http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

Indicates whether a specified string is Nothing, empty, or consists only of white-space characters.

In earlier versions, you could do something like this:

if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)

The String.IsNullOrEmpty method used above is equivalent to:

if (strSearch == null || strSearch == String.Empty)

Which means you still need to check for your "IsWhiteSpace" case with the .Trim().Length == 0 as per the example.

Reference for IsNullOrEmpty method

http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx

Indicates whether the specified string is Nothing or an Empty string.

Explanation:

You need to ensure strSearch (or any variable for that matter) is not null before you dereference it using the dot character (.) - i.e. before you do strSearch.SomeMethod() or strSearch.SomeProperty you need to check that strSearch != null.

In your example you want to make sure your string has a value, which means you want to ensure the string:

  • Is not null
  • Is not the empty string (String.Empty / "")
  • Is not just whitespace

In the cases above, you must put the "Is it null?" case first, so it doesn't go on to check the other cases (and error) when the string is null.

Connect Android Studio with SVN

You should open File/Settings/Version Control/Subversion and uncheck 3 options: Use command line client, Use system default Subversion configuration directory and Use system default Subversion configuration directory like http://screencast.com/t/rlh9H2WVpgo

And then go to network tab. Choose SSLv3 instead of All in the field SSL protocols like http://screencast.com/t/l5yw1jqOxV

Lastly, check in or out your source via svn. It works well

Is there a way to create multiline comments in Python?

From the accepted answer...

You can use triple-quoted strings. When they're not a docstring (first thing in a class/function/module), they are ignored.

This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.

If you try to run this code...

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

You'll get either...

ValueError: invalid \x escape

...on Python 2.x or...

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

...on Python 3.x.

The only way to do multi-line comments which are ignored by the parser is...

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()

Search for one value in any column of any table inside a database

Source: http://fullparam.wordpress.com/2012/09/07/fck-it-i-am-going-to-search-all-tables-all-collumns/

I have a solution from a while ago that I kept improving. Also searches within XML columns if told to do so, or searches integer values if providing a integer only string.

/* Reto Egeter, fullparam.wordpress.com */

DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))

WHILE @TableName IS NOT NULL
BEGIN
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF @TableName IS NOT NULL
BEGIN
DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + @TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + @TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO @ColumnNameTable
EXEC (@sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
BEGIN
PRINT @ColumnName
SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + '''
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(@sql)
IF @@ROWCOUNT > 0 IF @FullRowResult = 1
BEGIN
SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
EXEC(@sql)
END
DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
END 
END
END
SET NOCOUNT OFF

SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType

How to style SVG <g> element?

The style that you give the "g" element will apply the child elements, not the "g" element itself.

Add a rectangle element and position around the group you wish to style.

See: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g

EDIT: updated wording and added fiddle in comments.

Interview question: Check if one string is a rotation of other string

It's very easy to write in PHP using strlen and strpos functions:

function isRotation($string1, $string2) {
    return strlen($string1) == strlen($string2) && (($string1.$string1).strpos($string2) != -1);
}

I don't know what strpos uses internally, but if it uses KMP this will be linear in time.

Binding select element to object in Angular

Attention Angular 2+ users: for some reason, [value] does not work on elements. use [ngModel] instead.

<select [ngModel]="selectedCountry">
    <option *ngFor="let country of countries" [value]="country">{{country.name}}</option>
</select>

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

Add -lrt to the end of g++ command line. This links in the librt.so "Real Time" shared library.

Html.BeginForm and adding properties

I know this is old but you could create a custom extension if you needed to create that form over and over:

public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)
{
    return htmlHelper.BeginForm(null, null, FormMethod.Post, 
     new Dictionary<string, object>() { { "enctype", "multipart/form-data" } });
}

Usage then just becomes

<% using(Html.BeginMultipartForm()) { %>

How to truncate the time on a DateTime object in Python?

Here is yet another way which fits in one line but is not particularly elegant:

dt = datetime.datetime.fromordinal(datetime.date.today().toordinal())

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

I have been fighting with this during the whole weekend. But it's pretty easy to do it. What I did was to click on repair rather than uninstall. After repairing, I clicked on restart directly. After that, everything is working perfectly. You should try this, may be it can work also for you!!!

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

What exactly is nullptr?

From nullptr: A Type-safe and Clear-Cut Null Pointer:

The new C++09 nullptr keyword designates an rvalue constant that serves as a universal null pointer literal, replacing the buggy and weakly-typed literal 0 and the infamous NULL macro. nullptr thus puts an end to more than 30 years of embarrassment, ambiguity, and bugs. The following sections present the nullptr facility and show how it can remedy the ailments of NULL and 0.

Other references:

rand() returns the same number each time the program is run

You need to "seed" the generator. Check out this short video, it will clear things up.

https://www.thenewboston.com/videos.php?cat=16&video=17503

How to align a <div> to the middle (horizontally/width) of the page

This can be easily achieved via flex container.

.container{
 width: 100%;
 display: flex;
 height: 100vh;
 justify-content: center;
}

.item{
 align-self: center;
}

Preview Link

Merge a Branch into Trunk

The syntax is wrong, it should instead be

svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>

Getting Django admin url for an object

from django.core.urlresolvers import reverse
def url_to_edit_object(obj):
  url = reverse('admin:%s_%s_change' % (obj._meta.app_label,  obj._meta.model_name),  args=[obj.id] )
  return u'<a href="%s">Edit %s</a>' % (url,  obj.__unicode__())

This is similar to hansen_j's solution except that it uses url namespaces, admin: being the admin's default application namespace.

Custom designing EditText

android:background="#E1E1E1" 
// background add in layout
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffffff">
</EditText>

LaTeX table too wide. How to make it fit?

Use p{width} column specifier: e.g. \begin{tabular}{ l p{10cm} } will put column's content into 10cm-wide parbox, and the text will be properly broken to several lines, like in normal paragraph.

You can also use tabular* environment to specify width for the entire table.

Move an array element from one array position to another

In your example, because is an array of string we can use a ranking object to reorder the string array:

let rank =  { 'a': 0, 'b': 1, 'c': 2, 'd': 0.5, 'e': 4 };
arr.sort( (i, j) => rank[i] - rank[j] );

We can use this approach to write a move function that works on a string array:

_x000D_
_x000D_
function stringArrayMove(arr, from, to)
{
  let rank = arr.reduce( (p, c, i) => ( p[c] = i, p ), ({ }) );
  // rank = { 'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4 }
  rank[arr[from]] = to - 0.5;
  // rank = { 'a': 0, 'b': 1, 'c': 2, 'd': 1.5, 'e': 4 }
  arr.sort( (i, j) => rank[i] - rank[j] );
  // arr = [ 'a', 'd', 'b', 'c', 'e' ];
}

let arr = [ 'a', 'b', 'c', 'd', 'e' ];
stringArrayMove(arr, 3, 1);
console.log( JSON.stringify(arr) );
_x000D_
_x000D_
_x000D_

If, however, the thing we wanted to sort is an array of object, we can introduce the ranking as a new property of each object, i.e.

let arr = [ { value: 'a', rank: 0 },
            { value: 'b', rank: 1 },
            { value: 'c', rank: 2 },
            { value: 'd', rank: 0.5 },
            { value: 'e', rank: 4 } ];
arr.sort( (i, j) => i['rank'] - j['rank'] );

We can use Symbol to hide the visibility of this property, i.e. it will not be shown in JSON.stringify. We can generalize this in an objectArrayMove function:

_x000D_
_x000D_
function objectArrayMove(arr, from, to) {
  let rank = Symbol("rank");
  arr.forEach( (item, i) => item[rank] = i );
  arr[from][rank] = to - 0.5;
  arr.sort( (i, j) => i[rank] - j[rank]);
}
let arr = [ { value: 'a' }, { value: 'b' }, { value: 'c' }, { value: 'd' }, { value: 'e' } ];
console.log( 'array before move: ', JSON.stringify( arr ) );
// array before move:  [{"value":"a"},{"value":"b"},{"value":"c"},{"value":"d"},{"value":"e"}]
objectArrayMove(arr, 3, 1);
console.log( 'array after move: ', JSON.stringify( arr ) );
// array after move:  [{"value":"a"},{"value":"d"},{"value":"b"},{"value":"c"},{"value":"e"}]
_x000D_
_x000D_
_x000D_

Running EXE with parameters

To start the process with parameters, you can use following code:

string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);

To kill/exit the program again, you can use following code:

proc.CloseMainWindow(); 
proc.Close();

Simple mediaplayer play mp3 from file path?

String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();   
mediaPlayer.start()

and this play from raw folder.

int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());

            MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
            mediaPlayer.prepare();
            mediaPlayer.start();

mycontext=application.this. use.

JavaScript - Use variable in string match

Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:

var re = new RegExp(yyy, 'g');
xxx.match(re);

Any flags you need (such as /g) can go into the second parameter.

How to use Collections.sort() in Java?

Sort the unsorted hashmap in ascending order.

// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) 
{
                return o2.getValue().compareTo(o1.getValue());
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

can't load package: package .: no buildable Go source files

If you want all packages in that repository, use ... to signify that, like:

go get code.google.com/p/go.text/...

Adding 30 minutes to time formatted as H:i in PHP

Your current solution does not work because $time is a string - it needs to be a Unix timestamp. You can do this instead:

$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );

Read next word in java

You can just use Scanner to read word by word, Scanner.next() reads the next word

try {
  Scanner s = new Scanner(new File(filename));

  while (s.hasNext()) {
    System.out.println("word:" + s.next());
  }
} catch (IOException e) {
  System.out.println("Error accessing input file!");
}

How do I pass a URL with multiple parameters into a URL?

You have to escape the & character. Turn your

&

into

&amp;

and you should be good.

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

Hi you can make something like this:

  1. Create class which implements AsyncTask

    // TASK 
    public class SomeClass extends AsyncTask<Void, Void, String>>
    {
    
        private OnTaskExecutionFinished _task_finished_event;
    
        public interface OnTaskExecutionFinished
        {
            public void OnTaskFihishedEvent(String Reslut);
        }
    
        public void setOnTaskFinishedEvent(OnTaskExecutionFinished _event)
        {
            if(_event != null)
            {
                this._task_finished_event = _event;
            }
        }
    
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
    
        }
    
        @Override
        protected String doInBackground(Void... params)
        {
            // do your background task here ...
    
            return "Done!";
        }
    
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if(this._task_finished_event != null)
            {
                this._task_finished_event.OnTaskFihishedEvent(result);
            }
            else
            {
                Log.d("SomeClass", "task_finished even is null");
            }
        }
    }
    
  2. Add in Main Activity

    // MAIN ACTIVITY
    public class MyActivity extends ListActivity
    {
       ...
        SomeClass _some_class = new SomeClass();
        _someclass.setOnTaskFinishedEvent(new _some_class.OnTaskExecutionFinished()
        {
        @Override
        public void OnTaskFihishedEvent(String result)
        {
            Toast.makeText(getApplicationContext(),
                    "Phony thread finished: " + result,
                    Toast.LENGTH_SHORT).show();
        }
    
       });
       _some_class.execute();
       ...
     }
    

Delete everything in a MongoDB database

Simplest way to delete a database say blog:

> use blog
switched to db blog
> db.dropDatabase();
{ "dropped" : "blog", "ok" : 1 }

How do you connect to multiple MySQL databases on a single webpage?

$dbh1 = mysql_connect($hostname, $username, $password);  
$dbh2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbh1); 
mysql_select_db('database2',$dbh2); 

mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);

This is the most obvious solution that I use but just remember, if the username / password for both the database is exactly same in the same host, this solution will always be using the first connection. So don't be confused that this is not working in such case. What you need to do is, create 2 different users for the 2 databases and it will work.

substring index range

0: U

1: n

2: i

3: v

4: e

5: r

6: s

7: i

8: t

9: y

Start index is inclusive

End index is exclusive

Javadoc link

Does HTML5 <video> playback support the .avi format?

Short answer: No. Use WebM or Ogg instead.

This article covers just about everything you need to know about the <video> element, including which browsers support which container formats and codecs.

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

How do I select last 5 rows in a table without sorting?

The way your question is phrased makes it sound like you think you have to physically resort the data in the table in order to get it back in the order you want. If so, this is not the case, the ORDER BY clause exists for this purpose. The physical order in which the records are stored remains unchanged when using ORDER BY. The records are sorted in memory (or in temporary disk space) before they are returned.

Note that the order that records get returned is not guaranteed without using an ORDER BY clause. So, while any of the the suggestions here may work, there is no reason to think they will continue to work, nor can you prove that they work in all cases with your current database. This is by design - I am assuming it is to give the database engine the freedom do as it will with the records in order to obtain best performance in the case where there is no explicit order specified.

Assuming you wanted the last 5 records sorted by the field Name in ascending order, you could do something like this, which should work in either SQL 2000 or 2005:

select Name 
from (
    select top 5 Name 
    from MyTable 
    order by Name desc
) a 
order by Name asc

Shorthand if/else statement Javascript

Appears you are having 'y' default to 1: An arrow function would be useful in 2020:

let x = (y = 1) => //insert operation with y here

Let 'x' be a function where 'y' is a parameter which would be assigned a default to '1' if it is some null or undefined value, then return some operation with y.

Parsing JSON using Json.net

I don't know about JSON.NET, but it works fine with JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1):

using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
    public string OBJECT_NAME { get; set; }
    public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
    public int id { get; set; }
}
public class SubObject
{
    public NameTypePair attributes { get; set; }
    public Position position { get; set; }
}
public class Position
{
    public int x { get; set; }
    public int y { get; set; }
}
public class Foo
{
    public Foo() { objects = new List<SubObject>(); }
    public string displayFieldName { get; set; }
    public NameTypePair fieldAliases { get; set; }
    public PositionType positionType { get; set; }
    public Ref reference { get; set; }
    public List<SubObject> objects { get; set; }
}
static class Program
{

    const string json = @"{
  ""displayFieldName"" : ""OBJECT_NAME"", 
  ""fieldAliases"" : {
    ""OBJECT_NAME"" : ""OBJECT_NAME"", 
    ""OBJECT_TYPE"" : ""OBJECT_TYPE""
  }, 
  ""positionType"" : ""point"", 
  ""reference"" : {
    ""id"" : 1111
  }, 
  ""objects"" : [
    {
      ""attributes"" : {
        ""OBJECT_NAME"" : ""test name"", 
        ""OBJECT_TYPE"" : ""test type""
      }, 
      ""position"" : 
      {
        ""x"" : 5, 
        ""y"" : 7
      }
    }
  ]
}";


    static void Main()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Foo foo = ser.Deserialize<Foo>(json);
    }


}

Edit:

Json.NET works using the same JSON and classes.

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

Link: Serializing and Deserializing JSON with Json.NET

jQuery changing style of HTML element

I think you can use this code also: and you can manage your class css better

<style>
   .navigationClass{
        display: inline-block;
        padding: 0px 0px 0px 6px;
        background-color: whitesmoke;
        border-radius: 2px;
    }
</style>
<div id="header" class="row">
    <div id="logo" class="col_12">And the winner is<span>n't...</span></div> 
    <div id="navigation" class="row"> 
        <ul id="pirra">
            <li><a href="#">Why?</a></li>
            <li><a href="#">Synopsis</a></li>
            <li><a href="#">Stills/Photos</a></li>
            <li><a href="#">Videos/clips</a></li>
            <li><a href="#">Quotes</a></li>
            <li><a href="#">Quiz</a></li>
        </ul>
    </div>
 <script>
    $(document).ready(function() {
$('#navigation ul li').addClass('navigationClass'); //add class navigationClass to the #navigation .

});
 </script>

Apache: Restrict access to specific source IP inside virtual host

For Apache 2.4, you would use the Require IP directive. So to only allow machines from the 192.168.0.0/24 network (range 192.168.0.0 - 192.168.0.255)

<VirtualHost *:80>
    <Location />
      Require ip 192.168.0.0/24
    </Location>
    ...
</VirtualHost>

And if you just want the localhost machine to have access, then there's a special Require local directive.

The local provider allows access to the server if any of the following conditions is true:

  • the client address matches 127.0.0.0/8
  • the client address is ::1
  • both the client and the server address of the connection are the same

This allows a convenient way to match connections that originate from the local host:

<VirtualHost *:80>
    <Location />
      Require local
    </Location>
    ...
</VirtualHost>

How to get the current directory in a C program?

Look up the man page for getcwd.

How do I detect if software keyboard is visible on Android Device or not?

It works with adjustNothing flag of activity and lifecycle events are used. Also with Kotlin:

/**
 * This class uses a PopupWindow to calculate the window height when the floating keyboard is opened and closed
 *
 * @param activity The parent activity
 *  The root activity that uses this KeyboardManager
 */
class KeyboardManager(private val activity: AppCompatActivity) : PopupWindow(activity), LifecycleObserver {

    private var observerList = mutableListOf<((keyboardTop: Int) -> Unit)>()

    /** The last value of keyboardTop */
    private var keyboardTop: Int = 0

    /** The view that is used to calculate the keyboard top  */
    private val popupView: View?

    /** The parent view  */
    private var parentView: View

    var isKeyboardShown = false
        private set

    /**
     * Create transparent view which will be stretched over to the full screen
     */
    private fun createFullScreenView(): View {
        val view = LinearLayout(activity)
        view.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT)
        view.background = ColorDrawable(Color.TRANSPARENT)
        return view
    }

    init {
        this.popupView = createFullScreenView()
        contentView = popupView

        softInputMode = LayoutParams.SOFT_INPUT_ADJUST_RESIZE or LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
        inputMethodMode = INPUT_METHOD_NEEDED

        parentView = activity.findViewById(android.R.id.content)

        width = 0
        height = LayoutParams.MATCH_PARENT

        popupView.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            popupView.getWindowVisibleDisplayFrame(rect)

            val keyboardTop = rect.bottom
            if (this.keyboardTop != keyboardTop) {
                isKeyboardShown = keyboardTop < this.keyboardTop
                this.keyboardTop = keyboardTop
                observerList.forEach { it(keyboardTop) }
            }
        }
        activity.lifecycle.addObserver(this)
    }

    /**
     * This must be called after the onResume of the Activity or inside view.post { } .
     * PopupWindows are not allowed to be registered before the onResume has finished
     * of the Activity
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun start() {
        parentView.post {
            if (!isShowing && parentView.windowToken != null) {
                setBackgroundDrawable(ColorDrawable(0))
                showAtLocation(parentView, Gravity.NO_GRAVITY, 0, 0)
            }
        }
    }

    /**
     * This manager will not be used anymore
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun close() {
        activity.lifecycle.removeObserver(this)
        observerList.clear()
        dismiss()
    }

    /**
     * Set the keyboard top observer. The observer will be notified when the keyboard top has changed.
     * For example when the keyboard is opened or closed
     *
     * @param observer The observer to be added to this provider
     */
    fun registerKeyboardTopObserver(observer: (keyboardTop: Int) -> Unit) {
        observerList.add(observer)
    }
}

Useful method to keep view always above the keyboard

fun KeyboardManager.updateBottomMarginIfKeyboardShown(
        view: View,
        activity: AppCompatActivity,
        // marginBottom of view when keyboard is hide
        marginBottomHideKeyboard: Int,
        // marginBottom of view when keybouard is shown
        marginBottomShowKeyboard: Int
) {
    registerKeyboardTopObserver { bottomKeyboard ->
        val bottomView = ViewUtils.getFullViewBounds(view).bottom
        val maxHeight = ScreenUtils.getFullScreenSize(activity.windowManager).y
        // Check that view is within the window size
        if (bottomView < maxHeight) {
            if (bottomKeyboard < bottomView) {
                ViewUtils.updateMargin(view, bottomMargin = bottomView - bottomKeyboard +
                        view.marginBottom + marginBottomShowKeyboard)
            } else ViewUtils.updateMargin(view, bottomMargin = marginBottomHideKeyboard)
        }
    }
}

Where getFullViewBounds

fun getLocationOnScreen(view: View): Point {
    val location = IntArray(2)
    view.getLocationOnScreen(location)
    return Point(location[0], location[1])
}

fun getFullViewBounds(view: View): Rect {
     val location = getLocationOnScreen(view)
     return Rect(location.x, location.y, location.x + view.width,
            location.y + view.height)
 }

Where getFullScreenSize

fun getFullScreenSize(wm: WindowManager? = null) =
            getScreenSize(wm) { getRealSize(it) }

private fun getScreenSize(wm: WindowManager? = null, block: Display.(Point) -> Unit): Point {
    val windowManager = wm ?: App.INSTANCE.getSystemService(Context.WINDOW_SERVICE)
            as WindowManager
    val point = Point()
    windowManager.defaultDisplay.block(point)
    return point
}

Where updateMargin

fun updateMargin(
        view: View,
        leftMargin: Int? = null,
        topMargin: Int? = null,
        rightMargin: Int? = null,
        bottomMargin: Int? = null
) {
    val layoutParams = view.layoutParams as ViewGroup.MarginLayoutParams
    if (leftMargin != null) layoutParams.leftMargin = leftMargin
    if (topMargin != null) layoutParams.topMargin = topMargin
    if (rightMargin != null) layoutParams.rightMargin = rightMargin
    if (bottomMargin != null) layoutParams.bottomMargin = bottomMargin
    view.layoutParams = layoutParams
}

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});

How can I pad an integer with zeros on the left?

If performance is important in your case you could do it yourself with less overhead compared to the String.format function:

/**
 * @param in The integer value
 * @param fill The number of digits to fill
 * @return The given value left padded with the given number of digits
 */
public static String lPadZero(int in, int fill){

    boolean negative = false;
    int value, len = 0;

    if(in >= 0){
        value = in;
    } else {
        negative = true;
        value = - in;
        in = - in;
        len ++;
    }

    if(value == 0){
        len = 1;
    } else{         
        for(; value != 0; len ++){
            value /= 10;
        }
    }

    StringBuilder sb = new StringBuilder();

    if(negative){
        sb.append('-');
    }

    for(int i = fill; i > len; i--){
        sb.append('0');
    }

    sb.append(in);

    return sb.toString();       
}

Performance

public static void main(String[] args) {
    Random rdm;
    long start; 

    // Using own function
    rdm = new Random(0);
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        lPadZero(rdm.nextInt(20000) - 10000, 4);
    }
    System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");

    // Using String.format
    rdm = new Random(0);        
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        String.format("%04d", rdm.nextInt(20000) - 10000);
    }
    System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}

Result

Own function: 1697ms

String.format: 38134ms

How to replace text of a cell based on condition in excel

You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM. Then simply type where it says TYPE: what you want to say in QUOTES.

Example.. "OTHER"

gson throws MalformedJsonException

I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing } character. What's the length of result1 versus result2? I'll note that result2 as you've quoted it has 169 characters.

GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t, \n, \r, and space count as whitespace. In particular, note that trailing NUL (\0) characters do not count as whitespace and will cause this error.

If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:

Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);

Where are static variables stored in C and C++?

Well this question is bit too old, but since nobody points out any useful information: Check the post by 'mohit12379' explaining the store of static variables with same name in the symbol table: http://www.geekinterview.com/question_details/24745

How to check if a file exists from inside a batch file

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

Convert object of any type to JObject with Json.NET

JObject implements IDictionary, so you can use it that way. For ex,

var cycleJson  = JObject.Parse(@"{""name"":""john""}");

//add surname
cycleJson["surname"] = "doe";

//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });

So the final json will be

{
  "name": "john",
  "surname": "doe",
  "complexObj": {
    "id": 1,
    "name": "test"
  }
}

You can also use dynamic keyword

dynamic cycleJson  = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });

How to convert JSON string into List of Java object?

use below simple code, no need to use any library

String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);

How to open the command prompt and insert commands using Java?

The following works for me on Snow Leopard:

Runtime rt = Runtime.getRuntime();
String[] testArgs = {"touch", "TEST"};
rt.exec(testArgs);

Thing is, if you want to read the output of that command, you need to read the input stream of the process. For instance,

Process pr = rt.exec(arguments);
BufferedReader r = new BufferedReader(new InputStreamReader(pr.getInputStream()));

Allows you to read the line-by-line output of the command pretty easily.

The problem might also be that MS-DOS does not interpret your order of arguments to mean "start a new command prompt". Your array should probably be:

{"start", "cmd.exe", "\c"}

To open commands in the new command prompt, you'd have to use the Process reference. But I'm not sure why you'd want to do that when you can just use exec, as the person before me commented.

How to bind DataTable to Datagrid

In cs file:

    private DataTable _dataTable;

    public DataTable DataTable
    {
        get { return _dataTable; }
        set { _dataTable = value; }
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this._dataTable = new DataTable("table");

        this._dataTable.Columns.Add("col0");
        this._dataTable.Columns.Add("col1");
        this._dataTable.Columns.Add("col2");

        this._dataTable.Rows.Add("data00", "data01", "data02");
        this._dataTable.Rows.Add("data10", "data11", "data22");
        this._dataTable.Rows.Add("data20", "data21", "data22");

        this.grid1.DataContext = this;

    }

In Xaml file:

<DataGrid x:Name="grid1"
          Margin="10"
          AutoGenerateColumns="True"
          ItemsSource="{Binding Path=DataTable, Mode=TwoWay}" />