Programs & Examples On #Google groups api

Angular2 change detection: ngOnChanges not firing for nested object

Not the cleanest approach, but you can just clone the object each time you change the value?

   rawLapsData = Object.assign({}, rawLapsData);

I think I would prefer this approach over implementing your own ngDoCheck() but maybe someone like @GünterZöchbauer could chime in.

Check if Nullable Guid is empty in c#

You should use the HasValue property:

SomeProperty.HasValue

For example:

if (SomeProperty.HasValue)
{
    // Do Something
}
else
{
    // Do Something Else
}

FYI

public Nullable<System.Guid> SomeProperty { get; set; }

is equivalent to:

public System.Guid? SomeProperty { get; set; }

The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx

Getting all file names from a folder using C#

Take a look at Directory.GetFiles Method (String, String) (MSDN).

This method returns all the files as an array of filenames.

Eliminating NAs from a ggplot

Try remove_missing instead with vars = the_variable. It is very important that you set the vars argument, otherwise remove_missing will remove all rows that contain an NA in any column!! Setting na.rm = TRUE will suppress the warning message.

ggplot(data = remove_missing(MyData, na.rm = TRUE, vars = the_variable),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
       geom_bar(stat="bin") 

How to access random item in list?

I usually use this little collection of extension methods:

public static class EnumerableExtension
{
    public static T PickRandom<T>(this IEnumerable<T> source)
    {
        return source.PickRandom(1).Single();
    }

    public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)
    {
        return source.Shuffle().Take(count);
    }

    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
    {
        return source.OrderBy(x => Guid.NewGuid());
    }
}

For a strongly typed list, this would allow you to write:

var strings = new List<string>();
var randomString = strings.PickRandom();

If all you have is an ArrayList, you can cast it:

var strings = myArrayList.Cast<string>();

Set environment variables from file of key/value pairs

Here's my take on this. I had the following requirements:

  • Ignore commented lines
  • Allow spaces in the value
  • Allow empty lines
  • Ability to pass a custom env file while defaulting to .env
  • Allow exporting as well as running commands inline
  • Exit if env file doesn't exist
source_env() {
  [ "$#" -eq 1 ] && env="$1" || env=".env"
  [ -f "$env" ] || { echo "Env file $env doesn't exist"; return 1; }
  eval $(grep -Ev '^#|^$' "$env" | sed -e 's/=\(.*\)/="\1/g' -e 's/$/"/g' -e 's/^/export /')
}

Usage after saving the function to your .bash_profile or equivalent:

source_env                # load default .env file
source_env .env.dev       # load custom .env file
(source_env && COMMAND)   # run command without saving vars to environment

Inspired by Javier and some of the other comments.

Convert string with commas to array

More "Try it Yourself" examples below.

Definition and Usage The split() method is used to split a string into an array of substrings, and returns the new array.

Tip: If an empty string ("") is used as the separator, the string is split between each character.

Note: The split() method does not change the original string.

var res = str.split(",");

How to tell if homebrew is installed on Mac OS X

The standard way of figuring out if something is installed is to use which.

If Brew is installed.

>>> which brew
/usr/local/bin/brew

If Brew is not installed.

>>> which brew
brew not found

Note: The "not installed" message depends on your shell. zsh is shown above. bash will just not print anything. csh will say brew: Command not found. In the "installed" case, all shells will print the path.)

It works with all command line programs. Try which grep or which python. Since it tells you the program that you're running, it's helpful when debugging as well.

How to resolve conflicts in EGit

As it's an issue we face more than often, below are the steps to resolve it.

  1. Open the Git perspective. In the Git Repository view, go to on Branches ? Local ? master and right click ? Merge...

  2. It should auto select Remote Tracking ? *origin/master. Press Merge.

  3. Launch stage view in Eclipse.

  4. Double click the files which initially showed conflict

  5. In the conflict merge view, by selecting the left arrow for all the non-conflict + conflict changes from left to right, you can resolve all the conflicts.

  6. Save the merged file.

  7. Do a Team ? pull from Eclipse again.

You are all set :)

Iterate all files in a directory using a 'for' loop

Here's my go with comments in the code.

I'm just brushing up by biatch skills so forgive any blatant errors.

I tried to write an all in one solution as best I can with a little modification where the user requires it.

Some important notes: Just change the variable recursive to FALSE if you only want the root directories files and folders processed. Otherwise, it goes through all folders and files.

C&C most welcome...

@echo off
title %~nx0
chcp 65001 >NUL
set "dir=c:\users\%username%\desktop"
::
:: Recursive Loop routine - First Written by Ste on - 2020.01.24 - Rev 1
::
setlocal EnableDelayedExpansion
rem THIS IS A RECURSIVE SOLUTION [ALBEIT IF YOU CHANGE THE RECURSIVE TO FALSE, NO]
rem By removing the /s switch from the first loop if you want to loop through
rem the base folder only.
set recursive=TRUE
if %recursive% equ TRUE ( set recursive=/s ) else ( set recursive= )
endlocal & set recursive=%recursive%
cd /d %dir%
echo Directory %cd%
for %%F in ("*") do (echo    ? %%F)                                 %= Loop through the current directory. =%
for /f "delims==" %%D in ('dir "%dir%" /ad /b %recursive%') do (    %= Loop through the sub-directories only if the recursive variable is TRUE. =%
  echo Directory %%D
  echo %recursive% | find "/s" >NUL 2>NUL && (
    pushd %%D
    cd /d %%D
    for /f "delims==" %%F in ('dir "*" /b') do (                      %= Then loop through each pushd' folder and work on the files and folders =%
      echo %%~aF | find /v "d" >NUL 2>NUL && (                        %= This will weed out the directories by checking their attributes for the lack of 'd' with the /v switch therefore you can now work on the files only. =%
      rem You can do stuff to your files here.
      rem Below are some examples of the info you can get by expanding the %%F variable.
      rem Uncomment one at a time to see the results.
      echo    ? %%~F           &rem expands %%F removing any surrounding quotes (")
      rem echo    ? %%~dF          &rem expands %%F to a drive letter only
      rem echo    ? %%~fF          &rem expands %%F to a fully qualified path name
      rem echo    ? %%~pF          &rem expands %%A to a path only
      rem echo    ? %%~nF          &rem expands %%F to a file name only
      rem echo    ? %%~xF          &rem expands %%F to a file extension only
      rem echo    ? %%~sF          &rem expanded path contains short names only
      rem echo    ? %%~aF          &rem expands %%F to file attributes of file
      rem echo    ? %%~tF          &rem expands %%F to date/time of file
      rem echo    ? %%~zF          &rem expands %%F to size of file
      rem echo    ? %%~dpF         &rem expands %%F to a drive letter and path only
      rem echo    ? %%~nxF         &rem expands %%F to a file name and extension only
      rem echo    ? %%~fsF         &rem expands %%F to a full path name with short names only
      rem echo    ? %%~dp$dir:F    &rem searches the directories listed in the 'dir' environment variable and expands %%F to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
      rem echo    ? %%~ftzaF       &rem expands %%F to a DIR like output line
      )
      )
    popd
    )
  )
echo/ & pause & cls

Conditional Replace Pandas

Try this:

df.my_channel = df.my_channel.where(df.my_channel <= 20000, other= 0)

or

df.my_channel = df.my_channel.mask(df.my_channel > 20000, other= 0)

Having trouble setting working directory

I just had this error message happen. When searching for why, I figured out that there's a related issue that can occur if you're not paying attention - the same error occurs if the directory you are trying to move into does not exist.

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

You can use localStorage to save the data for later use, but you can not save to a file using JavaScript (in the browser).

To be comprehensive: You can not store something into a file using JavaScript in the Browser, but using HTML5, you can read files.

Center Div inside another (100% width) div

Just add margin: 0 auto; to the inside div.

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

You are missing a field annotated with @Id. Each @Entity needs an @Id - this is the primary key in the database.

If you don't want your entity to be persisted in a separate table, but rather be a part of other entities, you can use @Embeddable instead of @Entity.

If you want simply a data transfer object to hold some data from the hibernate entity, use no annotations on it whatsoever - leave it a simple pojo.

Update: In regards to SQL views, Hibernate docs write:

There is no difference between a view and a base table for a Hibernate mapping. This is transparent at the database level

Find common substring between two strings

def common_start(sa, sb):
    """ returns the longest common substring from the beginning of sa and sb """
    def _iter():
        for a, b in zip(sa, sb):
            if a == b:
                yield a
            else:
                return

    return ''.join(_iter())
>>> common_start("apple pie available", "apple pies")
'apple pie'

Or a slightly stranger way:

def stop_iter():
    """An easy way to break out of a generator"""
    raise StopIteration

def common_start(sa, sb):
    return ''.join(a if a == b else stop_iter() for a, b in zip(sa, sb))

Which might be more readable as

def terminating(cond):
    """An easy way to break out of a generator"""
    if cond:
        return True
    raise StopIteration

def common_start(sa, sb):
    return ''.join(a for a, b in zip(sa, sb) if terminating(a == b))

Java Strings: "String s = new String("silly");"

String is a special built-in class of the language. It is for the String class only in which you should avoid saying

String s = new String("Polish");

Because the literal "Polish" is already of type String, and you're creating an extra unnecessary object. For any other class, saying

CaseInsensitiveString cis = new CaseInsensitiveString("Polish");

is the correct (and only, in this case) thing to do.

How to install 2 Anacondas (Python 2 and 3) on Mac OS

Edit!: Please be sure that you should have both Python installed on your computer.

Maybe my answer is late for you but I can help someone who has the same problem!

You don't have to download both Anaconda.

If you are using Spyder and Jupyter in Anaconda environmen and,

If you have already Anaconda 2 type in Terminal:

    python3 -m pip install ipykernel

    python3 -m ipykernel install --user

If you have already Anaconda 3 then type in terminal:

    python2 -m pip install ipykernel

    python2 -m ipykernel install --user

Then before use Spyder you can choose Python environment like below! Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!

Anaconda spyder Python 2.7 or 3.5

Also this is Jupyter. You can choose python version like this!

Jupyter Notebook

I hope it will help.

Best way to call a JSON WebService from a .NET Console

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string
string GET(string url) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            return reader.ReadToEnd();
        }
    }
    catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }
}

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/

POST looks like this:

// POST a JSON string
void POST(string url, string jsonContent) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/json";

    using (Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }
    long length = 0;
    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            length = response.ContentLength;
        }
    }
    catch (WebException ex) {
        // Log exception and throw as for GET example above
    }
}

I use code like this in automated tests of our web service.

How to write a PHP ternary operator

You could also do:

echo "yes" ?: "no" // Assuming that yes is a variable that can be false.

Instead of:

echo (true)  ? "yes" : "no";

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

How to use format() on a moment.js duration?

You can use numeral.js to format your duration:

numeral(your_duration.asSeconds()).format('00:00:00') // result: hh:mm:ss

How can I add a hint or tooltip to a label in C# Winforms?

Just to share my idea...

I created a custom class to inherit the Label class. I added a private variable assigned as a Tooltip class and a public property, TooltipText. Then, gave it a MouseEnter delegate method. This is an easy way to work with multiple Label controls and not have to worry about assigning your Tooltip control for each Label control.

    public partial class ucLabel : Label
    {
        private ToolTip _tt = new ToolTip();

        public string TooltipText { get; set; }

        public ucLabel() : base() {
            _tt.AutoPopDelay = 1500;
            _tt.InitialDelay = 400;
//            _tt.IsBalloon = true;
            _tt.UseAnimation = true;
            _tt.UseFading = true;
            _tt.Active = true;
            this.MouseEnter += new EventHandler(this.ucLabel_MouseEnter);
        }

        private void ucLabel_MouseEnter(object sender, EventArgs ea)
        {
            if (!string.IsNullOrEmpty(this.TooltipText))
            {
                _tt.SetToolTip(this, this.TooltipText);
                _tt.Show(this.TooltipText, this.Parent);
            }
        }
    }

In the form or user control's InitializeComponent method (the Designer code), reassign your Label control to the custom class:

this.lblMyLabel = new ucLabel();

Also, change the private variable reference in the Designer code:

private ucLabel lblMyLabel;

Create a symbolic link of directory in Ubuntu

This is the behavior of ln if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx to be the symlink, you should remove that directory first and run that same command.

