Programs & Examples On #Armv6

Questions related to ARMv6 Architecture. ARMv6 architecture introduced Thumb-2, TrustZone and SIMD support. ARM11 series of processors are based on ARMv6 architecture.

How to install the Raspberry Pi cross compiler on my Linux host machine?

You may use clang as well. It used to be faster than GCC, and now it is quite a stable thing. It is much easier to build clang from sources (you can really drink cup of coffee during build process).

In short:

  1. Get clang binaries (sudo apt-get install clang).. or download and build (read instructions here)
  2. Mount your raspberry rootfs (it may be the real rootfs mounted via sshfs, or an image).
  3. Compile your code:

    path/to/clang --target=arm-linux-gnueabihf --sysroot=/some/path/arm-linux-gnueabihf/sysroot my-happy-program.c -fuse-ld=lld
    

Optionally you may use legacy arm-linux-gnueabihf binutils. Then you may remove "-fuse-ld=lld" flag at the end.

Below is my cmake toolchain file.

toolchain.cmake

set(CMAKE_SYSTEM_VERSION 1)
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)

# Custom toolchain-specific definitions for your project
set(PLATFORM_ARM "1")
set(PLATFORM_COMPILE_DEFS "COMPILE_GLES")

# There we go!
# Below, we specify toolchain itself!

set(TARGET_TRIPLE arm-linux-gnueabihf)

# Specify your target rootfs mount point on your compiler host machine
set(TARGET_ROOTFS /Volumes/rootfs-${TARGET_TRIPLE})

# Specify clang paths
set(LLVM_DIR /Users/stepan/projects/shared/toolchains/llvm-7.0.darwin-release-x86_64/install)
set(CLANG ${LLVM_DIR}/bin/clang)
set(CLANGXX ${LLVM_DIR}/bin/clang++)

# Specify compiler (which is clang)
set(CMAKE_C_COMPILER   ${CLANG})
set(CMAKE_CXX_COMPILER ${CLANGXX})

# Specify binutils

set (CMAKE_AR      "${LLVM_DIR}/bin/llvm-ar" CACHE FILEPATH "Archiver")
set (CMAKE_LINKER  "${LLVM_DIR}/bin/llvm-ld" CACHE FILEPATH "Linker")
set (CMAKE_NM      "${LLVM_DIR}/bin/llvm-nm" CACHE FILEPATH "NM")
set (CMAKE_OBJDUMP "${LLVM_DIR}/bin/llvm-objdump" CACHE FILEPATH "Objdump")
set (CMAKE_RANLIB  "${LLVM_DIR}/bin/llvm-ranlib" CACHE FILEPATH "ranlib")

# You may use legacy binutils though.
#set(BINUTILS /usr/local/Cellar/arm-linux-gnueabihf-binutils/2.31.1)
#set (CMAKE_AR      "${BINUTILS}/bin/${TARGET_TRIPLE}-ar" CACHE FILEPATH "Archiver")
#set (CMAKE_LINKER  "${BINUTILS}/bin/${TARGET_TRIPLE}-ld" CACHE FILEPATH "Linker")
#set (CMAKE_NM      "${BINUTILS}/bin/${TARGET_TRIPLE}-nm" CACHE FILEPATH "NM")
#set (CMAKE_OBJDUMP "${BINUTILS}/bin/${TARGET_TRIPLE}-objdump" CACHE FILEPATH "Objdump")
#set (CMAKE_RANLIB  "${BINUTILS}/bin/${TARGET_TRIPLE}-ranlib" CACHE FILEPATH "ranlib")

# Specify sysroot (almost same as rootfs)
set(CMAKE_SYSROOT ${TARGET_ROOTFS})
set(CMAKE_FIND_ROOT_PATH ${TARGET_ROOTFS})

# Specify lookup methods for cmake
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

# Sometimes you also need this:
# set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)

# Specify raspberry triple
set(CROSS_FLAGS "--target=${TARGET_TRIPLE}")

# Specify other raspberry related flags
set(RASP_FLAGS "-D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS")

# Gather and distribute flags specified at prev steps.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")

# Use clang linker. Why?
# Well, you may install custom arm-linux-gnueabihf binutils,
# but then, you also need to recompile clang, with customized triple;
# otherwise clang will try to use host 'ld' for linking,
# so... use clang linker.
set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld)

"Warning: iPhone apps should include an armv6 architecture" even with build config set

In addition to Nick's answer about Xcode 4.2, you may also need to review your info.plist file. It seems as if new projects started in Xcode 4.2 by default specify 'armv7' in the 'Required Device Capabilities'. You'll need to remove this if wanting to support devices that run armv6 (e.g. the iPhone 3G).

enter image description here

Delete armv7 from the 'Required device capabilities' in yourProjectName-Info.plist

Build fat static library (device + simulator) using Xcode and SDK 4+

I needed a fat static lib for JsonKit so created a static lib project in Xcode and then ran this bash script in the project directory. So long as you've configured the xcode project with "Build active configuration only" turned off, you should get all architectures in one lib.

#!/bin/bash
xcodebuild -sdk iphoneos
xcodebuild -sdk iphonesimulator
lipo -create -output libJsonKit.a build/Release-iphoneos/libJsonKit.a build/Release-iphonesimulator/libJsonKit.a

How do you rotate a two dimensional array?

Based on the plethora of other answers, I came up with this in C#:

/// <param name="rotation">The number of rotations (if negative, the <see cref="Matrix{TValue}"/> is rotated counterclockwise; 
/// otherwise, it's rotated clockwise). A single (positive) rotation is equivalent to 90° or -270°; a single (negative) rotation is 
/// equivalent to -90° or 270°. Matrices may be rotated by 90°, 180°, or 270° only (or multiples thereof).</param>
/// <returns></returns>
public Matrix<TValue> Rotate(int rotation)
{
    var result = default(Matrix<TValue>);

    //This normalizes the requested rotation (for instance, if 10 is specified, the rotation is actually just +-2 or +-180°, but all 
    //correspond to the same rotation).
    var d = rotation.ToDouble() / 4d;
    d = d - (int)d;

    var degree = (d - 1d) * 4d;

    //This gets the type of rotation to make; there are a total of four unique rotations possible (0°, 90°, 180°, and 270°).
    //Each correspond to 0, 1, 2, and 3, respectively (or 0, -1, -2, and -3, if in the other direction). Since
    //1 is equivalent to -3 and so forth, we combine both cases into one. 
    switch (degree)
    {
        case -3:
        case +1:
            degree = 3;
            break;
        case -2:
        case +2:
            degree = 2;
            break;
        case -1:
        case +3:
            degree = 1;
            break;
        case -4:
        case  0:
        case +4:
            degree = 0;
            break;
    }
    switch (degree)
    {
        //The rotation is 0, +-180°
        case 0:
        case 2:
            result = new TValue[Rows, Columns];
            break;
        //The rotation is +-90°
        case 1:
        case 3:
            result = new TValue[Columns, Rows];
            break;
    }

    for (uint i = 0; i < Columns; ++i)
    {
        for (uint j = 0; j < Rows; ++j)
        {
            switch (degree)
            {
                //If rotation is 0°
                case 0:
                    result._values[j][i] = _values[j][i];
                    break;
                //If rotation is -90°
                case 1:
                    //Transpose, then reverse each column OR reverse each row, then transpose
                    result._values[i][j] = _values[j][Columns - i - 1];
                    break;
                //If rotation is +-180°
                case 2:
                    //Reverse each column, then reverse each row
                    result._values[(Rows - 1) - j][(Columns - 1) - i] = _values[j][i];
                    break;
                //If rotation is +90°
                case 3:
                    //Transpose, then reverse each row
                    result._values[i][j] = _values[Rows - j - 1][i];
                    break;
            }
        }
    }
    return result;
}

Where _values corresponds to a private two-dimensional array defined by Matrix<TValue> (in the form of [][]). result = new TValue[Columns, Rows] is possible via implicit operator overload and converts the two-dimensional array to Matrix<TValue>. The two properties Columns and Rows are public properties that get the number of columns and rows of the current instance:

public uint Columns 
    => (uint)_values[0].Length;

public uint Rows 
    => (uint)_values.Length;

Assuming, of course, that you prefer to work with unsigned indices ;-)

All of this allows you to specify how many times it should be rotated and whether it should be rotated left (if less than zero) or right (if greater than zero). You can improve this to check for rotation in actual degrees, but then you'd want to throw an exception if the value isn't a multiple of 90. With that input, you could change the method accordingly:

public Matrix<TValue> Rotate(int rotation)
{
    var _rotation = (double)rotation / 90d;

    if (_rotation - Math.Floor(_rotation) > 0)
    {
        throw new NotSupportedException("A matrix may only be rotated by multiples of 90.").
    }

    rotation = (int)_rotation;
    ...
}

Since a degree is more accurately expressed by double than int, but a matrix can only rotate in multiples of 90, it is far more intuitive to make the argument correspond to something else that can be accurately represented by the data structure used. int is perfect because it can tell you how many times to rotate it up to a certain unit (90) as well as the direction. double may very well be able to tell you that also, but it also includes values that aren't supported by this operation (which is inherently counter-intuitive).

How do I ignore all files in a folder with a Git repository in Sourcetree?

After beating my head on this for at least an hour, I offer this answer to try to expand on the comments some others have made. To ignore a folder/directory, do the following: if you don't have a .gitignore file in the root of your project (that name exactly ".gitignore"), create a dummy text file in the folder you want to exclude. Inside of Source Tree, right click on it and select Ignore. You'll get a popup that looks like this.

enter image description here

Select "Everything underneath" and select the folder you want to ignore from the drop-down list. This will create a .gitignore file in your root directory and put the folder specification in it.

If you do have a .gitignore folder already in your root folder, you could follow the same approach above, or you can just edit the .gitignore file and add the folder you want to exclude. It's just a text file. Note that it uses forward slashes in path names rather than backslashes, as we Windows users are accustomed to. I tried creating a .gitignore text file by hand in Windows Explorer, but it didn't let me create a file without a name (i.e. with only the extension).

Note that adding the .gitignore and the file specification will have no effect on files that are already being tracked. If you're already tracking these, you'll have to stop tracking them. (Right-click on the folder or file and select Stop Tracking.) You'll then see them change from having a green/clean or amber/changed icon to a red/removed icon. On your next commit the files will be removed from the repository and thereafter appear with a blue/ignored icon. Another contributor asked why Ignore was disabled for particular files and I believe it was because he was trying to ignore a file that was already being tracked. You can only ignore a file that has a blue question mark icon.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

How to read a PEM RSA private key from .NET

With respect to easily importing the RSA private key, without using 3rd party code such as BouncyCastle, I think the answer is "No, not with a PEM of the private key alone."

However, as alluded to above by Simone, you can simply combine the PEM of the private key (*.key) and the certificate file using that key (*.crt) into a *.pfx file which can then be easily imported.

To generate the PFX file from the command line:

openssl pkcs12 -in a.crt -inkey a.key -export -out a.pfx

Then use normally with the .NET certificate class such as:

using System.Security.Cryptography.X509Certificates;

X509Certificate2 combinedCertificate = new X509Certificate2(@"C:\path\to\file.pfx");

Now you can follow the example from MSDN for encrypting and decrypting via RSACryptoServiceProvider:

I left out that for decrypting you would need to import using the PFX password and the Exportable flag. (see: BouncyCastle RSAPrivateKey to .NET RSAPrivateKey)

X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;
X509Certificate2 cert = new X509Certificate2("my.pfx", "somepass", flags);

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
RSAParameters rsaParam = rsa.ExportParameters(true); 

how to remove css property using javascript?

actually, if you already know the property, this will do it...

for example:

<a href="test.html" style="color:white;zoom:1.2" id="MyLink"></a>

    var txt = "";
    txt = getStyle(InterTabLink);
    setStyle(InterTabLink, txt.replace("zoom\:1\.2\;","");

    function setStyle(element, styleText){
        if(element.style.setAttribute)
            element.style.setAttribute("cssText", styleText );
        else
            element.setAttribute("style", styleText );
    }

    /* getStyle function */
    function getStyle(element){
        var styleText = element.getAttribute('style');
        if(styleText == null)
            return "";
        if (typeof styleText == 'string') // !IE
            return styleText;
        else  // IE
            return styleText.cssText;
    } 

Note that this only works for inline styles... not styles you've specified through a class or something like that...

Other note: you may have to escape some characters in that replace statement, but you get the idea.

how to load url into div tag

<html>
<head>
<script type="text/javascript">
    $(document).ready(function(){
    $("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content"></div>
</body>
</html>

Formula px to dp, dp to px android

You can use [DisplayMatrics][1] and determine the screen density. Something like this:

int pixelsValue = 5; // margin in pixels
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(pixelsValue * d);

As I remember it's better to use flooring for offsets and rounding for widths.

Set cookies for cross origin requests

Pim's answer is very helpful. In my case, I have to use

Expires / Max-Age: "Session"

If it is a dateTime, even it is not expired, it still won't send the cookie to the backend:

Expires / Max-Age: "Thu, 21 May 2020 09:00:34 GMT"

Hope it is helpful for future people who may meet same issue.

Yii2 data provider default sorting

Try to this one

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

$sort = $dataProvider->getSort();

$sort->defaultOrder = ['id' => SORT_ASC];

$dataProvider->setSort($sort);

Set Focus After Last Character in Text Box

This works fine for me . [Ref: the very nice plug in by Gavin G]

(function($){
    $.fn.focusTextToEnd = function(){
        this.focus();
        var $thisVal = this.val();
        this.val('').val($thisVal);
        return this;
    }
}(jQuery));

$('#mytext').focusTextToEnd();

Redirect non-www to www in .htaccess

Write in .htaccess :)

## Redirect from non-www to www (remove the two lines below to enable)
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

How to get Tensorflow tensor dimensions (shape) as int values?

2.0 Compatible Answer: In Tensorflow 2.x (2.1), you can get the dimensions (shape) of the tensor as integer values, as shown in the Code below:

Method 1 (using tf.shape):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.shape.as_list()
print(Shape)   # [2,3]

Method 2 (using tf.get_shape()):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.get_shape().as_list()
print(Shape)   # [2,3]

Selecting data from two different servers in SQL Server

Querying across 2 different databases is a distributed query. Here is a list of some techniques plus the pros and cons:

  1. Linked servers: Provide access to a wider variety of data sources than SQL Server replication provides
  2. Linked servers: Connect with data sources that replication does not support or which require ad hoc access
  3. Linked servers: Perform better than OPENDATASOURCE or OPENROWSET
  4. OPENDATASOURCE and OPENROWSET functions: Convenient for retrieving data from data sources on an ad hoc basis. OPENROWSET has BULK facilities as well that may/may not require a format file which might be fiddley
  5. OPENQUERY: Doesn't support variables
  6. All are T-SQL solutions. Relatively easy to implement and set up
  7. All are dependent on connection between source and destionation which might affect performance and scalability

Boolean vs tinyint(1) for boolean values in MySQL

boolean isn't a distinct datatype in MySQL; it's just a synonym for tinyint. See this page in the MySQL manual.

Personally I would suggest use tinyint as a preference, because boolean doesn't do what you think it does from the name, so it makes for potentially misleading code. But at a practical level, it really doesn't matter -- they both do the same thing, so you're not gaining or losing anything by using either.

How to get root view controller?

if you are trying to access the rootViewController you set in your appDelegate. try this:

Objective-C

YourViewController *rootController = (YourViewController*)[[(YourAppDelegate*)
                                   [[UIApplication sharedApplication]delegate] window] rootViewController];

Swift

let appDelegate  = UIApplication.sharedApplication().delegate as AppDelegate
let viewController = appDelegate.window!.rootViewController as YourViewController

Swift 3

let appDelegate  = UIApplication.shared.delegate as! AppDelegate
let viewController = appDelegate.window!.rootViewController as! YourViewController

Swift 4 & 4.2

let viewController = UIApplication.shared.keyWindow!.rootViewController as! YourViewController

Swift 5 & 5.1 & 5.2

let viewController = UIApplication.shared.windows.first!.rootViewController as! YourViewController

How do I copy to the clipboard in JavaScript?

This solution was found here. The document.execCommand("copy"); is not supported on Internet Explorer 8 and earlier.

_x000D_
_x000D_
const copyBtn =  document.getElementById("copyBtn");
const input = document.getElementById("input");

function copyText() {
  const value = input.value;
  
  input.select(); // selects the input variable as the text to be copied
  input.setSelectionRange(0, 99999); // this is used to set the selection range for mobile devices
  
  document.execCommand("copy"); // copies the selected text
  
  alert("Copied the text " + value); // displays the copied text in a prompt
}

copyBtn.onmousedown = function () {
  copyText();
}
_x000D_
<input type="text" id="input" placeholder="Type text to copy... "/>
<button id="copyBtn">
  Copy
</button>
_x000D_
_x000D_
_x000D_

Remove the newline character in a list read from a file

You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.

See http://docs.python.org/release/2.3/lib/module-string.html

How to create jar file with package structure?

Step 1: Go to directory where the classes are kept using command prompt (or Linux shell prompt)
Like for Project.
C:/workspace/MyProj/bin/classess/com/test/*.class

Go directory bin using command:

cd C:/workspace/MyProj/bin

Step 2: Use below command to generate jar file.

jar cvf helloworld.jar com\test\hello\Hello.class  com\test\orld\HelloWorld.class

Using the above command the classes will be placed in a jar in a directory structure.

Understanding repr( ) function in Python

>>> x = 'foo'
>>> x
'foo'

So the name x is attached to 'foo' string. When you call for example repr(x) the interpreter puts 'foo' instead of x and then calls repr('foo').

>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"

repr actually calls a magic method __repr__ of x, which gives the string containing the representation of the value 'foo' assigned to x. So it returns 'foo' inside the string "" resulting in "'foo'". The idea of repr is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr.

>>> eval("'foo'")
'foo'

When we call eval("'foo'"), it's the same as we type 'foo' in the interpreter. It's as we directly type the contents of the outer string "" in the interpreter.

>>> eval('foo')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    eval('foo')
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined

If we call eval('foo'), it's the same as we type foo in the interpreter. But there is no foo variable available and an exception is raised.

>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>> 

str is just the string representation of the object (remember, x variable refers to 'foo'), so this function returns string.

>>> str(5)
'5'

String representation of integer 5 is '5'.

>>> str('foo')
'foo'

And string representation of string 'foo' is the same string 'foo'.

Change directory command in Docker?

You can run a script, or a more complex parameter to the RUN. Here is an example from a Dockerfile I've downloaded to look at previously:

RUN cd /opt && unzip treeio.zip && mv treeio-master treeio && \
    rm -f treeio.zip && cd treeio && pip install -r requirements.pip

Because of the use of '&&', it will only get to the final 'pip install' command if all the previous commands have succeeded.

In fact, since every RUN creates a new commit & (currently) an AUFS layer, if you have too many commands in the Dockerfile, you will use up the limits, so merging the RUNs (when the file is stable) can be a very useful thing to do.

pip install returning invalid syntax

You need to be in the specific folder where pip.exe exists, then do the following steps:

  1. open cmd.exe
  2. write the following command:
    cd "The path to the python folder"

or in my case, i wrote

    cd C:\Users\username\AppData\Local\Programs\Python\Python37-32\Scripts
  1. then write the following command
    pip install *anypackage*

How to convert Nvarchar column to INT

Your CAST() looks correct.

Your CONVERT() is not correct. You are quoting the column as a string. You will want something like

CONVERT(INT, A.my_NvarcharColumn)

** notice without the quotes **

The only other reason why this could fail is if you have a non-numeric character in the field value or if it's out of range.

You can try something like the following to verify it's numeric and return a NULL if it's not:

SELECT
 CASE
  WHEN ISNUMERIC(A.my_NvarcharColumn) = 1 THEN CONVERT(INT, A.my_NvarcharColumn)
  ELSE NULL
 END AS my_NvarcharColumn

Returning JSON from a PHP Script

Yeah, you'll need to use echo to display output. Mimetype: application/json

pandas unique values multiple columns

list(set(df[['Col1', 'Col2']].as_matrix().reshape((1,-1)).tolist()[0]))

The output will be ['Mary', 'Joe', 'Steve', 'Bob', 'Bill']

Compiler error "archive for required library could not be read" - Spring Tool Suite

In my case I had to manually delete all the files in .m2\repository folder and then open command prompt and run mvn -install command in my project directory.

ReactJS and images in public folder

the react docs explain this nicely in the documentation, you have to use process.env.PUBLIC_URL with images placed in the public folder. See here for more info

return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

You can use json_decode(Your variable Name):

json_decode($result)

I was getting value from Model.where a column has value like this way

{"dayList":[
            {"day":[1,2,3,4],"time":[{"in_time":"10:00"},{"late_time":"15:00"},{"out_time":"16:15"}]
             },
             {"day":[5,6,7],"time":[{"in_time":"10:00"},{"late_time":"15:00"},{"out_time":"16:15"}]}
           ]
}

so access this value form model. you have to use this code.

$dayTimeListObject = json_decode($settingAttendance->bio_attendance_day_time,1);

 foreach ( $dayTimeListObject['dayList'] as $dayListArr)
 {
     foreach ( $dayListArr['day'] as $dayIndex)
     {
         if( $dayIndex == Date('w',strtotime('2020-02-11')))
         {
             $dayTimeList= $dayListArr['time'];
         }
     }
 }

 return $dayTimeList[2]['out_time'] ;

You can also define caste in your Model file.

 protected $casts = [
    'your-column-name' => 'json'
  ];

so after this no need of this line .

$dayTimeListObject = json_decode($settingAttendance->bio_attendance_day_time,1);

you can directly access this code.

$settingAttendance->bio_attendance_day_time

Difference between @Mock and @InjectMocks

In your test class, the tested class should be annotated with @InjectMocks. This tells Mockito which class to inject mocks into:

@InjectMocks
private SomeManager someManager;

From then on, we can specify which specific methods or objects inside the class, in this case, SomeManager, will be substituted with mocks:

@Mock
private SomeDependency someDependency;

In this example, SomeDependency inside the SomeManager class will be mocked.

Generate preview image from Video file?

Two ways come to mind:

  • Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that

  • Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.

Unable to preventDefault inside passive event listener

For me

document.addEventListener("mousewheel", this.mousewheel.bind(this), { passive: false });

did the trick (the { passive: false } part).

jQuery window scroll event does not fire up

To whom its just not working to (like me) no matter what you tried: <element onscroll="myFunction()"></element> works like a charm

exactly as they explain in W3 schools https://www.w3schools.com/tags/ev_onscroll.asp

command/usr/bin/codesign failed with exit code 1- code sign error

Today, 2020 year, I've solved this problem with Xcode 11.7, Xcode 12.0 and Xcode 12.1 following these steps:

Identifying the bad certificate:

  • From you Keychains select Login
  • From Category select Certificates
  • Find any Apple Certificate that has the blue +
  • Double click on the certificate.
  • Expand the Trust

If it's messed up then the "When using this certificate" is set to "Always Trust" along with the blue +

Fixing the bad certificate:

  • Just set it to "Use System Defaults" and close it.
  • You'll get a pop up. Type in your password to update settings.
  • Close KeyChain.
  • Go back to your project, clean and run.

Problem should have gone away. If that didn't work then go back to Keychain and just double check and see if there are any other Apple certificates that are set to Always Trust and repeat the process.

Move textfield when keyboard appears swift

The best way is using NotificationCenter to catch keyboard actions. You can follow the steps in this short article https://medium.com/@demirciy/keyboard-handling-deb1a96a8207

How to sum the values of one column of a dataframe in spark/scala

Using spark sql query..just incase if it helps anyone!

import org.apache.spark.sql.SparkSession 
import org.apache.spark.SparkConf 
import org.apache.spark.sql.functions._ 
import org.apache.spark.SparkContext 
import java.util.stream.Collectors

val conf = new SparkConf().setMaster("local[2]").setAppName("test")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5, 6, 7)).toDF()

df.createOrReplaceTempView("steps")
val sum = spark.sql("select  sum(steps) as stepsSum from steps").map(row => row.getAs("stepsSum").asInstanceOf[Long]).collect()(0)
println("steps sum = " + sum) //prints 28

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

If you have other parameters in the query, beyond the IN list, then the following extension to JG's answer may be useful.

ids = [1, 5, 7, 213]
sql = "select * from person where type=%s and id in (%s)"
in_ids = ', '.join(map(lambda x: '%s', ids))
sql = sql % ('%s', in_ids)
params = []
params.append(type)
params.extend(ids)
cursor.execute(sql, tuple(params))

That is, join all the params in a linear array, then pass it as a tuple to the execute method.

Capturing count from an SQL query

Complementing in C# with SQL:

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
    lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
    lblCount.Text = "0";
}
conn.Close(); //Remember close the connection

Html/PHP - Form - Input as array

in addition: for those who have a empty POST variable, don't use this:

name="[levels][level][]"

rather use this (as it is already here in this example):

name="levels[level][]"

Initial bytes incorrect after Java AES/CBC decryption

Looks to me like you are not dealing properly with your Initialization Vector (IV). It's been a long time since I last read about AES, IVs and block chaining, but your line

IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());

does not seem to be OK. In the case of AES, you can think of the initialization vector as the "initial state" of a cipher instance, and this state is a bit of information that you can not get from your key but from the actual computation of the encrypting cipher. (One could argue that if the IV could be extracted from the key, then it would be of no use, as the key is already given to the cipher instance during its init phase).

Therefore, you should get the IV as a byte[] from the cipher instance at the end of your encryption

  cipherOutputStream.close();
  byte[] iv = encryptCipher.getIV();

and you should initialize your Cipher in DECRYPT_MODE with this byte[] :

  IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

Then, your decryption should be OK. Hope this helps.

CFNetwork SSLHandshake failed iOS 9

If your backend uses a secure connection ant you get using NSURLSession

CFNetwork SSLHandshake failed (-9801)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)

you need to check your server configuration especially to get ATS version and SSL certificate Info:

Instead of just Allowing Insecure Connection by setting NSExceptionAllowsInsecureHTTPLoads = YES , instead you need to Allow Lowered Security in case your server do not meet the min requirement (v1.2) for ATS (or better to fix server side).

Allowing Lowered Security to a Single Server

<key>NSExceptionDomains</key>
<dict>
    <key>api.yourDomaine.com</key>
    <dict>
        <key>NSExceptionMinimumTLSVersion</key>
        <string>TLSv1.0</string>
        <key>NSExceptionRequiresForwardSecrecy</key>
        <false/>
    </dict>
</dict>

use openssl client to investigate certificate and get your server configuration using openssl client :

openssl s_client  -connect api.yourDomaine.com:port //(you may need to specify port or  to try with https://... or www.)

..find at the end

SSL-Session:
    Protocol  : TLSv1
    Cipher    : AES256-SHA
    Session-ID: //
    Session-ID-ctx: 
    Master-Key: //
    Key-Arg   : None
    Start Time: 1449693038
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)

App Transport Security (ATS) require Transport Layer Security (TLS) protocol version 1.2.

Requirements for Connecting Using ATS:

The requirements for a web service connection to use App Transport Security (ATS) involve the server, connection ciphers, and certificates, as follows:

Certificates must be signed with one of the following types of keys:

  • Secure Hash Algorithm 2 (SHA-2) key with a digest length of at least 256 (that is, SHA-256 or greater)

  • Elliptic-Curve Cryptography (ECC) key with a size of at least 256 bits

  • Rivest-Shamir-Adleman (RSA) key with a length of at least 2048 bits An invalid certificate results in a hard failure and no connection.

The following connection ciphers support forward secrecy (FS) and work with ATS:

TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

Update: it turns out that openssl only provide the minimal protocol version Protocol : TLSv1 links

Sort a list of lists with a custom compare function

Since the OP was asking for using a custom compare function (and this is what led me to this question as well), I want to give a solid answer here:

Generally, you want to use the built-in sorted() function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.

How the custom comparator works

When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):

  • return a negative value (< 0) when the left item should be sorted before the right item
  • return a positive value (> 0) when the left item should be sorted after the right item
  • return 0 when both the left and the right item have the same weight and should be ordered "equally" without precedence

In the particular case of the OP's question, the following custom compare function can be used:

def compare(item1, item2):
    return fitness(item1) - fitness(item2)

Using the minus operation is a nifty trick because it yields to positive values when the weight of left item1 is bigger than the weight of the right item2. Hence item1 will be sorted after item2.

If you want to reverse the sort order, simply reverse the subtraction: return fitness(item2) - fitness(item1)

Calling sorted() in Python 2

sorted(mylist, cmp=compare)

or:

sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))

Calling sorted() in Python 3

from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))

or:

from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))

What is the equivalent to getLastInsertId() in Cakephp?

This is interesting, I also stumbled upon this issue. What you asked perhaps how to get the last ID of a certain model regardless of it's state, whether it's just been inserted or not. To further understand what getInsertID does, we need to take a look at the source:

Link 1: http://api20.cakephp.org/view_source/model#line-3375

public function getInsertID() {
  return $this->_insertID
}

Yup, that's the only piece of code inside that function. It means that cakephp caches any last inserted ID, instead of retrieve it from the database. That's why you get nothing if you use that function when you haven't done any record creation on the model.

I made a small function to get the last ID of a certain table, but please note that this should not be used as a replacement of getLastID() or getLastInsertID(), since it has an entirely different purpose.

Add the function lastID() to the AppModel as shown below so that it can be used system wide. It has it's limit, which can't be used on model with composite primary key.

class AppModel extends Model {
  public function lastID() {
    $data = $this->find('first', 
      array(
        'order' => array($this->primaryKey . ' DESC'),
        'fields' => array($this->primaryKey)
      )
    );

    return $data[$this->name][$this->primaryKey];
  }
}

Original Source : Class Model

What is the format specifier for unsigned short int?

Try using the "%h" modifier:

scanf("%hu", &length);
        ^

ISO/IEC 9899:201x - 7.21.6.1-7

Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.

What does $1 [QSA,L] mean in my .htaccess file?

Not the place to give a complete tutorial, but here it is in short;

RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

L means if the rule matches, don't process any more RewriteRules below this one.

For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

Mongoose's find method with $or condition does not work properly

According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."

So add indexes for your other fields and it will work. I had a similar problem and this solved it.

You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/

Get page title with Selenium WebDriver using Java

You can do it easily by Assertion using Selenium Testng framework.

Steps:

1.Create Firefox browser session

2.Initialize expected title name.

3.Navigate to "www.google.com" [As per you requirement, you can change] and wait for some time (15 seconds) to load the page completely.

4.Get the actual title name using "driver.getTitle()" and store it in String variable.

5.Apply the Assertion like below, Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle ),"Page title name not matched or Problem in loading grid");

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.myapplication.Utilty;

public class PageTitleVerification
{   
private static WebDriver driver = new FirefoxDriver();

@Test
public void test01_GooglePageTitleVerify()
{               
driver.navigate().to("https://www.google.com/");
String expectedGooglePageTitle = "Google";      
Utility.waitForElementInDOM(driver, "Google Search", 15);   
//Get page title
String actualGooglePageTitlte=driver.getTitle();
System.out.println("Google page title" + actualGooglePageTitlte);   
//Verify expected page title and actual page title is same  
Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle 
),"Page title not matched or Problem in loading url page");     
}
}

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Utility {

/*Wait for an element to be present in DOM before specified time (in seconds ) has 
elapsed */
public static void waitForElementInDOM(WebDriver driver,String elementIdentifier, 
long timeOutInSeconds) 
{       
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds        
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier))); 
}
catch(NoSuchElementException e)
{           
e.printStackTrace();
}           
}
}

