Programs & Examples On #Tzinfo

Retrieving subfolders names in S3 bucket from boto3

Why not use the s3path package which makes it as convenient as working with pathlib? If you must however use boto3:

Using boto3.resource

This builds upon the answer by itz-azhar to apply an optional limit. It is obviously substantially simpler to use than the boto3.client version.

import logging
from typing import List, Optional

import boto3
from boto3_type_annotations.s3 import ObjectSummary  # pip install boto3_type_annotations

log = logging.getLogger(__name__)
_S3_RESOURCE = boto3.resource("s3")

def s3_list(bucket_name: str, prefix: str, *, limit: Optional[int] = None) -> List[ObjectSummary]:
    """Return a list of S3 object summaries."""
    # Ref: https://stackoverflow.com/a/57718002/
    return list(_S3_RESOURCE.Bucket(bucket_name).objects.limit(count=limit).filter(Prefix=prefix))


if __name__ == "__main__":
    s3_list("noaa-gefs-pds", "gefs.20190828/12/pgrb2a", limit=10_000)

Using boto3.client

This uses list_objects_v2 and builds upon the answer by CpILL to allow retrieving more than 1000 objects.

import logging
from typing import cast, List

import boto3

log = logging.getLogger(__name__)
_S3_CLIENT = boto3.client("s3")

def s3_list(bucket_name: str, prefix: str, *, limit: int = cast(int, float("inf"))) -> List[dict]:
    """Return a list of S3 object summaries."""
    # Ref: https://stackoverflow.com/a/57718002/
    contents: List[dict] = []
    continuation_token = None
    if limit <= 0:
        return contents
    while True:
        max_keys = min(1000, limit - len(contents))
        request_kwargs = {"Bucket": bucket_name, "Prefix": prefix, "MaxKeys": max_keys}
        if continuation_token:
            log.info(  # type: ignore
                "Listing %s objects in s3://%s/%s using continuation token ending with %s with %s objects listed thus far.",
                max_keys, bucket_name, prefix, continuation_token[-6:], len(contents))  # pylint: disable=unsubscriptable-object
            response = _S3_CLIENT.list_objects_v2(**request_kwargs, ContinuationToken=continuation_token)
        else:
            log.info("Listing %s objects in s3://%s/%s with %s objects listed thus far.", max_keys, bucket_name, prefix, len(contents))
            response = _S3_CLIENT.list_objects_v2(**request_kwargs)
        assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
        contents.extend(response["Contents"])
        is_truncated = response["IsTruncated"]
        if (not is_truncated) or (len(contents) >= limit):
            break
        continuation_token = response["NextContinuationToken"]
    assert len(contents) <= limit
    log.info("Returning %s objects from s3://%s/%s.", len(contents), bucket_name, prefix)
    return contents


if __name__ == "__main__":
    s3_list("noaa-gefs-pds", "gefs.20190828/12/pgrb2a", limit=10_000)

How to handle errors with boto3?

In case you have to deal with the arguably unfriendly logs client (CloudWatch Logs put-log-events), this is what I had to do to properly catch Boto3 client exceptions:

try:
    ### Boto3 client code here...

except boto_exceptions.ClientError as error:
    Log.warning("Catched client error code %s",
                error.response['Error']['Code'])

    if error.response['Error']['Code'] in ["DataAlreadyAcceptedException",
                                           "InvalidSequenceTokenException"]:
        Log.debug(
            "Fetching sequence_token from boto error response['Error']['Message'] %s",
            error.response["Error"]["Message"])
        # NOTE: apparently there's no sequenceToken attribute in the response so we have
        # to parse response["Error"]["Message"] string
        sequence_token = error.response["Error"]["Message"].split(":")[-1].strip(" ")
        Log.debug("Setting sequence_token to %s", sequence_token)

This works both at first attempt (with empty LogStream) and subsequent ones.

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

Bundler 2

If you need to update from bundler v1 to v2 follow this official guide.

For a fast solution:

  1. In root fo your application run bundle config set path "/bundle" to add a custom path for bundler use, in this case I set /bundle, you can use whatever.

    1.2 [Alternative solution] You can use a bundler file (~/.bundle/config) also, to use this I recommend set bundler folders in environment, like a Docker image, for example. Here the official guide.

  2. You don't need to delete your Gemfile.lock, It's a bad practice and this can cause other future problems. Commit Gemfile.lock normaly, sometimes you need to update your bundle with bundle install or install individual gem.

You can see all the configs for bundler version 2 here.

How to convert Django Model object to dict with its fields and values?

Simplest way,

  1. If your query is Model.Objects.get():

    get() will return single instance so you can direct use __dict__ from your instance

    model_dict = Model.Objects.get().__dict__

  2. for filter()/all():

    all()/filter() will return list of instances so you can use values() to get list of objects.

    model_values = Model.Objects.all().values()

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

I think you can't achieve what you want in a more efficient manner than you proposed.

The underlying problem is that the timestamps (as you seem aware) are made up of two parts. The data that represents the UTC time, and the timezone, tz_info. The timezone information is used only for display purposes when printing the timezone to the screen. At display time, the data is offset appropriately and +01:00 (or similar) is added to the string. Stripping off the tz_info value (using tz_convert(tz=None)) doesn't doesn't actually change the data that represents the naive part of the timestamp.

So, the only way to do what you want is to modify the underlying data (pandas doesn't allow this... DatetimeIndex are immutable -- see the help on DatetimeIndex), or to create a new set of timestamp objects and wrap them in a new DatetimeIndex. Your solution does the latter:

pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])

For reference, here is the replace method of Timestamp (see tslib.pyx):

def replace(self, **kwds):
    return Timestamp(datetime.replace(self, **kwds),
                     offset=self.offset)

You can refer to the docs on datetime.datetime to see that datetime.datetime.replace also creates a new object.

If you can, your best bet for efficiency is to modify the source of the data so that it (incorrectly) reports the timestamps without their timezone. You mentioned:

I want to work with timezone naive timeseries (to avoid the extra hassle with timezones, and I do not need them for the case I am working on)

I'd be curious what extra hassle you are referring to. I recommend as a general rule for all software development, keep your timestamp 'naive values' in UTC. There is little worse than looking at two different int64 values wondering which timezone they belong to. If you always, always, always use UTC for the internal storage, then you will avoid countless headaches. My mantra is Timezones are for human I/O only.

How do I convert datetime.timedelta to minutes, hours in Python?

There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. timedelta object supports str() operation that will do this. It works even in Python 2.6.

>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'

Failed to build gem native extension — Rails install

mkmf is part of the ruby1.9.1-dev package. This package contains the header files needed for extension libraries for Ruby 1.9.1. You need to install the ruby1.9.1-dev package by doing:

sudo apt-get install ruby1.9.1-dev

Then you can install Rails as per normal.

Generally it's easier to just do:

sudo apt-get install ruby-dev

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

How to make an unaware datetime timezone aware in python

Python 3.9 adds the zoneinfo module so now only the standard library is needed!

from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)

Attach a timezone:

>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'

Attach the system's local timezone:

>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'

Subsequently it is properly converted to other timezones:

>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'

Wikipedia list of available time zones


Windows has no system time zone database, so here an extra package is needed:

pip install tzdata  

There is a backport to allow use of zoneinfo in Python 3.6 to 3.8:

pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo

incompatible character encodings: ASCII-8BIT and UTF-8

I have a suspicion that you either copy/pasted a part of your Haml template into the file, or you're working with a non-Unicode/non-UTF-8 friendly editor.

See if you can recreate that file from the scratch in a UTF-8 friendly editor. There are plenty for any platform and see whether this fixes your problem. Start by erasing the line with #content and retyping it manually.

Python strptime() and timezones?

The datetime module documentation says:

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

See that [0:6]? That gets you (year, month, day, hour, minute, second). Nothing else. No mention of timezones.

Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.

It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:

When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.

Note that this doesn't work with %Z, so the case is important. See the following example:

In [1]: from datetime import datetime

In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')

In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: None

In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')

In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: UTC+10:00

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

use -n parameter to install like for cocoapods:

sudo gem install cocoapods -n /usr/local/bin

Python: Figure out local timezone

Avoiding non-standard module (seems to be a missing method of datetime module):

from datetime import datetime
utcOffset_min = int(round((datetime.now() - datetime.utcnow()).total_seconds())) / 60   # round for taking time twice
utcOffset_h = utcOffset_min / 60
assert(utcOffset_min == utcOffset_h * 60)   # we do not handle 1/2 h timezone offsets

print 'Local time offset is %i h to UTC.' % (utcOffset_h)

Why does datetime.datetime.utcnow() not contain timezone information?

Note that for Python 3.2 onwards, the datetime module contains datetime.timezone. The documentation for datetime.utcnow() says:

An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc).

So, datetime.utcnow() doesn't set tzinfo to indicate that it is UTC, but datetime.now(datetime.timezone.utc) does return UTC time with tzinfo set.

So you can do:

>>> import datetime
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2014, 7, 10, 2, 43, 55, 230107, tzinfo=datetime.timezone.utc)

How do I print a datetime in the local timezone?

As of python 3.2, using only standard library functions:

u_tm = datetime.datetime.utcfromtimestamp(0)
l_tm = datetime.datetime.fromtimestamp(0)
l_tz = datetime.timezone(l_tm - u_tm)

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=l_tz)
str(t)
'2009-07-10 18:44:59.193982-07:00'

Just need to use l_tm - u_tm or u_tm - l_tm depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.

And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.

How to install python-dateutil on Windows?

First confirm that you have in C:/python##/Lib/Site-packages/ a folder dateutil, perhaps you download it, you should already have pip,matplotlib, six##,,confirm you have installed dateutil by--- go to the cmd, cd /python, you should have a folder /Scripts. cd to Scripts, then type --pip install python-dateutil -- ----This applies to windows 7 Ultimate 32bit, Python 3.4------

What are all the uses of an underscore in Scala?

Here are some more examples where _ is used:

val nums = List(1,2,3,4,5,6,7,8,9,10)

nums filter (_ % 2 == 0)

nums reduce (_ + _)

nums.exists(_ > 5)

nums.takeWhile(_ < 8)

In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)

How to convert string to boolean php

filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

$string = 1; // true
$string ='1'; // true
$string = 'true'; // true
$string = 'trUe'; // true
$string = 'TRUE'; // true
$string = 0; // false
$string = '0'; // false
$string = 'false'; // false
$string = 'False'; // false
$string = 'FALSE'; // false
$string = 'sgffgfdg'; // null

You must specify

FILTER_NULL_ON_FAILURE
otherwise you'll get always false even if $string contains something else.

How to get a reversed list view on a list in Java?

Its not exactly elegant, but if you use List.listIterator(int index) you can get a bi-directional ListIterator to the end of the list:

//Assume List<String> foo;
ListIterator li = foo.listIterator(foo.size());

while (li.hasPrevious()) {
   String curr = li.previous()
}

How to get the request parameters in Symfony 2?

Inside a controller:

$request = $this->getRequest();
$username = $request->get('username');

Do conditional INSERT with SQL?

It is possible with EXISTS condition. WHERE EXISTS tests for the existence of any records in a subquery. EXISTS returns true if the subquery returns one or more records. Here is an example

UPDATE  TABLE_NAME 
SET val1=arg1 , val2=arg2
WHERE NOT EXISTS
    (SELECT FROM TABLE_NAME WHERE val1=arg1 AND val2=arg2)

Fill remaining vertical space with CSS using display:flex

The example below includes scrolling behaviour if the content of the expanded centre component extends past its bounds. Also the centre component takes 100% of remaining space in the viewport.

jsfiddle here

html, body, .r_flex_container{
    height: 100%;
    display: flex;
    flex-direction: column;
    background: red;
    margin: 0;
}
.r_flex_container {
    display:flex;
    flex-flow: column nowrap;
    background-color:blue;
}

.r_flex_fixed_child {
    flex:none;
    background-color:black;
    color:white;

}
.r_flex_expand_child {
    flex:auto;
    background-color:yellow;
    overflow-y:scroll;
}

Example of html that can be used to demonstrate this behaviour

<html>
<body>
    <div class="r_flex_container">
      <div class="r_flex_fixed_child">
        <p> This is the fixed 'header' child of the flex container </p>
      </div>
      <div class="r_flex_expand_child">
            <article>this child container expands to use all of the space given to it -  but could be shared with other expanding childs in which case they would get equal space after the fixed container space is allocated. 
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,
            </article>
      </div>
      <div class="r_flex_fixed_child">
        this is the fixed footer child of the flex container
        asdfadsf
        <p> another line</p>
      </div>

    </div>
</body>
</html>

Disable webkit's spin buttons on input type="number"?

It seems impossible to prevent spinners from appearing in Opera. As a temporary workaround, you can make room for the spinners. As far as I can tell, the following CSS adds just enough padding, only in Opera:

noindex:-o-prefocus,
input[type=number] {
    padding-right: 1.2em;
}

HTML tag <a> want to add both href and onclick working

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>

Anaconda Installed but Cannot Launch Navigator

100% Solved. While Installing make sure you are connected to Internet. If already installed anaconda, open the anaconda command prompt and type following command:

conda install -c anaconda anaconda-navigator
(internet connection is required)

Note: In some cases restarting may solve the issue of navigator.

How do you make a deep copy of an object?

Use XStream(http://x-stream.github.io/). You can even control which properties you can ignore through annotations or explicitly specifying the property name to XStream class. Moreover you do not need to implement clonable interface.

How to get the max of two values in MySQL?

Use GREATEST()

E.g.:

SELECT GREATEST(2,1);

Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)

Get only part of an Array in Java?