Python Image Library fails with message "decoder JPEG not available" - PIL

Rolo's answer is excellent, however I had to reinstall Pillow by bypassing pip cache (introduced with pip 7) otherwise it won't get properly recompiled!!! The command is:

pip install -I --no-cache-dir -v Pillow

and you can see if Pillow has been properly configured by reading in the logs this:

PIL SETUP SUMMARY
    --------------------------------------------------------------------
    version      Pillow 2.8.2
    platform     linux 3.4.3 (default, May 25 2015, 15:44:26)
                 [GCC 4.8.2]
    --------------------------------------------------------------------
    *** TKINTER support not available
    --- JPEG support available
    *** OPENJPEG (JPEG2000) support not available
    --- ZLIB (PNG/ZIP) support available
    --- LIBTIFF support available
    --- FREETYPE2 support available
    *** LITTLECMS2 support not available
    *** WEBP support not available
    *** WEBPMUX support not available
    --------------------------------------------------------------------

as you can see the support for jpg, tiff and so on is enabled, because I previously installed the required libraries via apt (libjpeg-dev libpng12-dev libfreetype6-dev libtiff-dev)

Using json_encode on objects in PHP (regardless of scope)

$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

Laravel: Get base url

By the way, if your route has a name like:

Route::match(['get', 'post'], 'specialWay/edit', 'SpecialwayController@edit')->name('admin.spway.edit');

You can use the route() function like this:

<form method="post" action="{{route('admin.spway.edit')}}" class="form form-horizontal" id="form-spway-edit">

Other useful functions:

$uri = $request->path();
$url = $request->url();
$url = $request->fullUrl();
asset()
app_path();
// ...

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php

How do you launch the JavaScript debugger in Google Chrome?

Now google chrome has introduce new feature. By Using this feature You can edit you code in chrome browse. (Permanent change on code location)

For that Press F12 --> Source Tab -- (right side) --> File System - in that please select your location of code. and then chrome browser will ask you permission and after that code will be sink with green color. and you can modify your code and it will also reflect on you code location (It means it will Permanent change)

Thanks

What's the best way to trim std::string?

Here's what I came up with:

std::stringstream trimmer;
trimmer << str;
trimmer >> str;

Stream extraction eliminates whitespace automatically, so this works like a charm.
Pretty clean and elegant too, if I do say so myself. ;)

SQL - ORDER BY 'datetime' DESC

Remove the quotes here:

is:

ORDER BY = 'post_datetime DESC' AND LIMIT = '3'

Should be:

ORDER BY post_datetime DESC LIMIT 3

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

In addition to trying 2Toad's answer, I also ended up having to close Visual Studio and delete my .vs folder. After that, everything built correctly.

Incidentally, the error I was encountering didn't specify my Temp folder at all, but was referencing something else that was obviously system-generated. I neglected to save the specific error :\

CSS opacity only to background color, not the text on it?

For anyone coming across this thread, here's a script called thatsNotYoChild.js that I just wrote that solves this problem automatically:

http://www.impressivewebs.com/fixing-parent-child-opacity/

Basically, it separates children from the parent element, but keeps the element in the same physical location on the page.

How to get the unix timestamp in C#

Updated code from Brad with few things: You don't need Math.truncate, conversion to int or long automatically truncates the value. In my version I am using long instead of int (We will run out of 32 bit signed integers in 2038 year). Also, added timestamp parsing.

public static class DateTimeHelper
{
    /// <summary>
     /// Converts a given DateTime into a Unix timestamp
     /// </summary>
     /// <param name="value">Any DateTime</param>
     /// <returns>The given DateTime in Unix timestamp format</returns>
    public static long ToUnixTimestamp(this DateTime value)
    {
        return (long)(value.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    }

    /// <summary>
    /// Gets a Unix timestamp representing the current moment
    /// </summary>
    /// <param name="ignored">Parameter ignored</param>
    /// <returns>Now expressed as a Unix timestamp</returns>
    public static long UnixTimestamp(this DateTime ignored)
    {
        return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    }

    /// <summary>
    /// Returns a local DateTime based on provided unix timestamp
    /// </summary>
    /// <param name="timestamp">Unix/posix timestamp</param>
    /// <returns>Local datetime</returns>
    public static DateTime ParseUnixTimestamp(long timestamp)
    {
        return (new DateTime(1970, 1, 1)).AddSeconds(timestamp).ToLocalTime();
    }

}

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

This error happens when you have a __unicode__ method that is a returning a field that is not entered. Any blank field is None and Python cannot convert None, so you get the error.

In your case, the problem most likely is with the PCE model's __unicode__ method, specifically the field its returning.

You can prevent this by returning a default value:

def __unicode__(self):
   return self.some_field or u'None'

Empty brackets '[]' appearing when using .where

Stuarts' answer is correct, but if you are not sure if you are saving the titles in lowercase, you can also make a case insensitive search

There are a lot of answered questions in Stack Overflow with more data on this:

Example 1

Example 2

How to get response body using HttpURLConnection, when code other than 2xx is returned?

Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

How to make a flat list out of list of lists?

Although it wasn't asked in the original question, there is also an interest in flattenning several times if there are lists of lists of lists...

Also doing at most depth times of un-nesting. Or total flattening (when depth is None), i.e. converting any nesting depth to one global flat list, same as infinite depth.

And supporting varying depth of list-nesting.

Everything that is achieved in my next recursive flatten(l, depth) function and example below, doesn't depend on any module import and works lazily (emits iterator):

Try it online!

def flatten(l, depth = 1):
    done, ndepth = False, None
    if depth is not None:
        done, ndepth = depth <= 0, depth - 1
    if not isinstance(l, list):
        l, done = [l], True
    return iter(l) if done else (e1 for e0 in l for e1 in flatten(e0, ndepth))

l = [ [ [1, [2], 3], [4, 5] ], [ [6, 7], [8, [9, 10]] ] , ['ab', 'c'], 11, 12 ]
    
for depth in [0, 1, 2, 3, 4, None]:
    print('depth', str(depth).rjust(5), ':', list(flatten(l, depth = depth)))

Outputs:

depth     0 : [[[1, [2], 3], [4, 5]], [[6, 7], [8, [9, 10]]], ['ab', 'c'], 11, 12]
depth     1 : [[1, [2], 3], [4, 5], [6, 7], [8, [9, 10]], 'ab', 'c', 11, 12]
depth     2 : [1, [2], 3, 4, 5, 6, 7, 8, [9, 10], 'ab', 'c', 11, 12]
depth     3 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'ab', 'c', 11, 12]
depth     4 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'ab', 'c', 11, 12]
depth  None : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'ab', 'c', 11, 12]

How can I undo a mysql statement that I just executed?

in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:

copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (e.g. XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.

since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.

How to Debug Variables in Smarty like in PHP var_dump()

For what it's worth, you can do {$varname|@debug_print_var} to get a var_dump()-esque output for your variable.

How to use "not" in xpath?

Use boolean function like below:

//a[(contains(@id, 'xx'))=false]

How to convert java.util.Date to java.sql.Date?

Nevermind....

public class MainClass {

  public static void main(String[] args) {
    java.util.Date utilDate = new java.util.Date();
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    System.out.println("utilDate:" + utilDate);
    System.out.println("sqlDate:" + sqlDate);

  }

}

explains it. The link is http://www.java2s.com/Tutorial/Java/0040__Data-Type/ConvertfromajavautilDateObjecttoajavasqlDateObject.htm

No resource identifier found for attribute '...' in package 'com.app....'

I've been searching answer but couldn't find but finally I could fix this by adding play-service-ads dependency let's try this

*) File -> Project Structure... -> Under the module you can find app and there is a option called dependencies and you can add com.google.android.gms:play-services-ads:x.x.x dependency to your project

I faced this problem when I try to import eclipse project into android studio

Click here to see screenshot

Cannot serve WCF services in IIS on Windows 8

You can also achieve this by Turning windows feature ON. enter image description here enter image description here

How do I make an HTML button not reload the page

In HTML:

<form onsubmit="return false">
</form>

in order to avoid refresh at all "buttons", even with onclick assigned.

Converting year and month ("yyyy-mm" format) to a date?

Since dates correspond to a numeric value and a starting date, you indeed need the day. If you really need your data to be in Date format, you can just fix the day to the first of each month manually by pasting it to the date:

month <- "2009-03"
as.Date(paste(month,"-01",sep=""))

How do I programmatically force an onchange event on an input?

If you add all your events with this snippet of code:

//put this somewhere in your JavaScript:
HTMLElement.prototype.addEvent = function(event, callback){
  if(!this.events)this.events = {};
  if(!this.events[event]){
    this.events[event] = [];
    var element = this;
    this['on'+event] = function(e){
      var events = element.events[event];
      for(var i=0;i<events.length;i++){
        events[i](e||event);
      }
    }
  }
  this.events[event].push(callback);
}
//use like this:
element.addEvent('change', function(e){...});

then you can just use element.on<EVENTNAME>() where <EVENTNAME> is the name of your event, and that will call all events with <EVENTNAME>

Which is the fastest algorithm to find prime numbers?

If it has to be really fast you can include a list of primes:
http://www.bigprimes.net/archive/prime/

If you just have to know if a certain number is a prime number, there are various prime tests listed on wikipedia. They are probably the fastest method to determine if large numbers are primes, especially because they can tell you if a number is not a prime.

HashMap: One Key, multiple Values

Libraries exist to do this, but the simplest plain Java way is to create a Map of List like this:

Map<Object,ArrayList<Object>> multiMap = new HashMap<>();

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

I found another reason for this type of error: in my case, someone set the conf/catalina.properties setting tomcat.util.scan.StandardJarScanFilter.jarsToSkip property to * to avoid log warning messages, thereby skipping the necessary scan by Tomcat. Changing this back to the Tomcat default and adding an appropriate list of jars to skip (not including jstl-1.2 or spring-webmvc) solved the problem.

using lodash .groupBy. how to add your own keys for grouped output?

Isn't it this simple?

var result = _(data)
            .groupBy(x => x.color)
            .map((value, key) => ({color: key, users: value}))
            .value();

Manually adding a Userscript to Google Chrome

The best thing to do is to install the Tampermonkey extension.

This will allow you to easily install Greasemonkey scripts, and to easily manage them. Also it makes it easier to install userscripts directly from sites like OpenUserJS, MonkeyGuts, etc.

Finally, it unlocks most all of the GM functionality that you don't get by installing a GM script directly with Chrome. That is, more of what GM on Firefox can do, is available with Tampermonkey.


But, if you really want to install a GM script directly, it's easy a right pain on Chrome these days...

Chrome After about August, 2014:

You can still drag a file to the extensions page and it will work... Until you restart Chrome. Then it will be permanently disabled. See Continuing to "protect" Chrome users from malicious extensions for more information. Again, Tampermonkey is the smart way to go. (Or switch browsers altogether to Opera or Firefox.)

Chrome 21+ :