WCF error: The caller was not authenticated by the service

I was able to resolve the shared issue by following below steps:

  1. Go to IIS-->Sites-->Your Site-->
  2. Features View Pane-->Authentication
  3. Set Anonymous Authentication to Disabled
  4. Set Windows Authentication to Enabled

enter image description here

How to run an .ipynb Jupyter Notebook from terminal?

From the command line you can convert a notebook to python with this command:

jupyter nbconvert --to python nb.ipynb

https://github.com/jupyter/nbconvert

You may have to install the python mistune package:

sudo pip install -U mistune

How to convert int to float in C?

This can give you the correct Answer

#include <stdio.h>
int main()
{
    float total=100, number=50;
    float percentage;
    percentage=(number/total)*100;
    printf("%0.2f",percentage);
    return 0;
}

Win32Exception (0x80004005): The wait operation timed out

I tried the other answers here as well as a few others. I even stopped and restarted the SQL services. Nothing worked.

However, restarting my computer did work.

How to get all properties values of a JavaScript Object (without knowing the keys)?

Apparently - as I recently learned - this is the fastest way to do it:

var objs = {...};
var objKeys = Object.keys(obj);
for (var i = 0, objLen = objKeys.length; i < objLen; i++) {
    // do whatever in here
    var obj = objs[objKeys[i]];
}

What is the max size of localStorage values?

Don't assume 5MB is available - localStorage capacity varies by browser, with 2.5MB, 5MB and unlimited being the most common values. Source: http://dev-test.nemikor.com/web-storage/support-test/

The entity cannot be constructed in a LINQ to Entities query

Here is one way to do this without declaring aditional class:

public List<Product> GetProducts(int categoryID)
{
    var query = from p in db.Products
            where p.CategoryID == categoryID
            select new { Name = p.Name };
    var products = query.ToList().Select(r => new Product
    {
        Name = r.Name;
    }).ToList();

    return products;
}

However, this is only to be used if you want to combine multiple entities in a single entity. The above functionality (simple product to product mapping) is done like this:

public List<Product> GetProducts(int categoryID)
{
    var query = from p in db.Products
            where p.CategoryID == categoryID
            select p;
    var products = query.ToList();

    return products;
}