The length of an array in Java is immutable. So, you need to copy the desired part as a new array.
Use copyOfRange method from java.util.Arrays class:

int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);

startIndex is the initial index of the range to be copied, inclusive.
endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)

E.g.:

   //index   0   1   2   3   4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2);          // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4);          // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)

How do I wait until Task is finished in C#?

Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    string result = string.Empty;
    Task continuation = responseTask.ContinueWith(x => result = Print(x));
    continuation.Wait();
    return result;
}

private static string Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    Task continuation = task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    continuation.Wait();  
    return result;
}

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

Batch Files - Error Handling

I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.

yourCommand && (
  echo yourCommand was successful
) || (
  echo yourCommand failed
)

There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.

yourCommand && (
  someCommandThatMayFail
) || (
  echo This will fire if yourCommand or someCommandThatMayFail raises an error
)

The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call ), which does nothing except set the ERRORLEVEL to 0. There is a corollary (call) that does nothing except set the ERRORLEVEL to 1.

yourCommand && (
  someCommandThatMayFail
  (call )
) || (
  echo This can only fire if yourCommand raises an error
)

See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.

How to delete object from array inside foreach loop?

You can also use references on foreach values:

foreach($array as $elementKey => &$element) {
    // $element is the same than &$array[$elementKey]
    if (isset($element['id']) and $element['id'] == 'searched_value') {
        unset($element);
    }
}

Appending a vector to a vector

While saying "the compiler can reserve", why rely on it? And what about automatic detection of move semantics? And what about all that repeating of the container name with the begins and ends?

Wouldn't you want something, you know, simpler?

(Scroll down to main for the punchline)

#include <type_traits>
#include <vector>
#include <iterator>
#include <iostream>

template<typename C,typename=void> struct can_reserve: std::false_type {};

template<typename T, typename A>
struct can_reserve<std::vector<T,A>,void>:
    std::true_type
{};

template<int n> struct secret_enum { enum class type {}; };
template<int n>
using SecretEnum = typename secret_enum<n>::type;

template<bool b, int override_num=1>
using EnableFuncIf = typename std::enable_if< b, SecretEnum<override_num> >::type;
template<bool b, int override_num=1>
using DisableFuncIf = EnableFuncIf< !b, -override_num >;

template<typename C, EnableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t n ) {
  c.reserve(n);
}
template<typename C, DisableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t ) { } // do nothing

template<typename C,typename=void>
struct has_size_method:std::false_type {};
template<typename C>
struct has_size_method<C, typename std::enable_if<std::is_same<
  decltype( std::declval<C>().size() ),
  decltype( std::declval<C>().size() )
>::value>::type>:std::true_type {};

namespace adl_aux {
  using std::begin; using std::end;
  template<typename C>
  auto adl_begin(C&&c)->decltype( begin(std::forward<C>(c)) );
  template<typename C>
  auto adl_end(C&&c)->decltype( end(std::forward<C>(c)) );
}
template<typename C>
struct iterable_traits {
    typedef decltype( adl_aux::adl_begin(std::declval<C&>()) ) iterator;
    typedef decltype( adl_aux::adl_begin(std::declval<C const&>()) ) const_iterator;
};
template<typename C> using Iterator = typename iterable_traits<C>::iterator;
template<typename C> using ConstIterator = typename iterable_traits<C>::const_iterator;
template<typename I> using IteratorCategory = typename std::iterator_traits<I>::iterator_category;

template<typename C, EnableFuncIf< has_size_method<C>::value, 1>... >
std::size_t size_at_least( C&& c ) {
    return c.size();
}

template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 2>... >
std::size_t size_at_least( C&& c ) {
    using std::begin; using std::end;
  return end(c)-begin(c);
};
template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  !std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 3>... >
std::size_t size_at_least( C&& c ) {
  return 0;
};

template < typename It >
auto try_make_move_iterator(It i, std::true_type)
-> decltype(make_move_iterator(i))
{
    return make_move_iterator(i);
}
template < typename It >
It try_make_move_iterator(It i, ...)
{
    return i;
}


#include <iostream>
template<typename C1, typename C2>
C1&& append_containers( C1&& c1, C2&& c2 )
{
  using std::begin; using std::end;
  try_reserve( c1, size_at_least(c1) + size_at_least(c2) );

  using is_rvref = std::is_rvalue_reference<C2&&>;
  c1.insert( end(c1),
             try_make_move_iterator(begin(c2), is_rvref{}),
             try_make_move_iterator(end(c2), is_rvref{}) );

  return std::forward<C1>(c1);
}

struct append_infix_op {} append;
template<typename LHS>
struct append_on_right_op {
  LHS lhs;
  template<typename RHS>
  LHS&& operator=( RHS&& rhs ) {
    return append_containers( std::forward<LHS>(lhs), std::forward<RHS>(rhs) );
  }
};

template<typename LHS>
append_on_right_op<LHS> operator+( LHS&& lhs, append_infix_op ) {
  return { std::forward<LHS>(lhs) };
}
template<typename LHS,typename RHS>
typename std::remove_reference<LHS>::type operator+( append_on_right_op<LHS>&& lhs, RHS&& rhs ) {
  typename std::decay<LHS>::type retval = std::forward<LHS>(lhs.lhs);
  return append_containers( std::move(retval), std::forward<RHS>(rhs) );
}

template<typename C>
void print_container( C&& c ) {
  for( auto&& x:c )
    std::cout << x << ",";
  std::cout << "\n";
};

int main() {
  std::vector<int> a = {0,1,2};
  std::vector<int> b = {3,4,5};
  print_container(a);
  print_container(b);
  a +append= b;
  const int arr[] = {6,7,8};
  a +append= arr;
  print_container(a);
  print_container(b);
  std::vector<double> d = ( std::vector<double>{-3.14, -2, -1} +append= a );
  print_container(d);
  std::vector<double> c = std::move(d) +append+ a;
  print_container(c);
  print_container(d);
  std::vector<double> e = c +append+ std::move(a);
  print_container(e);
  print_container(a);
}

hehe.

Now with move-data-from-rhs, append-array-to-container, append forward_list-to-container, move-container-from-lhs, thanks to @DyP's help.

Note that the above does not compile in clang thanks to the EnableFunctionIf<>... technique. In clang this workaround works.

How to get the Full file path from URI

  public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}

Using this method we can get string filepath from Uri.

How do I get the current username in Windows PowerShell?

I have used $env:username in the past, but a colleague pointed out it's an environment variable and can be changed by the user and therefore, if you really want to get the current user's username, you shouldn't trust it.

I'd upvote Mark Seemann's answer: [System.Security.Principal.WindowsIdentity]::GetCurrent().Name

But I'm not allowed to. With Mark's answer, if you need just the username, you may have to parse it out since on my system, it returns hostname\username and on domain joined machines with domain accounts it will return domain\username.

I would not use whoami.exe since it's not present on all versions of Windows, and it's a call out to another binary and may give some security teams fits.

Set equal width of columns in table layout in Android

Try this.

It boils down to adding android:stretchColumns="*" to your TableLayout root and setting android:layout_width="0dp" to all the children in your TableRows.

<TableLayout
    android:stretchColumns="*"   // Optionally use numbered list "0,1,2,3,..."
>
    <TableRow
        android:layout_width="0dp"
    >

Android: I lost my android key store, what should I do?

If you lost a keystore file, don't create/update the new one with another set of value. First do the thorough search. Because it will overwrite the old one, so it will not match to your previous apk.

If you use eclipse most probably it will store in default path. For MAC (eclipse) it will be in your elispse installation path something like:

/Applications/eclipse/Eclipse.app/Contents/MacOS/

then your keystore file without any extension. You need root privilege to access this path (file).

How to sort a collection by date in MongoDB?

Sushant Gupta's answers are a tad bit outdated and don't work anymore.

The following snippet should be like this now :

collection.find({}, {"sort" : ['datefield', 'asc']} ).toArray(function(err,docs) {});

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

Time complexity of accessing a Python dict

My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.

I use a dictionary to memoize values. That seems to be a bottleneck.

This is evidence of a bug in your memoization method.

using batch echo with special characters

In order to use special characters, such as '>' on Windows with echo, you need to place a special escape character before it.

For instance

echo A->B

will not work since '>' has to be escaped by '^':

 echo A-^>B

See also escape sequences. enter image description here

There is a short batch file, which prints a basic set of special character and their escape sequences.

Execute bash script from URL

bash | curl http://your.url.here/script.txt

actual example:

juan@juan-MS-7808:~$ bash | curl https://raw.githubusercontent.com/JPHACKER2k18/markwe/master/testapp.sh


Oh, wow im alive


juan@juan-MS-7808:~$ 

Assigning variables with dynamic names in Java

What you need is named array. I wanted to write the following code:

int[] n = new int[4];

for(int i=1;i<4;i++)
{
    n[i] = 5;
}

How to vertically center a "div" element for all browsers using CSS?

Actually you need two div's for vertical centering. The div containing the content must have a width and height.

_x000D_
_x000D_
#container {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  margin-top: -200px;_x000D_
  /* half of #content height*/_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#content {_x000D_
  width: 624px;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
  height: 395px;_x000D_
  border: 1px solid #000000;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="content">_x000D_
    <h1>Centered div</h1>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is the result

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

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

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

How can I remove the last character of a string in python?

The easiest is

as @greggo pointed out

string="mystring";
string[:-1]

Built in Python hash() function

Most answers suggest this is because of different platforms, but there is more to it. From the documentation of object.__hash__(self):

By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n²) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.

Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).

Even running on the same machine will yield varying results across invocations:

$ python -c "print(hash('http://stackoverflow.com'))"
-3455286212422042986
$ python -c "print(hash('http://stackoverflow.com'))"
-6940441840934557333

While:

$ python -c "print(hash((1,2,3)))"
2528502973977326415
$ python -c "print(hash((1,2,3)))"
2528502973977326415

See also the environment variable PYTHONHASHSEED:

If this variable is not set or set to random, a random value is used to seed the hashes of str, bytes and datetime objects.

If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.

Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.

The integer must be a decimal number in the range [0, 4294967295]. Specifying the value 0 will disable hash randomization.

For example:

$ export PYTHONHASHSEED=0                            
$ python -c "print(hash('http://stackoverflow.com'))"
-5843046192888932305
$ python -c "print(hash('http://stackoverflow.com'))"
-5843046192888932305

Select 50 items from list at random to write to file

One easy way to select random items is to shuffle then slice.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables

Trigger function when date is selected with jQuery UI datepicker

If you are also interested in the case where the user closes the date selection dialog without selecting a date (in my case choosing no date also has meaning) you can bind to the onClose event:

$('#datePickerElement').datepicker({
         onClose: function (dateText, inst) {
            //you will get here once the user is done "choosing" - in the dateText you will have 
            //the new date or "" if no date has been selected             
      });

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

paste is good for this job:

paste -d " "  - - < filename

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

I'm going to assume that your lack of quotes around the selector is just a transcription error, but you should check it anyway. Also, I don't see where you are actually giving the form an id. Usually you do this with the htmlAttributes parameter. I don't see you using the signature that has it. Again, though, if the form is submitting at all, this could be a transcription error.

If the selector and the id aren't the problem I'm suspicious that it might be because the click handler is added via markup when you use the Ajax BeginForm extension. You might try using $('form').trigger('submit') or in the worst case, have the click handler on the anchor create a hidden submit button in the form and click it. Or even create your own ajax submission using pure jQuery (which is probably what I would do).

Lastly, you should realize that by replacing the submit button, you're going to totally break this for people who don't have javascript enabled. The way around this is to also have a button hidden using a noscript tag and handle both AJAX and non-AJAX posts on the server.

BTW, it's consider standard practice, Microsoft not withstanding, to add the handlers via javascript not via markup. This keeps your javascript organized in one place so you can more easily see what's going on on the form. Here's an example of how I would use the trigger mechanism.

  $(function() {
      $('form#ajaxForm').find('a.submit-link').click( function() {
           $('form#ajaxForm').trigger('submit');
      }).show();
  }

<% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
     new AjaxOptions
     {
       UpdateTargetId = "DescriptionDiv",
       HttpMethod = "post"
     }, new { id = "ajaxForm" } )) {%>
   Description:
   <%= Html.TextBox("Description", Model.Description) %><br />
   <a href="#" class="submit-link" style="display: none;">Save</a>
   <noscript>
       <input type="submit" value="Save" />
   </noscript>
<% } %>

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

Remove border radius from Select tag in bootstrap 3

Using the SVG from @ArnoTenkink as an data url combined with the accepted answer, this gives us the perfect solution for retina displays.

select.form-control:not([multiple]) {
    border-radius: 0;
    appearance: none;
    background-position: right 50%;
    background-repeat: no-repeat;
    background-image: url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%20%3C%21DOCTYPE%20svg%20PUBLIC%20%22-//W3C//DTD%20SVG%201.1//EN%22%20%22http%3A//www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22%3E%20%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%2214px%22%20height%3D%2212px%22%20viewBox%3D%220%200%2014%2012%22%20enable-background%3D%22new%200%200%2014%2012%22%20xml%3Aspace%3D%22preserve%22%3E%20%3Cpolygon%20points%3D%223.862%2C7.931%200%2C4.069%207.725%2C4.069%20%22/%3E%3C/svg%3E);
    padding: .5em;
    padding-right: 1.5em
}

Checking Maven Version

You need to add path to svn.exe file to system environment, variable PATH, after that you can run command mvn from any folder. You can do it from command line(cmd.exe) like this, for example:

set PATH=%PATH%;C:\maven\bin

Or you can got to the folder where mvn.exe is, and run your command there.

And you need not mvn -version, but mvn --version parameter.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

Operato union