Chrome is changing the way extensions are installed. Userscripts are pared-down extensions on Chrome but. Starting in Chrome 21, link-click behavior is disabled for userscripts. To install a user script, drag the **.user.js* file into the Extensions page (chrome://extensions in the address input).

Older Chrome versions:

Merely drag your **.user.js* files into any Chrome window. Or click on any Greasemonkey script-link.

You'll get an installation warning:
Initial warning

Click Continue.


You'll get a confirmation dialog:
confirmation dialog

Click Add.


Notes:

  1. Scripts installed this way have limitations compared to a Greasemonkey (Firefox) script or a Tampermonkey script. See Cross-browser user-scripting, Chrome section.

Controlling the Script and name:

By default, Chrome installs scripts in the Extensions folder1, full of cryptic names and version numbers. And, if you try to manually add a script under this folder tree, it will be wiped the next time Chrome restarts.

To control the directories and filenames to something more meaningful, you can:

  1. Create a directory that's convenient to you, and not where Chrome normally looks for extensions. For example, Create: C:\MyChromeScripts\.

  2. For each script create its own subdirectory. For example, HelloWorld.

  3. In that subdirectory, create or copy the script file. For example, Save this question's code as: HelloWorld.user.js.

  4. You must also create a manifest file in that subdirectory, it must be named: manifest.json.

    For our example, it should contain:

    {
        "manifest_version": 2,
        "content_scripts": [ {
            "exclude_globs":    [  ],
            "include_globs":    [ "*" ],
            "js":               [ "HelloWorld.user.js" ],
            "matches":          [   "https://stackoverflow.com/*",
                                    "https://stackoverflow.com/*"
                                ],
            "run_at": "document_end"
        } ],
        "converted_from_user_script": true,
        "description":  "My first sensibly named script!",
        "name":         "Hello World",
        "version":      "1"
    }
    

    The manifest.json file is automatically generated from the meta-block by Chrome, when an user script is installed. The values of @include and @exclude meta-rules are stored in include_globs and exclude_globs, @match (recommended) is stored in the matches list. "converted_from_user_script": true is required if you want to use any of the supported GM_* methods.

  5. Now, in Chrome's Extension manager (URL = chrome://extensions/), Expand "Developer mode".

  6. Click the Load unpacked extension... button.

  7. For the folder, paste in the folder for your script, In this example it is: C:\MyChromeScripts\HelloWorld.

  8. Your script is now installed, and operational!

  9. If you make any changes to the script source, hit the Reload link for them to take effect:

    Reload link




1 The folder defaults to:

Windows XP:
  Chrome  : %AppData%\..\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\
  Chromium: %AppData%\..\Local Settings\Application Data\Chromium\User Data\Default\Extensions\

Windows Vista/7/8:
  Chrome  : %LocalAppData%\Google\Chrome\User Data\Default\Extensions\
  Chromium: %LocalAppData%\Chromium\User Data\Default\Extensions\

Linux:
  Chrome  : ~/.config/google-chrome/Default/Extensions/
  Chromium: ~/.config/chromium/Default/Extensions/

Mac OS X:
  Chrome  : ~/Library/Application Support/Google/Chrome/Default/Extensions/
  Chromium: ~/Library/Application Support/Chromium/Default/Extensions/

Although you can change it by running Chrome with the --user-data-dir= option.

Creating multiline strings in JavaScript

Also do note that, when extending string over multiple lines using forward backslash at end of each line, any extra characters (mostly spaces, tabs and comments added by mistake) after forward backslash will cause unexpected character error, which i took an hour to find out

var string = "line1\  // comment, space or tabs here raise error
line2";

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

I think that this is as easy as I can explain it. Please, anyone is welcome to correct me or add to this.

SOAP is a message format used by disconnected systems (like across the internet) to exchange information / data. It does with XML messages going back and forth.

Web services transmit or receive SOAP messages. They work differently depending on what language they are written in.

How do I launch a Git Bash window with particular working directory using a script?

Windows 10

This is basically @lengxuehx's answer, but updated for Win 10, and it assumes your bash installation is from Git Bash for Windows from git's official downloads.

cmd /c (start /b "%cd%" "C:\Program Files\GitW\git-bash.exe") && exit

I ended up using this after I lost my context-menu items for Git Bash as my command to run from the registry settings. In case you're curious about that, I did this:

  1. Create a new key called Bash in the shell key at HKEY_CLASSES_ROOT\Directory\Background\shell
  2. Add a string value to Icon (not a new key!) that is the full path to your git-bash.exe, including the git-bash.exe part. You might need to wrap this in quotes.
  3. Edit the default value of Bash to the text you want to use in the context menu enter image description here
  4. Add a sub-key to Bash called command
  5. Modify command's default value to cmd /c (start /b "%cd%" "C:\Program Files\GitW\git-bash.exe") && exit enter image description here

Then you should be able to close the registry and start using Git Bash from anywhere that's a real directory. For example, This PC is not a real directory.

enter image description here

Switching to landscape mode in Android Emulator

In my windows-8 laptop, ctrl + fn + F11 works.

How to vertically align an image inside a div

An easy way which work for me:

img {
    vertical-align: middle;
    display: inline-block;
    position: relative;
}

It works for Google Chrome very well. Try this one out in a different browser.

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

As i have also faced this issue today morning and none of the answers helped me out particularly in my case. And after trying for hours i figured out the issue.

Actually while working in storyboard by mistake, i just renamed my "Main.storyboard" to ".storyboard" and changing it back to "Main.storyboard" solved my issue.

SOLUTION(As per my issue): May be you have renamed any file due to which xcode couldn't load it and raised an issue. For example: as mentioned above the case of changing "Executable File" name
Possible Issue area: May be the last few files you were working in.

UILabel is not auto-shrinking text to fit label size

Coming late to the party, but since I had the additional requirement of having one word per line, this one addition did the trick for me:

label.numberOfLines = [labelString componentsSeparatedByString:@" "].count;

Apple Docs say:

Normally, the label text is drawn with the font you specify in the font property. If this property is set to YES, however, and the text in the text property exceeds the label’s bounding rectangle, the receiver starts reducing the font size until the string fits or the minimum font size is reached. In iOS 6 and earlier, this property is effective only when the numberOfLines property is set to 1.

But this is a lie. A lie I tell you! It's true for all iOS versions. Specifically, this is true when using a UILabel within a UICollectionViewCell for which the size is determined by constraints adjusted dynamically at runtime via custom layout (ex. self.menuCollectionViewLayout.itemSize = size).

So when used in conjunction with adjustsFontSizeToFitWidth and minimumScaleFactor, as mentioned in previous answers, programmatically setting numberOfLines based on word count solved the autoshrink problem. Doing something similar based on word count or even character count might produce a "close enough" solution.

File Upload using AngularJS

The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:

Working Demo of select-ng-files Directive that Works with ng-model1

_x000D_
_x000D_
angular.module("app",[]);

angular.module("app").directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" select-ng-files ng-model="fileList" multiple>
    
    <h2>Files</h2>
    <div ng-repeat="file in fileList">
      {{file.name}}
    </div>
  </body>
_x000D_
_x000D_
_x000D_


$http.post from a FileList

$scope.upload = function(url, fileList) {
    var config = { headers: { 'Content-Type': undefined },
                   transformResponse: angular.identity
                 };
    var promises = fileList.map(function(file) {
        return $http.post(url, file, config);
    });
    return $q.all(promises);
};

When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

Tesseract OCR simple example

Ok. I found the solution here tessnet2 fails to load the Ans given by Adam

Apparently i was using wrong version of tessdata. I was following the the source page instruction intuitively and that caused the problem.

it says

Quick Tessnet2 usage

  1. Download binary here, add a reference of the assembly Tessnet2.dll to your .NET project.

  2. Download language data definition file here and put it in tessdata directory. Tessdata directory and your exe must be in the same directory.

After you download the binary, when you follow the link to download the language file, there are many language files. but none of them are right version. you need to select all version and go to next page for correct version (tesseract-2.00.eng)! They should either update download binary link to version 3 or put the the version 2 language file on the first page. Or at least bold mention the fact that this version issue is a big deal!

Anyway I found it. Thanks everyone.

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

Button text toggle in jquery

$(".pushme").click(function () {
  var button = $(this);
  button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")           
});

This ternary operator has an implicit return. If the expression before ? is true it returns "DON'T PUSH ME", else returns "PUSH ME"

This if-else statement:

if (condition) { return A }
else { return B }

has the equivalent ternary expression:

condition ? A : B

visual c++: #include files from other projects in the same solution

#include has nothing to do with projects - it just tells the preprocessor "put the contents of the header file here". If you give it a path that points to the correct location (can be a relative path, like ../your_file.h) it will be included correctly.

You will, however, have to learn about libraries (static/dynamic libraries) in order to make such projects link properly - but that's another question.

How to calculate the number of days between two dates?

Here is my implementation:

function daysBetween(one, another) {
  return Math.round(Math.abs((+one) - (+another))/8.64e7);
}

+<date> does the type coercion to the integer representation and has the same effect as <date>.getTime() and 8.64e7 is the number of milliseconds in a day.

Count number of vector values in range with R

Use which:

 set.seed(1)
 x <- sample(10, 50, replace = TRUE)
 length(which(x > 3 & x < 5))
 # [1]  6

Replace \n with actual new line in Sublime Text

Fool proof method (no RegEx and Ctrl+Enter didn't work for me as it was just jumping to next Find):

First, select an occurrence of \n and hit Ctrl+H (brings up the Replace... dialogue, also accessible through Find -> Replace... menu). This populates the Find what field.

Go to the end of any line of your file (press End if your keyboard has it) and select the end of line by holding down Shift and pressing ? (right arrow) EXACTLY once. Then copy-paste this into the Replace with field.

(the animation is for finding true new lines; works the same for replacing them)

enter image description here

Add a new line to a text file in MS-DOS

echo "text to echo" > file.txt

How to create a new file in unix?

The command is lowercase: touch filename.

Keep in mind that touch will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch

If you always want an empty file, one way to do so would be to use:

echo "" > filename

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

Since you're using php-fpm you should take advantage of fastcgi_finish_request() for processing requests you know can take longer.

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

Something like

select *
  from foo
 where regexp_like( col1, '[^[:alpha:]]' ) ;

should work

SQL> create table foo( col1 varchar2(100) );

Table created.

SQL> insert into foo values( 'abc' );

1 row created.

SQL> insert into foo values( 'abc123' );

1 row created.

SQL> insert into foo values( 'def' );

1 row created.

SQL> select *
  2    from foo
  3   where regexp_like( col1, '[^[:alpha:]]' ) ;

COL1
--------------------------------------------------------------------------------
abc123

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

How to Implement Custom Table View Section Headers and Footers with Storyboard

In iOS 6.0 and above, things have changed with the new dequeueReusableHeaderFooterViewWithIdentifier API.

I have written a guide (tested on iOS 9), which can be summarised as such:

  1. Subclass UITableViewHeaderFooterView
  2. Create Nib with the subclass view, and add 1 container view which contains all other views in the header/footer
  3. Register the Nib in viewDidLoad
  4. Implement viewForHeaderInSection and use dequeueReusableHeaderFooterViewWithIdentifier to get back the header/footer

mssql convert varchar to float

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED

above will return values

however below query wont work

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED

as @INPUT_1 actually has varchar in it.

So your output column must have a varchar in it.

What are the First and Second Level caches in (N)Hibernate?

1.1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

1.2) Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also.

Quoted from: http://javabeat.net/introduction-to-hibernate-caching/

Convert SQL Server result set into string

DECLARE @result varchar(1000)

SELECT @result = ISNULL(@result, '') + StudentId + ',' FROM Student WHERE condition = xyz

select substring(@result, 0, len(@result) - 1) --trim extra "," at end

Read pdf files with php

You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com

Getting SyntaxError for print with keyword argument end=' '

Basically, it occurs in python2.7 here is my code of how it works:

  i=5
while(i):
    print i,
    i=i-1
Output:
5 4 3 2 1

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

EDIT: Handlebars now has a built-in way of accomplishing this; see the selected answer above. When working with plain Mustache, the below still applies.

Mustache can iterate over items in an array. So I'd suggest creating a separate data object formatted in a way Mustache can work with:

var o = {
  bob : 'For sure',
  roger: 'Unknown',
  donkey: 'What an ass'
},
mustacheFormattedData = { 'people' : [] };

for (var prop in o){
  if (o.hasOwnProperty(prop)){
    mustacheFormattedData['people'].push({
      'key' : prop,
      'value' : o[prop]
     });
  }
}

Now, your Mustache template would be something like:

{{#people}}
  {{key}} : {{value}}
{{/people}}

Check out the "Non-Empty Lists" section here: https://github.com/janl/mustache.js

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

Actually you can use if/else and switch and any other statement inline in dart / flutter.

Use an immediate anonymous function

class StatmentExample extends StatelessWidget {
  Widget build(BuildContext context) {
    return Text((() {
      if(true){
        return "tis true";}

      return "anything but true";
    })());
  }
}

ie wrap your statements in a function

(() {
  // your code here
}())

I would heavily recommend against putting too much logic directly with your UI 'markup' but I found that type inference in Dart needs a little bit of work so it can be sometimes useful in scenarios like that.

Use the ternary operator

condition ? Text("True") : null,

Use If or For statements or spread operators in collections

children: [
  ...manyItems,
  oneItem,
  if(canIKickIt)
    ...kickTheCan
  for (item in items)
    Text(item)

Use a method

child: getWidget()

Widget getWidget() {
  if (x > 5) ...
  //more logic here and return a Widget

Redefine switch statement

As another alternative to the ternary operator, you could create a function version of the switch statement such as in the following post https://stackoverflow.com/a/57390589/1058292.

  child: case2(myInput,
  {
    1: Text("Its one"),
    2: Text("Its two"),
  }, Text("Default"));

How to do relative imports in Python?

main.py
setup.py
app/ ->
    __init__.py
    package_a/ ->
       __init__.py
       module_a.py
    package_b/ ->
       __init__.py
       module_b.py
  1. You run python main.py.
  2. main.py does: import app.package_a.module_a
  3. module_a.py does import app.package_b.module_b

Alternatively 2 or 3 could use: from app.package_a import module_a

That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

What's the simplest way to extend a numpy array in 2 dimensions?

maybe you need this.

>>> x = np.array([11,22])
>>> y = np.array([18,7,6])
>>> z = np.array([1,3,5])
>>> np.concatenate((x,y,z))
array([11, 22, 18,  7,  6,  1,  3,  5])

Is there a "between" function in C#?

Or if you want to bound the value to the interval:

public static T EnsureRange<T>(this T value, T min, T max) where T : IComparable<T>
    {
        if (value.CompareTo(min) < 0)
            return min;
        else if (value.CompareTo(max) > 0)
            return max;
        else
            return value;
    }

It is like two-sided Math.Min/Max

Should I use pt or px?

pt is a derivation (abbreviation) of "point" which historically was used in print type faces where the size was commonly "measured" in "points" where 1 point has an approximate measurement of 1/72 of an inch, and thus a 72 point font would be 1 inch in size.

px is an abbreviation for "pixel" which is a simple "dot" on either a screen or a dot matrix printer or other printer or device which renders in a dot fashion - as opposed to old typewriters which had a fixed size, solid striker which left an imprint of the character by pressing on a ribbon, thus leaving an image of a fixed size.

Closely related to point are the terms "uppercase" and "lowercase" which historically had to do with the selection of the fixed typographical characters where the "captital" characters where placed in a box (case) above the non-captitalized characters which were place in a box below, and thus the "lower" case.

There were different boxes (cases) for different typographical fonts and sizes, but still and "upper" and "lower" case for each of those.

Another term is the "pica" which is a measure of one character in the font, thus a pica is 1/6 of an inch or 12 point units of measure (12/72) of measure.

Strickly speaking the measurement is on computers 4.233mm or 0.166in whereas the old point (American) is 1/72.27 of an inch and French is 4.512mm (0.177in.). Thus my statement of "approximate" regarding the measurements.

Further, typewriters as used in offices, had either and "Elite" or a "Pica" size where the size was 10 and 12 characters per inch repectivly.

Additionally, the "point", prior to standardization was based on the metal typographers "foot" size, the size of the basic footprint of one character, and varied somewhat in size.

Note that a typographical "foot" was originally from a deceased printers actual foot. A typographic foot contains 72 picas or 864 points.

As to CSS use, I prefer to use EM rather than px or pt, thus gaining the advantage of scaling without loss of relative location and size.

EDIT: Just for completeness you can think of EM (em) as an element of measure of one font height, thus 1em for a 12pt font would be the height of that font and 2em would be twice that height. Note that for a 12px font, 2em is 24 pixels. SO 10px is typically 0.63em of a standard font as "most" browsers base on 16px = 1em as a standard font size.

How to loop through a plain JavaScript object with the objects as members?

ECMAScript-2017, just finalized a month ago, introduces Object.values(). So now you can do this:

let v;
for (v of Object.values(validation_messages))
   console.log(v.your_name);   // jimmy billy

How can moment.js be imported with typescript?

Update

Apparently, moment now provides its own type definitions (according to sivabudh at least from 2.14.1 upwards), thus you do not need typings or @types at all.

import * as moment from 'moment' should load the type definitions provided with the npm package.

That said however, as said in moment/pull/3319#issuecomment-263752265 the moment team seems to have some issues in maintaining those definitions (they are still searching someone who maintains them).


You need to install moment typings without the --ambient flag.

Then include it using import * as moment from 'moment'

Removing character in list of strings

Here's a short one-liner using regular expressions:

print [re.compile(r"8").sub("", m) for m in mylist]

If we separate the regex operations and improve the namings:

pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res

Modify a Column's Type in sqlite3

It is possible by recreating table.Its work for me please follow following step:

  1. create temporary table using as select * from your table
  2. drop your table, create your table using modify column type
  3. now insert records from temp table to your newly created table
  4. drop temporary table

do all above steps in worker thread to reduce load on uithread

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

Render HTML to PDF in Django site

https://github.com/nigma/django-easy-pdf

Template:

{% extends "easy_pdf/base.html" %}

{% block content %}
    <div id="content">
        <h1>Hi there!</h1>
    </div>
{% endblock %}

View:

from easy_pdf.views import PDFTemplateView

class HelloPDFView(PDFTemplateView):
    template_name = "hello.html"

If you want to use django-easy-pdf on Python 3 check the solution suggested here.

Trim leading and trailing spaces from a string in awk

just use a regex as a separator:

', *' - for leading spaces

' *,' - for trailing spaces

for both leading and trailing:

awk -F' *,? *' '{print $1","$2}' input.txt

How do I display images from Google Drive on a website?

I have the same problem right now but this article helps me. Updates for the year 2020!

I got the solution from this article:
https://dev.to/imamcu07/embed-or-display-image-to-html-page-from-google-drive-3ign

These are the steps from the article:

  1. Upload your image to google drive.
  2. Share your image from the sharing option.
  3. Copy your sharing link (Sample: https://drive.google.com/file/d/14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp/view?usp=sharing)
  4. Copy the id from your link, in the above link, the id is: 14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp
  5. Have a look at the below link and replace the ID. https://drive.google.com/thumbnail?id=1jNWSPr_BOSbm7iIJQTTbl7lXX06NH9_r

After Replace ID: https://drive.google.com/thumbnail?id=14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp

  1. Now insert the link to your <img> tag.

And now it should work.

ImageMagick security policy 'PDF' blocking conversion

Well, I added

  <policy domain="coder" rights="read | write" pattern="PDF" />

just before </policymap> in /etc/ImageMagick-7/policy.xml and that makes it work again, but not sure about the security implications of that.

How to remove old Docker containers

UPDATED 2021 (NEWEST)

docker container prune

This - 2017 (OLD) way

To remove ALL STOPPED CONTAINERS

docker rm $(docker ps -a -q)

To remove ALL CONTAINERS (STOPPED AND NON STOPPED)

docker rm  -f $(docker ps -a -q)

How do I convert a column of text URLs into active hyperlinks in Excel?

Thank you Cassiopeia for code. I change his code to work with local addresses and made little changes to his conditions. I removed following conditions:

  1. Change http:/ to file:///
  2. Removed all type of white space conditions
  3. Changed 10k cell range condition to 100k

Sub HyperAddForLocalLinks()
Dim CellsWithSpaces As String
    'Converts each text hyperlink selected into a working hyperlink
    Application.ScreenUpdating = False
    Dim NotPresent As Integer
    NotPresent = 0

    For Each xCell In Selection
        xCell.Formula = Trim(xCell.Formula)
            If InStr(xCell.Formula, "file:///") <> 0 Then
                Hyperstring = Trim(xCell.Formula)
            Else
                Hyperstring = "file:///" & Trim(xCell.Formula)
            End If

            ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=Hyperstring

        i = i + 1
        If i = 100000 Then Exit Sub
Nextxcell:
      Next xCell
    Application.ScreenUpdating = True
End Sub

Using FileUtils in eclipse

Open the project's properties---> Java Build Path ---> Libraries tab ---> Add External Jars

will allow you to add jars.

You need to download commonsIO from here.

Subscript out of bounds - general definition and solution?

This came from standford's sna free tutorial and it states that ...

# Reachability can only be computed on one vertex at a time. To # get graph-wide statistics, change the value of "vertex" # manually or write a for loop. (Remember that, unlike R objects, # igraph objects are numbered from 0.)

ok, so when ever using igraph, the first roll/column is 0 other than 1, but matrix starts at 1, thus for any calculation under igraph, you would need x-1, shown at

this_node_reach <- subcomponent(g, (i - 1), mode = m)

but for the alter calculation, there is a typo here

alter = this_node_reach[j] + 1

delete +1 and it will work alright

Finding the path of the program that will execute from the command line in Windows

As the thread mentioned in the comment, get-command in powershell can also work it out. For example, you can type get-command npm and the output is as below:

enter image description here

Making div content responsive

@media screen and (max-width : 760px) (for tablets and phones) and use with this: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Duplicate symbols for architecture x86_64 under Xcode

just uninstall the pod which it is related to and reinstall them.

How I can filter a Datatable?

You can use DataView.

DataView dv = new DataView(yourDatatable);
dv.RowFilter = "query"; // query example = "id = 10"


http://www.csharp-examples.net/dataview-rowfilter/

"Keep Me Logged In" - the best approach

Security Notice: Basing the cookie off an MD5 hash of deterministic data is a bad idea; it's better to use a random token derived from a CSPRNG. See ircmaxell's answer to this question for a more secure approach.

Usually I do something like this:

  1. User logs in with 'keep me logged in'
  2. Create session
  3. Create a cookie called SOMETHING containing: md5(salt+username+ip+salt) and a cookie called somethingElse containing id
  4. Store cookie in database
  5. User does stuff and leaves ----
  6. User returns, check for somethingElse cookie, if it exists, get the old hash from the database for that user, check of the contents of cookie SOMETHING match with the hash from the database, which should also match with a newly calculated hash (for the ip) thus: cookieHash==databaseHash==md5(salt+username+ip+salt), if they do, goto 2, if they don't goto 1

Off course you can use different cookie names etc. also you can change the content of the cookie a bit, just make sure it isn't to easily created. You can for example also create a user_salt when the user is created and also put that in the cookie.

Also you could use sha1 instead of md5 (or pretty much any algorithm)

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

Recently I faced the issue while working on some legacy code. After googling I found that the issue is everywhere but without any concrete resolution. I worked on various parts of the exception message and analyzed below.

Analysis:

  1. SSLException: exception happened with the SSL (Secure Socket Layer), which is implemented in javax.net.ssl package of the JDK (openJDK/oracleJDK/AndroidSDK)
  2. Read error ssl=# I/O error during system call: Error occured while reading from the Secure socket. It happened while using the native system libraries/driver. Please note that all the platforms solaris, Windows etc. have their own socket libraries which is used by the SSL. Windows uses WINSOCK library.
  3. Connection reset by peer: This message is reported by the system library (Solaris reports ECONNRESET, Windows reports WSAECONNRESET), that the socket used in the data transfer is no longer usable because an existing connection was forcibly closed by the remote host. One needs to create a new secure path between the host and client

Reason:

Understanding the issue, I try finding the reason behind the connection reset and I came up with below reasons:

  • The peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close.
  • This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with Network dropped connection on reset(On Windows(WSAENETRESET)) and Subsequent operations fail withConnection reset by peer(On Windows(WSAECONNRESET)).
  • If the target server is protected by Firewall, which is true in most of the cases, the Time to live (TTL) or timeout associated with the port forcibly closes the idle connection at given timeout. this is something of our interest

Resolution:

  1. Events on the server side such as sudden service stop, rebooted, network interface disabled can not be handled by any means.
  2. On the server side, Configure firewall for the given port with the higher Time to Live (TTL) or timeout values such as 3600 secs.
  3. Clients can "try" keeping the network active to avoid or reduce the Connection reset by peer.
  4. Normally on going network traffic keeps the connection alive and problem/exception is not seen frequently. Strong Wifi has least chances of Connection reset by peer.
  5. With the mobile networks 2G, 3G and 4G where the packet data delivery is intermittent and dependent on the mobile network availability, it may not reset the TTL timer on the server side and results into the Connection reset by peer.

Here are the terms suggested to set on various forums to resolve the issue

  • ConnectionTimeout: Used only at the time out making the connection. If host takes time to connection higher value of this makes the client wait for the connection.
  • SoTimeout: Socket timeout-It says the maximum time within which the a data packet is received to consider the connection as active.If no data received within the given time, the connection is assumed as stalled/broken.
  • Linger: Upto what time the socket should not be closed when data is queued to be sent and the close socket function is called on the socket.
  • TcpNoDelay: Do you want to disable the buffer that holds and accumulates the TCP packets and send them once a threshold is reached? Setting this to true will skip the TCP buffering so that every request is sent immediately. Slowdowns in the network may be caused by an increase in network traffic due to smaller and more frequent packet transmission.

So none of the above parameter helps keeping the network alive and thus ineffective.

I found one setting that may help resolving the issue which is this functions

setKeepAlive(true)
setSoKeepalive(HttpParams params, enableKeepalive="true") 

How did I resolve my issue?

  • Set the HttpConnectionParams.setSoKeepAlive(params, true)
  • Catch the SSLException and check for the exception message for Connection reset by peer
  • If exception is found, store the download/read progress and create a new connection.
  • If possible resume the download/read else restart the download

I hope the details help. Happy Coding...

How to use SVG markers in Google Maps API v3

I know this post is a bit old, but I have seen so much bad information on this at SO that I could scream. So I just gotta throw my two cents in with a whole different approach that I know works, as I use it reliably on many maps. Besides that, I believe the OP wanted the ability to rotate the arrow marker around the map point as well, which is different than rotating the icon around it's own x,y axis which will change where the arrow marker points to on the map.

First, remember we are playing with Google maps and SVG, so we must accomodate the way in which Google deploys it's implementation of SVG for markers (or actually symbols). Google sets its anchor for the SVG marker image at 0,0 which IS NOT the upper left corner of the SVG viewBox. In order to get around this, you must draw your SVG image a bit differently to give Google what it wants... yes the answer is in the way you actually create the SVG path in your SVG editor (Illustrator, Inkscape, etc...).

The first step, is to get rid of the viewBox. This can be done by setting the viewBox in your XML to 0... that's right, just one zero instead of the usual four arguments for the viewBox. This turns the view box off (and yes, this is semantically correct). You will probably notice the size of your image jump immeadiately when you do this, and that is because the svg no longer has a base (the viewBox) to scale the image. So we create that reference directly, by setting the width and height to the actual number of pixels you wish your image to be in the XML editor of your SVG editor.

By setting the width and height of the svg image in the XML editor you create a baseline for scaling of the image, and this size becomes a value of 1 for the marker scale properties by default. You can see the advantage this has for dynamic scaling of the marker.

Now that you have your image sized, move the image until the part of the image you wish to have as the anchor is over the 0,0 coordinates of the svg editor. Once you have done this copy the value of the d attribute of the svg path. You will notice about half of the numbers are negative, which is the result of aligning your anchor point for the 0,0 of the image instead of the viewBox.

Using this technique will then let you rotate the marker correctly, around the lat and lng point on the map. This is the only reliable way to bind the point on the svg marker you want to the lat and long of the marker location.

I tried to make a JSFiddle for this, but there is some bug in there implementation, one of the reasons I am not so fond of reinterpreted code. So instead, I have included a fully self-contained example below that you can try out, adapt, and use as a reference. This is the same code I tried at JSFiddle that failed, yet it sails through Firebug without a whimper.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta name="viewport"  content="width=device-width, initial-scale=1" />
    <meta name="author"    content="Drew G. Stimson, Sr. ( Epiphany )" />
    <title>Create Draggable and Rotatable SVG Marker</title>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false"> </script>
    <style type="text/css">
      #document_body {
        margin:0;
        border: 0;
        padding: 10px;
        font-family: Arial,sans-serif;
        font-size: 14px;
        font-weight: bold;
        color: #f0f9f9;
        text-align: center;
        text-shadow: 1px 1px 1px #000;
        background:#1f1f1f;
      }
      #map_canvas, #rotation_control {
        margin: 1px;
        border:1px solid #000;
        background:#444;
        -webkit-border-radius: 4px;
           -moz-border-radius: 4px;
                border-radius: 4px;
      }
      #map_canvas { 
        width: 100%;
        height: 360px;
      }
      #rotation_control { 
        width: auto;
        padding:5px;
      }
      #rotation_value { 
        margin: 1px;
        border:1px solid #999;
        width: 60px;
        padding:2px;
        font-weight: bold;
        color: #00cc00;
        text-align: center;
        background:#111;
        border-radius: 4px;
      }
</style>

<script type="text/javascript">
  var map, arrow_marker, arrow_options;
  var map_center = {lat:41.0, lng:-103.0};
  var arrow_icon = {
    path: 'M -1.1500216e-4,0 C 0.281648,0 0.547084,-0.13447 0.718801,-0.36481 l 17.093151,-22.89064 c 0.125766,-0.16746 0.188044,-0.36854 0.188044,-0.56899 0,-0.19797 -0.06107,-0.39532 -0.182601,-0.56215 -0.245484,-0.33555 -0.678404,-0.46068 -1.057513,-0.30629 l -11.318243,4.60303 0,-26.97635 C 5.441639,-47.58228 5.035926,-48 4.534681,-48 l -9.06959,0 c -0.501246,0 -0.906959,0.41772 -0.906959,0.9338 l 0,26.97635 -11.317637,-4.60303 c -0.379109,-0.15439 -0.812031,-0.0286 -1.057515,0.30629 -0.245483,0.33492 -0.244275,0.79809 0.0055,1.13114 L -0.718973,-0.36481 C -0.547255,-0.13509 -0.281818,0 -5.7002158e-5,0 Z',
    strokeColor: 'black',
    strokeOpacity: 1,
    strokeWeight: 1,
    fillColor: '#fefe99',
    fillOpacity: 1,
    rotation: 0,
    scale: 1.0
  };

function init(){
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    center: map_center,
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.HYBRID
  });
  arrow_options = {
    position: map_center,
    icon: arrow_icon,
    clickable: false,
    draggable: true,
    crossOnDrag: true,
    visible: true,
    animation: 0,
    title: 'I am a Draggable-Rotatable Marker!' 
  };
  arrow_marker = new google.maps.Marker(arrow_options);
  arrow_marker.setMap(map);
}
function setRotation(){
  var heading = parseInt(document.getElementById('rotation_value').value);
  if (isNaN(heading)) heading = 0;
  if (heading < 0) heading = 359;
  if (heading > 359) heading = 0;
  arrow_icon.rotation = heading;
  arrow_marker.setOptions({icon:arrow_icon});
  document.getElementById('rotation_value').value = heading;
}
</script>
</head>
<body id="document_body" onload="init();">
  <div id="rotation_control">
    <small>Enter heading to rotate marker&nbsp;&nbsp;&nbsp;&nbsp;</small>
    Heading&deg;<input id="rotation_value" type="number" size="3" value="0" onchange="setRotation();" />
    <small>&nbsp;&nbsp;&nbsp;&nbsp;Drag marker to place marker</small>
    </div>
    <div id="map_canvas"></div>