AutoComplete TextBox Control

    private void TurnOnAutocomplete()
    {
        textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        textBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
        AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
        string[] arrayOfWowrds = new string[];

        try
        {
            //Read in data Autocomplete list to a string[]
            string[] arrayOfWowrds = new string[];
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message, "File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        collection.AddRange(arrayOFWords);
        textBox.AutoCompleteCustomSource = collection;
    }

You only need to call this once after you have your data needed for the autocomplete list. Once bound it stays with the textBox. You do not need to or want to call it every time the text is changed in the textBox, that will kill your program.

How to Automatically Start a Download in PHP?

my code works for txt,doc,docx,pdf,ppt,pptx,jpg,png,zip extensions and I think its better to use the actual MIME types explicitly.

$file_name = "a.txt";

// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);

header('Content-disposition: attachment; filename='.$file_name);

if(strtolower($ext) == "txt")
{
    header('Content-type: text/plain'); // works for txt only
}
else
{
    header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);

Git: Installing Git in PATH with GitHub client for Windows

Updated for the Github Desktop

Search up "Edit the system environment variables" on windows search

  • Click environmental variable on the bottom right corner

  • Find path under system variables and click edit on it

  • Click new to add a new path

  • add this path: C:\Users\yourUserName\AppData\Local\GitHubDesktop\bin\github.exe

To make sure everything is working fine, open cmd, and type github.exe

"Unable to launch the IIS Express Web server" error

In my case i tried following things to fix this problem.

  1. Delete the iisexpress folder from "MyDocuments"

  2. Go to Solution Explorer --> Right click on the Project --> Go to Properties --> Go to Web tab --> See the Servers --> click on radio button "USe Visual Studio Developtment Server"

I hope this will help you.

How to append in a json file in Python?

json_obj=json.dumps(a_dict, ensure_ascii=False)

getFilesDir() vs Environment.getDataDirectory()

From the HERE and HERE

public File getFilesDir ()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

public static File getExternalStorageDirectory ()

Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().

Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.

On devices with multiple users (as described by UserManager), each user has their own isolated external storage. Applications only have access to the external storage for the user they're running as.

If you want to get your application path use getFilesDir() which will give you path /data/data/your package/files

You can get the path using the Environment var of your data/package using the

getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath(); which will return the path from the root directory of your external storage as /storage/sdcard/Android/data/your pacakge/files/data

To access the external resources you have to provide the permission of WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in your manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Check out the Best Documentation to get the paths of direcorty

How to give environmental variable path for file appender in configuration file in log4j

you CAN give it environment variables. Just preppend env: before the variable name, like this:

value="${env:MY_HOME}/logs/message.log"

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

Alternatively to injection and even worse Singleton, you can call Detach method before Add.

EntityFramework 6: ((IObjectContextAdapter)cs).ObjectContext.Detach(city1);

EntityFramework 4: cs.Detach(city1);

There is yet another way, in case you don't need first DBContext object. Just wrap it with using keyword:

Payroll.Entities.City city1;
using (CityService cs = new CityService())
{
  city1 = cs.SelectCity(Convert.ToInt64(cmbCity.SelectedItem.Value));
}

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

Here is my one liner. Here 'c' is the name of the column

df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()

How do I specify local .gem files in my Gemfile?

I would unpack your gem in the application vendor folder

gem unpack your.gem --target /path_to_app/vendor/gems/

Then add the path on the Gemfile to link unpacked gem.

gem 'your', '2.0.1', :path => 'vendor/gems/your'

BULK INSERT with identity (auto-increment) column

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

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

Create your table:

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

Open a command window an run:

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

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

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

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

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

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

Team Build Error: The Path ... is already mapped to workspace

I had a similar problem with Visual Studio 2010 complaining about an already-mapped-workspace, but instead of deleting the entire workspace, I used the following from the Visual Studio Command Prompt: "tf workspace PROBLEM_WORKSPACE_NAME". This brought up an "Edit Workspace" dialog. From there I was able to remove the path in question from the "Working Folders" list, which got rid of the error.

Match everything except for specified strings

All except word "red"

_x000D_
_x000D_
var href = '(text-1) (red) (text-3) (text-4) (text-5)';_x000D_
_x000D_
var test = href.replace(/\((\b(?!red\b)[\s\S]*?)\)/g, testF); _x000D_
_x000D_
function testF(match, p1, p2, offset, str_full) {_x000D_
  p1 = "-"+p1+"-";_x000D_
  return p1;_x000D_
}_x000D_
_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

All except word "red"

_x000D_
_x000D_
var href = '(text-1) (frede) (text-3) (text-4) (text-5)';_x000D_
_x000D_
var test = href.replace(/\(([\s\S]*?)\)/g, testF); _x000D_
_x000D_
function testF(match, p1, p2, offset, str_full) {_x000D_
  p1 = p1.replace(/red/g, '');_x000D_
  p1 = "-"+p1+"-";_x000D_
  return p1;_x000D_
}_x000D_
_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

How to configure logging to syslog in Python?

Is your syslog.conf set up to handle facility=user?

You can set the facility used by the python logger with the facility argument, something like this:

handler = logging.handlers.SysLogHandler(facility=SysLogHandler.LOG_DAEMON)

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

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

PHP 7.x

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

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

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

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

How to access the last value in a vector?

Package data.table includes last function

library(data.table)
last(c(1:10))
# [1] 10

Turning off some legends in a ggplot

You can simply add show.legend=FALSE to geom to suppress the corresponding legend

How do you make div elements display inline?

An inline div is a freak of the web & should be beaten until it becomes a span (at least 9 times out of 10)...

<span>foo</span>
<span>bar</span>
<span>baz</span>

...answers the original question...

div inside php echo

Try this,

<?php  if ( ($cart->count_product) > 0) { ?>
         <div class="my_class"><?php print $cart->count_product; ?></div>
<?php } else { 
          print ''; 
}  ?>

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For Boto3 , use this code.

import boto3
from botocore.client import Config


s3 = boto3.resource('s3',
        aws_access_key_id='xxxxxx',
        aws_secret_access_key='xxxxxx',
        region_name='us-south-1',
        config=Config(signature_version='s3v4')
        )

Save file/open file dialog box, using Swing & Netbeans GUI editor

Here is an example

private void doOpenFile() {
    int result = myFileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        Path path = myFileChooser.getSelectedFile().toPath();

        try {
            String contentString = "";

            for (String s : Files.readAllLines(path, StandardCharsets.UTF_8)) {
                contentString += s;
            }

            jText.setText(contentString);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private void doSaveFile() {
    int result = myFileChooser.showSaveDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        // We'll be making a mytmp.txt file, write in there, then move it to
        // the selected
        // file. This takes care of clearing that file, should there be
        // content in it.
        File targetFile = myFileChooser.getSelectedFile();

        try {
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }

            FileWriter fw = new FileWriter(targetFile);

            fw.write(jText.getText());
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to create a multi line body in C# System.Net.Mail.MailMessage

Sometimes you don't want to create a html e-mail. I solved the problem this way :

Replace \n by \t\n

The tab will not be shown, but the newline will work.

Get current cursor position

You get the cursor position by calling GetCursorPos.

POINT p;
if (GetCursorPos(&p))
{
    //cursor position now in p.x and p.y
}

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
{
    //p.x and p.y are now relative to hwnd's client area
}

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

Using Service to run background and create notification

The question is relatively old, but I hope this post still might be relevant for others.

TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

What this test-application(and instruction) is about:

Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.

When should you use it:

Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

What to do:

  1. First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <Button
            android:id="@+id/sendNotifications"
            android:onClick="onSendNotificationsButtonClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start Sending Notifications Every 2 Hours!" />
    </RelativeLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void onSendNotificationsButtonClick(View view) {
            NotificationEventReceiver.setupAlarm(getApplicationContext());
        }   
    }
    

    and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.

  2. Then let's create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

    Here, we'll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case - wakefully start IntentService, which we'll specify in the later steps. This IntentService would generate notifications for us.

    Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later

    NB1! As I'm using WakefulBroadcastReceiver, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />

    NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

    NotificationEventReceiver.java

    public class NotificationEventReceiver extends WakefulBroadcastReceiver {
    
        private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
        private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
        private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    
        public static void setupAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent alarmIntent = getStartPendingIntent(context);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    getTriggerAt(new Date()),
                    NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
                    alarmIntent);
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Intent serviceIntent = null;
            if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
                serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
            } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
                serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
            }
    
            if (serviceIntent != null) {
                startWakefulService(context, serviceIntent);
            }
        }
    
        private static long getTriggerAt(Date now) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
            return calendar.getTimeInMillis();
        }
    
        private static PendingIntent getStartPendingIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        public static PendingIntent getDeleteIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_DELETE_NOTIFICATION);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    }
    
  3. Now let's create an IntentService to actually create notifications.

    There, we specify onHandleIntent() which is responses on NotificationEventReceiver's intent we passed in startWakefulService method.

    If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder we're composing new notification and showing it by NotificationManager.notify. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

    NotificationIntentService.java

    public class NotificationIntentService extends IntentService {
    
        private static final int NOTIFICATION_ID = 1;
        private static final String ACTION_START = "ACTION_START";
        private static final String ACTION_DELETE = "ACTION_DELETE";
    
        public NotificationIntentService() {
            super(NotificationIntentService.class.getSimpleName());
        }
    
        public static Intent createIntentStartNotificationService(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_START);
            return intent;
        }
    
        public static Intent createIntentDeleteNotification(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_DELETE);
            return intent;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
            try {
                String action = intent.getAction();
                if (ACTION_START.equals(action)) {
                    processStartNotification();
                }
                if (ACTION_DELETE.equals(action)) {
                    processDeleteNotification(intent);
                }
            } finally {
                WakefulBroadcastReceiver.completeWakefulIntent(intent);
            }
        }
    
        private void processDeleteNotification(Intent intent) {
            // Log something?
        }
    
        private void processStartNotification() {
            // Do something. For example, fetch fresh data from backend to create a rich notification?
    
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle("Scheduled Notification")
                    .setAutoCancel(true)
                    .setColor(getResources().getColor(R.color.colorAccent))
                    .setContentText("This notification has been triggered by Notification Service")
                    .setSmallIcon(R.drawable.notification_icon);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    NOTIFICATION_ID,
                    new Intent(this, NotificationActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
    
            final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTIFICATION_ID, builder.build());
        }
    }
    
  4. Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).

    NotificationServiceStarterReceiver.java

    public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationEventReceiver.setupAlarm(context);
        }
    }
    
  5. We need to also register all our services, broadcast receivers in AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="klogi.com.notificationbyschedule">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <service
                android:name=".notifications.NotificationIntentService"
                android:enabled="true"
                android:exported="false" />
    
            <receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
            <receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.TIMEZONE_CHANGED" />
                    <action android:name="android.intent.action.TIME_SET" />
                </intent-filter>
            </receiver>
    
            <activity
                android:name=".NotificationActivity"
                android:label="@string/title_activity_notification"
                android:theme="@style/AppTheme.NoActionBar"/>
        </application>
    
    </manifest>
    

That's it!

The source code for this project you can find here. I hope, you will find this post helpful.

How to compare types

Try the following

typeField == typeof(string)
typeField == typeof(DateTime)

The typeof operator in C# will give you a Type object for the named type. Type instances are comparable with the == operator so this is a good method for comparing them.

Note: If I remember correctly, there are some cases where this breaks down when the types involved are COM interfaces which are embedded into assemblies (via NoPIA). Doesn't sound like this is the case here.

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

Objective-C: Extract filename from path string

Taken from the NSString reference, you can use :

NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];

The lastPathComponent call will return thefile.ext, and the stringByDeletingPathExtension will remove the extension suffix from the end.

Do I need to close() both FileReader and BufferedReader?

You Don't need to close the wrapped reader/writer.

If you've taken a look at the docs (Reader.close(),Writer.close()), You'll see that in Reader.close() it says:

Closes the stream and releases any system resources associated with it.

Which just says that it "releases any system resources associated with it". Even though it doesn't confirm.. it gives you a nudge to start looking deeper. and if you go to Writer.close() it only states that it closes itself.

In such cases, we refer to OpenJDK to take a look at the source code.

At BufferedWriter Line 265 you'll see out.close(). So it's not closing itself.. It's something else. If you search the class for occurences of "out" you'll notice that in the constructor at Line 87 that out is the writer the class wraps where it calls another constructor and then assigning out parameter to it's own out variable..

