Programs & Examples On #Try finally

Java Try Catch Finally blocks without Catch

Java versions before version 7 allow for these three combinations of try-catch-finally...

try - catch
try - catch - finally
try - finally

finally block will be always executed no matter of what's going on in the try or/and catch block. so if there is no catch block, the exception won't be handled here.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

  • Java try block must be followed by either catch or finally block.
  • For each try block there can be zero or more catch blocks, but only one finally block.
  • The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

Why do we need the "finally" clause in Python?

Using delphi professionally for some years taught me to safeguard my cleanup routines using finally. Delphi pretty much enforces the use of finally to clean up any resources created before the try block, lest you cause a memory leak. This is also how Java, Python and Ruby works.

resource = create_resource
try:
  use resource
finally:
  resource.cleanup

and resource will be cleaned up regardless of what you do between try and finally. Also, it won't be cleaned up if execution never reaches the try block. (i.e. create_resource itself throws an exception) It makes your code "exception safe".

As to why you actually need a finally block, not all languages do. In C++ where you have automatically called destructors which enforce cleanup when an exception unrolls the stack. I think this is a step up in the direction of cleaner code compared to try...finally languages.

{    
  type object1;
  smart_pointer<type> object1(new type());
} // destructors are automagically called here in LIFO order so no finally required.

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

Thanks to @user2630576 and @Ed.S.

the following worked a treat:

BACKUP LOG [database] TO DISK = 'D:\database.bak'
GO

ALTER DATABASE [database] SET RECOVERY SIMPLE

use [database]

declare @log_File_Name varchar(200)

select @log_File_Name = name from sysfiles where filename like '%LDF'

declare @i int = FILE_IDEX ( @log_File_Name)

dbcc shrinkfile ( @i , 50)

ALTER DATABASE [database] SET RECOVERY FULL

How to create Password Field in Model Django

Use widget as PasswordInput

from django import forms
class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    class Meta:
        model = User

How to set 'X-Frame-Options' on iframe?

You can not really add the x-iframe in your HTML body as it has to be provided by the site owner and it lies within the server rules.

What you can probably do is create a PHP file which loads the content of target URL and iframe that php URL, this should work smoothly.

How do I keep a label centered in WinForms?

Some minor additional content for setting programmatically:

Label textLabel = new Label() { 
        AutoSize = false, 
        TextAlign = ContentAlignment.MiddleCenter, 
        Dock = DockStyle.None, 
        Left = 10, 
        Width = myDialog.Width - 10
};            

Dockstyle and Content alignment may differ from your needs. For example, for a simple label on a wpf form I use DockStyle.None.

Is there a way I can capture my iPhone screen as a video?

I've continued to research this item myself, and it does appear to remain beyond us at this point.

I even tried buying a Apple Composite AV Cable, but it doesn't capture screen, just video playing like YouTube, etc.

So I decided to go with the iShowU path and that has worked out well so far.

Thanks Guys!

How can I generate a list of files with their absolute path in Linux?

stat

Absolute path of a single file:

stat -c %n "$PWD"/foo/bar

Importing a GitHub project into Eclipse

It can be done in two ways:

1.Use clone Git

2.You can set it up manually by rearranging folders given in it. make a two separate folder 'src' and 'res' and place appropriate classes and xml file given by library. and then import project from eclipse and make it as library, that's it.

Is it possible to have SSL certificate for IP address, not domain name?

The answer is yes. In short, it is a subject alternative name (SAN) certificate that contains IPs where you would typically see DNS entries. The certificate type is not limited to Public IPs - that restriction is only imposed by a signing authority rather than the technology. I just wanted to clarify that point. I suspect you really just want to get rid of that pesky insecure prompt on your internal websites and devices without the cost and hassle of giving them DNS names then paying for a CA to issue a cert every year or two. You should NOT be trying to convince the world that your IP address is a reputable website and folks should feel comfortable providing their payment information. Now that we have established why no reputable organization wants to issue this type of certificate, lets just do it ourselves with a self signed SAN certificate. Internally I have a trusted certificate that is deployed to all of our hosts, then I sign this type of certificate with it and all devices become trusted. Doing that here is beyond the scope of the question but I think it relevant to the discussion as the question and solution go hand in hand. To be concise, here is how to generate an individual self signed SAN certificate with IP addresses. Expand the IP list to include your entire subnet and use one cert for everything.

#!/bin/bash
#using: OpenSSL 1.1.1c FIPS  28 May 2019 / CentOS Linux release 8.2.2004

C=US ; ST=Confusion ; L=Anywhere ; O=Private\ Subnet ; [email protected]
BITS=2048
CN=RFC1918
DOM=company.com
SUBJ="/C=$C/ST=$ST/L=$L/O=$O/CN=$CN.$DOM"

openssl genrsa -out ip.key $BITS

SAN='\n[SAN]\nsubjectAltName=IP:192.168.1.0,IP:192.168.1.1,IP:192.168.1.2,IP:192.168.1.3,IP:192.168.1.4,IP:192.168.1.5,IP:192.168.1.6,IP:192.168.1.7,IP:192.168.1.8,IP:192.168.1.9,IP:192.168.1.10'

cp /etc/pki/tls/openssl.cnf /tmp/openssl.cnf
echo -e "$SAN" >> /tmp/openssl.cnf

openssl req -subj "$SUBJ" -new -x509 -days 10950 \
    -key ip.key -out ip.crt -batch \
    -set_serial 168933982 \
    -config /tmp/openssl.cnf \
    -extensions SAN

openssl x509 -in ip.crt -noout -text

jQuery: get the file name selected from <input type="file" />

Add a hidden reset button :

<input id="Reset1" type="reset" value="reset" class="hidden" />

Click the reset button to clear the input.

$("#Reset1").click();

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

JS jQuery - check if value is in array

As to your bonus question, try if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)

How to select the row with the maximum value in each group

Here's another data.table solution, since which.max does not work on characters

library(data.table)
group <- data.table(Subject=ID, pt=Value, Event=Event)

group[, .SD[order(pt, decreasing = TRUE) == 1], by = Subject]

How to include files outside of Docker's build context?

Using docker-compose, I accomplished this by creating a service that mounts the volumes that I need and committing the image of the container. Then, in the subsequent service, I rely on the previously committed image, which has all of the data stored at mounted locations. You will then have have to copy these files to their ultimate destination, as host mounted directories do not get committed when running a docker commit command

You don't have to use docker-compose to accomplish this, but it makes life a bit easier

# docker-compose.yml

version: '3'
  services:
    stage:
      image: alpine
      volumes:
        - /host/machine/path:/tmp/container/path
      command: bash -c "cp -r /tmp/container/path /final/container/path"
    setup:
      image: stage
# setup.sh

# Start "stage" service
docker-compose up stage

# Commit changes to an image named "stage"
docker commit $(docker-compose ps -q stage) stage

# Start setup service off of stage image
docker-compose up setup

How can I drop a table if there is a foreign key constraint in SQL Server?

You have to drop the constraint before drop your table.

You can use those queries to find all FKs in your table and find the FKs in the tables in which your table is used.

Declare @SchemaName VarChar(200) = 'Your Schema name'
Declare @TableName VarChar(200) = 'Your Table Name'

-- Find FK in This table.
SELECT 
    ' IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = 
OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + 
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +

    'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(FK.parent_object_id) +
    '.[' + OBJECT_NAME(FK.parent_object_id) + 
    '] DROP CONSTRAINT ' + FK.name
    , S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O 
  ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S 
  ON (O.schema_id = S.schema_id)  
WHERE 
      O.name = @TableName
      And S.name = @SchemaName