</body>
</html>

This is exactly what Google does for it's own few symbols available in the SYMBOL class of the Maps API, so if that doesn't convince you... Anyway, I hope this will help you to correctly make and set up a SVG marker for your Google maps endevours.

Refreshing all the pivot tables in my excel workbook with a macro

ActiveWorkbook.RefreshAll refreshes everything, not only the pivot tables but also the ODBC queries. I have a couple of VBA queries that refer to Data connections and using this option crashes as the command runs the Data connections without the detail supplied from the VBA

I recommend the option if you only want the pivots refreshed

Sub RefreshPivotTables()     
  Dim pivotTable As PivotTable     
  For Each pivotTable In ActiveSheet.PivotTables         
    pivotTable.RefreshTable     
  Next 
End Sub 

View/edit ID3 data for MP3 files

I wrapped mp3 decoder library and made it available for .net developers. You can find it here:

http://sourceforge.net/projects/mpg123net/

Included are the samples to convert mp3 file to PCM, and read ID3 tags.

How to remove multiple deleted files in Git repository

git add -u 

updates all your changes

Stopping an Android app from console

I tried all answers here on Linux nothing worked for debugging on unrooted device API Level 23, so i found an Alternative for debugging From Developer Options -> Apps section -> check Do Not keep activities that way when ever you put the app in background it gets killed