So.. What about others? You can see similar code at BufferedReader Line 514, BufferedInputStream Line 468 and InputStreamReader Line 199. Others i don't know but this should be enough to assume that they do.

Java ArrayList for integers

List of Integer.

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

ShowAllData method of Worksheet class failed

I am also the same problem. I think the reason are,

1) When my activecell is within the table, "ActiveSheet.ShowAllData" can be work. 2) When my activecell not within the table, "ActiveSheet.ShowAllData" cannot work.Using this code, ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=1 can clear the filter.

Parsing arguments to a Java command line program

Simple code for command line in java:

class CMDLineArgument
{
    public static void main(String args[])
    {
        String name=args[0];
        System.out.println(name);
    }
}

How to add element in List while iterating in java?

I do this by adding the elements to an new, empty tmp List, then adding the tmp list to the original list using addAll(). This prevents unnecessarily copying a large source list.

Imagine what happens when the OP's original list has a few million items in it; for a while you'll suck down twice the memory.

In addition to conserving resources, this technique also prevents us from having to resort to 80s-style for loops and using what are effectively array indexes which could be unattractive in some cases.

How to send POST in angularjs with multiple params?

Here is the direct solution:

// POST api/<controller>
[HttpPost, Route("postproducts/{product1}/{product2}")]
public void PostProducts([FromUri]Product product, Product product2)
{
    Product productOne = product; 
    Product productTwo = product2; 
}

$scope.url = 'http://localhost:53263/api/Products/' +
                 $scope.product + '/' + $scope.product2
$http.post($scope.url)
    .success(function(response) {
        alert("success") 
    })
    .error(function() { alert("fail") });
};

If you are sane you do this:

var $scope.products.product1 = product1;
var $scope.products.product2 = product2;

And then send products in the body (like a balla).

How to measure the a time-span in seconds using System.currentTimeMillis()?

long start = System.currentTimeMillis();
counter.countPrimes(1000000);
long end = System.currentTimeMillis();

System.out.println("Took : " + ((end - start) / 1000));

UPDATE

An even more accurate solution would be:

final long start = System.nanoTime();
counter.countPrimes(1000000);
final long end = System.nanoTime();

System.out.println("Took: " + ((end - start) / 1000000) + "ms");
System.out.println("Took: " + (end - start)/ 1000000000 + " seconds");

How to load my app from Eclipse to my Android phone instead of AVD

Some people may have the issue where your phone might not immediately get recognized by the computer as an emulator, especially if you're given the option to choose why your phone is connected to the computer on your phone. These options are:

  • charge only
  • Media device (MTP)
  • Camera file transfer (PTP)
  • Share mobile network
  • Install driver

Of these options, choose MTP and follow the instructions found in the quotes of other answers.

  • Hope this helps!

goto run menu -> run configuration. right click on android application on the right side and click new. fill the corresponding details like project name under the android tab. then under the target tab. select 'launch on all compatible devices and then select active devices from the drop down list'. save the configuration and run it by either clicking run on the 'run' button on the bottom right side of the window or close the window and run again

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

You can use ALTER to update a view, but this is different than the Oracle command since it only works if the view already exists. Probably better off with DaveK's answer since that will always work.

Rename Excel Sheet with VBA Macro

Suggest you add handling to test if any of the sheets to be renamed already exist:

Sub Test()

Dim ws As Worksheet
Dim ws1 As Worksheet
Dim strErr As String

On Error Resume Next
For Each ws In ActiveWorkbook.Sheets
Set ws1 = Sheets(ws.Name & "_v1")
    If ws1 Is Nothing Then
        ws.Name = ws.Name & "_v1"
    Else
         strErr = strErr & ws.Name & "_v1" & vbNewLine
    End If
Set ws1 = Nothing
Next
On Error GoTo 0

If Len(strErr) > 0 Then MsgBox strErr, vbOKOnly, "these sheets already existed"

End Sub

Hidden features of Windows batch files

Bail on error.

IF "%errorlevel%" NEQ "0" (
   echo "ERROR:  Something broke.  Bailing out."
   exit /B 1
)

How to use the ConfigurationManager.AppSettings

\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this

 <add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />

In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have

 con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

Set a default parameter value for a JavaScript function

To anyone interested in having there code work in Microsoft Edge, do not use defaults in function parameters.

function read_file(file, delete_after = false) {
    #code
}

In that example Edge will throw an error "Expecting ')'"

To get around this use

function read_file(file, delete_after) {
  if(delete_after == undefined)
  {
    delete_after = false;
  }
  #code
}

As of Aug 08 2016 this is still an issue

Convert String to Uri

What are you going to do with the URI?

If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.

HttpGet get = new HttpGet("http://stackoverflow.com");

How to convert hex to ASCII characters in the Linux shell?

Some python3 one-liners that work with any number of bytes.

Decoding hex (with strip, so that it's ok to have a newline on stdin):

$ echo 666f6f0a | python3 -c "import sys, binascii; sys.stdout.buffer.write(binascii.unhexlify(input().strip()))"
foo

Encoding hex:

$ echo foo | python3 -c "import sys, binascii; print(binascii.hexlify(sys.stdin.buffer.read()).decode())"
666f6f0a

text-align: right; not working for <label>

You can make a text align to the right inside of any element, including labels.

Html:

<label>Text</label>

Css:

label {display:block; width:x; height:y; text-align:right;}

This way, you give a width and height to your label and make any text inside of it align to the right.

How can I introduce multiple conditions in LIKE operator?

This might help:

select * from tbl where col like '[ABC-XYZ-PQR]%'

I've used this in SQL Server 2005 and it worked.

Multiple Buttons' OnClickListener() android

You could set the property:

android:onClick="buttonClicked"

in the xml file for each of those buttons, and use this in the java code:

public void buttonClicked(View view) {

    if (view.getId() == R.id.button1) {
        // button1 action
    } else if (view.getId() == R.id.button2) {
        //button2 action
    } else if (view.getId() == R.id.button3) {
        //button3 action
    }

}

Deserialize a json string to an object in python

If you are embracing the type hints in Python 3.6, you can do it like this:

def from_json(data, cls):
    annotations: dict = cls.__annotations__ if hasattr(cls, '__annotations__') else None
    if issubclass(cls, List):
        list_type = cls.__args__[0]
        instance: list = list()
        for value in data:
            instance.append(from_json(value, list_type))
        return instance
    elif issubclass(cls, Dict):
            key_type = cls.__args__[0]
            val_type = cls.__args__[1]
            instance: dict = dict()
            for key, value in data.items():
                instance.update(from_json(key, key_type), from_json(value, val_type))
            return instance
    else:
        instance : cls = cls()
        for name, value in data.items():
            field_type = annotations.get(name)
            if inspect.isclass(field_type) and isinstance(value, (dict, tuple, list, set, frozenset)):
                setattr(instance, name, from_json(value, field_type))
            else:
                setattr(instance, name, value)
        return instance

Which then allows you do instantiate typed objects like this:

class Bar:
    value : int

class Foo:
    x : int
    bar : List[Bar]


obj : Foo = from_json(json.loads('{"x": 123, "bar":[{"value": 3}, {"value": 2}, {"value": 1}]}'), Foo)
print(obj.x)
print(obj.bar[2].value)

This syntax requires Python 3.6 though and does not cover all cases - for example, support for typing.Any... But at least it does not pollute the classes that need to be deserialized with extra init/tojson methods.

@Autowired - No qualifying bean of type found for dependency at least 1 bean

Missing the 'implements' keyword in the impl classes might also be the issue

How to convert float number to Binary?

x = float(raw_input("enter number between 0 and 1: "))

p = 0
while ((2**p)*x) %1 != 0:
    p += 1
    # print p

    num = int (x * (2 ** p))
    # print num

    result = ''
    if num == 0:
        result = '0'
    while num > 0:
        result = str(num%2) + result
        num = num / 2

    for i in range (p - len(result)):
        result = '0' + result
    result = result[0:-p] + '.' + result[-p:]

print result #this will print result for the decimal portion

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

Different binary trees with n nodes:

(1/(n+1))*(2nCn)

where C=combination eg.

n=6,
possible binary trees=(1/7)*(12C6)=132

Main differences between SOAP and RESTful web services in Java

REST is an architecture.
REST will give human-readable results.
REST is stateless.
REST services are easily cacheable.

SOAP is a protocol. It can run on top of JMS, FTP, and HTTP.

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

Convert InputStream to BufferedReader

BufferedReader can't wrap an InputStream directly. It wraps another Reader. In this case you'd want to do something like:

BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

html table cell width for different rows

As far as i know that is impossible and that makes sense since what you are trying to do is against the idea of tabular data presentation. You could however put the data in multiple tables and remove any padding and margins in between them to achieve the same result, at least visibly. Something along the lines of:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <style type="text/css">_x000D_
    .mytable {_x000D_
      border-collapse: collapse;_x000D_
      width: 100%;_x000D_
      background-color: white;_x000D_
    }_x000D_
    .mytable-head {_x000D_
      border: 1px solid black;_x000D_
      margin-bottom: 0;_x000D_
      padding-bottom: 0;_x000D_
    }_x000D_
    .mytable-head td {_x000D_
      border: 1px solid black;_x000D_
    }_x000D_
    .mytable-body {_x000D_
      border: 1px solid black;_x000D_
      border-top: 0;_x000D_
      margin-top: 0;_x000D_
      padding-top: 0;_x000D_
      margin-bottom: 0;_x000D_
      padding-bottom: 0;_x000D_
    }_x000D_
    .mytable-body td {_x000D_
      border: 1px solid black;_x000D_
      border-top: 0;_x000D_
    }_x000D_
    .mytable-footer {_x000D_
      border: 1px solid black;_x000D_
      border-top: 0;_x000D_
      margin-top: 0;_x000D_
      padding-top: 0;_x000D_
    }_x000D_
    .mytable-footer td {_x000D_
      border: 1px solid black;_x000D_
      border-top: 0;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <table class="mytable mytable-head">_x000D_
    <tr>_x000D_
      <td width="25%">25</td>_x000D_
      <td width="50%">50</td>_x000D_
      <td width="25%">25</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <table class="mytable mytable-body">_x000D_
    <tr>_x000D_
      <td width="50%">50</td>_x000D_
      <td width="30%">30</td>_x000D_
      <td width="20%">20</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <table class="mytable mytable-body">_x000D_
    <tr>_x000D_
      <td width="16%">16</td>_x000D_
      <td width="68%">68</td>_x000D_
      <td width="16%">16</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <table class="mytable mytable-footer">_x000D_
    <tr>_x000D_
      <td width="20%">20</td>_x000D_
      <td width="30%">30</td>_x000D_
      <td width="50%">50</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

JSFIDDLE

I don't know your requirements but i'm sure there's a more elegant solution.

jQuery counter to count up to a target number

A different approach. Use Tween.js for the counter. It allows the counter to slow down, speed up, bounce, and a slew of other goodies, as the counter gets to where its going.

http://jsbin.com/ekohep/2/edit#javascript,html,live

Enjoy :)

PS, doesn't use jQuery - but obviously could.

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

this.getClass().getClassLoader().getResource("...") and NullPointerException

tul,

  • When you use .getClass().getResource(fileName) it considers the location of the fileName is the same location of the of the calling class.
  • When you use .getClass().getClassLoader().getResource(fileName) it considers the location of the fileName is the root - in other words bin folder.

Source :

package Sound;
public class ResourceTest {
    public static void main(String[] args) {
        String fileName = "Kalimba.mp3";
        System.out.println(fileName);
        System.out.println(new ResourceTest().getClass().getResource(fileName));
        System.out.println(new ResourceTest().getClass().getClassLoader().getResource(fileName));
    }
}

Output :

Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Sound/Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Kalimba.mp3

What is a NullReferenceException, and how do I fix it?

Adding a case when the class name for entity used in entity framework is same as class name for a web form code-behind file.

Suppose you have a web form Contact.aspx whose codebehind class is Contact and you have an entity name Contact.

Then following code will throw a NullReferenceException when you call context.SaveChanges()

Contact contact = new Contact { Name = "Abhinav"};
var context = new DataContext();
context.Contacts.Add(contact);
context.SaveChanges(); // NullReferenceException at this line

For the sake of completeness DataContext class

public class DataContext : DbContext 
{
    public DbSet<Contact> Contacts {get; set;}
}

and Contact entity class. Sometimes entity classes are partial classes so that you can extend them in other files too.

public partial class Contact 
{
    public string Name {get; set;}
}

The error occurs when both the entity and codebehind class are in same namespace. To fix this, rename the entity class or the codebehind class for Contact.aspx.

Reason I am still not sure about the reason. But whenever any of the entity class will extend System.Web.UI.Page this error occurs.

For discussion have a look at NullReferenceException in DbContext.saveChanges()

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

jQuery and TinyMCE: textarea value doesn't submit

var text = tinyMCE.activeEditor.getContent();
$('#textareaid').remove();
$('<textarea id="textareaid" name="textareaid">'+text+'</textarea>').insertAfter($('[name=someinput]'));

Go: panic: runtime error: invalid memory address or nil pointer dereference

Make sure that you handle all the errors by sending a return value.

`if err!=nil{
    return nil, err
 }`

Python constructors and __init__

coonstructors are called automatically when you create a new object, thereby "constructing" the object. The reason you can have more than one init is because names are just references in python, and you are allowed to change what each variable references whenever you want (hence dynamic typing)

def func(): #now func refers to an empty funcion
    pass
...
func=5      #now func refers to the number 5
def func():
    print "something"    #now func refers to a different function

in your class definition, it just keeps the later one

Tools: replace not replacing in Android manifest

I also went through this problem and changed that:

<application  android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

to

 <application tools:replace="android:allowBackup" android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

How can apply multiple background color to one div

With :after and :before you can do that.

HTML:

<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>

CSS:

div {
    height: 100px;
    position: relative;
}
.a {
    background: #9C9E9F;
}
.b {
    background: linear-gradient(to right, #9c9e9f, #f6f6f6);
}
.a:after, .c:before, .c:after {
    content: '';
    width: 50%;
    height: 100%;
    top: 0;
    right: 0;
    display: block;
    position: absolute;
}
.a:after {
    background: #f6f6f6;    
}
.c:before {
    background: #9c9e9f;
    left: 0;
}
.c:after {
    background: #33CCFF;
    right: 0;
    height: 80%;
}

And a demo.

PHP UML Generator

phUML

phUML is fully automatic UML class diagramm generator written in PHP, licensed under the BSD license. It is capable of parsing any PHP5 object oriented source code and create an appropriate image representation of the oo structure based on the UML specification.

UML Example

./phuml -r /var/www/my_project -graphviz -createAssociations false -neato out.png

Step by step guide

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

if you want to use parentheses in laravel 4 and don't forget return
In Laravel 4 (at least) you need to use $a, $b in parentheses as in the example

$a = 1;
$b = 1;
$c = 1;
$d = 1;
Model::where(function ($query) use ($a, $b) {
    return $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
    return $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
});

This is my result: enter image description here

How to remove undefined and null values from an object using lodash?

With lodash (or underscore) You may do

var my_object = { a:undefined, b:2, c:4, d:undefined, e:null };

var passedKeys = _.reject(Object.keys(my_object), function(key){ return _.isUndefined(my_object[key]) || _.isNull(my_object[key]) })

newObject = {};
_.each(passedKeys, function(key){
    newObject[key] = my_object[key];
});

Otherwise, with vanilla JavaScript, you can do

var my_object = { a:undefined, b:2, c:4, d:undefined };
var new_object = {};

Object.keys(my_object).forEach(function(key){
    if (typeof my_object[key] != 'undefined' && my_object[key]!=null){
        new_object[key] = my_object[key];
    }
});

Not to use a falsey test, because not only "undefined" or "null" will be rejected, also is other falsey value like "false", "0", empty string, {}. Thus, just to make it simple and understandable, I opted to use explicit comparison as coded above.

How to get client IP address in Laravel 5+

I used the Sebastien Horin function getIp and request()->ip() (at global request), because to localhost the getIp function return null:

$this->getIp() ?? request()->ip();

The getIp function:

public function getIp(){
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
    if (array_key_exists($key, $_SERVER) === true){
        foreach (explode(',', $_SERVER[$key]) as $ip){
            $ip = trim($ip); // just to be safe
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                return $ip;
            }
        }
    }
}

}