select * from tableA where tableA.Field1 in (1,2,...999)
union
select * from tableA where tableA.Field1 in (1000,1001,...1999)
union
select * from tableA where tableA.Field1 in (2000,2001,...2999)

Is there any way to set environment variables in Visual Studio Code?

In the VSCode launch.json you can use "env" and configure all your environment variables there:

{
    "version": "0.2.0",
    "configurations": [
        {           
            "env": {
                "NODE_ENV": "development",
                "port":"1337"
            },
            ...
        }
    ]
}

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

jQuery load first 3 elements, click "load more" to display next 5 elements

Simple and with little changes. And also hide load more when entire list is loaded.

jsFiddle here.

$(document).ready(function () {
    // Load the first 3 list items from another HTML file
    //$('#myList').load('externalList.html li:lt(3)');
    $('#myList li:lt(3)').show();
    $('#showLess').hide();
    var items =  25;
    var shown =  3;
    $('#loadMore').click(function () {
        $('#showLess').show();
        shown = $('#myList li:visible').size()+5;
        if(shown< items) {$('#myList li:lt('+shown+')').show();}
        else {$('#myList li:lt('+items+')').show();
             $('#loadMore').hide();
             }
    });
    $('#showLess').click(function () {
        $('#myList li').not(':lt(3)').hide();
    });
});

How to uncommit my last commit in Git

If you aren't totally sure what you mean by "uncommit" and don't know if you want to use git reset, please see "Revert to a previous Git commit".

If you're trying to understand git reset better, please see "Can you explain what "git reset" does in plain English?".


If you know you want to use git reset, it still depends what you mean by "uncommit". If all you want to do is undo the act of committing, leaving everything else intact, use:

git reset --soft HEAD^

If you want to undo the act of committing and everything you'd staged, but leave the work tree (your files intact):

git reset HEAD^

And if you actually want to completely undo it, throwing away all uncommitted changes, resetting everything to the previous commit (as the original question asked):

git reset --hard HEAD^

The original question also asked it's HEAD^ not HEAD. HEAD refers to the current commit - generally, the tip of the currently checked-out branch. The ^ is a notation which can be attached to any commit specifier, and means "the commit before". So, HEAD^ is the commit before the current one, just as master^ is the commit before the tip of the master branch.

Here's the portion of the git-rev-parse documentation describing all of the ways to specify commits (^ is just a basic one among many).

Getting an Embedded YouTube Video to Auto Play and Loop

All of the answers didn't work for me, I checked the playlist URL and seen that playlist parameter changed to list! So it should be:

&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs

So here is the full code I use make a clean, looping, autoplay video:

<iframe width="100%" height="425" src="https://www.youtube.com/embed/MavEpJETfgI?autoplay=1&showinfo=0&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs&rel=0" frameborder="0" allowfullscreen></iframe>

Using a list as a data source for DataGridView

this Func may help you . it add every list object to grid view

private void show_data()
        {
            BindingSource Source = new BindingSource();

            for (int i = 0; i < CC.Contects.Count; i++)
            {
                Source.Add(CC.Contects.ElementAt(i));
            };


            Data_View.DataSource = Source;

        }

I write this for simple database app

Generate Row Serial Numbers in SQL Query

select ROW_NUMBER() over (order by pk_field ) as srno 
from TableName

Parse JSON object with string and value only

My pseudocode example will be as follows:

JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();

for (each json in jsonArray) {
    String id = json.get("id");
    String name = json.get("name");

    newJson.put(id, name);
}

return newJson;

The project cannot be built until the build path errors are resolved.

This happens when libraries added to the project doesn't have the correct path.

  1. Right click on your project (from package explorer)
  2. Got build path -> configure build path
  3. Select the libraries tab
  4. Fix the path error (give the correct path) by editing jars or classes at fault

How to implode array with key and value without foreach in PHP

Change

-    return substr($result, (-1 * strlen($glue)));
+    return substr($result, 0, -1 * strlen($glue));

if you want to resive the entire String without the last $glue

function key_implode(&$array, $glue) {
    $result = "";
    foreach ($array as $key => $value) {
        $result .= $key . "=" . $value . $glue;
    }
    return substr($result, (-1 * strlen($glue)));
}

And the usage:

$str = key_implode($yourArray, ",");

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

How to exclude particular class name in CSS selector?

In modern browsers you can do:

.reMode_hover:not(.reMode_selected):hover{}

Consult http://caniuse.com/css-sel3 for compatibility information.

Return Result from Select Query in stored procedure to a List

Building on some of the responds here, i'd like to add an alternative way. Creating a generic method using reflection, that can map any Stored Procedure response to a List. That is, a List of any type you wish, as long as the given type contains similarly named members to the Stored Procedure columns in the response. Ideally, i'd probably use Dapper for this - but here goes:

private static SqlConnection getConnectionString() // Should be gotten from config in secure storage.
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = "it.hurts.when.IP";
            builder.UserID = "someDBUser";
            builder.Password = "someDBPassword";
            builder.InitialCatalog = "someDB";
            return new SqlConnection(builder.ConnectionString);
        }

        public static List<T> ExecuteSP<T>(string SPName, List<SqlParameter> Params)
        {
            try
            {
                DataTable dataTable = new DataTable();

                using (SqlConnection Connection = getConnectionString())
                {
                    // Open connection
                    Connection.Open();

                    // Create command from params / SP
                    SqlCommand cmd = new SqlCommand(SPName, Connection);

                    // Add parameters
                    cmd.Parameters.AddRange(Params.ToArray());
                    cmd.CommandType = CommandType.StoredProcedure;

                    // Make datatable for conversion
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dataTable);
                    da.Dispose();

                    // Close connection
                    Connection.Close();
                }

                // Convert to list of T
                var retVal = ConvertToList<T>(dataTable);
                return retVal;
            }
            catch (SqlException e)
            {
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

        /// <summary>
        /// Converts datatable to List<someType> if possible.
        /// </summary>
        public static List<T> ConvertToList<T>(DataTable dt)
        {
            try // Necesarry unfotunately.
            {
                var columnNames = dt.Columns.Cast<DataColumn>()
                    .Select(c => c.ColumnName)
                    .ToList();

                var properties = typeof(T).GetProperties();

                return dt.AsEnumerable().Select(row =>
                    {
                        var objT = Activator.CreateInstance<T>();

                        foreach (var pro in properties)
                        {
                            if (columnNames.Contains(pro.Name))
                            {
                                if (row[pro.Name].GetType() == typeof(System.DBNull)) pro.SetValue(objT, null, null);
                                else pro.SetValue(objT, row[pro.Name], null);
                            }
                        }

                        return objT;
                    }).ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to write data to list. Often this occurs due to type errors (DBNull, nullables), changes in SP's used or wrongly formatted SP output.");
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

Gist: https://gist.github.com/Big-al/4c1ff3ed87b88570f8f6b62ee2216f9f

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

One liner for Python based on scai's answer, but a) takes stdin, b) makes the result repeatable with seed, c) picks out only 200 of all lines.

$ cat file | python -c "import random, sys; 
  random.seed(100); print ''.join(random.sample(sys.stdin.readlines(), 200))," \
  > 200lines.txt

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

In you xxx.framework podspec file add follow config avoid pod package contains arm64 similator archs

s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }

How to scan multiple paths using the @ComponentScan annotation?

I use:

@ComponentScan(basePackages = {"com.package1","com.package2","com.package3", "com.packagen"})

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

How to return a result from a VBA function

For non-object return types, you have to assign the value to the name of your function, like this:

Public Function test() As Integer
    test = 1
End Function

Example usage:

Dim i As Integer
i = test()

If the function returns an Object type, then you must use the Set keyword like this:

Public Function testRange() As Range
    Set testRange = Range("A1")
End Function

Example usage:

Dim r As Range
Set r = testRange()

Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:

Function test(ByVal justReturnOne As Boolean) As Integer
    If justReturnOne Then
        test = 1
        Exit Function
    End If
    'more code...
    test = 2
End Function

Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx

How to make a query with group_concat in sql server

Please run the below query, it doesn't requires STUFF and GROUP BY in your case:

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , CAST((
          SELECT  T.maskdetail+','
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH(''))as varchar(max)) as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid

Change connection string & reload app.config at run time

Yeah, when ASP.NET web.config gets updated, the whole application gets restarted which means the web.config gets reloaded.

TypeError: method() takes 1 positional argument but 2 were given

It occurs when you don't specify the no of parameters the __init__() or any other method looking for.

For example:

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj=Dog("JIMMY",1,2,3,"WOOF")

When you run the above programme, it gives you an error like that:

TypeError: __init__() takes 1 positional argument but 6 were given

How we can get rid of this thing?

Just pass the parameters, what __init__() method looking for

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

Create html documentation for C# code

The above method for Visual Studio didn't seem to apply to Visual Studio 2013, but I was able to find the described checkbox using the Project Menu and selecting my project (probably the last item on the submenu) to get to the dialog with the checkbox (on the Build tab).

ImportError: No module named pythoncom

If you're on windows you probably want the pywin32 library, which includes pythoncom and a whole lot of other stuff that is pretty standard.

Is this a good way to clone an object in ES6?

if you don't want to use json.parse(json.stringify(object)) you could create recursively key-value copies:

function copy(item){
  let result = null;
  if(!item) return result;
  if(Array.isArray(item)){
    result = [];
    item.forEach(element=>{
      result.push(copy(element));
    });
  }
  else if(item instanceof Object && !(item instanceof Function)){ 
    result = {};
    for(let key in item){
      if(key){
        result[key] = copy(item[key]);
      }
    }
  }
  return result || item;
}

But the best way is to create a class that can return a clone of it self

class MyClass{
    data = null;
    constructor(values){ this.data = values }
    toString(){ console.log("MyClass: "+this.data.toString(;) }
    remove(id){ this.data = data.filter(d=>d.id!==id) }
    clone(){ return new MyClass(this.data) }
}

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I had the same issue with Xcode... black screen on launching apps, no debugging and clicking would lock up Xcode.

I finally found the problem... following the lead that the simulator could not connect to Xcode I took a look at my etc/hosts file and found that months ago to solve a different issue I had edited the host file to map localhost to my fixed IP instead of the default... my value:

10.0.1.17 localhost

This should work since that is my IP, but changing it back to the default IP fixed Xcode...

127.0.0.1 localhost

Hope this helps.

How to write log to file

I prefer the simplicity and flexibility of the 12 factor app recommendation for logging. To append to a log file you can use shell redirection. The default logger in Go writes to stderr (2).

./app 2>> logfile

See also: http://12factor.net/logs

JavaScript - cannot set property of undefined

you never set d[a] to any value.

Because of this, d[a] evaluates to undefined, and you can't set properties on undefined.

If you add d[a] = {} right after d = {} things should work as expected.

Alternatively, you could use an object initializer:

d[a] = {
    greetings: b,
    data: c
};

Or you could set all the properties of d in an anonymous function instance:

d = new function () {
    this[a] = {
        greetings: b,
        data: c
    };
};

If you're in an environment that supports ES2015 features, you can use computed property names:

d = {
  [a]: {
    greetings: b,
    data: c
  }
};

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Setting the classpath in java using Eclipse IDE

Try this:

Project -> Properties -> Java Build Path -> Add Class Folder.

If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.

HTML/CSS--Creating a banner/header

For the image that is not showing up. Open the image in the Image editor and check the type you are probably name it as "gif" but its saved in a different format that's one reason that the browser is unable to render it and it is not showing.
For the image stretching issue please specify the actual width and height dimensions in #banner instead of width: 100%; height: 200px that you have specified.

How do I compile and run a program in Java on my Mac?

Compiling and running a Java application on Mac OSX, or any major operating system, is very easy. Apple includes a fully-functional Java runtime and development environment out-of-the-box with OSX, so all you have to do is write a Java program and use the built-in tools to compile and run it.

Writing Your First Program

The first step is writing a simple Java program. Open up a text editor (the built-in TextEdit app works fine), type in the following code, and save the file as "HelloWorld.java" in your home directory.

public class HelloWorld {
    public static void main(String args[]) {
        System.out.println("Hello World!");
    }
}

For example, if your username is David, save it as "/Users/David/HelloWorld.java". This simple program declares a single class called HelloWorld, with a single method called main. The main method is special in Java, because it is the method the Java runtime will attempt to call when you tell it to execute your program. Think of it as a starting point for your program. The System.out.println() method will print a line of text to the screen, "Hello World!" in this example.

Using the Compiler

Now that you have written a simple Java program, you need to compile it. Run the Terminal app, which is located in "Applications/Utilities/Terminal.app". Type the following commands into the terminal:

cd ~
javac HelloWorld.java

You just compiled your first Java application, albeit a simple one, on OSX. The process of compiling will produce a single file, called "HelloWorld.class". This file contains Java byte codes, which are the instructions that the Java Virtual Machine understands.

Running Your Program

To run the program, type the following command in the terminal.

java HelloWorld

This command will start a Java Virtual Machine and attempt to load the class called HelloWorld. Once it loads that class, it will execute the main method I mentioned earlier. You should see "Hello World!" printed in the terminal window. That's all there is to it.

As a side note, TextWrangler is just a text editor for OSX and has no bearing on this situation. You can use it as your text editor in this example, but it is certainly not necessary.

Installing a pip package from within a Jupyter Notebook not working

%pip install fedex    #fedex = package name

in 2019.

In older versions of conda:

import sys
!{sys.executable} -m pip install fedex     #fedex = package name

*note - you do need to import sys

Java ArrayList for integers

you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.

so if you want your code to work just put.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);

Is there a limit on number of tcp/ip connections between machines on linux?

Is your server single-threaded? If so, what polling / multiplexing function are you using?

Using select() does not work beyond the hard-coded maximum file descriptor limit set at compile-time, which is hopeless (normally 256, or a few more).

poll() is better but you will end up with the scalability problem with a large number of FDs repopulating the set each time around the loop.

epoll() should work well up to some other limit which you hit.

10k connections should be easy enough to achieve. Use a recent(ish) 2.6 kernel.

How many client machines did you use? Are you sure you didn't hit a client-side limit?

HTML to PDF with Node.js

In case you arrive here looking for a way to make PDF from view templates in Express, a colleague and I made express-template-to-pdf

which allows you to generate PDF from whatever templates you're using in Express - Pug, Nunjucks, whatever.

It depends on html-pdf and is written to use in your routes just like you use res.render:

const pdfRenderer = require('@ministryofjustice/express-template-to-pdf')

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')

app.use(pdfRenderer())

If you've used res.render then using it should look obvious:

app.use('/pdf', (req, res) => {
    res.renderPDF('helloWorld', { message: 'Hello World!' });
})

You can pass options through to html-pdf to control the PDF document page size etc

Merely building on the excellent work of others.

Python: printing a file to stdout

Sure. Assuming you have a string with the file's name called fname, the following does the trick.

with open(fname, 'r') as fin:
    print(fin.read())

How do you import an Eclipse project into Android Studio now?

Export from Eclipse

  1. Update your Eclipse ADT Plugin to 22.0 or higher, then go to File | Export

  2. Go to Android now then click on Generate Gradle build files, then it would generate gradle file for you.

    enter image description here

  3. Select your project you want to export

    enter image description here

  4. Click on finish now

    enter image description here

Import into Android Studio

  1. In Android Studio, close any projects currently open. You should see the Welcome to Android Studio window.

  2. Click Import Project.

  3. Locate the project you exported from Eclipse, expand it, select it and click OK.

Call web service in excel

In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.

Sub Demo()
    Dim XDoc As MSXML2.DOMDocument
    Dim xEmpDetails As MSXML2.IXMLDOMNode
    Dim xParent As MSXML2.IXMLDOMNode
    Dim xChild As MSXML2.IXMLDOMNode
    Dim query As String
    Dim Col, Row As Integer
    Dim objWS As New clsws_GlobalWeather

    Set XDoc = New MSXML2.DOMDocument
    XDoc.async = False
    XDoc.validateOnParse = False
    query = objWS.wsm_GetCitiesByCountry("india")

    If Not XDoc.LoadXML(query) Then  'strXML is the string with XML'
        Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
    End If
    XDoc.LoadXML (query)

    Set xEmpDetails = XDoc.DocumentElement
    Set xParent = xEmpDetails.FirstChild
    Worksheets("Sheet3").Cells(1, 1).Value = "Country"
    Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
    Worksheets("Sheet3").Cells(1, 2).Value = "City"
    Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
    Row = 2
    Col = 1
    For Each xParent In xEmpDetails.ChildNodes
        For Each xChild In xParent.ChildNodes
            Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
            Col = Col + 1
        Next xChild
        Row = Row + 1
        Col = 1
    Next xParent
End Sub

How can I switch word wrap on and off in Visual Studio Code?

Go to the Preferences tab (menu FileSettings), and then search as “word wrap”. The following animated image is helpful too.

Enter image description here

PHP check whether property exists in object or class

property_exists( mixed $class , string $property )

if (property_exists($ob, 'a')) 

isset( mixed $var [, mixed $... ] )

if (isset($ob->a))

isset() will return false if property is null

Example 1:

$ob->a = null
var_dump(isset($ob->a)); // false

Example 2:

class Foo
{
   public $bar = null;
}

$foo = new Foo();

var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

goto command prompt

netstat -aon

for linux

netstat -tulpn | grep 'your_port_number'

it will show you something like

 TCP    192.1.200.48:2053      24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:2055      24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:2126      213.146.189.201:12350  ESTABLISHED     1308
 TCP    192.1.200.48:3918      192.1.200.2:8073       ESTABLISHED     1504
 TCP    192.1.200.48:3975      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:3976      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:4039      209.85.153.100:80      ESTABLISHED     248
 TCP    192.1.200.48:8080      209.85.153.100:80      ESTABLISHED     248

check which process has binded your port. here in above example its 248 now if you are sure that you need to kill that process fire

Linux:

kill -9 248

Windows:

taskkill /f /pid 248

it will kill that process

Can HTTP POST be limitless?

In an application I was developing I ran into what appeared to be a POST limit of about 2KB. It turned out to be that I was accidentally encoding the parameters into the URL instead of passing them in the body. So if you're running into a problem there, there is definitely a very small limit on the size of POST data you can send encoded into the URL.

SVG gradient using CSS

Building on top of what Finesse wrote, here is a simpler way to target the svg and change it's gradient.

This is what you need to do:

  1. Assign classes to each color stop defined in the gradient element.
  2. Target the css and change the stop-color for each of those stops using plain classes.
  3. Win!

Some benefits of using classes instead of :nth-child is that it'll not be affected if you reorder your stops. Also, it makes the intent of each class clear - you'll be left wondering whether you needed a blue color on the first child or the second one.

I've tested it on all Chrome, Firefox and IE11:

_x000D_
_x000D_
.main-stop {_x000D_
  stop-color: red;_x000D_
}_x000D_
.alt-stop {_x000D_
  stop-color: green;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
  <linearGradient id="gradient">_x000D_
    <stop class="main-stop" offset="0%" />_x000D_
    <stop class="alt-stop" offset="100%" />_x000D_
  </linearGradient>_x000D_
  <rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

See an editable example here: https://jsbin.com/gabuvisuhe/edit?html,css,output

svn cleanup: sqlite: database disk image is malformed

During app development I found that the messages come from the frequent and massive INSERT and UPDATE operations. Make sure to INSERT and UPDATE multiple rows or data in one single operation.

var updateStatementString : String! = ""

for item in cardids {

let newstring = "UPDATE "+TABLE_NAME+" SET pendingImages = '\(pendingImage)\' WHERE cardId = '\(item)\';"
            updateStatementString.append(newstring)

        }


        print(updateStatementString)
        let results = dbManager.sharedInstance.update(updateStatementString: updateStatementString)

        return Int64(results)

Why can't a text column have a default value in MySQL?

Without any deep knowledge of the mySQL engine, I'd say this sounds like a memory saving strategy. I assume the reason is behind this paragraph from the docs:

Each BLOB or TEXT value is represented internally by a separately allocated object. This is in contrast to all other data types, for which storage is allocated once per column when the table is opened.

It seems like pre-filling these column types would lead to memory usage and performance penalties.

How to form a correct MySQL connection string?

Here is an example:

MySqlConnection con = new MySqlConnection(
    "Server=ServerName;Database=DataBaseName;UID=username;Password=password");

MySqlCommand cmd = new MySqlCommand(
    " INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
    OSGconv.deciLon+"')", con);

con.Open();
cmd.ExecuteNonQuery();
con.Close();

String contains another two strings

string d = "You hit ssomeones for 50 damage";
string a = "damage";
string b = "someone";

if (d.Contains(a) && d.Contains(b))
{
    Response.Write(" " + d);

}
else
{
    Response.Write("The required string not contain in d");
}

Opening PDF String in new window with javascript

An updated version of answer by @Noby Fujioka:

function showPdfInNewTab(base64Data, fileName) {  
  let pdfWindow = window.open("");
  pdfWindow.document.write("<html<head><title>"+fileName+"</title><style>body{margin: 0px;}iframe{border-width: 0px;}</style></head>");
  pdfWindow.document.write("<body><embed width='100%' height='100%' src='data:application/pdf;base64, " + encodeURI(base64Data)+"#toolbar=0&navpanes=0&scrollbar=0'></embed></body></html>");
}

JPanel Padding in Java

When you need padding inside the JPanel generally you add padding with the layout manager you are using. There are cases that you can just expand the border of the JPanel.

MySQL ORDER BY multiple column ASC and DESC

i think u miss understand about table relation..

users : scores = 1 : *

just join is not a solution.

is this your intention?

SELECT users.username, avg(scores.point), avg(scores.avg_time)
FROM scores, users
WHERE scores.user_id = users.id
GROUP BY users.username
ORDER BY avg(scores.point) DESC, avg(scores.avg_time)
LIMIT 0, 20

(this query to get each users average point and average avg_time by desc point, asc )avg_time

if you want to get each scores ranking? use left outer join

SELECT users.username, scores.point, scores.avg_time
FROM scores left outer join users on scores.user_id = users.id
ORDER BY scores.point DESC, scores.avg_time
LIMIT 0, 20

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

How to assert two list contain the same elements in Python?

Given

l1 = [a,b]
l2 = [b,a]

In Python >= 3.0

assertCountEqual(l1, l2) # True

In Python >= 2.7, the above function was named:

assertItemsEqual(l1, l2) # True

In Python < 2.7

import unittest2
assertItemsEqual(l1, l2) # True

Via six module (Any Python version)

import unittest
import six
class MyTest(unittest.TestCase):
    def test(self):
        six.assertCountEqual(self, self.l1, self.l2) # True

Is there a decorator to simply cache function return values?

If you are using Django and want to cache views, see Nikhil Kumar's answer.


But if you want to cache ANY function results, you can use django-cache-utils.

It reuses Django caches and provides easy to use cached decorator:

from cache_utils.decorators import cached

@cached(60)
def foo(x, y=0):
    print 'foo is called'
    return x+y

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

Convert one date format into another in PHP

Try this:

$old_date = date('y-m-d-h-i-s');
$new_date = date('Y-m-d H:i:s', strtotime($old_date));

Hide/encrypt password in bash file to stop accidentally seeing it

Following line in above code is not working

DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)

Correct line is:

DB_PASSWORD=`echo $PASSWORD|base64 -d`

And save the password in other file as PASSWORD.

Get path from open file in Python

You can get it like this also.

filepath = os.path.abspath(f.name)

javax.naming.NameNotFoundException

I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
+-- greetBean.java
+-- greetHome.java
+-- greetRemote.java
+-- META-INF
    +-- ejb-jar.xml
    +-- jboss.xml

But as already mentioned, this tutorial is full of mistakes:

  • there is an extra character (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)
  • a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)
  • the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:

<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.

How to completely uninstall Android Studio from windows(v10)?

Uninstall your android studio in control panel and remove all data in your file manager about android studio.

How do I get some variable from another class in Java?

I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.

To run the code in setNum you have to call it. If you don't call it, the default value is 0.

List append() in for loop

You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = []
for i in range(5):    
    a.append(i)
print(a)

is all you need. This works because lists are mutable.

Also see the docs on data structures.

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

They aren't the same though, are they? One is a copy, the other is a swap. Hence the function names.

My favourite is:

a = b;

Where a and b are vectors.

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • How to install .MSI using PowerShell

    #Variables
    $computername = Get-Content 'M:\Applications\Powershell\comp list\Test.txt'
    $sourcefile = "\\server\Apps\LanSchool 7.7\Windows\Student.msi"
    #This section will install the software 
    foreach ($computer in $computername) 
    {
        $destinationFolder = "\\$computer\C$\download\LanSchool"
        #This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
        if (!(Test-Path -path $destinationFolder))
        {
            New-Item $destinationFolder -Type Directory
        }
        Copy-Item -Path $sourcefile -Destination $destinationFolder
        Invoke-Command -ComputerName $computer -ScriptBlock { & cmd /c "msiexec.exe /i c:\download\LanSchool\Student.msi" /qn ADVANCED_OPTIONS=1 CHANNEL=100}
    }
    

    I've searched all over for this myself and came up with zilch but have finally cobbled this working script together. It's working great! Thought I'd post here hopefully someone else can benefit. It pulls in a list of computers, copies the files down to the local machines and runs it. :) party on!

    Passing parameters to a JDBC PreparedStatement

    The problem was that you needed to add " ' ;" at the end.

    Object spread vs. Object.assign

    I'd like to summarize status of the "spread object merge" ES feature, in browsers, and in the ecosystem via tools.

    Spec

    Browsers: in Chrome, in SF, Firefox soon (ver 60, IIUC)

    • Browser support for "spread properties" shipped in Chrome 60, including this scenario.
    • Support for this scenario does NOT work in current Firefox (59), but DOES work in my Firefox Developer Edition. So I believe it will ship in Firefox 60.
    • Safari: not tested, but Kangax says it works in Desktop Safari 11.1, but not SF 11
    • iOS Safari: not teseted, but Kangax says it works in iOS 11.3, but not in iOS 11
    • not in Edge yet

    Tools: Node 8.7, TS 2.1

    Links

    Code Sample (doubles as compatibility test)

    var x = { a: 1, b: 2 };
    var y = { c: 3, d: 4, a: 5 };
    var z = {...x, ...y};
    console.log(z); // { a: 5, b: 2, c: 3, d: 4 }
    

    Again: At time of writing this sample works without transpilation in Chrome (60+), Firefox Developer Edition (preview of Firefox 60), and Node (8.7+).

    Why Answer?

    I'm writing this 2.5 years after the original question. But I had the very same question, and this is where Google sent me. I am a slave to SO's mission to improve the long tail.

    Since this is an expansion of "array spread" syntax I found it very hard to google, and difficult to find in compatibility tables. The closest I could find is Kangax "property spread", but that test doesn't have two spreads in the same expression (not a merge). Also, the name in the proposals/drafts/browser status pages all use "property spread", but it looks to me like that was a "first principal" the community arrived at after the proposals to use spread syntax for "object merge". (Which might explain why it is so hard to google.) So I document my finding here so others can view, update, and compile links about this specific feature. I hope it catches on. Please help spread the news of it landing in the spec and in browsers.

    Lastly, I would have added this info as a comment, but I couldn't edit them without breaking the authors' original intent. Specifically, I can't edit @ChillyPenguin's comment without it losing his intent to correct @RichardSchulte. But years later Richard turned out to be right (in my opinion). So I write this answer instead, hoping it will gain traction on the old answers eventually (might take years, but that's what the long tail effect is all about, after all).

    error: (-215) !empty() in function detectMultiScale

    The error occurs due to missing of xml files or incorrect path of xml file.

    Please try the following code,

    import numpy as np
    import cv2
    
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
    
    cap = cv2.VideoCapture(0)
    
    while 1:
        ret, img = cap.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    
        for (x,y,w,h) in faces:
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = img[y:y+h, x:x+w]
    
            eyes = eye_cascade.detectMultiScale(roi_gray)
            for (ex,ey,ew,eh) in eyes:
                cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
    
        cv2.imshow('img',img)
        k = cv2.waitKey(30) & 0xff
        if k == 27:
            break
    
    cap.release()
    cv2.destroyAllWindows()
    

    /etc/apt/sources.list" E212: Can't open file for writing

    I referenced to Zsolt in level 2, I input:

    :w !sudo tee % > /dev/null
    

    and then in my situation, I still can't modify the file, so it prompted that add "!". so I input

    :q! 
    

    then it works

    rotating axis labels in R

    Not sure if this is what you mean, but try setting las=1. Here's an example:

    require(grDevices)
    tN <- table(Ni <- stats::rpois(100, lambda=5))
    r <- barplot(tN, col=rainbow(20), las=1)
    

    output

    That represents the style of axis labels. (0=parallel, 1=all horizontal, 2=all perpendicular to axis, 3=all vertical)

    Select elements by attribute in CSS

    You can combine multiple selectors and this is so cool knowing that you can select every attribute and attribute based on their value like href based on their values with CSS only..

    Attributes selectors allows you play around some extra with id and class attributes

    Here is an awesome read on Attribute Selectors

    Fiddle

    _x000D_
    _x000D_
    a[href="http://aamirshahzad.net"][title="Aamir"] {_x000D_
      color: green;_x000D_
      text-decoration: none;_x000D_
    }_x000D_
    _x000D_
    a[id*="google"] {_x000D_
      color: red;_x000D_
    }_x000D_
    _x000D_
    a[class*="stack"] {_x000D_
      color: yellow;_x000D_
    }
    _x000D_
    <a href="http://aamirshahzad.net" title="Aamir">Aamir</a>_x000D_
    <br>_x000D_
    <a href="http://google.com" id="google-link" title="Google">Google</a>_x000D_
    <br>_x000D_
    <a href="http://stackoverflow.com" class="stack-link" title="stack">stack</a>
    _x000D_
    _x000D_
    _x000D_

    Browser support:
    IE6+, Chrome, Firefox & Safari

    You can check detail here.

    Mobile Safari: Javascript focus() method on inputfield only works with click?

    I have a search form with an icon that clears the text when clicked. However, the problem (on mobile & tablets) was that the keyboard would collapse/hide, as the click event removed focus was removed from the input.

    text search input with close icon

    Goal: after clearing the search form (clicking/tapping on x-icon) keep the keyboard visible!

    To accomplish this, apply stopPropagation() on the event like so:

    function clear ($event) {
        $event.preventDefault();
        $event.stopPropagation();
        self.query = '';
        $timeout(function () {
            document.getElementById('sidebar-search').focus();
        }, 1);
    }
    

    And the HTML form:

    <form ng-controller="SearchController as search"
        ng-submit="search.submit($event)">
            <input type="search" id="sidebar-search" 
                ng-model="search.query">
                    <span class="glyphicon glyphicon-remove-circle"
                        ng-click="search.clear($event)">
                    </span>
    </form>
    

    Delete all objects in a list

    Here's how you delete every item from a list.

    del c[:]
    

    Here's how you delete the first two items from a list.

    del c[:2]
    

    Here's how you delete a single item from a list (a in your case), assuming c is a list.

    del c[0]
    

    Maven: Non-resolvable parent POM

    I had the issue that two reactor build pom.xml files had the same artefactId.

    .htaccess: where is located when not in www base dir

    The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.

    Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.

    push() a two-dimensional array

    var r = 3; //start from rows 3
    var c = 5; //start from col 5
    
    var rows = 8;
    
    var cols = 7;
    
    
    for (var i = 0; i < rows; i++)
    
    {
    
     for (var j = 0; j < cols; j++)
    
     {
        if(j <= c && i <= r) {
          myArray[i][j] = 1;
        } else {
          myArray[i][j] = 0;
        }
    }
    
    }
    

    How to duplicate a git repository? (without forking)

    See https://help.github.com/articles/duplicating-a-repository

    Short version:

    In order to make an exact duplicate, you need to perform both a bare-clone and a mirror-push:

    mkdir foo; cd foo 
    # move to a scratch dir
    
    git clone --bare https://github.com/exampleuser/old-repository.git
    # Make a bare clone of the repository
    
    cd old-repository.git
    git push --mirror https://github.com/exampleuser/new-repository.git
    # Mirror-push to the new repository
    
    cd ..
    rm -rf old-repository.git  
    # Remove our temporary local repository
    

    NOTE: the above will work fine with any remote git repo, the instructions are not specific to github

    The above creates a new remote copy of the repo. Then clone it down to your working machine.

    Get value of multiselect box using jQuery or pure JS

    This got me the value and text of the selected options for the jQuery multiselect.js plugin:

    $("#selectBox").multiSelect({
        afterSelect: function(){
            var selections = [];
            $("#selectBox option:selected").each(function(){
                var optionValue = $(this).val();
                var optionText = $(this).text();
                console.log("optionText",optionText);                
                // collect all values
                selections.push(optionValue);
            });
    
            // use array "selections" here.. 
        }
    });   
    

    very usefull if you need it for your "onChange" event ;)

    What does request.getParameter return?

    Per the Javadoc:

    Returns the value of a request parameter as a String, or null if the parameter does not exist.

    Do note that it is possible to submit an empty parameter - such that the parameter exists, but has no value. For example, I could include &log=&somethingElse into the URL to enable logging, without needing to specify &log=true. In this case, the value will be an empty String ("").

    How to check if a table exists in MS Access for vb macros

    Access has some sort of system tables You can read about it a little here you can fire the folowing query to see if it exists ( 1 = it exists, 0 = it doesnt ;))

    SELECT Count([MSysObjects].[Name]) AS [Count]
    FROM MSysObjects
    WHERE (((MSysObjects.Name)="TblObject") AND ((MSysObjects.Type)=1));
    

    How to use orderby with 2 fields in linq?

    Use ThenByDescending:

    var hold = MyList.OrderBy(x => x.StartDate)
                     .ThenByDescending(x => x.EndDate)
                     .ToList();
    

    You can also use query syntax and say:

    var hold = (from x in MyList
               orderby x.StartDate, x.EndDate descending
               select x).ToList();
    

    ThenByDescending is an extension method on IOrderedEnumerable which is what is returned by OrderBy. See also the related method ThenBy.

    How can I select an element with multiple classes in jQuery?

    For better performance you can use

    $('div.a.b')
    

    This will look only through the div elements instead of stepping through all the html elements that you have on your page.

    How to access the contents of a vector from a pointer to the vector in C++?

    Access it like any other pointer value:

    std::vector<int>* v = new std::vector<int>();
    
    v->push_back(0);
    v->push_back(12);
    v->push_back(1);
    
    int twelve = v->at(1);
    int one = (*v)[2];
    
    // iterate it
    for(std::vector<int>::const_iterator cit = v->begin(), e = v->end; 
        cit != e;  ++cit)
    {
        int value = *cit;
    }
    
    // or, more perversely
    for(int x = 0; x < v->size(); ++x)
    {
        int value = (*v)[x];
    }
    
    // Or -- with C++ 11 support
    for(auto i : *v)
    {
       int value = i;
    }
    

    Multiple bluetooth connection

    Please take a look at the Android documentation.

    Using the Bluetooth APIs, an Android application can perform the following:

    • Scan for other Bluetooth devices
    • Query the local Bluetooth adapter for paired Bluetooth devices
    • Establish RFCOMM channels
    • Connect to other devices through service discovery
    • Transfer data to and from other devices
    • Manage multiple connections

    Get value of a specific object property in C# without knowing the class behind

    Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:

      object value = GetValue();
      string propertyName = "MyProperty";
    
      var parameter = Expression.Parameter(typeof(object));
      var cast = Expression.Convert(parameter, value.GetType());
      var propertyGetter = Expression.Property(cast, propertyName);
      var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
    
      var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
    
     var retrivedPropertyValue = propertyRetriver(value);
    

    This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.

    BULK INSERT with identity (auto-increment) column

    This is a very old post to answer, but none of the answers given solves the problem without changing the posed conditions, which I can't do.

    I solved it by using the OPENROWSET variant of BULK INSERT. This uses the same format file and works in the same way, but it allows the data file be read with a SELECT statement.

    Create your table:

    CREATE TABLE target_table(
    id bigint IDENTITY(1,1),
    col1 varchar(256) NULL,
    col2 varchar(256) NULL,
    col3 varchar(256) NULL)
    

    Open a command window an run:

    bcp dbname.dbo.target_table format nul -c -x -f C:\format_file.xml -t; -T
    

    This creates the format file based on how the table looks.

    Now edit the format file and remove the entire rows where FIELD ID="1" and COLUMN SOURCE="1", since this does not exist in our data file.
    Also adjust terminators as may be needed for your data file:

    <?xml version="1.0"?>
    <BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     <RECORD>
      <FIELD ID="2" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="256" COLLATION="Finnish_Swedish_CI_AS"/>
      <FIELD ID="3" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="256" COLLATION="Finnish_Swedish_CI_AS"/>
      <FIELD ID="4" xsi:type="CharTerm" TERMINATOR="\r\n" MAX_LENGTH="256" COLLATION="Finnish_Swedish_CI_AS"/>
     </RECORD>
     <ROW>
      <COLUMN SOURCE="2" NAME="col1" xsi:type="SQLVARYCHAR"/>
      <COLUMN SOURCE="3" NAME="col2" xsi:type="SQLVARYCHAR"/>
      <COLUMN SOURCE="4" NAME="col3" xsi:type="SQLVARYCHAR"/>
     </ROW>
    </BCPFORMAT>
    

    Now we can bulk load the data file into our table with a select, thus having full controll over the columns, in this case by not inserting data into the identity column:

    INSERT INTO target_table (col1,col2, col3)
    SELECT * FROM  openrowset(
    bulk 'C:\data_file.txt',
    formatfile='C:\format_file.xml') as t;
    

    Cross-browser custom styling for file upload button

    The best example is this one, No hiding, No jQuery, It's completely pure CSS

    http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/

    _x000D_
    _x000D_
    .custom-file-input::-webkit-file-upload-button {_x000D_
        visibility: hidden;_x000D_
    }_x000D_
    _x000D_
    .custom-file-input::before {_x000D_
        content: 'Select some files';_x000D_
        display: inline-block;_x000D_
        background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
        border: 1px solid #999;_x000D_
        border-radius: 3px;_x000D_
        padding: 5px 8px;_x000D_
        outline: none;_x000D_
        white-space: nowrap;_x000D_
        -webkit-user-select: none;_x000D_
        cursor: pointer;_x000D_
        text-shadow: 1px 1px #fff;_x000D_
        font-weight: 700;_x000D_
        font-size: 10pt;_x000D_
    }_x000D_
    _x000D_
    .custom-file-input:hover::before {_x000D_
        border-color: black;_x000D_
    }_x000D_
    _x000D_
    .custom-file-input:active::before {_x000D_
        background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
    }
    _x000D_
    <input type="file" class="custom-file-input">
    _x000D_
    _x000D_
    _x000D_

    Redirect to new Page in AngularJS using $location

    Try entering the url inside the function

    $location.url('http://www.google.com')
    

    What is the syntax for an inner join in LINQ to SQL?

    Try this :

         var data =(from t1 in dataContext.Table1 join 
                     t2 in dataContext.Table2 on 
                     t1.field equals t2.field 
                     orderby t1.Id select t1).ToList(); 
    

    Download and open PDF file using Ajax

    create a hidden iframe, then in your ajax code above:

    url: document.getElementById('myiframeid').src = your_server_side_url,

    and remove the window.open(response);

    cancelling a handler.postdelayed process

    Hope this gist help https://gist.github.com/imammubin/a587192982ff8db221da14d094df6fb4

    MainActivity as Screen Launcher with handler & runnable function, the Runnable run to login page or feed page with base preference login user with firebase.

    PHP DOMDocument loadHTML not encoding UTF-8 correctly

    You could prefix a line enforcing utf-8 encoding, like this:

    @$doc->loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $profile);
    

    And you can then continue with the code you already have, like:

    $doc->saveXML()
    

    Git Bash doesn't see my PATH

    Restart the computer after has added new value to PATH.

    Remove trailing newline from the elements of a string list

    All other answers, and mainly about list comprehension, are great. But just to explain your error:

    strip_list = []
    for lengths in range(1,20):
        strip_list.append(0) #longest word in the text file is 20 characters long
    for a in lines:
        strip_list.append(lines[a].strip())
    

    a is a member of your list, not an index. What you could write is this:

    [...]
    for a in lines:
        strip_list.append(a.strip())
    

    Another important comment: you can create an empty list this way:

    strip_list = [0] * 20
    

    But this is not so useful, as .append appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.

    So your code should be like:

    strip_list = []
    for a in lines:
        strip_list.append(a.strip())
    

    But, for sure, the best one is this one, as this is exactly the same thing:

    stripped = [line.strip() for line in lines]
    

    In case you have something more complicated than just a .strip, put this in a function, and do the same. That's the most readable way to work with lists.

    How to extract a substring using regex

    Since Java 9

    As of this version, you can use a new method Matcher::results with no args that is able to comfortably return Stream<MatchResult> where MatchResult represents the result of a match operation and offers to read matched groups and more (this class is known since Java 1.5).

    String string = "Some string with 'the data I want' inside and 'another data I want'.";
    
    Pattern pattern = Pattern.compile("'(.*?)'");
    pattern.matcher(string)
           .results()                       // Stream<MatchResult>
           .map(mr -> mr.group(1))          // Stream<String> - the 1st group of each result
           .forEach(System.out::println);   // print them out (or process in other way...)
    

    The code snippet above results in:

    the data I want
    another data I want
    

    The biggest advantage is in the ease of usage when one or more results is available compared to the procedural if (matcher.find()) and while (matcher.find()) checks and processing.

    Is there a way to select sibling nodes?

    Well... sure... just access the parent and then the children.

     node.parentNode.childNodes[]
    

    or... using jQuery:

    $('#innerId').siblings()
    

    Edit: Cletus as always is inspiring. I dug further. This is how jQuery gets siblings essentially:

    function getChildren(n, skipMe){
        var r = [];
        for ( ; n; n = n.nextSibling ) 
           if ( n.nodeType == 1 && n != skipMe)
              r.push( n );        
        return r;
    };
    
    function getSiblings(n) {
        return getChildren(n.parentNode.firstChild, n);
    }
    

    Write Array to Excel Range

    In my case, the program queries the database which returns a DataGridView. I then copy that to an array. I get the size of the just created array and then write the array to an Excel spreadsheet. This code outputs over 5000 lines of data in about two seconds.

    //private System.Windows.Forms.DataGridView dgvResults;
    dgvResults.DataSource = DB.getReport();
    
    Microsoft.Office.Interop.Excel.Application oXL;
    Microsoft.Office.Interop.Excel._Workbook oWB;
    Microsoft.Office.Interop.Excel._Worksheet oSheet;
    try
    {
        //Start Excel and get Application object.
        oXL = new Microsoft.Office.Interop.Excel.Application();
        oXL.Visible = true;
    
        oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
        oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
    
        var dgArray = new object[dgvResults.RowCount, dgvResults.ColumnCount+1];
        foreach (DataGridViewRow i in dgvResults.Rows)
        {
            if (i.IsNewRow) continue;
            foreach (DataGridViewCell j in i.Cells)
            {
                dgArray[j.RowIndex, j.ColumnIndex] = j.Value.ToString();
            }
        }
    
        Microsoft.Office.Interop.Excel.Range chartRange;
    
        int rowCount = dgArray.GetLength(0);
        int columnCount = dgArray.GetLength(1);
        chartRange = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[2, 1]; //I have header info on row 1, so start row 2
        chartRange = chartRange.get_Resize(rowCount, columnCount);
        chartRange.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, dgArray);
    
    
        oXL.Visible = false;
        oXL.UserControl = false;
        string outputFile = "Output_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
    
        oWB.SaveAs("c:\\temp\\"+outputFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
            false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    
        oWB.Close();
    }
    catch (Exception ex)
    {
        //...
    }
    

    Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

    Here's how you can mock your FileConnection

    Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
                                                               MockBehavior.Strict);
    fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
                  .Throws(new IOException());
    

    Then instantiate your Transfer class and use the mock in your method call

    Transfer transfer = new Transfer();
    transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);
    

    Update:

    First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.

    Since you are setting those properties using another dependency, I would write it like this:

    public class Transfer
    {
        public Transfer(IInternalConfig internalConfig)
        {
            source = internalConfig.GetFileConnection("source");
            destination = internalConfig.GetFileConnection("destination");
        }
    
        //you should consider making these private or protected fields
        public virtual IFileConnection source { get; set; }
        public virtual IFileConnection destination { get; set; }
    
        public virtual void GetFile(IFileConnection connection, 
            string remoteFilename, string localFilename)
        {
            connection.Get(remoteFilename, localFilename);
        }
    
        public virtual void PutFile(IFileConnection connection, 
            string localFilename, string remoteFilename)
        {
            connection.Get(remoteFilename, localFilename);
        }
    
        public virtual void TransferFiles(string sourceName, string destName)
        {
            var tempName = Path.GetTempFileName();
            GetFile(source, sourceName, tempName);
            PutFile(destination, tempName, destName);
        }
    }
    

    This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.

    format statement in a string resource file

    You should add formatted="false" to your string resource


    Here is an example

    In your strings.xml :

    <string name="all" formatted="false">Amount: %.2f%n  for %d days</string>
    

    In your code:

    yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));
    

    Using css transform property in jQuery

    If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

    Take it from this link : http://ricostacruz.com/jquery.transit/

    Retrieving JSON Object Literal from HttpServletRequest

    This is simple method to get request data from HttpServletRequest using Java 8 Stream API:

    String requestData = request.getReader().lines().collect(Collectors.joining());
    

    Select first empty cell in column F starting from row 1. (without using offset )

    If all you're trying to do is select the first blank cell in a given column, you can give this a try:

    Code:

    Public Sub SelectFirstBlankCell()
        Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
        Dim currentRowValue As String
    
        sourceCol = 6   'column F has a value of 6
        rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row
    
        'for every row, find the first blank cell and select it
        For currentRow = 1 To rowCount
            currentRowValue = Cells(currentRow, sourceCol).Value
            If IsEmpty(currentRowValue) Or currentRowValue = "" Then
                Cells(currentRow, sourceCol).Select
            End If
        Next
    End Sub
    

    Before Selection - first blank cell to select:

    enter image description here

    After Selection:

    enter image description here

    Adding quotes to a string in VBScript

    You can escape by doubling the quotes

    g="abcd """ & a & """"
    

    or write an explicit chr() call

    g="abcd " & chr(34) & a & chr(34)
    

    Enzyme - How to access and set <input> value?

    None of the above worked for me. This is what worked for me on Enzyme ^3.1.1:

    input.instance().props.onChange(({ target: { value: '19:00' } }));
    

    Here is the rest of the code for context:

    const fakeHandleChangeValues = jest.fn();
      const fakeErrors = {
        errors: [{
          timePeriod: opHoursData[0].timePeriod,
          values: [{
            errorIndex: 2,
            errorTime: '19:00',
          }],
        }],
        state: true,
      };
    const wrapper = mount(<AccessibleUI
        handleChangeValues={fakeHandleChangeValues}
        opHoursData={opHoursData}
        translations={translationsForRendering}
      />);
    const input = wrapper.find('#input-2').at(0);
    input.instance().props.onChange(({ target: { value: '19:00' } }));
    expect(wrapper.state().error).toEqual(fakeErrors);
    

    SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

    For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.

    e.g.

    var d = "";
    var json = JSON.parse(d);
    

    or if you are using AngularJS

    var d = "";
    var json = angular.fromJson(d);
    

    In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.

    Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.

    View's getWidth() and getHeight() returns 0

    We need to wait for view will be drawn. For this purpose use OnPreDrawListener. Kotlin example:

    val preDrawListener = object : ViewTreeObserver.OnPreDrawListener {
    
                    override fun onPreDraw(): Boolean {
                        view.viewTreeObserver.removeOnPreDrawListener(this)
    
                        // code which requires view size parameters
    
                        return true
                    }
                }
    
                view.viewTreeObserver.addOnPreDrawListener(preDrawListener)
    

    Load a UIView from nib in Swift

    My contribution:

    extension UIView {
        class func fromNib<T: UIView>() -> T {
            return Bundle(for: T.self).loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
        }
    }
    

    Then call it like this:

    let myCustomView: CustomView = UIView.fromNib()
    

    ..or even:

    let myCustomView: CustomView = .fromNib()
    

    The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

    Just had a similar issue when I ran pod install, I saw the following warnings/errors (related to CLANG_CXX_LIBRARY):

    The Error/Warning from Cocoapods

    [!] The `Project [Debug]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.debug.xcconfig'. This can lead to problems with the CocoaPods installation
        - Use the `$(inherited)` flag, or
        - Remove the build settings from the target.
    
    [!] The `Project [Release]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.release.xcconfig'. This can lead to problems with the CocoaPods installation
        - Use the `$(inherited)` flag, or
        - Remove the build settings from the target.
    

    The Fix

    1. Select your Project so you can see the Build Settings.
    2. Select your Target (AppName under Targets)
    3. Find C++ Standard Library (It will probably be in BOLD - This means it's overridden).
    4. Select the Line (So it's highlighted Blue), and press ? + DELETE (Command + Backspace)

    The line should not be bolded anymore and if you run pod install the warnings/errors should have disappeared.


    Visual Aid

    CLANG_CXX_LIBRARY Error/Warning with Cocoapods

    How to "comment-out" (add comment) in a batch/cmd?

    You can add comments to the end of a batch file with this syntax:

    @echo off
    :: Start of code
    ...
    :: End of code
    
    (I am a comment
    So I am!
    This can be only at the end of batch files
    

    Just make sure you never use a closing parentheses.

    Attributions: Leo Guttirez Ramirez on https://www.robvanderwoude.com/comments.php

    How do I deal with special characters like \^$.?*|+()[{ in my regex?

    Escape with a double backslash

    R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

    y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
    print(y)
    ## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
    cat(y)
    ## double quote: ", tab:    , newline: 
    ## , unicode point: €
    

    Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

    To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

    grepl("\\[", "a[b")
    ## [1] TRUE
    

    To match backslashes, you need to double escape, resulting in four backslashes.

    grepl("\\\\", c("a\\b", "a\nb"))
    ## [1]  TRUE FALSE
    

    The rebus package contains constants for each of the special characters to save you mistyping slashes.

    library(rebus)
    OPEN_BRACKET
    ## [1] "\\["
    BACKSLASH
    ## [1] "\\\\"
    

    For more examples see:

    ?SpecialCharacters
    

    Your problem can be solved this way:

    library(rebus)
    grepl(OPEN_BRACKET, "a[b")
    

    Form a character class

    You can also wrap the special characters in square brackets to form a character class.

    grepl("[?]", "a?b")
    ## [1] TRUE
    

    Two of the special characters have special meaning inside character classes: \ and ^.

    Backslash still needs to be escaped even if it is inside a character class.

    grepl("[\\\\]", c("a\\b", "a\nb"))
    ## [1]  TRUE FALSE
    

    Caret only needs to be escaped if it is directly after the opening square bracket.

    grepl("[ ^]", "a^b")  # matches spaces as well.
    ## [1] TRUE
    grepl("[\\^]", "a^b") 
    ## [1] TRUE
    

    rebus also lets you form a character class.

    char_class("?")
    ## <regex> [?]
    

    Use a pre-existing character class

    If you want to match all punctuation, you can use the [:punct:] character class.

    grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
    ## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE
    

    stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

    stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
    ## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
    

    You can also use the cross-platform syntax for accessing a UGC.

    stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
    ## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
    

    Use \Q \E escapes

    Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

    grepl("\\Q.\\E", "a.b")
    ## [1] TRUE
    

    rebus lets you write literal blocks of regular expressions.

    literal(".")
    ## <regex> \Q.\E
    

    Don't use regular expressions

    Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

    grepl("[", "a[b", fixed = TRUE)
    stringr::str_detect("a[b", fixed("["))
    stringi::stri_detect_fixed("a[b", "[")
    

    NPM: npm-cli.js not found when running npm

    On Windows 10:

    1. Press windows key, type edit the system environment variables then enter.
    2. Click environment variables...
    3. On the lower half of the window that opened with title Environment Variables there you will see a table titled System Variables, with two columns, the first one titled variable.
    4. Find the row with variable Path and click it.
    5. Click edit which will open a window titled Edit evironment variable.
    6. Here if you find

    C:\Program Files\nodejs\node_modules\npm\bin

    select it, and click edit button to your right, then edit the field to the path where you have the nodejs folder, in my case it was just shortening it to :

    C:\Program Files\nodejs

    Then I closed all my cmd or powershell terminals, opened them again and npm was working.

    Encoding as Base64 in Java

    Here are my two cents... Java 8 does contain its own implementation of Base64. However, I found one slightly disturbing difference. To illustrate, I will provide a code example:

    My codec wrapper:

    public interface MyCodec
    {
      static String apacheDecode(String encodedStr)
      {
        return new String(Base64.decodeBase64(encodedStr), Charset.forName("UTF-8"));
      }
    
      static String apacheEncode(String decodedStr)
      {
        byte[] decodedByteArr = decodedStr.getBytes(Charset.forName("UTF-8"));
        return Base64.encodeBase64String(decodedByteArr);
      }
    
      static String javaDecode(String encodedStr)
      {
        return new String(java.util.Base64.getDecoder().decode(encodedStr), Charset.forName("UTF-8"));
      }
    
      static String javaEncode(String decodedStr)
      {
        byte[] decodedByteArr = decodedStr.getBytes(Charset.forName("UTF-8"));
        return java.util.Base64.getEncoder().encodeToString(decodedByteArr);
      }
    }
    

    Test Class:

    public class CodecDemo
    {
      public static void main(String[] args)
      {
        String decodedText = "Hello World!";
    
        String encodedApacheText = MyCodec.apacheEncode(decodedText);
        String encodedJavaText = MyCodec.javaEncode(decodedText);
    
        System.out.println("Apache encoded text: " + MyCodec.apacheEncode(encodedApacheText));
        System.out.println("Java encoded text: " + MyCodec.javaEncode(encodedJavaText));
    
        System.out.println("Encoded results equal: " + encodedApacheText.equals(encodedJavaText));
    
        System.out.println("Apache decode Java: " + MyCodec.apacheDecode(encodedJavaText));
        System.out.println("Java decode Java: " + MyCodec.javaDecode(encodedJavaText));
    
        System.out.println("Apache decode Apache: " + MyCodec.apacheDecode(encodedApacheText));
        System.out.println("Java decode Apache: " + MyCodec.javaDecode(encodedApacheText));
      }
    }
    

    OUTPUT:

    Apache encoded text: U0dWc2JHOGdWMjl5YkdRaA0K
    
    Java encoded text: U0dWc2JHOGdWMjl5YkdRaA==
    Encoded results equal: false
    Apache decode Java: Hello World!
    Java decode Java: Hello World!
    Apache decode Apache: Hello World!
    Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character d
        at java.util.Base64$Decoder.decode0(Base64.java:714)
        at java.util.Base64$Decoder.decode(Base64.java:526)
        at java.util.Base64$Decoder.decode(Base64.java:549)
    

    Notice that the Apache encoded text contain additional line breaks (white spaces) at the end. Therefore, in order for my codec to yield the same result regardless of Base64 implementation, I had to call trim() on the Apache encoded text. In my case, I simply added the aforementioned method call to the my codec's apacheDecode() as follows:

    return Base64.encodeBase64String(decodedByteArr).trim();
    

    Once this change was made, the results are what I expected to begin with:

    Apache encoded text: U0dWc2JHOGdWMjl5YkdRaA==
    Java encoded text: U0dWc2JHOGdWMjl5YkdRaA==
    Encoded results equal: true
    Apache decode Java: Hello World!
    Java decode Java: Hello World!
    Apache decode Apache: Hello World!
    Java decode Apache: Hello World!
    

    CONCLUSION: If you want to switch from Apache Base64 to Java, you must:

    1. Decode encoded text with your Apache decoder.
    2. Encode resulting (plain) text with Java.

    If you switch without following these steps, most likely you will run into problems. That is how I made this discovery.

    How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

    Open it in a hex editor and make sure that the first three bytes are a UTF8 BOM (EF BB BF)

    How to check if an object implements an interface?

    For an instance

    Character.Gorgon gor = new Character.Gorgon();
    

    Then do

    gor instanceof Monster
    

    For a Class instance do

    Class<?> clazz = Character.Gorgon.class;
    Monster.class.isAssignableFrom(clazz);
    

    Applications are expected to have a root view controller at the end of application launch

    i got this problems too. i got my project run in xcode4.2.1. i've read all comments up there, but no one is cool for me. after a while, i find that i commented a piece of code.

    //self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    

    then i uncommented it. everything is ok for me. hope this would helpful for you guys.

    How to add favicon.ico in ASP.NET site

    _x000D_
    _x000D_
        <link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico" />
    _x000D_
    _x000D_
    _x000D_

    This worked for me. If anyone is troubleshooting while reading this - I found issues when my favicon.ico was not nested in the root folder. I had mine in the Resources folder and was struggling at that point.

    Where value in column containing comma delimited values

    SELECT * FROM TABLENAME WHERE FIND_IN_SET(@search, column)
    

    If it turns out your column has whitespaces in between the list items, use

    SELECT * FROM TABLENAME WHERE FIND_IN_SET(@search, REPLACE(column, ' ', ''))
    

    http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

    How to write multiple conditions of if-statement in Robot Framework

    The below code worked fine:

    Run Keyword if    '${value1}' \ \ == \ \ '${cost1}' \ and \ \ '${value2}' \ \ == \ \ 'cost2'    LOG    HELLO
    

    Force decimal point instead of comma in HTML5 number input (client-side)

    I found a blog article which seems to explain something related:
    HTML5 input type=number and decimals/floats in Chrome

    In summary:

    • the step helps to define the domain of valid values
    • the default step is 1
    • thus the default domain is integers (between min and max, inclusive, if given)

    I would assume that's conflating with the ambiguity of using a comma as a thousand separator vs a comma as a decimal point, and your 51,983 is actually a strangely-parsed fifty-one thousand, nine hundred and eight-three.

    Apparently you can use step="any" to widen the domain to all rational numbers in range, however I've not tried it myself. For latitude and longitude I've successfully used:

    <input name="lat" type="number" min="-90.000000" max="90.000000" step="0.000001">
    <input name="lon" type="number" min="-180.000000" max="180.000000" step="0.000001">
    

    It might not be pretty, but it works.

    SQL Server SELECT INTO @variable?

    If you wanted to simply assign some variables for later use, you can do them in one shot with something along these lines:

    declare @var1 int,@var2 int,@var3 int;
    
    select 
        @var1 = field1,
        @var2 = field2,
        @var3 = field3
    from
        table
    where
        condition
    

    If that's the type of thing you're after

    How do Mockito matchers work?

    Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify.

    Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.

    /* Mockito */  verify(foo).setPowerLevel(gt(9000));
    /* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));
    

    Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T where Hamcrest matcher methods return Matcher objects (of type Matcher<T>).

    Mockito matchers are invoked through static methods such as eq, any, gt, and startsWith on org.mockito.Matchers and org.mockito.AdditionalMatchers. There are also adapters, which have changed across Mockito versions:

    • For Mockito 1.x, Matchers featured some calls (such as intThat or argThat) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T> extended org.hamcrest.Matcher<T>, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.
    • For Mockito 2.0+, Mockito no longer has a direct dependency on Hamcrest. Matchers calls phrased as intThat or argThat wrap ArgumentMatcher<T> objects that no longer implement org.hamcrest.Matcher<T> but are used in similar ways. Hamcrest adapters such as argThat and intThat are still available, but have moved to MockitoHamcrest instead.

    Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:

    /* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
    verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));
    

    In the above statement: foo.setPowerLevel is a method that accepts an int. is(greaterThan(9000)) returns a Matcher<Integer>, which wouldn't work as a setPowerLevel argument. The Mockito matcher intThat wraps that Hamcrest-style Matcher and returns an int so it can appear as an argument; Mockito matchers like gt(9000) would wrap that entire expression into a single call, as in the first line of example code.

    What matchers do/return

    when(foo.quux(3, 5)).thenReturn(true);
    

    When not using argument matchers, Mockito records your argument values and compares them with their equals methods.

    when(foo.quux(eq(3), eq(5))).thenReturn(true);    // same as above
    when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different
    

    When you call a matcher like any or gt (greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture() it stores a matcher that saves its argument instead for later inspection.

    Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List<String> for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any() or argThat(...), which can cause a NullPointerException if trying to "auto-unbox" a null primitive value.

    Matchers like eq and gt take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.

    Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

    Implementation details

    Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.

    Most matcher calls only add to this stack, with an exception for matchers like and, or, and not. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:

    when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
    [6]      [5]  [1]       [4] [2]     [3]
    

    This will:

    1. Add anyInt() to the stack.
    2. Add gt(10) to the stack.
    3. Add lt(20) to the stack.
    4. Remove gt(10) and lt(20) and add and(gt(10), lt(20)).
    5. Call foo.quux(0, 0), which (unless otherwise stubbed) returns the default value false. Internally Mockito marks quux(int, int) as the most recent call.
    6. Call when(false), which discards its argument and prepares to stub method quux(int, int) identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any() matcher for its first argument and and(gt(10), lt(20)) for its second argument and clears the stack.

    This demonstrates a few rules:

    • Mockito can't tell the difference between quux(anyInt(), 0) and quux(0, anyInt()). They both look like a call to quux(0, 0) with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.

    • Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.

      int between10And20 = and(gt(10), lt(20));
      /* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
      // Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
      
      public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
      /* OK */  when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
      // The helper method calls the matcher methods in the right order.
      
    • The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when or verify, but Mockito can't check that automatically. You can check manually with Mockito.validateMockitoUsage().

    • In a call to when, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values). doReturn and doAnswer (etc) do not invoke the actual method and are often a useful alternative.

    • If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq matcher), Mockito would check the stack length against that call instead, and likely fail.

    • If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.

    Common problems

    • InvalidUseOfMatchersException:

      • Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when or verify call. Matchers should never be used as stubbed return values or fields/variables.

      • Check that you're not calling a mock as a part of providing a matcher argument.

      • Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.

    • NullPointerException with primitive arguments: (Integer) any() returns null while any(Integer.class) returns 0; this can cause a NullPointerException if you're expecting an int instead of an Integer. In any case, prefer anyInt(), which will return zero and also skip the auto-boxing step.

    • NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null), which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

    General troubleshooting

    • Use MockitoJUnitRunner, or explicitly call validateMockitoUsage in your tearDown or @After method (which the runner would do for you automatically). This will help determine whether you've misused matchers.

    • For debugging purposes, add calls to validateMockitoUsage in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.

    Stream file using ASP.NET MVC FileContentResult in a browser with a name?

    Actually, the absolutely easiest way is to do the following...

    byte[] content = your_byte[];
    
    FileContentResult result = new FileContentResult(content, "application/octet-stream") 
    {
      FileDownloadName = "your_file_name"
    };
    
    return result;
    

    Redirect from a view to another view

    That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

    public ActionResult SomeAction()
    {
        ...
        return RedirectToAction("SomeAction", "SomeController");
    }
    

    Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

    [Authorize]
    public ActionResult SomeProtectedAction()
    {
        ...
    }
    

    Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

    How to create folder with PHP code?

    You can create a directory with PHP using the mkdir() function.

    mkdir("/path/to/my/dir", 0700);

    You can use fopen() to create a file inside that directory with the use of the mode w.

    fopen('myfile.txt', 'w');

    w : Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

    Rename master branch for both local and remote Git repositories

    Good. My 2 cents. How about loggin in at the server, going to the git directory and renaming the branch in the bare repository. This does not have all the problems associated with reuploading the same branch. Actually, the 'clients' will automatically recognize the modified name and change their remote reference. Afterwards (or before) you can also modify the local name of the branch.

    How does one remove a Docker image?

    First of all, we have to stop and remove the Docker containers which are attached with the Docker image that we are going to remove.

    So for that, first

    • docker stop container-id - To stop the running container
    • docker rm container-id - To delete/remove the container

    then,

    • docker rmi image-id - To delete/remove the image

    How do I add records to a DataGridView in VB.Net?

    If you want to add the row to the end of the grid use the Add() method of the Rows collection...

    DataGridView1.Rows.Add(New String(){Value1, Value2, Value3})
    

    If you want to insert the row at a partiular position use the Insert() method of the Rows collection (as GWLlosa also said)...

    DataGridView1.Rows.Insert(rowPosition, New String(){value1, value2, value3})
    

    I know you mentioned you weren't doing databinding, but if you defined a strongly-typed dataset with a single datatable in your project, you could use that and get some nice strongly typed methods to do this stuff rather than rely on the grid methods...

    DataSet1.DataTable.AddRow(1, "John Doe", true)
    

    Hide Signs that Meteor.js was Used

    The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

    That being said, I suggest looking at buildwith.com

    You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

    Setting Remote Webdriver to run tests in a remote computer using Java

    • First you need to create HubNode(Server) and start the HubNode(Server) from command Line/prompt using Java: -jar selenium-server-standalone-2.44.0.jar -role hub
    • Then bind the node/Client to this Hub using Hub machines IPAddress or Name with any port number >1024. For Node Machine for example: Java -jar selenium-server-standalone-2.44.0.jar -role webdriver -hub http://HubmachineIPAddress:4444/grid/register -port 5566

    One more thing is that whenever we use Internet Explore or Google Chrome we need to set: System.setProperty("webdriver.ie.driver",path);

    Improve SQL Server query performance on large tables

    I know that you said that adding indexes is not an option but that would be the only option to eliminate the table scan you have. When you do a scan, SQL Server reads all 2 million rows on the table to fulfill your query.

    this article provides more info but remember: Seek = good, Scan = bad.

    Second, can't you eliminate the select * and select only the columns you need? Third, no "where" clause? Even if you have a index, since you are reading everything the best you will get is a index scan (which is better than a table scan, but it is not a seek, which is what you should aim for)

    Remove non-ascii character in string

    You can use the following regex to replace non-ASCII characters

    str = str.replace(/[^A-Za-z 0-9 \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '')
    

    However, note that spaces, colons and commas are all valid ASCII, so the result will be

    > str
    "INFO] :, , ,  (Higashikurume)"
    

    RegEx to extract all matches from string using RegExp.exec

    Based on Agus's function, but I prefer return just the match values:

    var bob = "&gt; bob &lt;";
    function matchAll(str, regex) {
        var res = [];
        var m;
        if (regex.global) {
            while (m = regex.exec(str)) {
                res.push(m[1]);
            }
        } else {
            if (m = regex.exec(str)) {
                res.push(m[1]);
            }
        }
        return res;
    }
    var Amatch = matchAll(bob, /(&.*?;)/g);
    console.log(Amatch);  // yeilds: [&gt;, &lt;]
    

    How to change button text or link text in JavaScript?

    Remove Quote. and use innerText instead of text

    function toggleText(button_id) 
    {                      //-----\/ 'button_id' - > button_id
       if (document.getElementById(button_id).innerText == "Lock") 
       {
           document.getElementById(button_id).innerText = "Unlock";
       }
       else 
       {
         document.getElementById(button_id).innerText = "Lock";
       }
    }
    

    How do I clone a generic List in Java?

    This is the code I use for that:

    ArrayList copy = new ArrayList (original.size());
    Collections.copy(copy, original);
    

    Hope is usefull for you

    Mysql 1050 Error "Table already exists" when in fact, it does not

    I had this problem on Win7 in Sql Maestro for MySql 12.3. Enormously irritating, a show stopper in fact. Nothing helped, not even dropping and recreating the database. I have this same setup on XP and it works there, so after reading your answers about permissions I realized that it must be Win7 permissions related. So I ran MySql as administrator and even though Sql Maestro was run normally, the error disappeared. So it must have been a permissions issue between Win7 and MySql.

    const to Non-const Conversion in C++

    The actual code to cast away the const-ness of your pointer would be:

    BoxT<T> * nonConstObj = const_cast<BoxT<T> *>(constObj);
    

    But note that this really is cheating. A better solution would either be to figure out why you want to modify a const object, and redesign your code so you don't have to.... or remove the const declaration from your vector, if it turns out you don't really want those items to be read-only after all.

    Recommended add-ons/plugins for Microsoft Visual Studio

    I don't fancy the Visual Studio bookmarks so I use DPACK to get the same kind of bookmarks as the Delph IDE provides.

    http://www.usysware.com/dpack/

    HTML radio buttons allowing multiple selections

    All radio buttons must have the same name attribute added.

    Apple Cover-flow effect using jQuery or other library?

    Is this what you are looking for?

    "Create an Apple Itunes-like banner rotator/slideshow with jQuery" is an article explaining how you can make such effect using jQuery.

    You can also view the live demo.

    What is an efficient way to implement a singleton pattern in Java?

    I use the Spring Framework to manage my singletons.

    It doesn't enforce the "singleton-ness" of the class (which you can't really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.

    How to prevent downloading images and video files from my website?

    If you want only authorised users to get the content, both the client and the server need to use encryption.

    For video and audio, a good solution is Azure Media Services, which has content protection and encryption. You embed the Azure media player in your browser and it streams the video from Azure.

    For documents and email, you can look at Azure Rights Management, which uses a special client. It doesn't currently work in ordinary web browsers, unfortunately, except for one-off, single-use codes.

    I'm not sure exactly how secure all this is, however. As others have pointed out, from a security point of view, once those downloaded bytes are in the "attacker's" RAM, they're as good as gone. No solution is 100% secure in this case (please correct me if I'm wrong). As with most security, the goal is to make it harder, so the 99% don't bother.

    Can I force pip to reinstall the current version?

    If you want to reinstall packages specified in a requirements.txt file, without upgrading, so just reinstall the specific versions specified in the requirements.txt file:

    pip install -r requirements.txt --ignore-installed
    

    Is there a command to refresh environment variables from the command prompt in Windows?

    The confusing thing might be that there are a few places to start the cmd from. In my case I ran cmd from windows explorer and the environment variables did not change while when starting cmd from the "run" (windows key + r) the environment variables were changed.

    In my case I just had to kill the windows explorer process from the task manager and then restart it again from the task manager.

    Once I did this I had access to the new environment variable from a cmd that was spawned from windows explorer.

    Laravel blade check empty foreach

    This is my best solution if I understood the question well:

    Use of $object->first() method to run the code inside if statement once, that is when on the first loop. The same concept is true with $object->last().

        @if($object->first())
            <div class="panel user-list">
              <table id="myCustomTable" class="table table-hover">
                  <thead>
                      <tr>
                         <th class="col-email">Email</th>
                      </tr>
                  </thead>
                  <tbody>
        @endif
    
        @foreach ($object as $data)
            <tr class="gradeX">
               <td class="col-name"><strong>{{ $data->email }}</strong></td>
            </tr>
        @endforeach
    
        @if($object->last())
                    </tbody>
                </table>
            </div>
        @endif
    

    Change color when hover a font awesome icon?

    if you want to change only the colour of the flag on hover use this:

    http://jsfiddle.net/uvamhedx/

    _x000D_
    _x000D_
    .fa-flag:hover {_x000D_
        color: red;_x000D_
    }
    _x000D_
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
    _x000D_
    <i class="fa fa-flag fa-3x"></i>
    _x000D_
    _x000D_
    _x000D_

    Get access to parent control from user control - C#

    Control has a property called Parent, which will give the parent control. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent.aspx

    eg Control p = this.Parent;

    Show only two digit after decimal

    Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.

      double value = 12.3457652133
      value =Double.parseDouble(new DecimalFormat("##.####").format(value));
    

    Select a Dictionary<T1, T2> with LINQ

    A more explicit option is to project collection to an IEnumerable of KeyValuePair and then convert it to a Dictionary.

    Dictionary<int, string> dictionary = objects
        .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
        .ToDictionary(x=>x.Key, x=>x.Value);
    

    Get index of a row of a pandas dataframe as an integer

    The nature of wanting to include the row where A == 5 and all rows upto but not including the row where A == 8 means we will end up using iloc (loc includes both ends of slice).

    In order to get the index labels we use idxmax. This will return the first position of the maximum value. I run this on a boolean series where A == 5 (then when A == 8) which returns the index value of when A == 5 first happens (same thing for A == 8).

    Then I use searchsorted to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc.

    i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
    df.iloc[i5:i8]
    

    enter image description here


    numpy

    you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.

    def find_between(df, col, v1, v2):
        vals = df[col].values
        mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
        idx = df.index.values
        i1, i2 = idx.searchsorted([mx1, mx2])
        return df.iloc[i1:i2]
    
    find_between(df, 'A', 5, 8)
    

    enter image description here


    timing
    enter image description here

    How can I SELECT multiple columns within a CASE WHEN on SQL Server?

    "Case" can return single value only, but you can use complex type:

    create type foo as (a int, b text);
    select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;
    

    How can I mimic the bottom sheet from the Maps app?

    Maybe you can try my answer https://github.com/AnYuan/AYPannel, inspired by Pulley. Smooth transition from moving the drawer to scrolling the list. I added a pan gesture on the container scroll view, and set shouldRecognizeSimultaneouslyWithGestureRecognizer to return YES. More detail in my github link above. Wish to help.

    Run bash script from Windows PowerShell

    It also can be run by exporting the bash and sh of the gitbash C:\Program Files\git\bin\ in the Advance section of the environment variable of the Windows Server.

    In Advance section in the path var kindly add the C:\Program Files\git\bin\ which will make the bash and the sh of the git-bash to be executable from the window cmd.

    Then,

    Run the shell file as

    bash shellscript.sh or sh shellscript.sh

    What does string::npos mean in this code?

    std::string::npos is implementation defined index that is always out of bounds of any std::string instance. Various std::string functions return it or accept it to signal beyond the end of the string situation. It is usually of some unsigned integer type and its value is usually std::numeric_limits<std::string::size_type>::max () which is (thanks to the standard integer promotions) usually comparable to -1.

    Android fade in and fade out with ImageView

    Have you thought of using TransitionDrawable instead of custom animations? https://developer.android.com/reference/android/graphics/drawable/TransitionDrawable.html

    One way to achieve what you are looking for is:

    // create the transition layers
    Drawable[] layers = new Drawable[2];
    layers[0] = new BitmapDrawable(getResources(), firstBitmap);
    layers[1] = new BitmapDrawable(getResources(), secondBitmap);
    
    TransitionDrawable transitionDrawable = new TransitionDrawable(layers);
    imageView.setImageDrawable(transitionDrawable);
    transitionDrawable.startTransition(FADE_DURATION);
    

    How to import RecyclerView for Android L-preview

    If anyone still has this issue - you don't have to change compileSdkVersion, this just defeats the whole purpose of support libraries.

    Instead, use these in your gradle.build file:

    compile 'com.android.support:cardview-v7:+'
    compile 'com.android.support:recyclerview-v7:+'
    compile 'com.android.support:palette-v7:+'`
    

    What is the purpose of willSet and didSet in Swift?

    NOTE

    willSet and didSet observers are not called when a property is set in an initializer before delegation takes place

    How to pass objects to functions in C++?

    There are some differences in calling conventions in C++ and Java. In C++ there are technically speaking only two conventions: pass-by-value and pass-by-reference, with some literature including a third pass-by-pointer convention (that is actually pass-by-value of a pointer type). On top of that, you can add const-ness to the type of the argument, enhancing the semantics.

    Pass by reference

    Passing by reference means that the function will conceptually receive your object instance and not a copy of it. The reference is conceptually an alias to the object that was used in the calling context, and cannot be null. All operations performed inside the function apply to the object outside the function. This convention is not available in Java or C.

    Pass by value (and pass-by-pointer)

    The compiler will generate a copy of the object in the calling context and use that copy inside the function. All operations performed inside the function are done to the copy, not the external element. This is the convention for primitive types in Java.

    An special version of it is passing a pointer (address-of the object) into a function. The function receives the pointer, and any and all operations applied to the pointer itself are applied to the copy (pointer), on the other hand, operations applied to the dereferenced pointer will apply to the object instance at that memory location, so the function can have side effects. The effect of using pass-by-value of a pointer to the object will allow the internal function to modify external values, as with pass-by-reference and will also allow for optional values (pass a null pointer).

    This is the convention used in C when a function needs to modify an external variable, and the convention used in Java with reference types: the reference is copied, but the referred object is the same: changes to the reference/pointer are not visible outside the function, but changes to the pointed memory are.

    Adding const to the equation

    In C++ you can assign constant-ness to objects when defining variables, pointers and references at different levels. You can declare a variable to be constant, you can declare a reference to a constant instance, and you can define all pointers to constant objects, constant pointers to mutable objects and constant pointers to constant elements. Conversely in Java you can only define one level of constant-ness (final keyword): that of the variable (instance for primitive types, reference for reference types), but you cannot define a reference to an immutable element (unless the class itself is immutable).

    This is extensively used in C++ calling conventions. When the objects are small you can pass the object by value. The compiler will generate a copy, but that copy is not an expensive operation. For any other type, if the function will not change the object, you can pass a reference to a constant instance (usually called constant reference) of the type. This will not copy the object, but pass it into the function. But at the same time the compiler will guarantee that the object is not changed inside the function.

    Rules of thumb

    This are some basic rules to follow:

    • Prefer pass-by-value for primitive types
    • Prefer pass-by-reference with references to constant for other types
    • If the function needs to modify the argument use pass-by-reference
    • If the argument is optional, use pass-by-pointer (to constant if the optional value should not be modified)

    There are other small deviations from these rules, the first of which is handling ownership of an object. When an object is dynamically allocated with new, it must be deallocated with delete (or the [] versions thereof). The object or function that is responsible for the destruction of the object is considered the owner of the resource. When a dynamically allocated object is created in a piece of code, but the ownership is transfered to a different element it is usually done with pass-by-pointer semantics, or if possible with smart pointers.

    Side note

    It is important to insist in the importance of the difference between C++ and Java references. In C++ references are conceptually the instance of the object, not an accessor to it. The simplest example is implementing a swap function:

    // C++
    class Type; // defined somewhere before, with the appropriate operations
    void swap( Type & a, Type & b ) {
       Type tmp = a;
       a = b;
       b = tmp;
    }
    int main() {
       Type a, b;
       Type old_a = a, old_b = b;
       swap( a, b );
       assert( a == old_b );
       assert( b == old_a ); 
    }
    

    The swap function above changes both its arguments through the use of references. The closest code in Java:

    public class C {
       // ...
       public static void swap( C a, C b ) {
          C tmp = a;
          a = b;
          b = tmp;
       }
       public static void main( String args[] ) {
          C a = new C();
          C b = new C();
          C old_a = a;
          C old_b = b;
          swap( a, b ); 
          // a and b remain unchanged a==old_a, and b==old_b
       }
    }
    

    The Java version of the code will modify the copies of the references internally, but will not modify the actual objects externally. Java references are C pointers without pointer arithmetic that get passed by value into functions.

    GUI-based or Web-based JSON editor that works like property explorer

    Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.

    Converting a structure to JSON is very straightforward:

    use strict;
    use warnings;
    use JSON::Any;
    
    my $data = { arbitrary structure in here };
    my $json_handler = JSON::Any->new(utf8=>1);
    my $json_string = $json_handler->objToJson($data);
    

    MySQL equivalent of DECODE function in Oracle

    You can use IF() where in Oracle you would have used DECODE().

    mysql> select if(emp_id=1,'X','Y') as test, emp_id from emps; 
    

    How to convert a Binary String to a base 10 integer in Java

    I love loops! Yay!

    String myString = "1001001"; //73
    

    While loop with accumulator, left to right (l doesn't change):

    int n = 0,
        j = -1,
        l = myString.length();
    while (++j < l) n = (n << 1) + (myString.charAt(j) == '0' ? 0 : 1);
    return n;
    

    Right to left with 2 loop vars, inspired by Convert boolean to int in Java (absolutely horrible):

    int n = 0,
        j = myString.length,
        i = 1;
    while (j-- != 0) n -= (i = i << 1) * new Boolean(myString.charAt(j) == '0').compareTo(true);
    return n >> 1;
    

    A somewhat more reasonable implementation:

    int n = 0,
        j = myString.length(),
        i = 1;
    while (j-- != 0) n += (i = i << 1) * (myString.charAt(j) == '0' ? 0 : 1);
    return n >> 1;
    

    A readable version :p

    int n = 0;
    for (int j = 0; j < myString.length(); j++) {
        n *= 2;
        n += myString.charAt(j) == '0' ? 0 : 1;
    }
    return n;
    

    Parsing a JSON array using Json.Net

    Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage

    And you can convert the entire object to a string, filename.json is expected to be located in documents folder.

            var text = File.ReadAllText("filename.json");
            var json = JsonValue.Parse(text);
    
            while (JsonValue.Null != null)
            {
                Console.WriteLine(json.ToString());
    
            }
            Console.ReadLine();
    

    Setting Action Bar title and subtitle

        <activity android:name=".yourActivity" android:label="@string/yourText" />
    

    Put this code into your android manifest file and it should set the title of the action bar to what ever you want!