P.S remember to uncheck it after you finished debugging

Working with select using AngularJS's ng-options

In CoffeeScript:

#directive
app.directive('select2', ->
    templateUrl: 'partials/select.html'
    restrict: 'E'
    transclude: 1
    replace: 1
    scope:
        options: '='
        model: '='
    link: (scope, el, atr)->
        el.bind 'change', ->
            console.log this.value
            scope.model = parseInt(this.value)
            console.log scope
            scope.$apply()
)
<!-- HTML partial -->
<select>
  <option ng-repeat='o in options'
          value='{{$index}}' ng-bind='o'></option>
</select>

<!-- HTML usage -->
<select2 options='mnuOffline' model='offlinePage.toggle' ></select2>

<!-- Conclusion -->
<p>Sometimes it's much easier to create your own directive...</p>

iOS9 Untrusted Enterprise Developer with no option to trust

On iOS 9.2 Profiles renamed to Device Management.
Now navigation looks like that:
Settings -> General -> Device Management -> Tap on necessary profile in list -> Trust.

ArrayList: how does the size increase?

ArrayList does increases the size on load factor on following cases:

  • Initial Capacity: 10
  • Load Factor: 1 (i.e. when the list is full)
  • Growth Rate: current_size + current_size/2

Context : JDK 7

While adding an element into the ArrayList, the following public ensureCapacityInternal calls and the other private method calls happen internally to increase the size. This is what dynamically increase the size of ArrayList. while viewing the code you can understand the logic by naming conventions, because of this reason I am not adding explicit description

public boolean add(E paramE) {
        ensureCapacityInternal(this.size + 1);
        this.elementData[(this.size++)] = paramE;
        return true;
    }

private void ensureCapacityInternal(int paramInt) {
        if (this.elementData == EMPTY_ELEMENTDATA)
            paramInt = Math.max(10, paramInt);
        ensureExplicitCapacity(paramInt);
    }
private void ensureExplicitCapacity(int paramInt) {
        this.modCount += 1;
        if (paramInt - this.elementData.length <= 0)
            return;
        grow(paramInt);
    }

private void grow(int paramInt) {
    int i = this.elementData.length;
    int j = i + (i >> 1);
    if (j - paramInt < 0)
        j = paramInt;
    if (j - 2147483639 > 0)
        j = hugeCapacity(paramInt);
    this.elementData = Arrays.copyOf(this.elementData, j);
}

How can I see what I am about to push with git?

Just wanted to add for PyCharm users: You can right-click on the file, -> Git -> Compare with branch

And then you can choose master (or any other)

Find out who is locking a file on a network share

PsFile does work on remote machines. If my login account already has access to the remote share, I can just enter:

psfile \\remote-share

(replace "remote-share" with the name of your file server) and it will list every opened document on that share, along with who has it open, and the file ID if I want to force the file closed. For me, this is a really long list, but it can be narrowed down by entering part of a path:

psfile \\remote-share I:\\Human_Resources

This is kind of tricky, since in my case this remote share is mounted as Z: on my local machine, but psfile identifies paths as they are defined on the remote file server, which in my case is I: (yours will be different). I just had to comb through the results of my first psfile run to see some of the paths it returned and then run it again with a partial path to narrow down the results.

Optionally, PsFile will let you specify credentials for the remote share if you need to supply them for access.

Lastly, a little known tip: if someone clicks on a file in Windows Explorer and cuts or copies the file with the intent to paste it somewhere else, that act also places a lock on the file.

Get selected option text with JavaScript

 <select class="cS" onChange="fSel2(this.value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select><br>

 <select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <script type="text/javascript"> "use strict";
   const s=document.querySelector(".cS");

 // options[this.selectedIndex].value
 let fSel = (sIdx) => console.log(sIdx,
     s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);

 let fSel2= (sIdx) => { // this.value
     console.log(sIdx, s.options[sIdx].text,
         s.options[sIdx].textContent, s.options[sIdx].label);
 }

 // options[this.selectedIndex].text
 // options[this.selectedIndex].textContent
 // options[this.selectedIndex].label
 // options[this.selectedIndex].innerHTML
 let fSel3= (sIdx) => {
     console.log(sIdx);
 }
 </script> // fSel