-- Find the FKs in the tables in which this table is used
  SELECT 
    ' IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =   
      OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
  + ''') AND parent_object_id = OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + 
 OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +

    ' ALTER TABLE ' +  OBJECT_SCHEMA_NAME(FK.parent_object_id) +
    '.[' + OBJECT_NAME(FK.parent_object_id) + 
    '] DROP CONSTRAINT ' + FK.name
    , S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O 
  ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S 
  ON (O.schema_id = S.schema_id)  
WHERE 
      O.name = @TableName
      And S.name = @SchemaName 

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

In my case, restarting SQL Server Service was enough to resolve the issue.

How can we dynamically allocate and grow an array

Visual Basic has a nice function : ReDim Preserve.

Someone has kindly written an equivalent function - you can find it here. I think it does exactly what you are asking for (and you're not re-inventing the wheel - you're copying someone else's)...

Is there a way to make mv create the directory to be moved to if it doesn't exist?

Code:

if [[ -e $1 && ! -e $2 ]]; then
   mkdir --parents --verbose -- "$(dirname -- "$2")"
fi
mv --verbose -- "$1" "$2"

Example:

arguments: "d1" "d2/sub"

mkdir: created directory 'd2'
renamed 'd1' -> 'd2/sub'

Recommended way to insert elements into map

  1. insert is not a recommended way - it is one of the ways to insert into map. The difference with operator[] is that the insert can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert.
  2. operator[] needs the default constructor because the map checks if the element exists. If it doesn't then it creates one using default constructor and returns a reference (or const reference to it).

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

Open youtube video in Fancybox jquery

$("a.more").click(function() {
                 $.fancybox({
                  'padding'             : 0,
                  'autoScale'   : false,
                  'transitionIn'        : 'none',
                  'transitionOut'       : 'none',
                  'title'               : this.title,
                  'width'               : 680,
                  'height'              : 495,
                  'href'                : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                  'type'                : 'swf',    // <--add a comma here
                  'swf'                 : {'allowfullscreen':'true'} // <-- flashvars here
                  });
                 return false;

            }); 

List submodules in a Git repository

In my version of Git [1], every Git submodule has a name and a path. They don't necessarily have to be the same [2]. Getting both in a reliable way, without checking out the submodules first (git update --init), is a tricky bit of shell wizardry.

Get a list of submodule names

I didn't find a way how to achieve this using git config or any other git command. Therefore we are back to regex on .gitmodules (super ugly). But it seems to be somewhat safe since git limits the possible code space allowed for submodule names. In addition, since you probably want to use this list for further shell processing, the solution below separate entries with NULL-bytes (\0).

$ sed -nre \
  's/^\[submodule \"(.*)\"]$/\1\x0/p' \
  "$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0"

And in your script:

#!/usr/bin/env bash

while IFS= read -rd '' submodule_name; do
  echo submodule name: "${submodule_name}"
done < <(
  sed -nre \
    's/^\[submodule \"(.*)\"]$/\1\x0/p' \
    "$(git rev-parse --show-toplevel)/.gitmodules" \
  | tr -d '\n' \
  | xargs -0 -n1 printf "%b\0"
)

Note: read -rd '' requires bash and won't work with sh.

Get a list of submodule paths

In my approach I try not to process the output from git config --get-regexp with awk, tr, sed, ... but instead pass it a zero byte separated back to git config --get. This is to avoid problems with newlines, spaces and other special characters (e.g. Unicode) in the submodule paths. In addition, since you probably want to use this list for further shell processing, the solution below separate entries with NULL-bytes (\0).

$ git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get

For example, in a Bash script you could then:

#!/usr/bin/env bash

while IFS= read -rd '' submodule_path; do
  echo submodule path: "${submodule_path}"
done < <(
  git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
  | xargs -0 -n1 git config --null --file .gitmodules --get
)

Note: read -rd '' requires bash and won't work with sh.


Footnotes

[1] Git version

$ git --version
git version 2.22.0

[2] Submodule with diverging name and path

Set up test repository:

$ git init test-name-path
$ cd test-name-path/
$ git checkout -b master
$ git commit --allow-empty -m 'test'
$ git submodule add ./ submodule-name
Cloning into '/tmp/test-name-path/submodule-name'...
done.
$ ls
submodule-name

$ cat .gitmodules
[submodule "submodule-name"]
    path = submodule-name
    url = ./

Move submodule to make name and path diverge:

$ git mv submodule-name/ submodule-path

$ ls
submodule-path

$ cat .gitmodules
[submodule "submodule-name"]
    path = submodule-path
    url = ./

$ git config --file .gitmodules --get-regexp '\.path$'
submodule.submodule-name.path submodule-path

Testing

Set up test repository:

$ git init test
$ cd test/
$ git checkout -b master
$ git commit --allow-empty -m 'test'
$
$ git submodule add ./ simplename
Cloning into '/tmp/test/simplename'...
done.
$
$ git submodule add ./ 'name with spaces'
Cloning into '/tmp/test/name with spaces'...
done.
$
$ git submodule add ./ 'future-name-with-newlines'
Cloning into '/tmp/test/future-name-with-newlines'...
done.
$ git mv future-name-with-newlines/ 'name
> with
> newlines'
$
$ git submodule add ./ 'name-with-unicode-'
Cloning into '/tmp/test/name-with-unicode-'...
done.
$
$ git submodule add ./ sub/folder/submodule
Cloning into '/tmp/test/sub/folder/submodule'...
done.
$
$ git submodule add ./ name.with.dots
Cloning into '/tmp/test/name.with.dots'...
done.
$
$ git submodule add ./ 'name"with"double"quotes'
Cloning into '/tmp/test/name"with"double"quotes'...
done.
$
$ git submodule add ./ "name'with'single'quotes"
Cloning into '/tmp/test/name'with'single'quotes''...
done.
$ git submodule add ./ 'name]with[brackets'
Cloning into '/tmp/test/name]with[brackets'...
done.
$ git submodule add ./ 'name-with-.path'
Cloning into '/tmp/test/name-with-.path'...
done.

.gitmodules:

[submodule "simplename"]
    path = simplename
    url = ./
[submodule "name with spaces"]
    path = name with spaces
    url = ./
[submodule "future-name-with-newlines"]
    path = name\nwith\nnewlines
    url = ./
[submodule "name-with-unicode-"]
    path = name-with-unicode-
    url = ./
[submodule "sub/folder/submodule"]
    path = sub/folder/submodule
    url = ./
[submodule "name.with.dots"]
    path = name.with.dots
    url = ./
[submodule "name\"with\"double\"quotes"]
    path = name\"with\"double\"quotes
    url = ./
[submodule "name'with'single'quotes"]
    path = name'with'single'quotes
    url = ./
[submodule "name]with[brackets"]
    path = name]with[brackets
    url = ./
[submodule "name-with-.path"]
    path = name-with-.path
    url = ./

Get list of submodule names

$ sed -nre \
  's/^\[submodule \"(.*)\"]$/\1\x0/p' \
  "$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0" \
| xargs -0 -n1 echo submodule name:
submodule name: simplename
submodule name: name with spaces
submodule name: future-name-with-newlines
submodule name: name-with-unicode-
submodule name: sub/folder/submodule
submodule name: name.with.dots
submodule name: name"with"double"quotes
submodule name: name'with'single'quotes
submodule name: name]with[brackets
submodule name: name-with-.path

Get list of submodule paths

$ git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get \
| xargs -0 -n1 echo submodule path:
submodule path: simplename
submodule path: name with spaces
submodule path: name
with
newlines
submodule path: name-with-unicode-
submodule path: sub/folder/submodule
submodule path: name.with.dots
submodule path: name"with"double"quotes
submodule path: name'with'single'quotes
submodule path: name]with[brackets
submodule path: name-with-.path

UnicodeEncodeError: 'charmap' codec can't encode characters

set PYTHONIOENCODING=utf-8
set PYTHONLEGACYWINDOWSSTDIO=utf-8

You may or may not need to set that second environment variable PYTHONLEGACYWINDOWSSTDIO.

Alternatively, this can be done in code (although it seems that doing it through env vars is recommended):

sys.stdin.reconfigure(encoding='utf-8')
sys.stdout.reconfigure(encoding='utf-8')

Additionally: Reproducing this error was a bit of a pain, so leaving this here too in case you need to reproduce it on your machine:

set PYTHONIOENCODING=windows-1252
set PYTHONLEGACYWINDOWSSTDIO=windows-1252

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

COUNT DISTINCT with CONDITIONS

Try the following statement:

select  distinct A.[Tag],
     count(A.[Tag]) as TAG_COUNT,
     (SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
     from [TagTbl] AS A GROUP BY A.[Tag]

The first field will be the tag the second will be the whole count the third will be the positive ones count.

How to access a dictionary element in a Django template?

Use Dictionary Items:

{% for key, value in my_dictionay.items %}
  <li>{{ key }} : {{ value }}</li>
{% endfor %}

How to open a page in a new window or tab from code-behind

This code works for me:

Dim script As String = "<script type=""text/javascript"">window.open('" & URL.ToString & "');</script>"
ClientScript.RegisterStartupScript(Me.GetType, "openWindow", script)

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

build and listener objects are presenting during system groovy execution. You can do this:

def myVar = build.getEnvironment(listener).get('myVar')

asp.net: Invalid postback or callback argument

My problem was that i had nested form tags. After removing the inner one, worked out for me.

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

SQL - using alias in Group By

At least in PostgreSQL you can use the column number in the resultset in your GROUP BY clause:

SELECT 
 itemName as ItemName,
 substring(itemName, 1,1) as FirstLetter,
 Count(itemName)
FROM table1
GROUP BY 1, 2

Of course this starts to be a pain if you are doing this interactively and you edit the query to change the number or order of columns in the result. But still.

Why would one mark local variables and method parameters as "final" in Java?

In the case of local variables, I tend to avoid this. It causes visual clutter, and is generally unnecessary - a function should be short enough or focus on a single impact to let you quickly see that you are modify something that shouldn't be.

In the case of magic numbers, I would put them as a constant private field anyway rather than in the code.

I only use final in situations where it is necessary (e.g., passing values to anonymous classes).

MySQL/SQL: Group by date only on a Datetime column

Or:

SELECT SUM(foo), DATE(mydate) mydate FROM a_table GROUP BY mydate;

More efficient (I think.) Because you don't have to cast mydate twice per row.

What is the use of style="clear:both"?

clear:both makes the element drop below any floated elements that precede it in the document.

You can also use clear:left or clear:right to make it drop below only those elements that have been floated left or right.

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
+------------+
+---------------------+
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |
+---------------------+

How to add a constant column in a Spark DataFrame?

As the other answers have described, lit and typedLit are how to add constant columns to DataFrames. lit is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.

You'll commonly be using lit to create org.apache.spark.sql.Column objects because that's the column type required by most of the org.apache.spark.sql.functions.

Suppose you have a DataFrame with a some_date DateType column and would like to add a column with the days between December 31, 2020 and some_date.

Here's your DataFrame:

+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+

Here's how to calculate the days till the year end:

val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
  .withColumn("days_till_yearend", diff)
  .show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23|               99|
|2020-01-05|              361|
|2020-04-12|              263|
+----------+-----------------+

You could also use lit to create a year_end column and compute the days_till_yearend like so:

import java.sql.Date

df
  .withColumn("yearend", lit(Date.valueOf("2020-12-31")))
  .withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
  .show()
+----------+----------+-----------------+
| some_date|   yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31|               99|
|2020-01-05|2020-12-31|              361|
|2020-04-12|2020-12-31|              263|
+----------+----------+-----------------+

Most of the time, you don't need to use lit to append a constant column to a DataFrame. You just need to use lit to convert a Scala type to a org.apache.spark.sql.Column object because that's what's required by the function.

See the datediff function signature:

enter image description here

As you can see, datediff requires two Column arguments.

Force flushing of output to a file while bash script is still running

This isn't a function of bash, as all the shell does is open the file in question and then pass the file descriptor as the standard output of the script. What you need to do is make sure output is flushed from your script more frequently than you currently are.

In Perl for example, this could be accomplished by setting:

$| = 1;

See perlvar for more information on this.

How to print variable addresses in C?

I tried in online compiler https://www.onlinegdb.com/online_c++_compiler

int main()
{
    cout<<"Hello World";
    int x = 10;
    int *p = &x;
    printf("\nAddress of x is %p\n", &x); // 0x7ffc7df0ea54
    printf("Address of p is %p\n", p);    // 0x7ffc7df0ea54

    return 0;
}

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to sort by column in descending order in Spark SQL?

import org.apache.spark.sql.functions.desc

df.orderBy(desc("columnname1"),desc("columnname2"),asc("columnname3"))

Default nginx client_max_body_size

You have to increase client_max_body_size in nginx.conf file. This is the basic step. But if your backend laravel then you have to do some changes in the php.ini file as well. It depends on your backend. Below I mentioned file location and condition name.

sudo vim /etc/nginx/nginx.conf.

After open the file adds this into HTTP section.

client_max_body_size 100M;

CSS display:table-row does not expand when width is set to 100%

You can nest table-cell directly within table. You muslt have a table. Starting eith table-row does not work. Try it with this HTML:

<html>
  <head>
    <style type="text/css">
.table {
  display: table;
  width: 100%;
}
.tr {
  display: table-row;
  width: 100%;
}
.td {
  display: table-cell;
}
    </style>
  </head>
  <body>

    <div class="table">
      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>
    </div>

      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>

    <div class="table">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
    </div>

  </body>
</html>

Removing Duplicate Values from ArrayList

if you want to use only arraylist then I am worried there is no better way which will create a huge performance benefit. But by only using arraylist i would check before adding into the list like following

void addToList(String s){
  if(!yourList.contains(s))
       yourList.add(s);
}

In this cases using a Set is suitable.

Import and Export Excel - What is the best library?

I've used Flexcel in the past and it was great. But this was more for programmatically creating and updating excel worksheets.

Error: «Could not load type MvcApplication»

I've seen this many times over the last decade and just had it again. There are many problems that result in the same error.

One cause is a renaming of files. If you're working with .cshtml files, check all namespaces within those files and within the Views\web.config file. For web forms, rename Default.aspx (related .cs and designer files are automatically renamed). The codebehind changes but the Inherits line in the markup doesn't. Change it manually. Double check the designer page. Sometimes (VS2005-8?) the designer page doesn't reflect a change in the namespace. Haven't seen this in 2010+.

Another issue is when it all works in VS or on your local PC but not when you deploy. This could be because the deployment environment isn't structured the same. For example, the error occurs if you place your code in a virtual directory under an application folder, but it doesn't occur if you create a new application folder and place all of your files in there. I don't understand this one, as I've had the new child/virtual folder set with the same permissions (or so I think) and (I believe) the application pool should work the same for everything in a given application folder.

In my case I've also had a bin folder with assemblies that are updated from other assemblies on the IIS server. Again, ensuring that these are run in a separate application folder resulted in success.

HTH

Android M Permissions: onRequestPermissionsResult() not being called

This issue was actually being caused by NestedFragments. Basically most fragments we have extend a HostedFragment which in turn extends a CompatFragment. Having these nested fragments caused issues which eventually were solved by another developer on the project.

He was doing some low level stuff like bit switching to get this working so I'm not too sure of the actual final solution

jQuery Force set src attribute for iframe

Setting src attribute didn't work for me. The iframe didn't display the url.

What worked for me was:

window.open(url, "nameof_iframe");

Hope it helps someone.

JS map return object

You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
  return {_x000D_
    country: elem.country,_x000D_
    launches: elem.launches+10,_x000D_
  } _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
_x000D_
_x000D_

How to set min-font-size in CSS

CSS Solution:

.h2{
  font-size: 2vw
}
@media (min-width: 700px) {
  .h2{
    /* Minimum font size */
    font-size: 14px
  }
}
@media (max-width: 1200px) {
  .h2{
    /* Maximum font size */
    font-size: 24px
  }
}

Just in case if some need scss mixin:

///
/// Viewport sized typography with minimum and maximum values
///
/// @author Eduardo Boucas (@eduardoboucas)
///
/// @param {Number}   $responsive  - Viewport-based size
/// @param {Number}   $min         - Minimum font size (px)
/// @param {Number}   $max         - Maximum font size (px)
///                                  (optional)
/// @param {Number}   $fallback    - Fallback for viewport-
///                                  based units (optional)
///
/// @example scss - 5vw font size (with 50px fallback),
///                 minumum of 35px and maximum of 150px
///  @include responsive-font(5vw, 35px, 150px, 50px);
///

@mixin responsive-font($responsive, $min, $max: false, $fallback: false) {
  $responsive-unitless: $responsive / ($responsive - $responsive + 1);
  $dimension: if(unit($responsive) == 'vh', 'height', 'width');
  $min-breakpoint: $min / $responsive-unitless * 100;

  @media (max-#{$dimension}: #{$min-breakpoint}) {
    font-size: $min;
  }

  @if $max {
    $max-breakpoint: $max / $responsive-unitless * 100;

    @media (min-#{$dimension}: #{$max-breakpoint}) {
      font-size: $max;
    }
  }

  @if $fallback {
    font-size: $fallback;
  }

  font-size: $responsive;
}

Is there a better jQuery solution to this.form.submit();?

In JQuery you can call

$("form:first").trigger("submit")

Don't know if that is much better. I think form.submit(); is pretty universal.

Close Bootstrap Modal

this worked for me:

<span class="button" data-dismiss="modal" aria-label="Close">cancel</span>

use this link modal close

Declaring variables in Excel Cells

You can use (hidden) cells as variables. E.g., you could hide Column C, set C1 to

=20

and use it as

=c1*20

Alternatively you can write VBA Macros which set and read a global variable.

Edit: AKX renders my Answer partially incorrect. I had no idea you could name cells in Excel.

Check if any type of files exist in a directory using BATCH script

For files in a directory, you can use things like:

if exist *.csv echo "csv file found"

or

if not exist *.csv goto nofile

how to fetch array keys with jQuery?

Don't Reinvent the Wheel, Use Underscore

I know the OP specifically mentioned jQuery but I wanted to put an answer here to introduce people to the helpful Underscore library if they are not aware of it already.

By leveraging the keys method in the Underscore library, you can simply do the following:

_.keys(foo)  #=> ["alfa", "beta"]

Plus, there's a plethora of other useful functions that are worth perusing.

What do 3 dots next to a parameter type mean in Java?

String... is the same as String[]

import java.lang.*;

public class MyClassTest {

    //public static void main(String... args) { 

    public static void main(String[] args) {
        for(String str: args) {
            System.out.println(str);
        }
    }
}

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

this is better approach and its successful :

Actions oAction = new Actions(driver);
oAction.moveToElement(Webelement);
oAction.contextClick(Webelement).build().perform();  /* this will perform right click */
WebElement elementOpen = driver.findElement(By.linkText("Open")); /*This will select menu after right click */

elementOpen.click();

Java ArrayList for integers

The [] makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values. Just use

List<Integer> list = new ArrayList<>();

to create the ArrayList and it will work.

Is it possible to change the speed of HTML's <marquee> tag?

I just do:

<marquee scrollamount="A number">Text here</marquee>

How to manually set REFERER header in Javascript?

Above solution does not work for me , I have tried following and it is working in all browsers.

simply made a fake ajax call, it will make a entry into referer header.

var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {}
    }
}
request.open("GET", url, true);
request.send();

Finding the source code for built-in Python functions?

Here is a cookbook answer to supplement @Chris' answer, CPython has moved to GitHub and the Mercurial repository will no longer be updated:

  1. Install Git if necessary.
  2. git clone https://github.com/python/cpython.git

  3. Code will checkout to a subdirectory called cpython -> cd cpython

  4. Let's say we are looking for the definition of print()...
  5. egrep --color=always -R 'print' | less -R
  6. Aha! See Python/bltinmodule.c -> builtin_print()

Enjoy.

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You can access afterRender hook by using plugins.

And here are all the plugin api available.

In html file:

<html>
  <canvas id="myChart"></canvas>
  <div id="imgWrap"></div>
</html>

In js file:

var chart = new Chart(ctx, {
  ...,
  plugins: [{
    afterRender: function () {
      // Do anything you want
      renderIntoImage()
    },
  }],
  ...,
});

const renderIntoImage = () => {
  const canvas = document.getElementById('myChart')
  const imgWrap = document.getElementById('imgWrap')
  var img = new Image();
  img.src = canvas.toDataURL()
  imgWrap.appendChild(img)
  canvas.style.display = 'none'
}

Is there a difference between PhoneGap and Cordova commands?

I found this difference which forced me to use a mixed bag of phonegap and cordova cli commands when building my app:

'phonegap plugin add' couldn't handle command line parameters correctly, whereas 'cordova platform add' works flawlessly

The command I use is:

'cordova plugin add https://github.com/crittercism/PhoneGap.git --variable IOS_APP_ID="[my_license_key]"

Note I am using phonegap 3.5

HTTP Get with 204 No Content: Is that normal

Http GET returning 204 is perfectly fine, and so is returning 404.

The important thing is that you define the design standards/guidelines for your API, so that all your endpoints use status codes consistently.

For example:

  • you may indicate that a GET endpoint that returns a collection of resources will return 204 if the collection is empty. In this case GET /complaints/year/2019/month/04 may return 204 if there are no complaints filed in April 2019. This is not an error on the client side, so we return a success status code (204). OTOH, GET /complaints/12345 may return 404 if complaint number 12345 doesn't exist.
  • if your API uses HATEOAS, 204 is probably a bad idea because the response should contain links to navigate to other states.

How to get pip to work behind a proxy server

On Ubuntu, you can set proxy by using

export http_proxy=http://username:password@proxy:port
export https_proxy=http://username:password@proxy:port

or if you are having SOCKS error use

export all_proxy=http://username:password@proxy:port

Then run pip

sudo -E pip3 install {packageName}

How do I test which class an object is in Objective-C?

You also can use

NSString *className = [[myObject class] description]; 

on any NSObject

How to use Elasticsearch with MongoDB?

Since mongo-connector now appears dead, my company decided to build a tool for using Mongo change streams to output to Elasticsearch.

Our initial results look promising. You can check it out at https://github.com/electionsexperts/mongo-stream. We're still early in development, and would welcome suggestions or contributions.

addEventListener in Internet Explorer

addEventListener is the proper DOM method to use for attaching event handlers.

Internet Explorer (up to version 8) used an alternate attachEvent method.

Internet Explorer 9 supports the proper addEventListener method.

The following should be an attempt to write a cross-browser addEvent function.

function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // W3C DOM
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE DOM
      elem.attachEvent("on"+evnt, func);
   }
   else { // No much to do
      elem["on"+evnt] = func;
   }
}

PHP: How to use array_filter() to filter array keys?

array filter function from php:

array_filter ( $array, $callback_function, $flag )

$array - It is the input array

$callback_function - The callback function to use, If the callback function returns true, the current value from array is returned into the result array.

$flag - It is optional parameter, it will determine what arguments are sent to callback function. If this parameter empty then callback function will take array values as argument. If you want to send array key as argument then use $flag as ARRAY_FILTER_USE_KEY. If you want to send both keys and values you should use $flag as ARRAY_FILTER_USE_BOTH .

For Example : Consider simple array

$array = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);

If you want to filter array based on the array key, We need to use ARRAY_FILTER_USE_KEY as third parameter of array function array_filter.

$get_key_res = array_filter($array,"get_key",ARRAY_FILTER_USE_KEY );

If you want to filter array based on the array key and array value, We need to use ARRAY_FILTER_USE_BOTH as third parameter of array function array_filter.

$get_both = array_filter($array,"get_both",ARRAY_FILTER_USE_BOTH );

Sample Callback functions:

 function get_key($key)
 {
    if($key == 'a')
    {
        return true;
    } else {
        return false;
    }
}
function get_both($val,$key)
{
    if($key == 'a' && $val == 1)
    {
        return true;
    }   else {
        return false;
    }
}

It will output

Output of $get_key is :Array ( [a] => 1 ) 
Output of $get_both is :Array ( [a] => 1 ) 

RecyclerView - How to smooth scroll to top of item on a certain position?

This is an extension function I wrote in Kotlin to use with the RecyclerView (based on @Paul Woitaschek answer):

fun RecyclerView.smoothSnapToPosition(position: Int, snapMode: Int = LinearSmoothScroller.SNAP_TO_START) {
  val smoothScroller = object : LinearSmoothScroller(this.context) {
    override fun getVerticalSnapPreference(): Int = snapMode
    override fun getHorizontalSnapPreference(): Int = snapMode
  }
  smoothScroller.targetPosition = position
  layoutManager?.startSmoothScroll(smoothScroller)
}

Use it like this:

myRecyclerView.smoothSnapToPosition(itemPosition)

Array to Hash Ruby

Enumerator includes Enumerable. Since 2.1, Enumerable also has a method #to_h. That's why, we can write :-

a = ["item 1", "item 2", "item 3", "item 4"]
a.each_slice(2).to_h
# => {"item 1"=>"item 2", "item 3"=>"item 4"}

Because #each_slice without block gives us Enumerator, and as per the above explanation, we can call the #to_h method on the Enumerator object.

How to debug Javascript with IE 8

This won't help you step through code or break on errors, but it's a useful way to get the same debug console for your project on all browsers.

myLog = function() {
    if (!myLog._div) { myLog.createDiv(); }

    var logEntry = document.createElement('span');
    for (var i=0; i < arguments.length; i++) {
        logEntry.innerHTML += myLog.toJson(arguments[i]) + '<br />';
    }
    logEntry.innerHTML += '<br />';

    myLog._div.appendChild(logEntry);
}
myLog.createDiv = function() {
    myLog._div = document.body.appendChild(document.createElement('div'));
    var props = {
        position:'absolute', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
        color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
        fontSize: '11px', whiteSpace: 'nowrap'
    }
    for (var key in props) { myLog._div.style[key] = props[key]; }
}
myLog.toJSON = function(obj) {
    if (typeof window.uneval == 'function') { return uneval(obj); }
    if (typeof obj == 'object') {
        if (!obj) { return 'null'; }
        var list = [];
        if (obj instanceof Array) {
            for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
            return '[' + list.join(',') + ']';
        } else {
            for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
            return '{' + list.join(',') + '}';
        }
    } else if (typeof obj == 'string') {
        return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
    } else {
        return new String(obj);
    }
}

myLog('log statement');
myLog('logging an object', { name: 'Marcus', likes: 'js' });

This is put together pretty hastily and is a bit sloppy, but it's useful nonetheless and can be improved easily!

Rotating a point about another point (2D)

If you rotate point (px, py) around point (ox, oy) by angle theta you'll get:

p'x = cos(theta) * (px-ox) - sin(theta) * (py-oy) + ox

p'y = sin(theta) * (px-ox) + cos(theta) * (py-oy) + oy

this is an easy way to rotate a point in 2D.

Initialize a string in C to empty string

In addition to Will Dean's version, the following are common for whole buffer initialization:

char s[10] = {'\0'};

or

char s[10];
memset(s, '\0', sizeof(s));

or

char s[10];
strncpy(s, "", sizeof(s));

javascript multiple OR conditions in IF statement

You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say

the id is not 1, and the id is not 2, and the id is not 3.

which translates to

if (id !== 1 && id !== 2 && id !== 3)

or alternatively for something more pythonesque:

if (!(id in [,1,2,3]))

Can overridden methods differ in return type?

Overriding and Return Types, and Covariant Returns
the subclass must define a method that matches the inherited version exactly. Or, as of Java 5, you're allowed to change the return type in the

sample code


                                                                                                            class Alpha {
          Alpha doStuff(char c) {
                  return new Alpha();
              }
           }
             class Beta extends Alpha {
                    Beta doStuff(char c) { // legal override in Java 1.5
                    return new Beta();
                    }
             } } 
As of Java 5, this code will compile. If you were to attempt to compile this code with a 1.4 compiler will say attempting to use incompatible return type – sandeep1987 1 min ago

Object spread vs. Object.assign

The spread operator spread the Array into the separate arguments of a function.

let iterableObjB = [1,2,3,4]
function (...iterableObjB)  //turned into
function (1,2,3,4)

Is there a way to create multiline comments in Python?

Yes, it is fine to use both:

'''
Comments
'''

and

"""
Comments
"""

But, the only thing you all need to remember while running in an IDE, is you have to 'RUN' the entire file to be accepted as multiple lines codes. Line by line 'RUN' won't work properly and will show an error.

form action with javascript

I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:

action="javascript:checkout()"

You try this?

Don't forget include the script reference in the html head.

I don't know cause of that works in firefox. Regards.

How to get/generate the create statement for an existing hive table?

Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:

step 1)
create a .sh file with the below content, say hive_table_ddl.sh

#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt  
wait
cat tableNames.txt |while read LINE
   do
   hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
   echo  -e "\n" >> HiveTableDDL.txt
   done
rm -f tableNames.txt
echo "Table DDL generated"

step 2)

Run the above shell script by passing 'db name' as paramanter

>bash hive_table_dd.sh <<databasename>>

output :

All the create table statements of your DB will be written into the HiveTableDDL.txt

Material effect on button with background color

v22.1 of appcompat-v7 introduced some new possibilities. Now it's possible to assign a specific theme only to one view.

Deprecated use of app:theme for styling Toolbar. You can now use android:theme for toolbars on all API level 7 and higher devices and android:theme support for all widgets on API level 11 and higher devices.

So instead of setting the desired color in a global theme, we create a new one and assign it only to the Button

Example:

<style name="MyColorButton" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorButtonNormal">@color/myColor</item>
</style>

And use this style as theme of your Button

<Button
 style="?android:attr/buttonStyleSmall"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Button1"
 android:theme="@style/MyColorButton"/>

How to turn on front flash light programmatically in Android?

Complete Code for android Flashlight App

Manifest

  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.user.flashlight"
      android:versionCode="1"
      android:versionName="1.0">

      <uses-sdk
          android:minSdkVersion="8"
          android:targetSdkVersion="17"/>

      <uses-permission android:name="android.permission.CAMERA" />
      <uses-feature android:name="android.hardware.camera"/>

      <application
          android:allowBackup="true"
          android:icon="@mipmap/ic_launcher"
          android:label="@string/app_name"
          android:theme="@style/AppTheme" >
          <activity
              android:name=".MainActivity"
              android:label="@string/app_name" >
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />

                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
      </application>

  </manifest>

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OFF"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="turnFlashOnOrOff" />
</RelativeLayout>

MainActivity.java

  import android.app.AlertDialog;
  import android.content.DialogInterface;
  import android.content.pm.PackageManager;
  import android.hardware.Camera;
  import android.hardware.Camera.Parameters;
  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Button;

  import java.security.Policy;

  public class MainActivity extends AppCompatActivity {

      Button button;
      private Camera camera;
      private boolean isFlashOn;
      private boolean hasFlash;
      Parameters params;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          button = (Button) findViewById(R.id.button);

          hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

          if(!hasFlash) {

              AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
              alert.setTitle("Error");
              alert.setMessage("Sorry, your device doesn't support flash light!");
              alert.setButton("OK", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      finish();
                  }
              });
              alert.show();
              return;
          }

          getCamera();

          button.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {

                  if (isFlashOn) {
                      turnOffFlash();
                      button.setText("ON");
                  } else {
                      turnOnFlash();
                      button.setText("OFF");
                  }

              }
          });
      }

      private void getCamera() {

          if (camera == null) {
              try {
                  camera = Camera.open();
                  params = camera.getParameters();
              }catch (Exception e) {

              }
          }

      }

      private void turnOnFlash() {

          if(!isFlashOn) {
              if(camera == null || params == null) {
                  return;
              }

              params = camera.getParameters();
              params.setFlashMode(Parameters.FLASH_MODE_TORCH);
              camera.setParameters(params);
              camera.startPreview();
              isFlashOn = true;
          }

      }

      private void turnOffFlash() {

              if (isFlashOn) {
                  if (camera == null || params == null) {
                      return;
                  }

                  params = camera.getParameters();
                  params.setFlashMode(Parameters.FLASH_MODE_OFF);
                  camera.setParameters(params);
                  camera.stopPreview();
                  isFlashOn = false;
              }
      }

      @Override
      protected void onDestroy() {
          super.onDestroy();
      }

      @Override
      protected void onPause() {
          super.onPause();

          // on pause turn off the flash
          turnOffFlash();
      }

      @Override
      protected void onRestart() {
          super.onRestart();
      }

      @Override
      protected void onResume() {
          super.onResume();

          // on resume turn on the flash
          if(hasFlash)
              turnOnFlash();
      }

      @Override
      protected void onStart() {
          super.onStart();

          // on starting the app get the camera params
          getCamera();
      }

      @Override
      protected void onStop() {
          super.onStop();

          // on stop release the camera
          if (camera != null) {
              camera.release();
              camera = null;
          }
      }

  }

redirect COPY of stdout to log file from within bash script itself

Neither of these is a perfect solution, but here are a couple things you could try:

exec >foo.log
tail -f foo.log &
# rest of your script

or

PIPE=tmp.fifo
mkfifo $PIPE
exec >$PIPE
tee foo.log <$PIPE &
# rest of your script
rm $PIPE

The second one would leave a pipe file sitting around if something goes wrong with your script, which may or may not be a problem (i.e. maybe you could rm it in the parent shell afterwards).

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will work with iPad on Safari on iOS 7.1.x from my testing, I'm not sure about iOS 6 though. However, it will not work on Firefox. There is a jQuery plugin which aims to be cross browser compliant called jScrollPane.

Also, there is a duplicate post here on Stack Overflow which has some other details.

Rails: Can't verify CSRF token authenticity when making a POST request

The simplest solution for the problem is do standard things in your controller or you can directely put it into ApplicationController

class ApplicationController < ActionController::Base protect_from_forgery with: :exception, prepend: true end

Bootstrap 3: how to make head of dropdown link clickable in navbar

Alternatively here's a simple jQuery solution:

$('#menu-main > li > .dropdown-toggle').click(function () {
    window.location = $(this).attr('href');
});

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

CLOCK_REALTIME represents the machine's best-guess as to the current wall-clock, time-of-day time. As Ignacio and MarkR say, this means that CLOCK_REALTIME can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.

CLOCK_MONOTONIC represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn't affected by changes in the system time-of-day clock.

If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, CLOCK_MONOTONIC is the best option.

Note that on Linux, CLOCK_MONOTONIC does not measure time spent in suspend, although by the POSIX definition it should. You can use the Linux-specific CLOCK_BOOTTIME for a monotonic clock that keeps running during suspend.

How to redirect the output of the time command to a file in Linux?

If you are using csh you can use:

/usr/bin/time --output=outfile -p $SHELL  -c 'your command'

For example:

/usr/bin/time --output=outtime.txt -p csh -c 'cat file'

How to set custom ActionBar color / style?

For Android 3.0 and higher only

When supporting Android 3.0 and higher only, you can define the action bar's background like this:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme" parent="@style/Theme.Holo.Light.DarkActionBar">
       <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>

<!-- ActionBar styles -->
  <style name="MyActionBar" parent="@style/Widget.Holo.Light.ActionBar.Solid.Inverse">
       <item name="android:background">#ff0000</item>
  </style>
</resources>

For Android 2.1 and higher

When using the Support Library, your style XML file might look like this:

<?xml version="1.0" encoding="utf-8"?>
  <resources>
  <!-- the theme applied to the application or activity -->
 <style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/MyActionBar</item>

    <!-- Support library compatibility -->
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>

<!-- ActionBar styles -->
<style name="MyActionBar"
       parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@drawable/actionbar_background</item>

    <!-- Support library compatibility -->
    <item name="background">@drawable/actionbar_background</item>
  </style>
 </resources>

Then apply your theme to your entire app or individual activities:

for more details Documentaion

how to select first N rows from a table in T-SQL?

Try this:

SELECT * FROM USERS LIMIT 10;

Cannot attach the file *.mdf as database

You already have an old copy of that database installed in Server Explorer. So its a simple naming collision in the Server Object Explorer / SQL server. You likely created the same database Catalog Name already before you decided to move it to the Apps_Data folder. So that Database name already exists and just needs to be deleted.

Just go into Visual Studio > View > SQL Server Object Explorer and delete the old database name and its connection. Retry your app again and it should install the .mdf file in App_Data and create the same exact database again in the Server Explorer.

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

How to style the menu items on an Android action bar

I did this way:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="android:actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="actionMenuTextColor">@color/colorAccent</item>
</style>

<style name="MenuTextAppearance" >
    <item name="android:textAppearance">@android:style/TextAppearance.Large</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
</style>

ERROR 403 in loading resources like CSS and JS in my index.php

You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.

Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.

Use superscripts in R axis labels

This is a quick example

plot(rnorm(30), xlab = expression(paste("4"^"th")))

How can I get a random number in Kotlin?

No need to use custom extension functions anymore. IntRange has a random() extension function out-of-the-box now.

val randomNumber = (0..10).random()

What is a bus error?

mmap minimal POSIX 7 example

"Bus error" happens when the kernel sends SIGBUS to a process.

A minimal example that produces it because ftruncate was forgotten:

#include <fcntl.h> /* O_ constants */
#include <unistd.h> /* ftruncate */
#include <sys/mman.h> /* mmap */

int main() {
    int fd;
    int *map;
    int size = sizeof(int);
    char *name = "/a";

    shm_unlink(name);
    fd = shm_open(name, O_RDWR | O_CREAT, (mode_t)0600);
    /* THIS is the cause of the problem. */
    /*ftruncate(fd, size);*/
    map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    /* This is what generates the SIGBUS. */
    *map = 0;
}

Run with:

gcc -std=c99 main.c -lrt
./a.out

Tested in Ubuntu 14.04.

POSIX describes SIGBUS as:

Access to an undefined portion of a memory object.

The mmap spec says that:

References within the address range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.

And shm_open says that it generates objects of size 0:

The shared memory object has a size of zero.

So at *map = 0 we are touching past the end of the allocated object.

Unaligned stack memory accesses in ARMv8 aarch64

This was mentioned at: What is a bus error? for SPARC, but here I will provide a more reproducible example.

All you need is a freestanding aarch64 program:

.global _start
_start:
asm_main_after_prologue:
    /* misalign the stack out of 16-bit boundary */
    add sp, sp, #-4
    /* access the stack */
    ldr w0, [sp]

    /* exit syscall in case SIGBUS does not happen */
    mov x0, 0
    mov x8, 93
    svc 0

That program then raises SIGBUS on Ubuntu 18.04 aarch64, Linux kernel 4.15.0 in a ThunderX2 server machine.

Unfortunately, I can't reproduce it on QEMU v4.0.0 user mode, I'm not sure why.

The fault appears to be optional and controlled by the SCTLR_ELx.SA and SCTLR_EL1.SA0 fields, I have summarized the related docs a bit further here.

How to highlight text using javascript

None of the other solutions really fit my needs, and although Stefan Steiger's solution worked as I expected I found it a bit too verbose.

Following is my attempt:

_x000D_
_x000D_
/**_x000D_
 * Highlight keywords inside a DOM element_x000D_
 * @param {string} elem Element to search for keywords in_x000D_
 * @param {string[]} keywords Keywords to highlight_x000D_
 * @param {boolean} caseSensitive Differenciate between capital and lowercase letters_x000D_
 * @param {string} cls Class to apply to the highlighted keyword_x000D_
 */_x000D_
function highlight(elem, keywords, caseSensitive = false, cls = 'highlight') {_x000D_
  const flags = caseSensitive ? 'gi' : 'g';_x000D_
  // Sort longer matches first to avoid_x000D_
  // highlighting keywords within keywords._x000D_
  keywords.sort((a, b) => b.length - a.length);_x000D_
  Array.from(elem.childNodes).forEach(child => {_x000D_
    const keywordRegex = RegExp(keywords.join('|'), flags);_x000D_
    if (child.nodeType !== 3) { // not a text node_x000D_
      highlight(child, keywords, caseSensitive, cls);_x000D_
    } else if (keywordRegex.test(child.textContent)) {_x000D_
      const frag = document.createDocumentFragment();_x000D_
      let lastIdx = 0;_x000D_
      child.textContent.replace(keywordRegex, (match, idx) => {_x000D_
        const part = document.createTextNode(child.textContent.slice(lastIdx, idx));_x000D_
        const highlighted = document.createElement('span');_x000D_
        highlighted.textContent = match;_x000D_
        highlighted.classList.add(cls);_x000D_
        frag.appendChild(part);_x000D_
        frag.appendChild(highlighted);_x000D_
        lastIdx = idx + match.length;_x000D_
      });_x000D_
      const end = document.createTextNode(child.textContent.slice(lastIdx));_x000D_
      frag.appendChild(end);_x000D_
      child.parentNode.replaceChild(frag, child);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
// Highlight all keywords found in the page_x000D_
highlight(document.body, ['lorem', 'amet', 'autem']);
_x000D_
.highlight {_x000D_
  background: lightpink;_x000D_
}
_x000D_
<p>Hello world lorem ipsum dolor sit amet, consectetur adipisicing elit. Est vel accusantium totam, ipsum delectus et dignissimos mollitia!</p>_x000D_
<p>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, corporis._x000D_
  <small>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium autem voluptas perferendis dolores ducimus velit error voluptatem, qui rerum modi?</small>_x000D_
</p>
_x000D_
_x000D_
_x000D_

I would also recommend using something like escape-string-regexp if your keywords can have special characters that would need to be escaped in regexes:

const keywordRegex = RegExp(keywords.map(escapeRegexp).join('|')), flags);

Dismissing a Presented View Controller

This is for view controller reusability.

Your view controller shouldn't care if it is being presented as a modal, pushed on a navigation controller, or whatever. If your view controller dismisses itself, then you're assuming it is being presented modally. You won't be able to push that view controller onto a navigation controller.

By implementing a protocol, you let the parent view controller decide how it should be presented/pushed and dismissed/popped.

Loop through all elements in XML using NodeList

Here is another way to loop through XML elements using JDOM.

        List<Element> nodeNodes = inputNode.getChildren();
        if (nodeNodes != null) {
            for (Element nodeNode : nodeNodes) {
                List<Element> elements = nodeNode.getChildren(elementName);
                if (elements != null) {
                    elements.size();
                    nodeNodes.removeAll(elements);
                }
            }

c++ array assignment of multiple values

const static int newvals[] = {34,2,4,5,6};

std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

How to take complete backup of mysql database using mysqldump command line utility

I am using MySQL 5.5.40. This version has the option --all-databases

mysqldump -u<username> -p<password> --all-databases --events > /tmp/all_databases__`date +%d_%b_%Y_%H_%M_%S`.sql

This command will create a complete backup of all databases in MySQL server to file named to current date-time.

Can we overload the main method in Java?

Yes, you can overload main method in Java. you have to call the overloaded main method from the actual main method.

Some dates recognized as dates, some dates not recognized. Why?

It's not that hard...

Check out this forum post:

http://www.pcreview.co.uk/forums/excel-not-recognizing-dates-dates-t3139469.html

The steps in short:

  1. Select only the column of "dates"
  2. Click Data > Text to Columns
  3. Click Next
  4. Click Next
  5. In step 3 of the wizard, check "Date" under Col data format, then choose: "DMY" from the droplist.
  6. Click Finish

How to set focus on a view when a layout is created and displayed?

You can try just hidding the keyboard. Something like this:

InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

How to run C program on Mac OS X using Terminal?

First save your program as program.c.

Now you need the compiler, so you need to go to App Store and install Xcode which is Apple's compiler and development tools. How to find App Store? Do a "Spotlight Search" by typing Space and start typing App Store and hit Enter when it guesses correctly.

App Store looks like this:

enter image description here

Xcode looks like this on App Store:

enter image description here

Then you need to install the command-line tools in Terminal. How to start Terminal? You need to do another "Spotlight Search", which means you type Space and start typing Terminal and hit Enter when it guesses Terminal.

Now install the command-line tools like this:

xcode-select --install

Then you can compile your code with by simply running gcc as in the next line without having to fire up the big, ugly software development GUI called Xcode:

gcc -Wall -o program program.c

Note: On newer versions of OS X, you would use clang instead of gcc, like this:

clang program.c -o program

Then you can run it with:

./program
Hello, world!

If your program is C++, you'll probably want to use one of these commands:

clang++ -o program program.cpp
g++ -std=c++11 -o program program.cpp
g++-7 -std=c++11 -o program program.cpp

How to reverse apply a stash?

The V1 git man page had a reference about un-applying a stash. The excerpt is below.

The newer V2 git man page doesn't include any reference to un-applying a stash but the below still works well

Un-applying a Stash In some use case scenarios you might want to apply stashed changes, do some work, but then un-apply those changes that originally came from the stash. Git does not provide such a stash un-apply command, but it is possible to achieve the effect by simply retrieving the patch associated with a stash and applying it in reverse:

$ git stash show -p stash@{0} | git apply -R

Again, if you don’t specify a stash, Git assumes the most recent stash:

$ git stash show -p | git apply -R

You may want to create an alias and effectively add a stash-unapply command to your Git. For example:

$ git config --global alias.stash-unapply '!git stash show -p | git apply -R'
$ git stash apply
$ #... work work work
$ git stash-unapply

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.

trigger body click with jQuery

As mentioned by Seeker, the problem could have been that you setup the click() function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.

An important point is to run such scripts after the document is ready. This is done by placing the click() initialization within that other function as in:

jQuery(document).ready(function()
  {
    jQuery("body").click(function()
      {
        // ... your click code here ...
      });
  });

This is usually the best method, especially if you include your JavaScript code in your <head> tag. If you include it at the very bottom of the page, then the ready() function is less important, but it may still be useful.

Display curl output in readable JSON format in Unix shell script

A few solutions to choose from:

json_pp: command utility available in Linux systems for JSON decoding/encoding

echo '{"type":"Bar","id":"1","title":"Foo"}' | json_pp -json_opt pretty,canonical
{
   "id" : "1",
   "title" : "Foo",
   "type" : "Bar"
}

You may want to keep the -json_opt pretty,canonical argument for predictable ordering.


: lightweight and flexible command-line JSON processor. It is written in portable C, and it has zero runtime dependencies.

echo '{"type":"Bar","id":"1","title":"Foo"}' | jq '.'
{
  "type": "Bar",
  "id": "1",
  "title": "Foo"
}

The simplest jq program is the expression ., which takes the input and produces it unchanged as output.

For additinal jq options check the manual


with :

echo '{"type":"Bar","id":"1","title":"Foo"}' | python -m json.tool
{
    "id": "1",
    "title": "Foo",
    "type": "Bar"
}

with and :

echo '{"type":"Bar","id":"1","title":"Foo"}' | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
{
 "type": "Bar",
 "id": "1",
 "title": "Foo"
}

CSS scrollbar style cross browser

As of IE6 I believe you cannot customize the scroll bar using those properties. The Chris Coyier article linked to above goes into nice detail about the options for webkit proprietary css for customizing the scroll bar.

If you really want a cross browser solution that you can fully customize you're going to have to use some JS. Here is a link to a nice plugin for it called FaceScroll: http://www.dynamicdrive.com/dynamicindex11/facescroll/index.htm

What does AND 0xFF do?

if byte1 is an 8-bit integer type then it's pointless - if it is more than 8 bits it will essentially give you the last 8 bits of the value:

    0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
 &  0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
    -------------------------------
    0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1

Does Java have an exponential operator?

There is no operator, but there is a method.

Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0

FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.

Bootstrap Modal before form Submit

I noticed some of the answers were not triggering the HTML5 required attribute (as stuff was being executed on the action of clicking rather than the action of form send, causing to bypass it when the inputs were empty):

  1. Have a <form id='xform'></form> with some inputs with the required attribute and place a <input type='submit'> at the end.
  2. A confirmation input where typing "ok" is expected <input type='text' name='xconf' value='' required>
  3. Add a modal_1_confirm to your html (to confirm the form of sending).
  4. (on modal_1_confirm) add the id modal_1_accept to the accept button.
  5. Add a second modal_2_errMsg to your html (to display form validation errors).
  6. (on modal_2_errMsg) add the id modal_2_accept to the accept button.
  7. (on modal_2_errMsg) add the id m2_Txt to the displayed text holder.
  8. The JS to intercept before the form is sent:

    $("#xform").submit(function(e){
        var msg, conf, preventSend;
    
        if($("#xform").attr("data-send")!=="ready"){
            msg="Error."; //default error msg
            preventSend=false;
    
            conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
    
            if(conf===""){
                msg="The field is empty.";
                preventSend=true;
            }else if(conf!=="ok"){
                msg="You didn't write \"ok\" correctly.";
                preventSend=true;
            }
    
            if(preventSend){ //validation failed, show the error
                $("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
                $("#modal_2_errMsg").modal("show");
            }else{ //validation passed, now let's confirm the action
                $("#modal_1_confirm").modal("show");
            }
    
            e.preventDefault();
            return false;
        }
    });
    

`9. Also some stuff when clicking the Buttons from the modals:

$("#modal_1_accept").click(function(){
    $("#modal_1_confirm").modal("hide");
    $("#xform").attr("data-send", "ready").submit();
});

$("#modal_2_accept").click(function(){
    $("#modal_2_errMsg").modal("hide");
});

Important Note: So just be careful if you add an extra way to show the modal, as simply clicking the accept button $("#modal_1_accept") will assume the validation passed and it will add the "ready" attribute:

  • The reasoning for this is that $("#modal_1_confirm").modal("show"); is shown only when it passed the validation, so clicking $("#modal_1_accept") should be unreachable without first getting the form validated.

How to serve up a JSON response using Go?

You can set your content-type header so clients know to expect json

w.Header().Set("Content-Type", "application/json")

Another way to marshal a struct to json is to build an encoder using the http.ResponseWriter

// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

There are at least 6 (!) ways to clone an array:

  • loop
  • slice
  • Array.from()
  • concat
  • spread operator (FASTEST)
  • map A.map(function(e){return e;});

There has been a huuuge BENCHMARKS thread, providing following information:

  • for blink browsers slice() is the fastest method, concat() is a bit slower, and while loop is 2.4x slower.

  • for other browsers while loop is the fastest method, since those browsers don't have internal optimizations for slice and concat.

This remains true in Jul 2016.

Below are simple scripts that you can copy-paste into your browser's console and run several times to see the picture. They output milliseconds, lower is better.

while loop

n = 1000*1000;
start = + new Date();
a = Array(n); 
b = Array(n); 
i = a.length;
while(i--) b[i] = a[i];
console.log(new Date() - start);

slice

n = 1000*1000;
start = + new Date();
a = Array(n); 
b = a.slice();
console.log(new Date() - start);

Please note that these methods will clone the Array object itself, array contents however are copied by reference and are not deep cloned.

origAr == clonedArr //returns false
origAr[0] == clonedArr[0] //returns true

Delete files in subfolder using batch script

You can use the /s switch for del to delete in subfolders as well.

Example

del D:\test\*.* /s

Would delete all files under test including all files in all subfolders.

To remove folders use rd, same switch applies.

rd D:\test\folder /s /q

rd doesn't support wildcards * though so if you want to recursively delete all subfolders under the test directory you can use a for loop.

for /r /d D:\test %a in (*) do rd %a /s /q

If you are using the for option in a batch file remember to use 2 %'s instead of 1.

What does 'corrupted double-linked list' mean

I ran into this error in some code where someone was calling exit() in one thread about the same time as main() returned, so all the global/static constructors were being kicked off in two separate threads simultaneously.

This error also manifests as double free or corruption, or a segfault/sig11 inside exit() or inside malloc_consolidate, and likely others. The call stack for the malloc_consolidate crash may resemble:

#0  0xabcdabcd in malloc_consolidate () from /lib/libc.so.6
#1  0xabcdabcd in _int_free () from /lib/libc.so.6
#2  0xabcdabcd in operator delete (...)
#3  0xabcdabcd in operator delete[] (...)
(...)

I couldn't get it to exhibit this problem while running under valgrind.

Closing Bootstrap modal onclick

You can hide the modal and popup the window to review the carts in validateShipping() function itself.

function validateShipping(){
...
...
$('#product-options').modal('hide');
//pop the window to select items
}

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

I had the same issue and took a whole day to figure out the problem. This error message by Facebook SDK is very vague. I had this problem due to openURL: method being overwritten in MyApplication. I removed the overwritten method and facebook login worked fine.

Creating layout constraints programmatically

Swift version

Updated for Swift 3

This example will show two methods to programmatically add the following constraints the same as if doing it in the Interface Builder:

Width and Height

enter image description here

Center in Container

enter image description here

Boilerplate code

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add constraints code here (choose one of the methods below)
    // ...
}

Method 1: Anchor Style

// width and height
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true

// center in container
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

// width and height
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true

// center in container
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • See also the Programmatically Creating Constraints documentation.
  • See this answer for a similar example of adding a pinning constraint.

iPhone 5 CSS media query

You should maybe down the "-webkit-min-device-pixel-ratio" to 1.5 to catch all iPhones ?

@media only screen and (max-device-width: 480px), only screen and (min-device-width: 640px) and (max-device-width: 1136px) and (-webkit-min-device-pixel-ratio: 1.5) {
/* iPhone only */
}

How to include a font .ttf using CSS?

Did you try format?

@font-face {
  font-family: 'The name of the Font Family Here';
  src: URL('font.ttf') format('truetype');
}

Read this article: http://css-tricks.com/snippets/css/using-font-face/

Also, might depend on browser as well.

How can I make a JPA OneToOne relation lazy

Most efficient mapping of a one-to-one association You can avoid all these problems and get rid of the foreign key column by using the same primary key value for both associated entities. You can do that by annotating the owning side of the association with @MapsId.

@Entity
public class Book {
 
    @Id
    @GeneratedValue
    private Long id;
 
    @OneToOne(mappedBy = "book", fetch = FetchType.LAZY, optional = false)
    private Manuscript manuscript;
 
    ...
}


@Entity
public class Manuscript {
 
    @Id
    private Long id;
 
    @OneToOne
    @MapsId
    @JoinColumn(name = "id")
    private Book book;
 
    ...
}


Book b = em.find(Book.class, 100L);
Manuscript m = em.find(Manuscript.class, b.getId());

More Detail click on this url

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

Compare two folders which has many files inside contents

I used

diff -rqyl folder1 folder2 --exclude=node_modules

in my nodejs apps.

How to check if an element is off-screen

  • Get the distance from the top of the given element
  • Add the height of the same given element. This will tell you the total number from the top of the screen to the end of the given element.
  • Then all you have to do is subtract that from total document height

    jQuery(function () {
        var documentHeight = jQuery(document).height();
        var element = jQuery('#you-element');
        var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true));
        alert(distanceFromBottom)
    });
    

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Open Turn On/Off Windows Features.

Make sure you have Active Directory Domain Services selected. If not, install it. enter image description here

Difference between signed / unsigned char

Representation is the same, the meaning is different. e.g, 0xFF, it both represented as "FF". When it is treated as "char", it is negative number -1; but it is 255 as unsigned. When it comes to bit shifting, it is a big difference since the sign bit is not shifted. e.g, if you shift 255 right 1 bit, it will get 127; shifting "-1" right will be no effect.

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

How to get file creation date/time in Bash/Debian?

ls -i file #output is for me 68551981
debugfs -R 'stat <68551981>' /dev/sda3 # /dev/sda3 is the disk on which the file exists

#results - crtime value
[root@loft9156 ~]# debugfs -R 'stat <68551981>' /dev/sda3
debugfs 1.41.12 (17-May-2010)
Inode: 68551981   Type: regular    Mode:  0644   Flags: 0x80000
Generation: 769802755    Version: 0x00000000:00000001
User:     0   Group:     0   Size: 38973440
File ACL: 0    Directory ACL: 0
Links: 1   Blockcount: 76128
Fragment:  Address: 0    Number: 0    Size: 0
 ctime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
 atime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013
 mtime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
**crtime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013**
Size of extra inode fields: 28
EXTENTS:
(0-511): 352633728-352634239, (512-1023): 352634368-352634879, (1024-2047): 288392192-288393215, (2048-4095): 355803136-355805183, (4096-6143): 357941248-357943295, (6144
-9514): 357961728-357965098

How do I create a new user in a SQL Azure database?

I followed the answers here but when I tried to connect with my new user, I got an error message stating "The server principal 'newuser' is not able to access the database 'master' under the current security context".

I had to also create a new user in the master table to successfully log in with SSMS.

USE [master]
GO
CREATE LOGIN [newuser] WITH PASSWORD=N'blahpw'
GO
CREATE USER [newuser] FOR LOGIN [newuser] WITH DEFAULT_SCHEMA=[dbo]
GO

USE [MyDatabase]
CREATE USER newuser FOR LOGIN newuser WITH DEFAULT_SCHEMA = dbo
GO
EXEC sp_addrolemember N'db_owner', N'newuser'
GO

How can I pass a parameter to a setTimeout() callback?

Note that the reason topicId was "not defined" per the error message is that it existed as a local variable when the setTimeout was executed, but not when the delayed call to postinsql happened. Variable lifetime is especially important to pay attention to, especially when trying something like passing "this" as an object reference.

I heard that you can pass topicId as a third parameter to the setTimeout function. Not much detail is given but I got enough information to get it to work, and it's successful in Safari. I don't know what they mean about the "millisecond error" though. Check it out here:

http://www.howtocreate.co.uk/tutorials/javascript/timers

Database, Table and Column Naming Conventions?

  1. No. A table should be named after the entity it represents. Person, not persons is how you would refer to whoever one of the records represents.
  2. Again, same thing. The column FirstName really should not be called FirstNames. It all depends on what you want to represent with the column.
  3. NO.
  4. Yes. Case it for clarity. If you need to have columns like "FirstName", casing will make it easier to read.

Ok. Thats my $0.02

How to read and write excel file

I edited the most voted one a little cuz it didn't count blanks columns or rows well not totally, so here is my code i tested it and now can get any cell in any part of an excel file. also now u can have blanks columns between filled column and it will read them

  try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;

int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();

int cols = 0; // No of columns
int tmp = 0;
int cblacks=0;

// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i <= 10 || i <= rows; i++) {
    row = sheet.getRow(i);
    if(row != null) {
        tmp = sheet.getRow(i).getPhysicalNumberOfCells();
        if(tmp >= cols) cols = tmp;else{rows++;cblacks++;}
    }

    cols++;
}
cols=cols+cblacks;
for(int r = 0; r < rows; r++) {
    row = sheet.getRow(r);
    if(row != null) {
        for(int c = 0; c < cols; c++) {
            cell = row.getCell(c);
            if(cell != null) {
                System.out.print(cell+"\n");//Your Code here
            }
        }
    }
}} catch(Exception ioe) {
ioe.printStackTrace();}

PHP Session timeout

Just check first the session is not already created and if not create one. Here i am setting it for 1 minute only.

<?php 
   if(!isset($_SESSION["timeout"])){
     $_SESSION['timeout'] = time();
   };
   $st = $_SESSION['timeout'] + 60; //session time is 1 minute
?>

<?php 
  if(time() < $st){
    echo 'Session will last 1 minute';
  }
?>

Changing java platform on which netbeans runs

For anyone on Mac OS X, you can find netbeans.conf here:

/Applications/NetBeans/NetBeans <version>.app/Contents/Resources/NetBeans/etc/netbeans.conf

In case anyone needs to know :)

How to draw checkbox or tick mark in GitHub Markdown table?

|checked|unchecked|crossed|
|---|---|---|
|&check;|_|&cross;|

Where

? via HTML Entity Code
? via HTML Entity Code
_ via underscore character
and table via markdown table syntax.

How to get status code from webclient?

Just in case someone else needs an F# version of the above described hack.

open System
open System.IO
open System.Net

type WebClientEx() =
     inherit WebClient ()
     [<DefaultValue>] val mutable m_Resp : WebResponse

     override x.GetWebResponse (req: WebRequest ) =
        x.m_Resp <- base.GetWebResponse(req)
        (req :?> HttpWebRequest).AllowAutoRedirect <- false;
        x.m_Resp

     override x.GetWebResponse (req: WebRequest , ar: IAsyncResult  ) =
        x.m_Resp <- base.GetWebResponse(req, ar)
        (req :?> HttpWebRequest).AllowAutoRedirect <- false;
        x.m_Resp

     member x.StatusCode with get() : HttpStatusCode = 
            if not (obj.ReferenceEquals (x.m_Resp, null)) && x.m_Resp.GetType() = typeof<HttpWebResponse> then
                (x.m_Resp :?> HttpWebResponse).StatusCode
            else
                HttpStatusCode.OK

let wc = new WebClientEx()
let st = wc.OpenRead("http://www.stackoverflow.com")
let sr = new StreamReader(st)
let res = sr.ReadToEnd()
wc.StatusCode
sr.Close()
st.Close()

How do I clear all variables in the middle of a Python script?

In the idle IDE there is Shell/Restart Shell. Cntrl-F6 will do it.

Use CSS to automatically add 'required field' asterisk to form inputs

input[required]{
    background-image: radial-gradient(#F00 15%, transparent 16%), radial-gradient(#F00 15%, transparent 16%);
    background-size: 1em 1em;
    background-position: right top;
    background-repeat: no-repeat;
}

How to make google spreadsheet refresh itself every 1 minute?

I had a similar problem with crypto updates. A kludgy hack that gets around this is to include a '+ now() - now()' stunt at the end of the cell formula, with the setting as above to recalculate every minute. This worked for my price updates, but, definitely an ugly hack.

How to take a screenshot programmatically on iOS

See this post it looks like you can use UIGetScreenImage() for now.

Get file content from URL?

Use file_get_contents in combination with json_decode and echo.

Oracle date "Between" Query

You need to convert those to actual dates instead of strings, try this:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('2010-01-15','YYYY-MM-DD') AND TO_DATE('2010-01-17', 'YYYY-MM-DD');

Edited to deal with format as specified:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('15-JAN-10','DD-MON-YY') AND TO_DATE('17-JAN-10','DD-MON-YY');

Configure Log4Net in web application

1: Add the following line into the AssemblyInfo class

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

2: Make sure you don't use .Net Framework 4 Client Profile as Target Framework (I think this is OK on your side because otherwise it even wouldn't compile)

3: Make sure you log very early in your program. Otherwise, in some scenarios, it will not be initialized properly (read more on log4net FAQ).

So log something during application startup in the Global.asax

public class Global : System.Web.HttpApplication
{
    private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(Global));
    protected void Application_Start(object sender, EventArgs e)
    {
        Log.Info("Startup application.");
    }
}

4: Make sure you have permission to create files and folders on the given path (if the folder itself also doesn't exist)

5: The rest of your given information looks ok

How can I convert a Timestamp into either Date or DateTime object?

java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");

Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.

grep a tab in UNIX

A good choice is to use 'sed as grep' (as explained in this classical sed tutorial).

sed -n 's/pattern/&/p' file

Examples (works in bash, sh, ksh, csh,..):

[~]$ cat testfile
12 3
1 4 abc
xa      c
        a       c\2
1 23

[~]$ sed -n 's/\t/&/p' testfile 
xa      c
        a       c\2

[~]$ sed -n 's/\ta\t/&/p' testfile
        a       c\2

How do I find the date a video (.AVI .MP4) was actually recorded?

I used the following online tool: https://www.get-metadata.com It allows to upload a file and analyze it and then shows all its metadata.

Set attribute without value

The attr() function is also a setter function. You can just pass it an empty string.

$('body').attr('data-body','');

An empty string will simply create the attribute with no value.

<body data-body>

Reference - http://api.jquery.com/attr/#attr-attributeName-value

attr( attributeName , value )

Uint8Array to string in Javascript

I am using this Typescript snippet:

function UInt8ArrayToString(uInt8Array: Uint8Array): string
{
    var s: string = "[";
    for(var i: number = 0; i < uInt8Array.byteLength; i++)
    {
        if( i > 0 )
            s += ", ";
        s += uInt8Array[i];
    }
    s += "]";
    return s;
}

Remove the type annotations if you need the JavaScript version. Hope this helps!

Cannot issue data manipulation statements with executeQuery()

This code works for me: I set values whit an INSERT and get the LAST_INSERT_ID() of this value whit a SELECT; I use java NetBeans 8.1, MySql and java.JDBC.driver

                try {

        String Query = "INSERT INTO `stock`(`stock`, `min_stock`,   
                `id_stock`) VALUES ("

                + "\"" + p.get_Stock().getStock() + "\", "
                + "\"" + p.get_Stock().getStockMinimo() + "\","
                + "" + "null" + ")";

        Statement st = miConexion.createStatement();
        st.executeUpdate(Query);

        java.sql.ResultSet rs;
        rs = st.executeQuery("Select LAST_INSERT_ID() from stock limit 1");                
        rs.next(); //para posicionar el puntero en la primer fila
        ultimo_id = rs.getInt("LAST_INSERT_ID()");
        } catch (SqlException ex) { ex.printTrace;}

Java 8 stream reverse order

Answering specific question of reversing with IntStream, below worked for me:

IntStream.range(0, 10)
  .map(x -> x * -1)
  .sorted()
  .map(Math::abs)
  .forEach(System.out::println);

Javascript code for showing yesterday's date and todays date

Yesterday Date can be calculated as:-

let now = new Date();
    var defaultDate = now - 1000 * 60 * 60 * 24 * 1;
    defaultDate = new Date(defaultDate);

Variable used in lambda expression should be final or effectively final

if it is not necessary to modify the variable than a general workaround for this kind of problem would be to extract the part of code which use lambda and use final keyword on method-parameter.

Regular expression to get a string between two strings in Javascript

If the data is on multiple lines then you may have to use the following,

/My cow ([\s\S]*)milk/gm

My cow always gives 
milk

Regex 101 example

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

How to install packages offline?

If you want install python libs and their dependencies offline, finish following these steps on a machine with the same os, network connected, and python installed:

1) Create a requirements.txt file with similar content (Note - these are the libraries you wish to download):

Flask==0.12
requests>=2.7.0
scikit-learn==0.19.1
numpy==1.14.3
pandas==0.22.0

One option for creating the requirements file is to use pip freeze > requirements.txt. This will list all libraries in your environment. Then you can go in to requirements.txt and remove un-needed ones.

2) Execute command mkdir wheelhouse && pip download -r requirements.txt -d wheelhouse to download libs and their dependencies to directory wheelhouse

3) Copy requirements.txt into wheelhouse directory

4) Archive wheelhouse into wheelhouse.tar.gz with tar -zcf wheelhouse.tar.gz wheelhouse

Then upload wheelhouse.tar.gz to your target machine:

1) Execute tar -zxf wheelhouse.tar.gz to extract the files

2) Execute pip install -r wheelhouse/requirements.txt --no-index --find-links wheelhouse to install the libs and their dependencies

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

That's called SQL INJECTION. The ' tries to open/close a string in your mysql query. You should always escape any string that gets into your queries.

for example,

instead of this:

"VALUES ('$sender_id') "

do this:

"VALUES ('". mysql_real_escape_string($sender_id)  ."') "

(or equivalent, of course)

However, it's better to automate this, using PDO, named parameters, prepared statements or many other ways. Research about this and SQL Injection (here you have some techniques).

Hope it helps. Cheers

Send inline image in email

Some minimal c# code to embed an image, can be:

MailMessage mailWithImg = GetMailWithImg();
MySMTPClient.Send(mailWithImg); //* Set up your SMTPClient before!

private MailMessage GetMailWithImg() {
    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;
    mail.AlternateViews.Add(GetEmbeddedImage("c:/image.png"));
    mail.From = new MailAddress("yourAddress@yourDomain");
    mail.To.Add("recipient@hisDomain");
    mail.Subject = "yourSubject";
    return mail;
}

private AlternateView GetEmbeddedImage(String filePath) {
    LinkedResource res = new LinkedResource(filePath);
    res.ContentId = Guid.NewGuid().ToString();
    string htmlBody = @"<img src='cid:" + res.ContentId + @"'/>";
    AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
    alternateView.LinkedResources.Add(res);
    return alternateView;
}

Oracle DateTime in Where Clause?

This is because a DATE column in Oracle also contains a time part. The result of the to_date() function is a date with the time set to 00:00:00 and thus it probably doesn't match any rows in the table.

You should use:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE trunc(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')

MySQL OPTIMIZE all tables?

From command line:

mysqlcheck -o <db_name> -u<username> -p

then type password

How can I check if a value is a json object?

If you want to test explicitly for valid JSON (as opposed to the absence of the returned value false), then you can use a parsing approach as described here.

How to get character array from a string?

You can also use Array.from.

_x000D_
_x000D_
var m = "Hello world!";
console.log(Array.from(m))
_x000D_
_x000D_
_x000D_

This method has been introduced in ES6.

Reference

Array.from

os.walk without digging into directories below

The suggestion to use listdir is a good one. The direct answer to your question in Python 2 is root, dirs, files = os.walk(dir_name).next().

The equivalent Python 3 syntax is root, dirs, files = next(os.walk(dir_name))

How can I obtain the element-wise logical NOT of a pandas Series?

I just give it a shot:

In [9]: s = Series([True, True, True, False])

In [10]: s
Out[10]: 
0     True
1     True
2     True
3    False

In [11]: -s
Out[11]: 
0    False
1    False
2    False
3     True

Is there an auto increment in sqlite?

What you do is correct, but the correct syntax for 'auto increment' should be without space:

CREATE TABLE people (id integer primary key autoincrement, first_name string, last_name string);

(Please also note that I changed your varchars to strings. That's because SQLite internally transforms a varchar into a string, so why bother?)

then your insert should be, in SQL language as standard as possible:

INSERT INTO people(id, first_name, last_name) VALUES (null, 'john', 'doe');

while it is true that if you omit id it will automatically incremented and assigned, I personally prefer not to rely on automatic mechanisms which could change in the future.

A note on autoincrement: although, as many pointed out, it is not recommended by SQLite people, I do not like the automatic reuse of ids of deleted records if autoincrement is not used. In other words, I like that the id of a deleted record will never, ever appear again.

HTH

how get yesterday and tomorrow datetime in c#

You want DateTime.Today.AddDays(1).

How do I resolve a TesseractNotFoundError?

Under Windows 10 OS environment, the following method works for me:

  1. https://github.com/tesseract-ocr/tesseract/wiki Download tesseract and install it. Windows version is available here: https://github.com/UB-Mannheim/tesseract/wiki

  2. Find script file pytesseract.py from C:\Users\User\Anaconda3\Lib\site-packages\pytesseract and open it. Change the following code from tesseract_cmd = 'tesseract' to: tesseract_cmd = 'D:/Program Files (x86)/Tesseract-OCR/tesseract.exe'

  3. You may also need add environment variable D:/Program Files (x86)/Tesseract-OCR/

Hope it works for you!

Data at the root level is invalid

This:

doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));

should be:

doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));

LoadXml() is for loading an XML string, not a file name.

Jenkins: Is there any way to cleanup Jenkins workspace?

If you want to just remove one dir (or file) you can use Groovy and Manage Jenkins ? Scripts Console run a script which removes it.

For example, you can look at the files with:

dh = new File('./bitnami/jenkins/jenkins_home/workspace/jobname/folder')
dh.eachFile {
  println(it)
}

And then, when you have the folder you want to delete in dh, you could simply append the next code:

dh.deleteDir()

And it will be deleted.

Note: The path shown in the example is for a Bitnami Jenkins installation, yours could be different.

make an html svg object also a clickable link

To accomplish this in all browsers you need to use a combination of @energee, @Richard and @Feuermurmel methods.

<a href="" style="display: block; z-index: 1;">
    <object data="" style="z-index: -1; pointer-events: none;" />
</a>

Adding:

  • pointer-events: none; makes it work in Firefox.
  • display: block; gets it working in Chrome, and Safari.
  • z-index: 1; z-index: -1; makes it work in IE as well.

What is the difference between 'protected' and 'protected internal'?

protected can be used by any subclasses from any assembly.

protected internal is everything that protected is, plus also anything in the same assembly can access it.

Importantly, it doesn't mean "subclasses in the same assembly" - it is the union of the two, not the intersection.

Proper way to return JSON using node or Express

That response is a string too, if you want to send the response prettified, for some awkward reason, you could use something like JSON.stringify(anObject, null, 3)

It's important that you set the Content-Type header to application/json, too.

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);

// > {"a":1}

Prettified:

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }, null, 3));
});
app.listen(3000);

// >  {
// >     "a": 1
// >  }

I'm not exactly sure why you want to terminate it with a newline, but you could just do JSON.stringify(...) + '\n' to achieve that.

Express

In express you can do this by changing the options instead.

'json replacer' JSON replacer callback, null by default

'json spaces' JSON response spaces for formatting, defaults to 2 in development, 0 in production

Not actually recommended to set to 40

app.set('json spaces', 40);

Then you could just respond with some json.

res.json({ a: 1 });

It'll use the 'json spaces' configuration to prettify it.

compare differences between two tables in mysql

 select t1.user_id,t2.user_id 
 from t1 left join t2 ON t1.user_id = t2.user_id 
 and t1.username=t2.username 
 and t1.first_name=t2.first_name 
 and t1.last_name=t2.last_name

try this. This will compare your table and find all matching pairs, if any mismatch return NULL on left.

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

How do I stop/start a scheduled task on a remote computer programmatically?

Here's what I found.

stop:

schtasks /end /s <machine name> /tn <task name>

start:

schtasks /run /s <machine name> /tn <task name>


C:\>schtasks /?

SCHTASKS /parameter [arguments]

Description:
    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system. Replaces AT.exe.

Parameter List:
    /Create         Creates a new scheduled task.

    /Delete         Deletes the scheduled task(s).

    /Query          Displays all scheduled tasks.

    /Change         Changes the properties of scheduled task.

    /Run            Runs the scheduled task immediately.

    /End            Stops the currently running scheduled task.

    /?              Displays this help message.

Examples:
    SCHTASKS
    SCHTASKS /?
    SCHTASKS /Run /?
    SCHTASKS /End /?
    SCHTASKS /Create /?
    SCHTASKS /Delete /?
    SCHTASKS /Query  /?
    SCHTASKS /Change /?

Git merge error "commit is not possible because you have unmerged files"

You need to do two things. First add the changes with

git add .
git stash  

git checkout <some branch>

It should solve your issue as it solved to me.

Android: TextView: Remove spacing and padding on top and bottom

You can try to use this attribute(ConstraintLayout):layout_constraintBaseline_toBaselineOf

Like this:

app:layout_constraintBaseline_toBaselineOf="@+id/textView"

enter image description here

enter image description here

Imitating a blink tag with CSS3 animations

There's actually no need for visibility or opacity - you can simply use color, which has the upside of keeping any "blinking" to the text only:

_x000D_
_x000D_
blink {_x000D_
    display: inline;_x000D_
    color: inherit;_x000D_
    animation: blink 1s steps(1) infinite;_x000D_
    -webkit-animation: blink 1s steps(1) infinite;_x000D_
}_x000D_
@keyframes blink { 50% { color: transparent; } }_x000D_
@-webkit-keyframes blink { 50% { color: transparent; } }
_x000D_
Here is some text, <blink>this text will blink</blink>, this will not.
_x000D_
_x000D_
_x000D_

Fiddle: http://jsfiddle.net/2r8JL/

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

How to delete all files and folders in a folder by cmd call

Yes! Use Powershell:

powershell -Command "Remove-Item 'c:\destination\*' -Recurse -Force"

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

How to return a specific status code and no contents from Controller?

This code might work for non-.NET Core MVC controllers:

this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);

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

I've had the same issue too, I didn't remember to start my WAMPSERVER, and so the connection couldn't be made... All you need to do is to start or restart your WAMPSERVER or your XAMMP again and it will work....

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

I used this code,

 <div style="visibility:hidden">
    <audio autoplay loop>
        <source src="Aakaasam-Yemaaya Chesave.mp3">
    </audio> 
</div>

It is working well but i want stop and pause button. So, we can stop if we don't want to listen.

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

Find the most frequent number in a NumPy array

I like the solution by JoshAdel.

But there is just one catch.

The np.bincount() solution only works on numbers.

If you have strings, collections.Counter solution will work for you.

Checking if a variable is an integer in PHP

All $_GET parameters have a string datatype, therefore, is_int will always return false.

You can see this by calling var_dump:

var_dump($_GET['p']); // string(2) "54"

Using is_numeric will provide the desired result (mind you, that allows values such as: 0x24).

submitting a form when a checkbox is checked

$(document).ready(
    function()
    {
        $("input:checkbox").change(
            function()
            {
                if( $(this).is(":checked") )
                {
                    $("#formName").submit();
                }
            }
        )
    }
);

Though it would probably be better to add classes to each of the checkboxes and do

$(".checkbox_class").change();

so that you can choose which checkboxes submit the form instead of all of them doing it.

How to remove underline from a name on hover

To keep the color and prevent an underline on the link:

legend.green-color a{
    color:green;
    text-decoration: none;
}

Python argparse: default value or specified value

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int

If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

then

% test.py 
Namespace(example=1)

How to debug Spring Boot application with Eclipse?

How to debug a remote staging or production Spring Boot application

Server-side

Let's assume you have successfully followed Spring Boot's guide on setting up your Spring Boot application as a service. Your application artifact resides in /srv/my-app/my-app.war, accompanied by a configuration file /srv/my-app/my-app.conf:

# This is file my-app.conf
# What can you do in this .conf file? The my-app.war is prepended with a SysV init.d script
# (yes, take a look into the war file with a text editor). As my-app.war is symlinked in the init.d directory, that init.d script
# gets executed. One of its step is actually `source`ing this .conf file. Therefore we can do anything in this .conf file that
# we can also do in a regular shell script.

JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,address=localhost:8002,server=y,suspend=n"
export SPRING_PROFILES_ACTIVE=staging

When you restart your Spring Boot application with sudo service my-app restart, then in its log file located at /var/log/my-app.log should be a line saying Listening for transport dt_socket at address: 8002.

Client-side (developer machine)

Open an SSH port-forwarding tunnel to the server: ssh -L 8002:localhost:8002 [email protected]. Keep this SSH session running.

In Eclipse, from the toolbar, select Run -> Debug Configurations -> select Remote Java Application -> click the New button -> select as Connection Type Standard (Socket Attach), as Host localhost, and as Port 8002 (or whatever you have configured in the steps before). Click Apply and then Debug.

The Eclipse debugger should now connect to the remote server. Switching to the Debug perspective should show the connected JVM and its threads. Breakpoints should fire as soon as they are remotely triggered.

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

python .replace() regex

No. Regular expressions in Python are handled by the re module.

article = re.sub(r'(?is)</html>.+', '</html>', article)

In general:

text_after = re.sub(regex_search_term, regex_replacement, text_before)

How to pass arguments to Shell Script through docker run

There are a few things interacting here:

  1. docker run your_image arg1 arg2 will replace the value of CMD with arg1 arg2. That's a full replacement of the CMD, not appending more values to it. This is why you often see docker run some_image /bin/bash to run a bash shell in the container.

  2. When you have both an ENTRYPOINT and a CMD value defined, docker starts the container by concatenating the two and running that concatenated command. So if you define your entrypoint to be file.sh, you can now run the container with additional args that will be passed as args to file.sh.

  3. Entrypoints and Commands in docker have two syntaxes, a string syntax that will launch a shell, and a json syntax that will perform an exec. The shell is useful to handle things like IO redirection, chaining multiple commands together (with things like &&), variable substitution, etc. However, that shell gets in the way with signal handling (if you've ever seen a 10 second delay to stop a container, this is often the cause) and with concatenating an entrypoint and command together. If you define your entrypoint as a string, it would run /bin/sh -c "file.sh", which alone is fine. But if you have a command defined as a string too, you'll see something like /bin/sh -c "file.sh" /bin/sh -c "arg1 arg2" as the command being launched inside your container, not so good. See the table here for more on how these two options interact

  4. The shell -c option only takes a single argument. Everything after that would get passed as $1, $2, etc, to that single argument, but not into an embedded shell script unless you explicitly passed the args. I.e. /bin/sh -c "file.sh $1 $2" "arg1" "arg2" would work, but /bin/sh -c "file.sh" "arg1" "arg2" would not since file.sh would be called with no args.

Putting that all together, the common design is:

FROM ubuntu:14.04
COPY ./file.sh /
RUN chmod 755 /file.sh
# Note the json syntax on this next line is strict, double quotes, and any syntax
# error will result in a shell being used to run the line.
ENTRYPOINT ["file.sh"]

And you then run that with:

docker run your_image arg1 arg2

There's a fair bit more detail on this at:

How can I parse a time string containing milliseconds in it with python?

I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.

The solution if datetime doesn't support %f and without needing a try/except is:

    (dt, mSecs) = row[5].strip().split(".") 
    dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
    mSeconds = datetime.timedelta(microseconds = int(mSecs))
    fullDateTime = dt + mSeconds 

This works for the input string "2010-10-06 09:42:52.266000"

Check to see if python script is running

I'm a big fan of Supervisor for managing daemons. It's written in Python, so there are plenty of examples of how to interact with or extend it from Python. For your purposes the XML-RPC process control API should work nicely.