javascript push multidimensional array

Arrays must have zero based integer indexes in JavaScript. So:

var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);

Or maybe you want to use objects (which are associative arrays):

var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);

which is equivalent to:

var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);

It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.

Command output redirect to file and terminal

Yes, if you redirect the output, it won't appear on the console. Use tee.

ls 2>&1 | tee /tmp/ls.txt

Is this the proper way to do boolean test in SQL?

I personally prefer using char(1) with values 'Y' and 'N' for databases that don't have a native type for boolean. Letters are more user frendly than numbers which assume that those reading it will now that 1 corresponds to true and 0 corresponds to false.

'Y' and 'N' also maps nicely when using (N)Hibernate.

Convert audio files to mp3 using ffmpeg

I had to purge my ffmpeg and then install another one from a ppa:

sudo apt-get purge ffmpeg
sudo apt-add-repository -y ppa:jon-severinsson/ffmpeg 
sudo apt-get update 
sudo apt-get install ffmpeg

Then convert:

 ffmpeg -i audio.ogg -f mp3 newfile.mp3

Make an Android button change background on click through XML

In the latest version of the SDK, you would use the setBackgroundResource method.

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setBackgroundResource(R.drawable.ImageResource);
   }
}

Check for null variable in Windows batch

The right thing would be to use a "if defined" statement, which is used to test for the existence of a variable. For example:

IF DEFINED somevariable echo Value exists

In this particular case, the negative form should be used:

IF NOT DEFINED somevariable echo Value missing

PS: the variable name should be used without "%" caracters.

Bootstrap: adding gaps between divs

I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>

Take nth column in a text file

You can use the cut command:

cut -d' ' -f3,5 < datafile.txt

prints

1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495

the

  • -d' ' - mean, use space as a delimiter
  • -f3,5 - take and print 3rd and 5th column

The cut is much faster for large files as a pure shell solution. If your file is delimited with multiple whitespaces, you can remove them first, like:

sed 's/[\t ][\t ]*/ /g' < datafile.txt | cut -d' ' -f3,5

where the (gnu) sed will replace any tab or space characters with a single space.

For a variant - here is a perl solution too:

perl -lanE 'say "$F[2] $F[4]"' < datafile.txt

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

Add the css

  <style type="text/css">
    textarea
    {

        border:1px solid #999999
        width:99%;
        margin:5px 0;
        padding:1%;
    }
</style>

To draw an Underline below the TextView in Android

If your TextView has fixed width, alternative solution can be to create a View which will look like an underline and position it right below your TextView.

<RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="match_parent">

        <TextView
            android:id="@+id/myTextView"
            android:layout_width="20dp"
            android:layout_height="wrap_content"/>

        <View
            android:layout_width="20dp"
            android:layout_height="1dp"
            android:layout_below="@+id/myTextView"
            android:background="#CCCCCC"/>
</RelativeLayout>

How to get duplicate items from a list using LINQ?

  List<String> list = new List<String> { "6", "1", "2", "4", "6", "5", "1" };

    var q = from s in list
            group s by s into g
            where g.Count() > 1
            select g.First();

    foreach (var item in q)
    {
        Console.WriteLine(item);

    }

How to specify maven's distributionManagement organisation wide?

Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository in your settings.xml or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.

A workaround is as follows. In the value:

releases::default::https://YOUR_NEXUS_URL/releases

you need to remove the default section, making it:

releases::https://YOUR_NEXUS_URL/releases

The prior version 2.8.2 does not have this bug.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

For PHP, put this line of code before you start printing your XML:

while(ob_get_level()) ob_end_clean();

At runtime, find all classes in a Java application that extend a base class

I use org.reflections:

Reflections reflections = new Reflections("com.mycompany");    
Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);

Another example:

public static void main(String[] args) throws IllegalAccessException, InstantiationException {
    Reflections reflections = new Reflections("java.util");
    Set<Class<? extends List>> classes = reflections.getSubTypesOf(java.util.List.class);
    for (Class<? extends List> aClass : classes) {
        System.out.println(aClass.getName());
        if(aClass == ArrayList.class) {
            List list = aClass.newInstance();
            list.add("test");
            System.out.println(list.getClass().getName() + ": " + list.size());
        }
    }
}

Wait until flag=true

I tried to used @Kiran approach like follow:

checkFlag: function() {
  var currentObject = this; 
  if(flag == false) {
      setTimeout(currentObject.checkFlag, 100); 
   } else {
     /* do something*/
   }
}

(framework that I am using force me to define functions this way). But without success because when execution come inside checkFlag function second time, this is not my object it is Window. So, I finished with code below

checkFlag: function() {
    var worker = setInterval (function(){
         if(flag == true){             
             /* do something*/
              clearInterval (worker);
         } 
    },100);
 }

Latest jQuery version on Google's CDN

I don't know if/where it's published, but you can get the latest release by omitting the minor and build numbers.

Latest 1.8.x:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

Latest 1.x:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

However, do keep in mind that these links have a much shorter cache timeout than with the full version number, so your users may be downloading them more than you'd like. See The crucial .0 in Google CDN references to jQuery 1.x.0 for more information.

Can jQuery check whether input content has changed?

You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):