But :

 <script type="text/javascript"> "use strict";
    const x=document.querySelector(".cS"),
          o=x.options, i=x.selectedIndex;
    console.log(o[i].value,
                o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
 </script> // .cS"

And also this :

 <select id="iSel" size="3">
     <option value="one">Un</option>
     <option value="two">Deux</option>
     <option value="three">Trois</option>
 </select>


 <script type="text/javascript"> "use strict";
    const i=document.getElementById("iSel");
    for(let k=0;k<i.length;k++) {
        if(k == i.selectedIndex) console.log("Selected ".repeat(3));
        console.log(`${Object.entries(i.options)[k][1].value}`+
                    ` => ` +
                    `${Object.entries(i.options)[k][1].innerHTML}`);
        console.log(Object.values(i.options)[k].value ,
                    " => ",
                    Object.values(i.options)[k].innerHTML);
        console.log("=".repeat(25));
    }
 </script>

Adding options to select with javascript

Often you have an array of related records, I find it easy and fairly declarative to fill select this way:

selectEl.innerHTML = array.map(c => '<option value="'+c.id+'">'+c.name+'</option>').join('');

This will replace existing options.
You can use selectEl.insertAdjacentHTML('afterbegin', str); to add them to the top instead.
And selectEl.insertAdjacentHTML('beforeend', str); to add them to the bottom of the list.

IE11 compatible syntax:

array.map(function (c) { return '<option value="'+c.id+'">'+c.name+'</option>'; }).join('');

Saving to CSV in Excel loses regional date format

You need to do a lot more work than 1. click export 2. Open file.

I think that when the Excel CSV documentation talks about OS and regional settings being interpreted, that means that Excel will do that when it opens the file (which is in their "special" csv format). See this article, "Excel formatting and features are not transferred to other file formats"

Also, Excel is actually storing a number, and converting to a date string only for display. When it exports to CSV, it is converting it to a different date string. If you want that date string to be non-default, you will need to convert your Excel cells to strings before performing your export.

Alternately, you could convert your dates to the number value that Excel is saving. Since that is a time code, it actually will obey OS and regional settings, assuming you import it properly. Notepad will only show you the 10-digit number, though.

Clear text input on click with AngularJS

Easiest way to clear/reset the text field on click is to clear/reset the scope

<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>

In Controller

$scope.clearfunction=function(event){
   event.searchAll=null;
}

Why does Java have an "unreachable statement" compiler error?

If the reason for allowing if (aBooleanVariable) return; someMoreCode; is to allow flags, then the fact that if (true) return; someMoreCode; does not generate a compile time error seems like inconsistency in the policy of generating CodeNotReachable exception, since the compiler 'knows' that true is not a flag (not a variable).

Two other ways which might be interesting, but don't apply to switching off part of a method's code as well as if (true) return:

Now, instead of saying if (true) return; you might want to say assert false and add -ea OR -ea package OR -ea className to the jvm arguments. The good point is that this allows for some granularity and requires adding an extra parameter to the jvm invocation so there is no need of setting a DEBUG flag in the code, but by added argument at runtime, which is useful when the target is not the developer machine and recompiling & transferring bytecode takes time.

There is also the System.exit(0) way, but this might be an overkill, if you put it in Java in a JSP then it will terminate the server.

Apart from that Java is by-design a 'nanny' language, I would rather use something native like C/C++ for more control.

How to get input textfield values when enter key is pressed in react js?

Use onKeyDown event, and inside that check the key code of the key pressed by user. Key code of Enter key is 13, check the code and put the logic there.

Check this example:

_x000D_
_x000D_
class CartridgeShell extends React.Component {_x000D_
_x000D_
   constructor(props) {_x000D_
      super(props);_x000D_
      this.state = {value:''}_x000D_
_x000D_
      this.handleChange = this.handleChange.bind(this);_x000D_
      this.keyPress = this.keyPress.bind(this);_x000D_
   } _x000D_
 _x000D_
   handleChange(e) {_x000D_
      this.setState({ value: e.target.value });_x000D_
   }_x000D_
_x000D_
   keyPress(e){_x000D_
      if(e.keyCode == 13){_x000D_
         console.log('value', e.target.value);_x000D_
         // put the login here_x000D_
      }_x000D_
   }_x000D_
_x000D_
   render(){_x000D_
      return(_x000D_
         <input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />_x000D_
      )_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id = 'app' />
_x000D_
_x000D_
_x000D_

Note: Replace the input element by Material-Ui TextField and define the other properties also.

How to get Spinner selected item value to string?

Get the selected item with Kotlin:

spinner.selectedItem.toString()

Embed image in a <button> element

The simplest way to put an image into a button:

<button onclick="myFunction()"><img src="your image name here.png"></button>

This will automatically resize the button to the size of the image.

git - Your branch is ahead of 'origin/master' by 1 commit

git reset HEAD^

then the modified files should show up.

You could move the modified files into a new branch

use,

git checkout -b newbranch

git checkout commit -m "files modified"

git push origin newbranch

git checkout master

then you should be on a clean branch, and your changes should be stored in newbranch. You could later just merge this change into the master branch

How to query a MS-Access Table from MS-Excel (2010) using VBA

Sub Button1_Click()
Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
    strSql = "SELECT Count(*) FROM mytable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.Fields(0) & " rows in MyTable"

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

End Sub

Capturing image from webcam in java?

Recommand using FMJ for multimedia relatived java app.

How can I get the current page name in WordPress?

Within the WordPress Loop:

if ( have_posts() ) : while ( have_posts() ) : the_post();
/******************************************/
echo get_the_title();
/******************************************/
endwhile; endif;

This will show you the current page title.

For reference: get_the_title()

How can I show an element that has display: none in a CSS rule?

try setting the display to block in your javascript instead of a blank value.

How to upload images into MySQL database using PHP code

Firstly, you should check if your image column is BLOB type!

I don't know anything about your SQL table, but if I'll try to make my own as an example.

We got fields id (int), image (blob) and image_name (varchar(64)).

So the code should look like this (assume ID is always '1' and let's use this mysql_query):

$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
    echo "Something went wrong! :("; 
}

You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.

Also your HTML form is out of standards. It should look like this:

<form action="insert_product.php" method="POST" enctype="multipart/form-data">
    <label>File: </label><input type="file" name="image" />
    <input type="submit" />
</form>

Sidenote:

When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string(), otherwise it will result in a syntax error.

push_back vs emplace_back

Specific use case for emplace_back: If you need to create a temporary object which will then be pushed into a container, use emplace_back instead of push_back. It will create the object in-place within the container.

Notes:

  1. push_back in the above case will create a temporary object and move it into the container. However, in-place construction used for emplace_back would be more performant than constructing and then moving the object (which generally involves some copying).
  2. In general, you can use emplace_back instead of push_back in all the cases without much issue. (See exceptions)

Why does git say "Pull is not possible because you have unmerged files"?

Steps to follow :

step-1 : git reset --hard HEAD  (if you want to reset it to head)
step-2 : git checkout Master 
step-3 : git branch -D <branch Name>
(Remote Branch name where you want to get pull) 
step-4 : git checkout <branch name>
step-5 : git pull. (now you will not get any
error)

Thanks, Sarbasish

How can I switch themes in Visual Studio 2012

Tools--> Options-->General-->Color Theme

How to exclude file only from root folder in Git

From the documentation:

If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file).

A leading slash matches the beginning of the pathname. For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".

So you should add the following line to your root .gitignore:

/config.php

Regex for Comma delimited list

I suggest you to do in the following way:

(\d+)(,\s*\d+)*

which would work for a list containing 1 or more elements.

Scrolling a div with jQuery

I don't know if this is exactly what you want, but did you know you can use the CSS overflow property to create scrollbars?

CSS:

div.box{
  width: 200px;
  height: 200px;
  overflow: scroll;
}

HTML:

<div class="box">
  All your text content...
</div>

How to grep recursively, but only in files with certain extensions?

How about:

find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print

How do I convert strings between uppercase and lowercase in Java?

Assuming that all characters are alphabetic, you can do this:

From lowercase to uppercase:

// Uppercase letters. 
class UpperCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('a' + i);
      System.out.print(ch); 

      // This statement turns off the 6th bit.   
      ch = (char) ((int) ch & 65503); // ch is now uppercase
      System.out.print(ch + " ");  
    } 
  } 
}

From uppercase to lowercase:

// Lowercase letters. 
class LowerCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('A' + i);
      System.out.print(ch);
      ch = (char) ((int) ch | 32); // ch is now uppercase
      System.out.print(ch + " ");  
    } 
  } 
}

Keep only first n characters in a string?

Use substring function
Check this out http://jsfiddle.net/kuc5as83/

var string = "1234567890"
var substr=string.substr(-8);
document.write(substr);

Output >> 34567890

substr(-8) will keep last 8 chars

var substr=string.substr(8);
document.write(substr);

Output >> 90

substr(8) will keep last 2 chars

var substr=string.substr(0, 8);
document.write(substr);

Output >> 12345678

substr(0, 8) will keep first 8 chars

Check this out string.substr(start,length)

How to get the title of HTML page with JavaScript?

Put in the URL bar and then click enter:

javascript:alert(document.title);

You can select and copy the text from the alert depending on the website and the web browser you are using.

HTML5 Canvas vs. SVG vs. div

Knowing the differences between SVG and Canvas would be helpful in selecting the right one.

Canvas

SVG

  • Resolution independent
  • Support for event handlers
  • Best suited for applications with large rendering areas (Google Maps)
  • Slow rendering if complex (anything that uses the DOM a lot will be slow)
  • Not suited for game application

How do I run two commands in one line in Windows CMD?

Try to create a .bat ot .cmd file with those lines using doskey key and $T which is equivalent to & to do several command line in just one line :

touch=echo off $T echo. ^> $* $T dir /B $T echo on

It'll create an empty file.

Example:

touch myfile

In cmd you'll get something like this:

enter image description here

But as mentioned previously by others, it is really advised to use & operator to do many command line in one line from CMD prompt.

Enjoy =)

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

Python lacks the tail recursion optimizations common in functional languages like lisp. In Python, recursion is limited to 999 calls (see sys.getrecursionlimit).

If 999 depth is more than you are expecting, check if the implementation lacks a condition that stops recursion, or if this test may be wrong for some cases.

I dare to say that in Python, pure recursive algorithm implementations are not correct/safe. A fib() implementation limited to 999 is not really correct. It is always possible to convert recursive into iterative, and doing so is trivial.

It is not reached often because in many recursive algorithms the depth tend to be logarithmic. If it is not the case with your algorithm and you expect recursion deeper than 999 calls you have two options:

1) You can change the recursion limit with sys.setrecursionlimit(n) until the maximum allowed for your platform:

sys.setrecursionlimit(limit):

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

2) You can try to convert the algorithm from recursive to iterative. If recursion depth is bigger than allowed by your platform, it is the only way to fix the problem. There are step by step instructions on the Internet and it should be a straightforward operation for someone with some CS education. If you are having trouble with that, post a new question so we can help.

What are the parameters for the number Pipe - Angular 2

The parameter has this syntax:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

So your example of '1.2-2' means:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits

How to deselect all selected rows in a DataGridView control?

Thanks Cody heres the c# for ref:

if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.None)
            {
                dgv_track.ClearSelection();
                dgv_track.CurrentCell = null;
            }
        }

How to add google-services.json in Android?

This error indicates your package_name in your google-services.json might be wrong. I personally had this issue when I used

buildTypes {
    ...

    debug {
        applicationIdSuffix '.debug'
    }
}

in my build.gradle. So, when I wanted to debug, the name of the application was ("all of a sudden") app.something.debug instead of app.something. I was able to run the debug when I changed the said package_name...

How can I express that two values are not equal to eachother?

"Not equals" can be expressed with the "not" operator ! and the standard .equals.

if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b

How to use multiprocessing queue in Python?

Just made a simple and general example for demonstrating passing a message over a Queue between 2 standalone programs. It doesn't directly answer the OP's question but should be clear enough indicating the concept.

Server:

multiprocessing-queue-manager-server.py

import asyncio
import concurrent.futures
import multiprocessing
import multiprocessing.managers
import queue
import sys
import threading
from typing import Any, AnyStr, Dict, Union


class QueueManager(multiprocessing.managers.BaseManager):

    def get_queue(self, ident: Union[AnyStr, int, type(None)] = None) -> multiprocessing.Queue:
        pass


def get_queue(ident: Union[AnyStr, int, type(None)] = None) -> multiprocessing.Queue:
    global q

    if not ident in q:
        q[ident] = multiprocessing.Queue()

    return q[ident]