$(document).ready(function() {  
    $("#fieldId").bind("keyup keydown keypress change blur", function() {
        if ($(this).val() != jQuery.data(this, "lastvalue") {
         alert("changed");
        }
        jQuery.data(this, "lastvalue", $(this).val());
    });
});

This would work pretty good against a long list of items too. Using jQuery.data means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc") to track many fields.

UPDATE: Added blur to the bind list.

Optional query string parameters in ASP.NET Web API

This issue has been fixed in the regular release of MVC4. Now you can do:

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
{
    // ...
}

and everything will work out of the box.

How to use php serialize() and unserialize()

When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.

Jar mismatch! Fix your dependencies

Right click on your project -> Android Tool -> Add support library

How to get JSON from URL in JavaScript?

With Chrome, Firefox, Safari, Edge, and Webview you can natively use the fetch API which makes this a lot easier, and much more terse.

If you need support for IE or older browsers, you can also use the fetch polyfill.

let url = 'https://example.com';

fetch(url)
.then(res => res.json())
.then((out) => {
  console.log('Checkout this JSON! ', out);
})
.catch(err => { throw err });

MDN: Fetch API

Even though Node.js does not have this method built-in, you can use node-fetch which allows for the exact same implementation.

C# Break out of foreach loop after X number of items

This should work.

int i = 1;
foreach (ListViewItem lvi in listView.Items) {
    ...
    if(++i == 50) break;
}

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

How to detect chrome and safari browser (webkit)

jQuery provides that:

if ($.browser.webkit){
    ...
}

Further reading at http://api.jquery.com/jQuery.browser/

Update

As noted in other answers/comments, it's always better to check for feature support than agent info. jQuery also provides an object for that: jQuery.support. Check the documentation to see the detailed list features to check for.

How to preview selected image in input type="file" in popup using jQuery?

Demo

HTML:

 <form id="form1" runat="server">
   <input type='file' id="imgInp" />
   <img id="blah" src="#" alt="your image" />
</form>

jQuery

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

Reference

Exclude property from type

Typescript 3.5

As of Typescript 3.5, the Omit helper will be included: TypeScript 3.5 RC - The Omit Helper Type

You can use it directly, and you should remove your own definition of the Omit helper when updating.

How do I delete specific lines in Notepad++?

Notepad++ v6.5

  1. Search menu -> Find... -> Mark tab -> Find what: your search text, check Bookmark Line, then Mark All. This will bookmark all the lines with the search term, you'll see the blue circles in the margin.

  2. Then Search menu -> Bookmark -> Remove Bookmarked Lines. This will delete all the bookmarked lines.

You can also use a regex to search. This method won't result in a blank line like John's and will actually delete the line.

Older Versions

  1. Search menu -> Find... -> Find what: your search text, check Bookmark Line and click Find All.
  2. Then Search -> Bookmark -> Remove Bookmarked Lines

Flutter: RenderBox was not laid out

Wrap your ListView in an Expanded widget

 Expanded(child:MyListView())

How to trigger event in JavaScript?

You could use this function i compiled together.

if (!Element.prototype.trigger)
  {
    Element.prototype.trigger = function(event)
    {
        var ev;

        try
        {
            if (this.dispatchEvent && CustomEvent)
            {
                ev = new CustomEvent(event, {detail : event + ' fired!'});
                this.dispatchEvent(ev);
            }
            else
            {
                throw "CustomEvent Not supported";
            }
        }
        catch(e)
        {
            if (document.createEvent)
            {
                ev = document.createEvent('HTMLEvents');
                ev.initEvent(event, true, true);

                this.dispatchEvent(event);
            }
            else
            {
                ev = document.createEventObject();
                ev.eventType = event;
                this.fireEvent('on'+event.eventType, event);
            }
        }
    }
  }

Trigger an event below:

var dest = document.querySelector('#mapbox-directions-destination-input');
dest.trigger('focus');

Watch Event:

dest.addEventListener('focus', function(e){
   console.log(e);
});

Hope this helps!

How to debug heap corruption errors?

You may also want to check to see whether you're linking against the dynamic or static C runtime library. If your DLL files are linking against the static C runtime library, then the DLL files have separate heaps.

Hence, if you were to create an object in one DLL and try to free it in another DLL, you would get the same message you're seeing above. This problem is referenced in another Stack Overflow question, Freeing memory allocated in a different DLL.

how to create Socket connection in Android?

Socket connections in Android are the same as in Java: http://www.oracle.com/technetwork/java/socket-140484.html

Things you need to be aware of:

  1. If phone goes to sleep your app will no longer execute, so socket will eventually timeout. You can prevent this with wake lock. This will eat devices battery tremendously - I know I wouldn't use that app.
  2. If you do this constantly, even when your app is not active, then you need to use Service.
  3. Activities and Services can be killed off by OS at any time, especially if they are part of an inactive app.

Take a look at AlarmManager, if you need scheduled execution of your code.

Do you need to run your code and receive data even if user does not use the app any more (i.e. app is inactive)?

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Android: where are downloaded files saved?

In my experience all the files which i have downloaded from internet,gmail are stored in

/sdcard/download

on ics

/sdcard/Download

You can access it using

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

How do you right-justify text in an HTML textbox?

Apply style="text-align: right" to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right.

MySQL Delete all rows from table and reset ID to zero

An interesting fact.

I was sure TRUNCATE will always perform better, but in my case, for a database with approximately 30 tables with foreign keys, populated with only a few rows, it took about 12 seconds to TRUNCATE all tables, as opposed to only a few hundred milliseconds to DELETE the rows. Setting the auto increment adds about a second in total, but it's still a lot better.

So I would suggest try both, see which works faster for your case.

Can I display the value of an enum with printf()?

enum A { foo, bar } a;
a = foo;
printf( "%d", a );   // see comments below

TypeError: object of type 'int' has no len() error assistance needed

Well, maybe an int does not posses the len attribute in Python like your error suggests?

Try:

len(str(numbers))

Specify the from user when sending email using the mail command

None of these worked for me (Ubuntu 12.04) but finally with trial & error I got:

echo 'my message blabla\nSecond line (optional of course)' | 
mail -s "Your message title"
-r 'Your full name<[email protected]>'
-Sreplyto="[email protected]"
[email protected][,[email protected]]

(all in one line, there is no space in "-Sreplyto")

I got this mail command from:

apt-get install mailutils

How to find the sum of an array of numbers

A short piece of JavaScript code would do this job:

var numbers = [1,2,3,4];
var totalAmount = 0;

for (var x = 0; x < numbers.length; x++) {

    totalAmount += numbers[x];
}

console.log(totalAmount); //10 (1+2+3+4)

Get top n records for each group of grouped results

Check this out:

SELECT
  p.Person,
  p.`Group`,
  p.Age
FROM
  people p
  INNER JOIN
  (
    SELECT MAX(Age) AS Age, `Group` FROM people GROUP BY `Group`
    UNION
    SELECT MAX(p3.Age) AS Age, p3.`Group` FROM people p3 INNER JOIN (SELECT MAX(Age) AS Age, `Group` FROM people GROUP BY `Group`) p4 ON p3.Age < p4.Age AND p3.`Group` = p4.`Group` GROUP BY `Group`
  ) p2 ON p.Age = p2.Age AND p.`Group` = p2.`Group`
ORDER BY
  `Group`,
  Age DESC,
  Person;

SQL Fiddle: http://sqlfiddle.com/#!2/cdbb6/15

How to cast an object in Objective-C

Typecasting in Objective-C is easy as:

NSArray *threeViews = @[[UIView new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];

However, what happens if first object is not UIView and you try to use it:

NSArray *threeViews = @[[NSNumber new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
CGRect firstViewFrame = firstView.frame; // CRASH!

It will crash. And it's easy to find such crash for this case, but what if those lines are in different classes and the third line is executed only once in 100 cases. I bet your customers find this crash, not you! A plausible solution is to crash early, like this:

UIView *firstView = (UIView *)threeViews[0];
NSAssert([firstView isKindOfClass:[UIView class]], @"firstView is not UIView");

Those assertions doesn't look very nice, so we could improve them with this handy category:

@interface NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object;
@end


@implementation NSObject (TypecastWithAssertion)

+ (instancetype)typecastWithAssertion:(id)object {
    if (object != nil)
        NSAssert([object isKindOfClass:[self class]], @"Object %@ is not kind of class %@", object, NSStringFromClass([self class]));
    return object;
}

@end

This is much better:

UIView *firstView = [UIView typecastWithAssertion:[threeViews[0]];

P.S. For collections type safety Xcode 7 have a much better than typecasting - generics

Display last git commit comment

If you want to see just the subject (first line) of the commit message:

git log -1 --format=%s

This was not previously documented in any answer. Alternatively, the approach by nos also shows it.

Reference:

How do I implement onchange of <input type="text"> with jQuery?

If you want to trigger the event as you type, use the following:

$('input[name=myInput]').on('keyup', function() { ... });

If you want to trigger the event on leaving the input field, use the following:

$('input[name=myInput]').on('change', function() { ... });

How to calculate the CPU usage of a process by PID in Linux from C?

Instead of parsing this from proc, one can use functions like getrusage() or clock_gettime() and calculate the cpu usage as a ratio or wallclock time and time the process/thread used on the cpu.

How to set default value for column of new created table from select statement in 11g

The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely

  • no primary key
  • no foreign keys
  • no grants
  • no indexes
  • ...

To achieve what you want, I'd either

  • use dbms_metadata.get_ddl to get the complete table structure, replace the table name with the new name, execute this statement, and do an INSERT afterward to copy the data
  • or keep using CTAS, extract the not null constraints for the source table from user_constraints and add them to the target table afterwards

What are the best practices for SQLite on Android?

Having had some issues, I think I have understood why I have been going wrong.

I had written a database wrapper class which included a close() which called the helper close as a mirror of open() which called getWriteableDatabase and then have migrated to a ContentProvider. The model for ContentProvider does not use SQLiteDatabase.close() which I think is a big clue as the code does use getWriteableDatabase In some instances I was still doing direct access (screen validation queries in the main so I migrated to a getWriteableDatabase/rawQuery model.

I use a singleton and there is the slightly ominous comment in the close documentation

Close any open database object

(my bolding).

So I have had intermittent crashes where I use background threads to access the database and they run at the same time as foreground.

So I think close() forces the database to close regardless of any other threads holding references - so close() itself is not simply undoing the matching getWriteableDatabase but force closing any open requests. Most of the time this is not a problem as the code is single threading, but in multi-threaded cases there is always the chance of opening and closing out of sync.

Having read comments elsewhere that explains that the SqLiteDatabaseHelper code instance counts, then the only time you want a close is where you want the situation where you want to do a backup copy, and you want to force all connections to be closed and force SqLite to write away any cached stuff that might be loitering about - in other words stop all application database activity, close just in case the Helper has lost track, do any file level activity (backup/restore) then start all over again.

Although it sounds like a good idea to try and close in a controlled fashion, the reality is that Android reserves the right to trash your VM so any closing is reducing the risk of cached updates not being written, but it cannot be guaranteed if the device is stressed, and if you have correctly freed your cursors and references to databases (which should not be static members) then the helper will have closed the database anyway.

So my take is that the approach is:

Use getWriteableDatabase to open from a singleton wrapper. (I used a derived application class to provide the application context from a static to resolve the need for a context).

Never directly call close.

Never store the resultant database in any object that does not have an obvious scope and rely on reference counting to trigger an implicit close().

If doing file level handling, bring all database activity to a halt and then call close just in case there is a runaway thread on the assumption that you write proper transactions so the runaway thread will fail and the closed database will at least have proper transactions rather than potentially a file level copy of a partial transaction.

How to change resolution (DPI) of an image?

It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.

For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.

To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.

Pseudo code

ratio = 300.0 / 72.0   // 4.167
image.width * ratio
image.height * ratio

Creating the checkbox dynamically using JavaScript?

   /* worked for me  */
     <div id="divid"> </div>
     <script type="text/javascript">
         var hold = document.getElementById("divid");
         var checkbox = document.createElement('input');
         checkbox.type = "checkbox";
         checkbox.name = "chkbox1";
         checkbox.id = "cbid";
         var label = document.createElement('label');
         var tn = document.createTextNode("Not A RoBot");
         label.htmlFor="cbid";
         label.appendChild(tn); 
         hold.appendChild(label);
         hold.appendChild(checkbox);
      </script>  

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

After trying a few of these answers and finding they don't scale well with multiple links (for example the accepted answer requires a line of jquery for every link you have), I came across a way that requires minimal code to get working, and it also appears to work perfectly, at least on Chrome.

You add this line to activate it:

$('[data-toggle="popover"]').popover();

And these settings to your anchor links:

data-toggle="popover" data-trigger="hover"

See it in action here, I'm using the same imports as the accepted answer so it should work fine on older projects.

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

Where are environment variables stored in the Windows Registry?

Here's where they're stored on Windows XP through Windows Server 2012 R2:

User Variables

HKEY_CURRENT_USER\Environment

System Variables

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Use fetch instead of XHR,then the request will not be prelighted even it's cross-domained.

How to count number of records per day?

select DateAdded, count(CustID)
from Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded

Calling C/C++ from Python?

I think cffi for python can be an option.

The goal is to call C code from Python. You should be able to do so without learning a 3rd language: every alternative requires you to learn their own language (Cython, SWIG) or API (ctypes). So we tried to assume that you know Python and C and minimize the extra bits of API that you need to learn.

http://cffi.readthedocs.org/en/release-0.7/

How do I copy a version of a single file from one git branch to another?

I would use git restore (available since git 2.23)

git restore --source otherbranch path/to/myfile.txt


Why it is better than other options?

git checkout otherbranch -- path/to/myfile.txt - It copy file to working directory but also to staging area (similar effect as if you would copy this file manually and executed git add on it). git restore doesn't touch staging area (unless told it to by --staged option).

git show otherbranch:path/to/myfile.txt > path/to/myfile.txt uses standard shell redirection. If you use Powershell then there might be problem with text enconding or you could get broken file if it's binary. With git restore changing files is done all by git executable.

Another advantage is that you can restore whole folder with:

git restore --source otherbranch path/to

or with git restore --overlay --source otherbranch path/to if you want to avoid deleting files. For example if there is less files on otherbranch than in current working directory (and these files are tracked) without --overlay option git restore will delete them. But this is good default bahaviour, you most likely want the state of directory to be "the same like in otherbranch", not "the same like in otherbranch but with additional files from my current branch"

Python unexpected EOF while parsing

Use raw_input instead of input :)

If you use input, then the data you type is is interpreted as a Python Expression which means that you end up with gawd knows what type of object in your target variable, and a heck of a wide range of exceptions that can be generated. So you should NOT use input unless you're putting something in for temporary testing, to be used only by someone who knows a bit about Python expressions.

raw_input always returns a string because, heck, that's what you always type in ... but then you can easily convert it to the specific type you want, and catch the specific exceptions that may occur. Hopefully with that explanation, it's a no-brainer to know which you should use.

Reference

Note: this is only for Python 2. For Python 3, raw_input() has become plain input() and the Python 2 input() has been removed.

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

Is it possible to declare a variable in Gradle usable in Java?

Example using system properties, set in build.gradle, read from Java application (following up from question in comments):

Basically, using the test task in build.gradle, with test task method systemProperty setting a system property that's passed at runtime:

apply plugin: 'java'
group = 'example'
version = '0.0.1-SNAPSHOT'

repositories {
    mavenCentral()
    // mavenLocal()
    // maven { url 'http://localhost/nexus/content/groups/public'; }
}

dependencies {
    testCompile 'junit:junit:4.8.2'
    compile 'ch.qos.logback:logback-classic:1.1.2'
}

test {
  logger.info '==test=='
  systemProperty 'MY-VAR1', 'VALUE-TEST'
}

And here's the rest of the sample code (which you could probably infer, but is included here anyway): it gets a system property MY-VAR1, expected at run-time to be set to VALUE-TEST:

package example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
  static final Logger log=LoggerFactory.getLogger(HelloWorld.class);
  public static void main(String args[]) {
    log.info("entering main...");
    final String val = System.getProperty("MY-VAR1", "UNSET (MAIN)");
    System.out.println("(main.out) hello, world: " + val);
    log.info("main.log) MY-VAR1=" + val);
  }
}

Testcase: if MY-VAR is unset, the test should fail:

package example;
...
public class HelloWorldTest {
    static final Logger log=LoggerFactory.getLogger(HelloWorldTest.class);
    @Test public void testEnv() {
        HelloWorld.main(new String[]{});
        final String val = System.getProperty("MY-VAR1", "UNSET (TEST)");
        System.out.println("(test.out) var1=" + val);
        log.info("(test.log) MY-VAR1=" + val);
        assertEquals("env MY-VAR1 set.", "VALUE-TEST", val);
    }
}

Run (note: test is passing):

$ gradle cleanTest test
:cleanTest
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test

BUILD SUCCESSFUL

I've found that the tricky part is actually getting the output from gradle... So, logging is configured here (slf4j+logback), and the log file shows the results (alternatively, run gradle --info cleanTest test; there are also properties that get stdout to the console, but, you know, why):

$ cat app.log
INFO Test worker example.HelloWorld - entering main...
INFO Test worker example.HelloWorld - main.log) MY-VAR1=VALUE-TEST
INFO Test worker example.HelloWorldTest - (test.log) MY-VAR1=VALUE-TEST

If you comment out "systemProperty..." (which, btw, only works in a test task), then:

example.HelloWorldTest > testEnv FAILED
    org.junit.ComparisonFailure at HelloWorldTest.java:14

For completeness, here is the logback config (src/test/resources/logback-test.xml):

<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>app.log</file>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%d %p %t %c - %m%n</pattern>
        </layout>
 </appender>
 <root level="info">
     <appender-ref ref="FILE"/>
</root>
</configuration> 

Files:

  • build.gradle
  • src/main/java/example/HelloWorld.java
  • src/test/java/example/HelloWorldTest.java
  • src/test/resources/logback-test.xml

Must issue a STARTTLS command first

Adding

props.put("mail.smtp.starttls.enable", "true");

solved my problem ;)

My problem was :

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. u186sm7971862pfu.82 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.example.sendmail.SendEmailExample2.main(SendEmailExample2.java:53)

python: restarting a loop

Just wanted to post an alternative which might be more genearally usable. Most of the existing solutions use a loop index to avoid this. But you don't have to use an index - the key here is that unlike a for loop, where the loop variable is hidden, the loop variable is exposed.

You can do very similar things with iterators/generators:

x = [1,2,3,4,5,6]
xi = iter(x)
ival = xi.next()
while not exit_condition(ival):
    # Do some ival stuff
    if ival == 4:
        xi = iter(x)
    ival = xi.next()

It's not as clean, but still retains the ability to write to the loop iterator itself.

Usually, when you think you want to do this, your algorithm is wrong, and you should rewrite it more cleanly. Probably what you really want to do is use a generator/coroutine instead. But it is at least possible.

PHP: Get key from array?

Here is a generic solution that you can add to your Array library. All you need to do is supply the associated value and the target array!

PHP Manual: array_search() (similiar to .indexOf() in other languages)

public function getKey(string $value, array $target)
{
    $key = array_search($value, $target);

    if ($key === null) {
        throw new InvalidArgumentException("Invalid arguments provided. Check inputs. Must be a (1) a string and (2) an array.");
    }

    if ($key === false) {
        throw new DomainException("The search value does not exists in the target array.");
    }

    return $key;
}

What is the difference between UTF-8 and Unicode?

Unicode is just a standard that defines a character set (UCS) and encodings (UTF) to encode this character set. But in general, Unicode is refered to the character set and not the standard.

Read The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) and Unicode In 5 Minutes.

Delete all nodes and relationships in neo4j 1.8

It will do the trick..

Match (n)-[r]-()
Delete n,r;

Cloning an array in Javascript/Typescript

Try this:

[https://lodash.com/docs/4.17.4#clone][1]

var objects = [{ 'a': 1 }, { 'b': 2 }];

var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

Leave you stuff there and Try the following as well:

Start > Right-click on My computer > Properties > Advanced system settings > Environment Variables > look for variable name called "Path" in the lower box

set path value value as: (you can just add it to the starting of line, don't forgot semi column in between )

c:\Program Files\java\jre7\bin

Oracle SqlPlus - saving output in a file but don't show on screen

Try this:

SET TERMOUT OFF; 
spool M:\Documents\test;
select * from employees;
/
spool off;

Notepad++ add to every line

In order to do it in one go:

  1. Copy and paste the following example text in your notepad++ window:

http:\blahblah.com

http:\blahnotblah.com

http:\blahandgainblah.com

  1. Press Ctrl+H on the notepad++ window
  2. In the Find what box type: ^(.+)$. Here ^ represents the start of the line. $ represents the end of the line. (.+) means any character in between the start and the end of the line and it would be group 1.
  3. In the Replace with box type: WhateverFrontText(\1)WhatEverEndText. Here (\1) means whatever text in a line.
  4. Check the check box Wrap around
  5. Search mode: Regular expression
  6. Result:

WhateverFrontTexthttp:\blahblah.comWhatEverEndText

WhateverFrontTexthttp:\blahnotblah.comWhatEverEndText

WhateverFrontTexthttp:\blahandgainblah.comWhatEverEndText

  1. Screenshot of the notepad++ options and result: enter image description here

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

You need to install popperjs along with bootstrap to get rid of this error.Note that if you are using "bootstrap": "^4.4.1", and @popperjs/core v2.x combinations,bootstrap may not support popperjs version. So downgrade your version.

Option 1: npm install popper.js@^1.12.9 --save

and Add following script between jquery and bootstrap scripts.

"node_modules/popper.js/dist/umd/popper.min.js",

Option 2: Add following script tag to index.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script

Getting full URL of action in ASP.NET MVC

I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.

Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).

I may have cheated a little, but it is exactly what I needed to force a https url:

<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>

I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.

how to get the last character of a string?

You can achieve this using different ways but with different performance,

1. Using bracket notation:

var str = "Test"; var lastLetter = str[str.length - 1];

But it's not recommended to use brackets. Check the reasons here

2. charAt[index]:

var lastLetter = str.charAt(str.length - 1)

This is readable and fastest among others. It is most recommended way.

3. substring:

str.substring(str.length - 1);

4. slice:

str.slice(-1);

It's slightly faster than substring.

You can check the performance here

With ES6:

You can use str.endsWith("t");

But it is not supported in IE. Check more details about endsWith here

Can one class extend two classes?

No you cannot make a class extend to two classes.

A possible solution is to make it extend from another class, and make that class extend from another again.

Get name of current script in Python

You can use __file__ to get the name of the current file. When used in the main module, this is the name of the script that was originally invoked.

If you want to omit the directory part (which might be present), you can use os.path.basename(__file__).

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { EmailComposer } from '@ionic-native/email-composer';

@Component({
  selector: 'page-about',
  templateUrl: 'about.html'
})
export class AboutPage {
  sendObj = {
    to: '',
    cc: '',
    bcc: '',
    attachments:'',
    subject:'',
    body:''
  }

  constructor(public navCtrl: NavController,private emailComposer: EmailComposer) {}

  sendEmail(){
  let email = {
    to: this.sendObj.to,
    cc: this.sendObj.cc,
    bcc: this.sendObj.bcc,
    attachments: [this.sendObj.attachments],
    subject: this.sendObj.subject,
    body: this.sendObj.body,
    isHtml: true
  }; 
  this.emailComposer.open(email);
  }  
 }

starts here html about

<ion-header>
  <ion-navbar>
    <ion-title>
      Send Invoice
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label stacked>To</ion-label>
    <ion-input [(ngModel)]="sendObj.to"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>CC</ion-label>
    <ion-input [(ngModel)]="sendObj.cc"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>BCC</ion-label>
    <ion-input [(ngModel)]="sendObj.bcc"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Add pdf</ion-label>
    <ion-input [(ngModel)]="sendObj.attachments" type="file"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Subject</ion-label>
    <ion-input [(ngModel)]="sendObj.subject"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Text message</ion-label>
    <ion-input [(ngModel)]="sendObj.body"></ion-input>
  </ion-item>

  <button ion-button full (click)="sendEmail()">Send Email</button>

</ion-content>


other stuff here

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
import { EmailComposer } from '@ionic-native/email-composer';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    EmailComposer,
    {provide: ErrorHandler, useClass: IonicErrorHandler},  
    File,
    FileOpener
  ]
})
export class AppModule {}

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

How do you easily create empty matrices javascript?

Coffeescript to the rescue!

[1..9].map -> [1..9].map -> null

How do I open a new window using jQuery?

It's not really something you need jQuery to do. There is a very simple plain old javascript method for doing this:

window.open('http://www.google.com','GoogleWindow', 'width=800, height=600');

That's it.

The first arg is the url, the second is the name of the window, this should be specified because IE will throw a fit about trying to use window.opener later if there was no window name specified (just a little FYI), and the last two params are width/height.

EDIT: Full specification can be found in the link mmmshuddup provided.