q: Dict[Union[AnyStr, int, type(None)], multiprocessing.Queue] = dict()
delattr(QueueManager, 'get_queue')


def init_queue_manager_server():
    if not hasattr(QueueManager, 'get_queue'):
        QueueManager.register('get_queue', get_queue)


def serve(no: int, term_ev: threading.Event):
    manager: QueueManager
    with QueueManager(authkey=QueueManager.__name__.encode()) as manager:
        print(f"Server address {no}: {manager.address}")

        while not term_ev.is_set():
            try:
                item: Any = manager.get_queue().get(timeout=0.1)
                print(f"Client {no}: {item} from {manager.address}")
            except queue.Empty:
                continue


async def main(n: int):
    init_queue_manager_server()
    term_ev: threading.Event = threading.Event()
    executor: concurrent.futures.ThreadPoolExecutor = concurrent.futures.ThreadPoolExecutor()

    i: int
    for i in range(n):
        asyncio.ensure_future(asyncio.get_running_loop().run_in_executor(executor, serve, i, term_ev))

    # Gracefully shut down
    try:
        await asyncio.get_running_loop().create_future()
    except asyncio.CancelledError:
        term_ev.set()
        executor.shutdown()
        raise


if __name__ == '__main__':
    asyncio.run(main(int(sys.argv[1])))

Client:

multiprocessing-queue-manager-client.py

import multiprocessing
import multiprocessing.managers
import os
import sys
from typing import AnyStr, Union


class QueueManager(multiprocessing.managers.BaseManager):

    def get_queue(self, ident: Union[AnyStr, int, type(None)] = None) -> multiprocessing.Queue:
        pass


delattr(QueueManager, 'get_queue')


def init_queue_manager_client():
    if not hasattr(QueueManager, 'get_queue'):
        QueueManager.register('get_queue')


def main():
    init_queue_manager_client()

    manager: QueueManager = QueueManager(sys.argv[1], authkey=QueueManager.__name__.encode())
    manager.connect()

    message = f"A message from {os.getpid()}"
    print(f"Message to send: {message}")
    manager.get_queue().put(message)


if __name__ == '__main__':
    main()

Usage

Server:

$ python3 multiprocessing-queue-manager-server.py N

N is a integer indicating how many servers should be created. Copy one of the <server-address-N> output by the server and make it the first argument of each multiprocessing-queue-manager-client.py.

Client:

python3 multiprocessing-queue-manager-client.py <server-address-1>

Result

Server:

Client 1: <item> from <server-address-1>

Gist: https://gist.github.com/89062d639e40110c61c2f88018a8b0e5


UPD: Created a package here.

Server:

import ipcq


with ipcq.QueueManagerServer(address=ipcq.Address.AUTO, authkey=ipcq.AuthKey.AUTO) as server:
    server.get_queue().get()

Client:

import ipcq


client = ipcq.QueueManagerClient(address=ipcq.Address.AUTO, authkey=ipcq.AuthKey.AUTO)
client.get_queue().put('a message')

enter image description here

Add and remove multiple classes in jQuery

easiest way to append class name using javascript. It can be useful when .siblings() are misbehaving.

document.getElementById('myId').className += ' active';

How to open a new window on form submit

No need for Javascript, you just have to add a target="_blank" attribute in your form tag.

<form target="_blank" action="http://example.com"
      method="post" id="mc-embedded-subscribe-form"
      name="mc-embedded-subscribe-form" class="validate"
>

Call js-function using JQuery timer

You can use this:

window.setInterval(yourfunction, 10000);

function yourfunction() { alert('test'); }

How do you set, clear, and toggle a single bit?

Setting a bit

Use the bitwise OR operator (|) to set a bit.

number |= 1UL << n;

That will set the nth bit of number. n should be zero, if you want to set the 1st bit and so on upto n-1, if you want to set the nth bit.

Use 1ULL if number is wider than unsigned long; promotion of 1UL << n doesn't happen until after evaluating 1UL << n where it's undefined behaviour to shift by more than the width of a long. The same applies to all the rest of the examples.

Clearing a bit

Use the bitwise AND operator (&) to clear a bit.

number &= ~(1UL << n);

That will clear the nth bit of number. You must invert the bit string with the bitwise NOT operator (~), then AND it.

Toggling a bit

The XOR operator (^) can be used to toggle a bit.

number ^= 1UL << n;

That will toggle the nth bit of number.

Checking a bit

You didn't ask for this, but I might as well add it.

To check a bit, shift the number n to the right, then bitwise AND it:

bit = (number >> n) & 1U;

That will put the value of the nth bit of number into the variable bit.

Changing the nth bit to x

Setting the nth bit to either 1 or 0 can be achieved with the following on a 2's complement C++ implementation:

number ^= (-x ^ number) & (1UL << n);

Bit n will be set if x is 1, and cleared if x is 0. If x has some other value, you get garbage. x = !!x will booleanize it to 0 or 1.

To make this independent of 2's complement negation behaviour (where -1 has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.

number ^= (-(unsigned long)x ^ number) & (1UL << n);

or

unsigned long newbit = !!x;    // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);

It's generally a good idea to use unsigned types for portable bit manipulation.

or

number = (number & ~(1UL << n)) | (x << n);

(number & ~(1UL << n)) will clear the nth bit and (x << n) will set the nth bit to x.

It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like the community wiki answer further down) or some sort of encapsulation.

How to find the Windows version from the PowerShell command line

If you want to differentiate between Windows 8.1 (6.3.9600) and Windows 8 (6.2.9200) use

(Get-CimInstance Win32_OperatingSystem).Version 

to get the proper version. [Environment]::OSVersion doesn't work properly in Windows 8.1 (it returns a Windows 8 version).

Unnamed/anonymous namespaces vs. static functions

In addition if one uses static keyword on a variable like this example:

namespace {
   static int flag;
}

It would not be seen in the mapping file

Remove part of a string

Maybe the most intuitive solution is probably to use the stringr function str_remove which is even easier than str_replace as it has only 1 argument instead of 2.

The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern).

See example:

strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")

[1] "_1121" "_1432" "_1121"

Mysql: Select all data between two dates

its very easy to handle this situation

You can use BETWEEN CLAUSE in combination with date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )

SELECT
    sc_cust_design.design_id as id,
    sc_cust_design.main_image,
    FROM
    sc_cust_design
WHERE
    sc_cust_design.publish = 1 
    AND **`datein`BETWEEN date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )**

Happy Coding :)

How to Import Excel file into mysql Database from PHP

For >= 2nd row values insert into table-

$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";

$count = 0;                                         // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    //print_r($emapData);
    //exit();
    $count++;                                      // add this line

    if($count>1){                                  // add this line
      $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
      mysql_query($sql);
    }                                              // add this line
}

$(document).ready not Working

Verify the following steps.

  1. Did you include jquery
  2. Check for errors in firebug

Those things should fix the problem

Performing user authentication in Java EE / JSF using j_security_check

It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.

How do I show the schema of a table in a MySQL database?

You can also use shorthand for describe as desc for table description.

desc [db_name.]table_name;

or

use db_name;
desc table_name;

You can also use explain for table description.

explain [db_name.]table_name;

See official doc

Will give output like:

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(10)     | NO   | PRI | NULL    |       |
| name     | varchar(20) | YES  |     | NULL    |       |
| age      | int(10)     | YES  |     | NULL    |       |
| sex      | varchar(10) | YES  |     | NULL    |       |
| sal      | int(10)     | YES  |     | NULL    |       |
| location | varchar(20) | YES  |     | Pune    |       |
+----------+-------------+------+-----+---------+-------+

Angular 2 Unit Tests: Cannot find name 'describe'

In order for TypeScript Compiler to use all visible Type Definitions during compilation, types option should be removed completely from compilerOptions field in tsconfig.json file.

This problem arises when there exists some types entries in compilerOptions field, where at the same time jest entry is missing.

So in order to fix the problem, compilerOptions field in your tscongfig.json should either include jest in types area or get rid of types comnpletely:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "types": ["reflect-metadata", "jest"],  //<--  add jest or remove completely
    "moduleResolution": "node",
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

How to crop an image in OpenCV using Python

It's very simple. Use numpy slicing.

import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)

using CASE in the WHERE clause

You don't have to use CASE...WHEN, you could use an OR condition, like this:

WHERE
  pw='correct'
  AND (id>=800 OR success=1) 
  AND YEAR(timestamp)=2011

this means that if id<800, success has to be 1 for the condition to be evaluated as true. Otherwise, it will be true anyway.

It is less common, however you could still use CASE WHEN, like this:

WHERE
  pw='correct'
  AND CASE WHEN id<800 THEN success=1 ELSE TRUE END 
  AND YEAR(timestamp)=2011

this means: return success=1 (which can be TRUE or FALSE) in case id<800, or always return TRUE otherwise.

When to use async false and async true in ajax function in jquery

ShowPopUpForToDoList: function (id, apprId, tab) {
    var snapShot = "isFromAlert";
    if (tab != "Request")
        snapShot = "isFromTodoList";
    $.ajax({
        type: "GET",
        url: common.GetRootUrl('ActionForm/SetParamForToDoList'),
        data: { id: id, tab: tab },
        async:false,
        success: function (data) {
            ActionForm.EditActionFormPopup(id, snapShot);
        }
    });
},

Here SetParamForToDoList will be excecuted first after the function ActionForm.EditActionFormPopup will fire.

Partition Function COUNT() OVER possible using DISTINCT

There is a very simple solution using dense_rank()

dense_rank() over (partition by [Mth] order by [UserAccountKey]) 
+ dense_rank() over (partition by [Mth] order by [UserAccountKey] desc) 
- 1

This will give you exactly what you were asking for: The number of distinct UserAccountKeys within each month.

How to set an HTTP proxy in Python 2.7?

For installing pip with get-pip.py behind a proxy I went with the steps below. My server was even behind a jump server.

From the jump server:

ssh -R 18080:proxy-server:8080 my-python-server

On the "python-server"

export https_proxy=https://localhost:18080 ; export http_proxy=http://localhost:18080 ; export ftp_proxy=$http_proxy
python get-pip.py

Success.

How to vertically align label and input in Bootstrap 3?

I'm sure you've found your answer by now, but for those who are still looking for an answer:

When input-lg is used, margins mismatch unless you use form-group-lg in addition to form-group class. Its example is in docs:

<form class="form-horizontal">
  <div class="form-group form-group-lg">
    <label class="col-sm-2 control-label" for="formGroupInputLarge">Large label</label>
    <div class="col-sm-10">
      <input class="form-control" type="text" id="formGroupInputLarge" placeholder="Large input">
    </div>
  </div>
  <div class="form-group form-group-sm">
    <label class="col-sm-2 control-label" for="formGroupInputSmall">Small label</label>
    <div class="col-sm-10">
      <input class="form-control" type="text" id="formGroupInputSmall" placeholder="Small input">
    </div>
  </div>
</form>

Setting Oracle 11g Session Timeout

Adam has already suggested database profiles.

You could check the SQLNET.ORA file. There's an EXPIRE_TIME parameter but this is for detecting lost connections, rather than terminating existing ones.

Given it happens overnight, it sounds more like an idle timeout, which could be down to a firewall between the app server and database server. Setting the EXPIRE_TIME may stop that happening (as there'll be check every 10 minutes to check the client is alive).

Or possibly the database is being shutdown and restarted and that is killing the connections.

Alternatively, you should be able to configure tomcat with a validationQuery so that it will automatically restart the connection without a tomcat restart

Java Singleton and Synchronization

Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:

Draconian synchronization:

private static YourObject instance;

public static synchronized YourObject getInstance() {
    if (instance == null) {
        instance = new YourObject();
    }
    return instance;
}

This solution requires that every thread be synchronized when in reality only the first few need to be.

Double check synchronization:

private static final Object lock = new Object();
private static volatile YourObject instance;

public static YourObject getInstance() {
    YourObject r = instance;
    if (r == null) {
        synchronized (lock) {    // While we were waiting for the lock, another 
            r = instance;        // thread may have instantiated the object.
            if (r == null) {  
                r = new YourObject();
                instance = r;
            }
        }
    }
    return r;
}

This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.

Initialization on Demand:

private static class InstanceHolder {
    private static final YourObject instance = new YourObject();
}

public static YourObject getInstance() {
    return InstanceHolder.instance;
}

This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance is called, InstanceHolder will be loaded and instance will be created, and since this is controlled by ClassLoaders, no additional synchronization is necessary.

Interactive shell using Docker Compose

You can do docker-compose exec SERVICE_NAME sh on the command line. The SERVICE_NAME is defined in your docker-compose.yml. For example,

services:
    zookeeper:
        image: wurstmeister/zookeeper
        ports:
          - "2181:2181"

The SERVICE_NAME would be "zookeeper".

delete word after or around cursor in VIM

In old vi, b moves the cursor to the beginning of the word before cursor, w moves the cursor to the beginning of the word after cursor, e moves cursor at the end of the word after cursor and dw deletes from the cursor to the end of the word.

If you type wbdw, you delete the word around cursor, even if the cursor is at the beginning or at the end of the word. Note that whitespaces after a word are considerer to be part of the word to be deleted.

Name attribute in @Entity and @Table

@Entity(name = "someThing") => this name will be used to name the Entity
@Table(name = "someThing")  => this name will be used to name a table in DB

So, in the first case your table and entity will have the same name, that will allow you to access your table with the same name as the entity while writing HQL or JPQL.

And in second case while writing queries you have to use the name given in @Entity and the name given in @Table will be used to name the table in the DB.

So in HQL your someThing will refer to otherThing in the DB.

Debug JavaScript in Eclipse

JavaScript is executed in the browser, which is pretty far removed from Eclipse. Eclipse would have to somehow hook into the browser's JavaScript engine to debug it. Therefore there's no built-in debugging of JavaScript via Eclipse, since JS isn't really its main focus anyways.

However, there are plug-ins which you can install to do JavaScript debugging. I believe the main one is the AJAX Toolkit Framework (ATF). It embeds a Mozilla browser in Eclipse in order to do its debugging, so it won't be able to handle cross-browser complications that typically arise when writing JavaScript, but it will certainly help.

Disable output buffering

The following works in Python 2.6, 2.7, and 3.2:

import os
import sys
buf_arg = 0
if sys.version_info[0] == 3:
    os.environ['PYTHONUNBUFFERED'] = '1'
    buf_arg = 1
sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', buf_arg)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', buf_arg)

Passing an array of parameters to a stored procedure

You could use the STRING_SPLIT function in SQL Server. You can check the documentation here.

DECLARE @YourListOfIds VARCHAR(1000) -- Or VARCHAR(MAX) depending on what you need

SET @YourListOfIds = '1,2,3,4,5,6,7,8'

SELECT * FROM YourTable
WHERE Id IN(SELECT CAST(Value AS INT) FROM STRING_SPLIT(@YourListOfIds, ','))

Relation between CommonJS, AMD and RequireJS?

The short answer would be:

CommonJS and AMD are specifications (or formats) on how modules and their dependencies should be declared in javascript applications.

RequireJS is a script loader library that is AMD compliant, curljs being another example.

CommonJS compliant:

Taken from Addy Osmani's book.

// package/lib is a dependency we require
var lib = require( "package/lib" );

// behavior for our module
function foo(){
    lib.log( "hello world!" );
}

// export (expose) foo to other modules as foobar
exports.foobar = foo;

AMD compliant:

// package/lib is a dependency we require
define(["package/lib"], function (lib) {

    // behavior for our module
    function foo() {
        lib.log( "hello world!" );
    }

    // export (expose) foo to other modules as foobar
    return {
        foobar: foo
    }
});

Somewhere else the module can be used with:

require(["package/myModule"], function(myModule) {
    myModule.foobar();
});

Some background:

Actually, CommonJS is much more than an API declaration and only a part of it deals with that. AMD started as a draft specification for the module format on the CommonJS list, but full consensus wasn't reached and further development of the format moved to the amdjs group. Arguments around which format is better state that CommonJS attempts to cover a broader set of concerns and that it's better suited for server side development given its synchronous nature, and that AMD is better suited for client side (browser) development given its asynchronous nature and the fact that it has its roots in Dojo's module declaration implementation.

Sources:

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017 and may leave the author guessing (which I am a victim of myself).

Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:

"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"


So, not supported are:

  • Start of String ancor \A, alternatively use the ^ caret to match postion before 1st char in string
  • End of String ancor \Z, alternatively use the $ dollar sign to match postion after last char in string
  • Positive LookBehind, e.g.: (?<=a)b (whilst postive LookAhead is supported)
  • Negative LookBehind, e.g.: (?<!a)b (whilst negative LookAhead is supported)
  • Atomic Grouping
  • Possessive Quantifiers
  • Unicode e.g.: \{uFFFF}
  • Named Capturing Groups. Alternatively use Numbered Capturing Groups
  • Inline modifiers, e.g.: /i (case sensitivity) or /g (global) etc. Set these through the RegExp object properties > RegExp.Global = True and RegExp.IgnoreCase = True if available.
  • Conditionals
  • Regular Expression Comments. Add these with regular ' comments in script

I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.

P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.

SpringMVC RequestMapping for GET parameters

This works in my case:

@RequestMapping(value = "/savedata",
            params = {"textArea", "localKey", "localFile"})
    @ResponseBody
    public void saveData(@RequestParam(value = "textArea") String textArea,
                         @RequestParam(value = "localKey") String localKey,
                         @RequestParam(value = "localFile") String localFile) {
}

Why is C so fast, and why aren't other languages as fast or faster?

The main factors are that it's a statically-typed language and that's compiled to machine code. Also, since it's a low-level language, it generally doesn't do anything you don't tell it to.

These are some other factors that come to mind.

  • Variables are not automatically initialized
  • No bounds checking on arrays
  • Unchecked pointer manipulation
  • No integer overflow checking
  • Statically-typed variables
  • Function calls are static (unless you use function pointers)
  • Compiler writers have had lots of time to improve the optimizing code. Also, people program in C for the purpose of getting the best performance, so there's pressure to optimize the code.
  • Parts of the language specification are implementation-defined, so compilers are free to do things in the most optimal way

Most static-typed languages could be compiled just as fast or faster than C though, especially if they can make assumptions that C can't because of pointer aliasing, etc.

Null check in VB

Your code is way more cluttered than necessary.

Replace (Not (X Is Nothing)) with X IsNot Nothing and omit the outer parentheses:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For i As Integer = 0 To comp.Container.Components.Count() - 1
        fixUIIn(comp.Container.Components(i), style)
    Next
End If

Much more readable. … Also notice that I’ve removed the redundant Step 1 and the probably redundant .Item.

But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each instead:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For Each component In comp.Container.Components
        fixUIIn(component, style)
    Next
End If

Error in plot.new() : figure margins too large in R

If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and trying plot() again may work.

enter image description here

Execute Insert command and return inserted Id in Sql

Change the query to

"INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ); SELECT SCOPE_IDENTITY()"

This will return the last inserted ID which you can then get with ExecuteScalar

SQL Last 6 Months

.... where yourdate_column > DATE_SUB(now(), INTERVAL 6 MONTH)

C# How do I click a button by hitting Enter whilst textbox has focus?

This is very much valid for WinForms. However, in WPF you need to do things differently, and it is easer. Set the IsDefault property of the Button relevant to this text-area as true.

Once you are done capturing the enter key, do not forget to toggle the properties accordingly.

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Other type of format :

$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';

curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

How to set the text/value/content of an `Entry` widget using a button in tkinter

Your problem is that when you do this:

a = Button(win, text="plant", command=setText("plant"))

it tries to evaluate what to set for the command. So when instantiating the Button object, it actually calls setText("plant"). This is wrong, because you don't want to call the setText method yet. Then it takes the return value of this call (which is None), and sets that to the command of the button. That's why clicking the button does nothing, because there is no command set for it.

If you do as Milan Skála suggested and use a lambda expression instead, then your code will work (assuming you fix the indentation and the parentheses).

Instead of command=setText("plant"), which actually calls the function, you can set command=lambda:setText("plant") which specifies something which will call the function later, when you want to call it.

If you don't like lambdas, another (slightly more cumbersome) way would be to define a pair of functions to do what you want:

def set_to_plant():
    set_text("plant")
def set_to_animal():
    set_text("animal")

and then you can use command=set_to_plant and command=set_to_animal - these will evaluate to the corresponding functions, but are definitely not the same as command=set_to_plant() which would of course evaluate to None again.

How do I get the MAX row with a GROUP BY in LINQ query?

In methods chain form:

db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
    {
        Serial_Number = g.Key,
        uid = g.Max(row => row.uid)
    });

How to select distinct rows in a datatable and store into an array

DataTable dtbs = new DataTable(); 
DataView dvbs = new DataView(dt); 
dvbs.RowFilter = "ColumnName='Filtervalue'"; 
dtbs = dvbs.ToTable();

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

for xcode 11.1which doesn't contain ipad pro iPad Pro (2nd Gen) 12.9" Display run this command in terminal

xcrun simctl create "iPad Pro (12.9-inch) (2nd generation)" "com.apple.CoreSimulator.SimDeviceType.iPad-Pro--12-9-inch---2nd-generation-" "com.apple.CoreSimulator.SimRuntime.iOS-13-1"

look here

Android: How to enable/disable option menu item on button click?

Anyway, the documentation covers all the things.

Changing menu items at runtime

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application.

E.g.

@Override
public boolean onPrepareOptionsMenu (Menu menu) {
    if (isFinalized) {
        menu.getItem(1).setEnabled(false);
        // You can also use something like:
        // menu.findItem(R.id.example_foobar).setEnabled(false);
    }
    return true;
}

On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

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

You can pass the DBNull.Value into the parameter's .Value property:

    SqlParameters[0] = new SqlParameter("LedgerID", SqlDbType.BigInt );
    SqlParameters[0].Value = DBNull.Value;

Just adjust for your two DateTime parameters, obviously - just showing how to use the DBNull.Value property value here.

Marc

Jackson and generic type reference

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

    public ArrayList<T> unmarshal(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

        try {
            Class c1 = this.targetclass.getClass();
            Class c2 = this.targetclass1.getClass();
            ArrayList<T> temp = (ArrayList<T>) 
                mapper.readValue(jsonString,  type);
            return temp ;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null ;
    }  
}

How to SSH into Docker?

Firstly you need to install a SSH server in the images you wish to ssh-into. You can use a base image for all your container with the ssh server installed. Then you only have to run each container mapping the ssh port (default 22) to one to the host's ports (Remote Server in your image), using -p <hostPort>:<containerPort>. i.e:

docker run -p 52022:22 container1 
docker run -p 53022:22 container2

Then, if ports 52022 and 53022 of host's are accessible from outside, you can directly ssh to the containers using the ip of the host (Remote Server) specifying the port in ssh with -p <port>. I.e.:

ssh -p 52022 myuser@RemoteServer --> SSH to container1

ssh -p 53022 myuser@RemoteServer --> SSH to container2

Remove border from buttons

You can also try background:none;border:0px to buttons.

also the css selectors are div#yes button{..} and div#no button{..} . hopes it helps

how to do file upload using jquery serialization

You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.

$.ajax({
    url: "ajax.php", 
    type: "POST",             
    data: new FormData('form'),
    contentType: false,       
    cache: false,             
    processData:false, 
    success: function(data) {
        $("#response").html(data);
    }
});

build maven project with propriatery libraries included

1 Either you can include that jar in your classpath of application
2 you can install particular jar file in your maven reopos by

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
    -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

Is embedding background image data into CSS as Base64 good or bad practice?

This answer is out of date and shouldn't be used.

1) Average latency is much faster on mobile in 2017. https://opensignal.com/reports/2016/02/usa/state-of-the-mobile-network

2) HTTP2 multiplexes https://http2.github.io/faq/#why-is-http2-multiplexed

"Data URIs" should definitely be considered for mobile sites. HTTP access over cellular networks comes with higher latency per request/response. So there are some use cases where jamming your images as data into CSS or HTML templates could be beneficial on mobile web apps. You should measure usage on a case-by-case basis -- I'm not advocating that data URIs should be used everywhere in a mobile web app.

Note that mobile browsers have limitations on total size of files that can be cached. Limits for iOS 3.2 were pretty low (25K per file), but are getting larger (100K) for newer versions of Mobile Safari. So be sure to keep an eye on your total file size when including data URIs.

http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/