Programs & Examples On #Formatexception

FormatException is thrown when the format of an argument does not meet the parameter specifications of the invoked method.

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

Deserialize Java 8 LocalDateTime with JacksonMapper

There are two problems with your code:

1. Use of wrong type

LocalDateTime does not support timezone. Given below is an overview of java.time types and you can see that the type which matches with your date-time string, 2016-12-01T23:00:00+00:00 is OffsetDateTime because it has a zone offset of +00:00.

enter image description here

Change your declaration as follows:

private OffsetDateTime startDate;

2. Use of wrong format

There are two problems with the format:

  • You need to use y (year-of-era ) instead of Y (week-based-year). Check this discussion to learn more about it. In fact, I recommend you use u (year) instead of y (year-of-era ). Check this answer for more details on it.
  • You need to use XXX or ZZZZZ for the offset part i.e. your format should be uuuu-MM-dd'T'HH:m:ssXXX.

Check the documentation page of DateTimeFormatter for more details about these symbols/formats.

Demo:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "2019-10-21T13:00:00+02:00";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:m:ssXXX");
        OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtf);
        System.out.println(odt);
    }
}

Output:

2019-10-21T13:00+02:00

Learn more about the modern date-time API from Trail: Date Time.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Mine is the console application (it should work for the windows application as well) and I had same problem. To solve it I used PlatformTarget as x64 as my System.Data.OracleClient.dll (64 bit file) is at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5. This will explicitly use 64 bit version of Oracle Client. This might help you if your solution works only on 64bit and if you are not using 32 bit dlls like dlls made in VB. I hope it will help you.

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

I've had the same problem when running my spring boot application with tomcat7:run

It gives error with the following dependency in maven pom.xml:

    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
    </dependency>
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/.m2/repository/org/apiguardian/apiguardian-api/1.1.0/apiguardian-api-1.1.0.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19

Jul 09, 2020 1:28:09 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/.m2/repository/org/apiguardian/apiguardian-api/1.1.0/apiguardian-api-1.1.0.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19

But when I correctly specify it in test scope, it does not give error:

    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <scope>test</scope>
    </dependency>

bad operand types for binary operator "&" java

You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.

if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){

Becomes

if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

Try this:

package my_default;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test {

    public static void main(String[] args) {
        try {
        // Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook();

        // Get first/desired sheet from the workbook
        XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);

        // XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
        // because you get Sheet index (1) is out of range (no sheets)

        //Write some information in the cells or do what you want
        XSSFRow row1 = sheet.createRow(0);
        XSSFCell r1c2 = row1.createCell(0);
        r1c2.setCellValue("NAME");
        XSSFCell r1c3 = row1.createCell(1);
        r1c3.setCellValue("AGE");


        //Save excel to HDD Drive
        File pathToFile = new File("D:\\test.xlsx");
        if (!pathToFile.exists()) {
            pathToFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(pathToFile);
        workbook.write(fos);
        fos.close();
        System.out.println("Done");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
    XSSFSheet sheet = null;
    int count = 0;

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        String sName = wb.getSheetName(i);
        if (sName.startsWith(prefix))
            count++;
    }

    if (count > 0) {
        sheet = wb.createSheet(prefix + count);
    } else
        sheet = wb.createSheet(prefix);

    if (isHidden)
        wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);

        return sheet;
    }

}

Converting Hexadecimal String to Decimal Integer

This is a little library that should help you with hexadecimals in Java: https://github.com/PatrykSitko/HEX4J

It can convert from and to hexadecimals. It supports:

  • byte
  • boolean
  • char
  • char[]
  • String
  • short
  • int
  • long
  • float
  • double (signed and unsigned)

With it, you can convert your String to hexadecimal and the hexadecimal to a float/double.

Example:

String hexValue = HEX4J.Hexadecimal.from.String("Hello World");
double doubleValue = HEX4J.Hexadecimal.to.Double(hexValue);

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

Try this: Open IIS Manager, change application pool's advance setting, change Enable 32 bit Application to false.

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

"N/A" is not an integer. It must throw NumberFormatException if you try to parse it to an integer.

Check before parsing or handle Exception properly.

  1. Exception Handling

    try{
        int i = Integer.parseInt(input);
    } catch(NumberFormatException ex){ // handle your exception
        ...
    }
    

or - Integer pattern matching -

String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
 ...
}

DateTime format to SQL format using C#

Another solution to pass DateTime from C# to SQL Server, irrespective of SQL Server language settings

supposedly that your Regional Settings show date as dd.MM.yyyy (German standard '104') then

DateTime myDateTime = DateTime.Now;
string sqlServerDate = "CONVERT(date,'"+myDateTime+"',104)"; 

passes the C# datetime variable to SQL Server Date type variable, considering the mapping as per "104" rules . Sql Server date gets yyyy-MM-dd

If your Regional Settings display DateTime differently, then use the appropriate matching from the SQL Server CONVERT Table

see more about Rules: https://www.techonthenet.com/sql_server/functions/convert.php

How to return a value from try, catch, and finally?

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

How do I convert a String to a BigInteger?

Using the constructor

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

Javadoc

@Value annotation type casting to Integer from String

This problem also occurs when you have 2 resources with the same file name; say "configurations.properties" within 2 different jar or directory path configured within the classpath. For example:

You have your "configurations.properties" in your process or web application (jar, war or ear). But another dependency (jar) have the same file "configurations.properties" in the same path. Then I suppose that Spring have no idea (@_@?) where to get the property and just sends the property name declared within the @Value annotation.

Post form data using HttpWebRequest

Both the field name and the value should be url encoded. format of the post data and query string are the same

The .net way of doing is something like this

NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("field1","value1");
outgoingQueryString.Add("field2", "value2");
string postdata = outgoingQueryString.ToString();

This will take care of encoding the fields and the value names

Is it possible to have empty RequestParam values use the defaultValue?

You can keep primitive type by setting default value, in the your case just add "required = false" property:

@RequestParam(value = "i", required = false, defaultValue = "10") int i

P.S. This page from Spring documentation might be useful: Annotation Type RequestParam

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}

The module was expected to contain an assembly manifest

BadImageFormatException, in my experience, is almost always to do with x86 versus x64 compiled assemblies. It sounds like your C++ assembly is compiled for x86 and you are running on an x64 process. Is that correct?

Instead of using AnyCPU/Mixed as the platform. Try to manually set it to x86 and see if it will run after that.

Hope this helps.

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I had this problem running unit tests (xunit) in Visual Studio 2015 and came across the following fix:

Menu Bar -> Test -> Test Settings -> Default Processor Architecture -> X64

Convert hex string to int

you can easily do it with parseInt with format parameter.

Integer.parseInt("-FF", 16) ; // returns -255

javadoc Integer

Tomcat 7 "SEVERE: A child container failed during start"

for me one case was I just missed to maven update project which caused the same issue

maven update project and try if you see any errors in POM.xml

Convert hexadecimal string (hex) to a binary string

Integer.parseInt(hex,16);    
System.out.print(Integer.toBinaryString(hex));

Parse hex(String) to integer with base 16 then convert it to Binary String using toBinaryString(int) method

example

int num = (Integer.parseInt("A2B", 16));
System.out.print(Integer.toBinaryString(num));

Will Print

101000101011

Max Hex vakue Handled by int is FFFFFFF

i.e. if FFFFFFF0 is passed ti will give error

Troubleshooting BadImageFormatException

What I found worked was checking the "Use the 64 bit version of IIS Express for Web Sites and Projects" option under the Projects and Solutions => Web Projects section under the Tools=>Options menu.

Convert an integer to an array of digits

I can not add comments to the decision of Vladimir, but you can immediately make an array deployed in the right direction. Here is my solution:

public static int[] splitAnIntegerIntoAnArrayOfNumbers (int a) {
    int temp = a;
    ArrayList<Integer> array = new ArrayList<Integer>();
    do{
        array.add(temp % 10);
        temp /= 10;
    } while  (temp > 0);

    int[] arrayOfNumbers = new int[array.size()];
    for(int i = 0, j = array.size()-1; i < array.size(); i++,j--) 
        arrayOfNumbers [j] = array.get(i);
    return arrayOfNumbers;
}

Important: This solution will not work for negative integers.

Integer.valueOf() vs. Integer.parseInt()

First Question: Difference between parseInt and valueOf in java?

Second Question:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

Third Question:

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
df.parse(p);

Convert hex color value ( #ffffff ) to integer value

Answer is really simple guys, in android if you want to convert hex color in to int, just use android Color class, example shown as below

this is for light gray color

Color.parseColor("#a8a8a8");

Thats it and you will get your result.

Converting a String array into an int Array in java

public static int[] strArrayToIntArray(String[] a){
    int[] b = new int[a.length];
    for (int i = 0; i < a.length; i++) {
        b[i] = Integer.parseInt(a[i]);
    }

    return b;
}

This is a simple function, that should help you. You can use him like this:

int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);

Android: converting String to int

Change

try {
    myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {

to

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

You get this exact error should you pass an old school .xls file into this API. Save the .xls as a .xlsx and then it will work.

Convert month int to month name

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);

See Here for more details.

Or

DateTime dt = DateTime.Now;
Console.WriteLine( dt.ToString( "MMMM" ) );

Or if you want to get the culture-specific abbreviated name.

GetAbbreviatedMonthName(1);

Reference

Understanding checked vs unchecked exceptions in Java

All of those are checked exceptions. Unchecked exceptions are subclasses of RuntimeException. The decision is not how to handle them, it's should your code throw them. If you don't want the compiler telling you that you haven't handled an exception then you use an unchecked (subclass of RuntimeException) exception. Those should be saved for situations that you can't recover from, like out of memory errors and the like.

Hexadecimal to Integer in Java

Try this

public static long Hextonumber(String hexval)
    {
        hexval="0x"+hexval;
//      String decimal="0x00000bb9";
        Long number = Long.decode(hexval);
//.......       System.out.println("String [" + hexval + "] = " + number);
        return number;
        //3001
    }

Converting double to string

Just use the following:

doublevalue+""; 

This will work for any data type.

Example:

Double dd=10.09;
String ss=dd+"";

System.BadImageFormatException: Could not load file or assembly

Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:

Go and set your choice as shown:

Double value to round up in Java

There is something fundamentally wrong with what you're trying to do. Binary floating-points values do not have decimal places. You cannot meaningfully round one to a given number of decimal places, because most "round" decimal values simply cannot be represented as a binary fraction. Which is why one should never use float or double to represent money.

So if you want decimal places in your result, that result must either be a String (which you already got with the DecimalFormat), or a BigDecimal (which has a setScale() method that does exactly what you want). Otherwise, the result cannot be what you want it to be.

Read The Floating-Point Guide for more information.

System.BadImageFormatException An attempt was made to load a program with an incorrect format

For running it on any CPU either 62 bit or 32 bit follow these steps: Right click on the name of the project in Solution Explorer> Properties>Build and have these under Configuration: Active(Release), Platform:Active(Any CPU) and Target:x86. and just beside the Run button Select option Release and Any CPU from the options. And then Save it and Run.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

In my case, I was running tests through MSTest and found out that I was deploying both a 32-bit and 64-bit DLL to the test directory. The program was favoring the 64-bit DLL and causing it to fail.

TL;DR Make sure you only deploy 32-bit DLLs to tests.

How to do an Integer.parseInt() for a decimal number?

Use,

String s="0.01";
int i= new Double(s).intValue();

How do I parse a string with a decimal point to a double?

string testString1 = "2,457";
string testString2 = "2.457";    
double testNum = 0.5;
char decimalSepparator;
decimalSepparator = testNum.ToString()[1];

Console.WriteLine(double.Parse(testString1.Replace('.', decimalSepparator).Replace(',', decimalSepparator)));
Console.WriteLine(double.Parse(testString2.Replace('.', decimalSepparator).Replace(',', decimalSepparator)));

Could not load file or assembly 'System.Data.SQLite'

Another way to get around this is just to upgrade your application to ELMAH 1.2 rather than 1.1.

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

I think you are using the 64-bit version of the tool to install a 32-bit application. I've also faced this issue today and used this Framework path to cater .

C:\Windows\Microsoft.NET\Framework\v4.0.30319

and it should install your 32-bit application just fine.

Java: Reading integers from a file into an array

File file = new File("E:/Responsibility.txt");  
    Scanner scanner = new Scanner(file);
    List<Integer> integers = new ArrayList<>();
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            integers.add(scanner.nextInt());
        } else {
            scanner.next();
        }
    }
    System.out.println(integers);

Should try...catch go inside or outside a loop?

setting up a special stack frame for the try/catch adds additional overhead, but the JVM may be able to detect the fact that you're returning and optimize this away.

depending on the number of iterations, performance difference will likely be negligible.

However i agree with the others that having it outside the loop make the loop body look cleaner.

If there's a chance that you'll ever want to continue on with the processing rather than exit if there an invalid number, then you would want the code to be inside the loop.

Catch multiple exceptions at once?

Wanted to added my short answer to this already long thread. Something that hasn't been mentioned is the order of precedence of the catch statements, more specifically you need to be aware of the scope of each type of exception you are trying to catch.

For example if you use a "catch-all" exception as Exception it will preceed all other catch statements and you will obviously get compiler errors however if you reverse the order you can chain up your catch statements (bit of an anti-pattern I think) you can put the catch-all Exception type at the bottom and this will be capture any exceptions that didn't cater for higher up in your try..catch block:

            try
            {
                // do some work here
            }
            catch (WebException ex)
            {
                // catch a web excpetion
            }
            catch (ArgumentException ex)
            {
                // do some stuff
            }
            catch (Exception ex)
            {
                // you should really surface your errors but this is for example only
                throw new Exception("An error occurred: " + ex.Message);
            }

I highly recommend folks review this MSDN document:

Exception Hierarchy

What's better at freeing memory with PHP: unset() or $var = null

unset code if not freeing immediate memory is still very helpful and would be a good practice to do this each time we pass on code steps before we exit a method. take note its not about freeing immediate memory. immediate memory is for CPU, what about secondary memory which is RAM.

and this also tackles about preventing memory leaks.

please see this link http://www.hackingwithphp.com/18/1/11/be-wary-of-garbage-collection-part-2

i have been using unset for a long time now.

better practice like this in code to instanly unset all variable that have been used already as array.

$data['tesst']='';
$data['test2']='asdadsa';
....
nth.

and just unset($data); to free all variable usage.

please see related topic to unset

How important is it to unset variables in PHP?

[bug]

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just after your Page_Load add this:

public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
}

Note that I don't do anything in the function.

EDIT: Tim answered the same thing. :) You can also find the answer Here

AddRange to a Collection

Here is a bit more advanced/production-ready version:

    public static class CollectionExtensions
    {
        public static TCol AddRange<TCol, TItem>(this TCol destination, IEnumerable<TItem> source)
            where TCol : ICollection<TItem>
        {
            if(destination == null) throw new ArgumentNullException(nameof(destination));
            if(source == null) throw new ArgumentNullException(nameof(source));

            // don't cast to IList to prevent recursion
            if (destination is List<TItem> list)
            {
                list.AddRange(source);
                return destination;
            }

            foreach (var item in source)
            {
                destination.Add(item);
            }

            return destination;
        }
    }

HTML5 iFrame Seamless Attribute

I thought this might be useful to someone:

in chrome version 32, a 2-pixels border automatically appears around iframes without the seamless attribute. It can be easily removed by adding this CSS rule:

iframe:not([seamless]) { border:none; }

Chrome uses the same selector with these default user-agent styles:

iframe:not([seamless]) {
  border: 2px inset;
  border-image-source: initial;
  border-image-slice: initial;
  border-image-width: initial;
  border-image-outset: initial;
  border-image-repeat: initial;
}

How to export library to Jar in Android Studio?

I was able to export a jar file in Android Studio using this tutorial: https://www.youtube.com/watch?v=1i4I-Nph-Cw "How To Export Jar From Android Studio "

I updated my answer to include all the steps for exporting a JAR in Android Studio:

1) Create Android application project, go to app->build.gradle

2) Change the following in this file:

  • modify apply plugin: 'com.android.application' to apply plugin: 'com.android.library'

  • remove the following: applicationId, versionCode and versionName

  • Add the following code:

// Task to delete old jar
task deleteOldJar(type: Delete){
   delete 'release/AndroidPlugin2.jar'
}
// task to export contents as jar
task exportJar(type: Copy) {
    from ('build/intermediates/bundles/release/')
    into ('release/')
    include ('classes.jar')
    rename('classes.jar', 'AndroidPlugin2.jar')
}
exportJar.dependsOn(deleteOldJar, build)

3) Don't forget to click sync now in this file (top right or use sync button).

4) Click on Gradle tab (usually middle right) and scroll down to exportjar

5) Once you see the build successful message in the run window, using normal file explorer go to exported jar using the path: C:\Users\name\AndroidStudioProjects\ProjectName\app\release you should see in this directory your jar file.

Good Luck :)

Styling the last td in a table with css

You can use the :last-of-type to catch last column of your table.

<style>
.table > tbody > tr > td:last-of-type {
    /* Give your style Here; */
}
</style>

How to cin to a vector

cin is delimited on space, so if you try to cin "1 2 3 4 5" into a single integer, your only going to be assigning 1 to the integer, a better option is to wrap your input and push_back in a loop, and have it test for a sentinel value, and on that sentinel value, call your write function. such as

int input;
cout << "Enter your numbers to be evaluated, and 10000 to quit: " << endl;
while(input != 10000) {
    cin >> input;
   V.push_back(input);
}
write_vector(V);

How to remove element from array in forEach loop?

I understood that you want to remove from the array using a condition and have another array that has items removed from the array. Is right?

How about this?

_x000D_
_x000D_
var review = ['a', 'b', 'c', 'ab', 'bc'];_x000D_
var filtered = [];_x000D_
for(var i=0; i < review.length;) {_x000D_
  if(review[i].charAt(0) == 'a') {_x000D_
    filtered.push(review.splice(i,1)[0]);_x000D_
  }else{_x000D_
    i++;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);
_x000D_
_x000D_
_x000D_

Hope this help...

By the way, I compared 'for-loop' to 'forEach'.

If remove in case a string contains 'f', a result is different.

_x000D_
_x000D_
var review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
var filtered = [];_x000D_
for(var i=0; i < review.length;) {_x000D_
  if( review[i].includes('f')) {_x000D_
    filtered.push(review.splice(i,1)[0]);_x000D_
  }else {_x000D_
    i++;_x000D_
  }_x000D_
}_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);_x000D_
/**_x000D_
 * review [  "concat",  "copyWithin",  "entries",  "every",  "includes",  "join",  "keys",  "map",  "pop",  "push",  "reduce",  "reduceRight",  "reverse",  "slice",  "some",  "sort",  "splice",  "toLocaleString",  "toSource",  "toString",  "values"] _x000D_
 */_x000D_
_x000D_
console.log("========================================================");_x000D_
review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
filtered = [];_x000D_
_x000D_
review.forEach(function(item,i, object) {_x000D_
  if( item.includes('f')) {_x000D_
    filtered.push(object.splice(i,1)[0]);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log("-----------------------------------------");_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);_x000D_
_x000D_
/**_x000D_
 * review [  "concat",  "copyWithin",  "entries",  "every",  "filter",  "findIndex",  "flatten",  "includes",  "join",  "keys",  "map",  "pop",  "push",  "reduce",  "reduceRight",  "reverse",  "slice",  "some",  "sort",  "splice",  "toLocaleString",  "toSource",  "toString",  "values"]_x000D_
 */
_x000D_
_x000D_
_x000D_

And remove by each iteration, also a result is different.

_x000D_
_x000D_
var review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
var filtered = [];_x000D_
for(var i=0; i < review.length;) {_x000D_
  filtered.push(review.splice(i,1)[0]);_x000D_
}_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);_x000D_
console.log("========================================================");_x000D_
review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
filtered = [];_x000D_
_x000D_
review.forEach(function(item,i, object) {_x000D_
  filtered.push(object.splice(i,1)[0]);_x000D_
});_x000D_
_x000D_
console.log("-----------------------------------------");_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);
_x000D_
_x000D_
_x000D_

How does HTTP file upload work?

Send file as binary content (upload without form or FormData)

In the given answers/examples the file is (most likely) uploaded with a HTML form or using the FormData API. The file is only a part of the data sent in the request, hence the multipart/form-data Content-Type header.

If you want to send the file as the only content then you can directly add it as the request body and you set the Content-Type header to the MIME type of the file you are sending. The file name can be added in the Content-Disposition header. You can upload like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

If you don't (want to) use forms and you are only interested in uploading one single file this is the easiest way to include your file in the request.

Warning: X may be used uninitialized in this function

When you use Vector *one you are merely creating a pointer to the structure but there is no memory allocated to it.

Simply use one = (Vector *)malloc(sizeof(Vector)); to declare memory and instantiate it.

Good font for code presentations?

I do a lot of such presentation and use Monaco for code and Chalkboard for text (within a template that, overall, has only small changes from the Blackboard one supplied with Keynote). Look at any of my presentations' PDFs (e.g. this one) and you can decide whether you like the effect.

Android canvas draw rectangle

The code is fine just setStyle of paint as STROKE

paint.setStyle(Paint.Style.STROKE);

Java code for getting current time

Try this way, more efficient and compatible:

SimpleDateFormat time_formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
String current_time_str = time_formatter.format(System.currentTimeMillis());
//Log.i("test", "current_time_str:" + current_time_str);

How to show and update echo on same line

Well I did not read correctly the man echo page for this.

echo had 2 options that could do this if I added a 3rd escape character.

The 2 options are -n and -e.

-n will not output the trailing newline. So that saves me from going to a new line each time I echo something.

-e will allow me to interpret backslash escape symbols.

Guess what escape symbol I want to use for this: \r. Yes, carriage return would send me back to the start and it will visually look like I am updating on the same line.

So the echo line would look like this:

echo -ne "Movie $movies - $dir ADDED!"\\r

I had to escape the escape symbol so Bash would not kill it. that is why you see 2 \ symbols in there.

As mentioned by William, printf can also do similar (and even more extensive) tasks like this.

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I usually use getReference method when i do not need to access database state (I mean getter method). Just to change state (I mean setter method). As you should know, getReference returns a proxy object which uses a powerful feature called automatic dirty checking. Suppose the following

public class Person {

    private String name;
    private Integer age;

}


public class PersonServiceImpl implements PersonService {

    public void changeAge(Integer personId, Integer newAge) {
        Person person = em.getReference(Person.class, personId);

        // person is a proxy
        person.setAge(newAge);
    }

}

If i call find method, JPA provider, behind the scenes, will call

SELECT NAME, AGE FROM PERSON WHERE PERSON_ID = ?

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

If i call getReference method, JPA provider, behind the scenes, will call

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

And you know why ???

When you call getReference, you will get a proxy object. Something like this one (JPA provider takes care of implementing this proxy)

public class PersonProxy {

    // JPA provider sets up this field when you call getReference
    private Integer personId;

    private String query = "UPDATE PERSON SET ";

    private boolean stateChanged = false;

    public void setAge(Integer newAge) {
        stateChanged = true;

        query += query + "AGE = " + newAge;
    }

}

So before transaction commit, JPA provider will see stateChanged flag in order to update OR NOT person entity. If no rows is updated after update statement, JPA provider will throw EntityNotFoundException according to JPA specification.

regards,

How to get exit code when using Python subprocess communicate method?

Popen.communicate will set the returncode attribute when it's done(*). Here's the relevant documentation section:

Popen.returncode 
  The child return code, set by poll() and wait() (and indirectly by communicate()). 
  A None value indicates that the process hasn’t terminated yet.

  A negative value -N indicates that the child was terminated by signal N (Unix only).

So you can just do (I didn't test it but it should work):

import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode

(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait.

How can I specify system properties in Tomcat configuration on startup?

cliff.meyers's original answer that suggested using <env-entry> will not help when using only System.getProperty()

According to the Tomcat 6.0 docs <env-entry> is for JNDI. So that means it won't have any effect on System.getProperty().

With the <env-entry> from cliff.meyers's example, the following code

System.getProperty("SMTP_PASSWORD");

will return null, not the value "abc123ftw".

According to the Tomcat 6 docs, to use <env-entry> you'd have to write code like this to use <env-entry>:

// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");

// Look up our data source
String s = (String)envCtx.lookup("SMTP_PASSWORD");

Caveat: I have not actually tried the example above. But I have tried <env-entry> with System.getProperty(), and that definitely does not work.

Using ListView : How to add a header view?

You can add as many headers as you like by calling addHeaderView() multiple times. You have to do it before setting the adapter to the list view.

And yes you can add header something like this way:

LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, myListView, false);
myListView.addHeaderView(header, null, false);

How do I find out what License has been applied to my SQL Server installation?

SELECT SERVERPROPERTY('LicenseType') as Licensetype, 
       SERVERPROPERTY('NumLicenses') as LicenseNumber,
       SERVERPROPERTY('productversion') as Productverion, 
       SERVERPROPERTY ('productlevel')as ProductLevel, 
       SERVERPROPERTY ('edition') as SQLEdition,@@VERSION as SQLversion

I had installed evaluation edition.Refer screenshot enter image description here

jQuery trigger file input

i had problems with custom client side validation for <input type="file"/> while using a fake button to trigger it and @Guillaume Bodi's solution worked for me (also with opacity: 0; on chrome)

$("#MyForm").on("click", "#fake-button", function () {
        $("#uploadInput").focus().trigger("click");
    });

and css style for upload input

#uploadInput {
opacity: 0.0; 
filter: alpha(opacity=0); /* IE lt 8 */
-ms-filter: "alpha(opacity=0)"; /* IE 8 */
-khtml-opacity: 0.0; /* Safari 1.x */
-moz-opacity: 0.0;
}

Loop and get key/value pair for JSON array using jQuery

var obj = $.parseJSON(result);
for (var prop in obj) {
    alert(prop + " is " + obj[prop]);
}

How to get div height to auto-adjust to background size?

If you know the ratio of the image at build time, want the height based off of the window height and you're ok targeting modern browsers (IE9+), then you can use viewport units for this:

.width-ratio-of-height {
  overflow-x: scroll;
  height: 100vh;
  width: 500vh; /* width here is 5x height */
  background-image: url("http://placehold.it/5000x1000");
  background-size: cover;
}

Not quite what the OP was asking, but probably a good fit for a lot of those viewing this question, so wanted to give another option here.

Fiddle: https://jsfiddle.net/6Lkzdnge/

Can't append <script> element

<script>
    ...
    ...jQuery("<script></script>")...
    ...
</script>

The </script> within the string literal terminates the entire script, to avoid that "</scr" + "ipt>" can be used instead.

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

Best way of invoking getter by reflection

You can invoke reflections and also, set order of sequence for getter for values through annotations

public class Student {

    private String grade;

    private String name;

    private String id;

    private String gender;

    private Method[] methods;

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Order {
        int value();
    }

    /**
     * Sort methods as per Order Annotations
     * 
     * @return
     */
    private void sortMethods() {

        methods = Student.class.getMethods();

        Arrays.sort(methods, new Comparator<Method>() {
            public int compare(Method o1, Method o2) {
                Order or1 = o1.getAnnotation(Order.class);
                Order or2 = o2.getAnnotation(Order.class);
                if (or1 != null && or2 != null) {
                    return or1.value() - or2.value();
                }
                else if (or1 != null && or2 == null) {
                    return -1;
                }
                else if (or1 == null && or2 != null) {
                    return 1;
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    /**
     * Read Elements
     * 
     * @return
     */
    public void readElements() {
        int pos = 0;
        /**
         * Sort Methods
         */
        if (methods == null) {
            sortMethods();
        }
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
                pos++;
                String value = "";
                try {
                    value = (String) method.invoke(this);
                }
                catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                System.out.println(name + " Pos: " + pos + " Value: " + value);
            }
        }
    }

    // /////////////////////// Getter and Setter Methods

    /**
     * @param grade
     * @param name
     * @param id
     * @param gender
     */
    public Student(String grade, String name, String id, String gender) {
        super();
        this.grade = grade;
        this.name = name;
        this.id = id;
        this.gender = gender;
    }

    /**
     * @return the grade
     */
    @Order(value = 4)
    public String getGrade() {
        return grade;
    }

    /**
     * @param grade the grade to set
     */
    public void setGrade(String grade) {
        this.grade = grade;
    }

    /**
     * @return the name
     */
    @Order(value = 2)
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the id
     */
    @Order(value = 1)
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the gender
     */
    @Order(value = 3)
    public String getGender() {
        return gender;
    }

    /**
     * @param gender the gender to set
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    /**
     * Main
     * 
     * @param args
     * @throws IOException
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Student student = new Student("A", "Anand", "001", "Male");
        student.readElements();
    }
  }

Output when sorted

getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A

Get started with Latex on Linux

yum -y install texlive

was not enough for my centos distro to get the latex command.

This site https://gist.github.com/melvincabatuan/350f86611bc012a5c1c6 contains additional packages. In particular:

yum -y install texlive texlive-latex texlive-xetex

was enough but the author also points out these as well:

yum -y install texlive-collection-latex
yum -y install texlive-collection-latexrecommended
yum -y install texlive-xetex-def
yum -y install texlive-collection-xetex

Only if needed:

yum -y install texlive-collection-latexextra

How can I export the schema of a database in PostgreSQL?

pg_dump -s databasename -t tablename -U user -h host -p port > tablename.sql

this will limit the schema dump to the table "tablename" of "databasename"

How to check if an appSettings key exists?

I think the LINQ expression may be best:

   const string MyKey = "myKey"

   if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey))
          {
              // Key exists
          }

jQuery function after .append

Yes you can add a callback function to any DOM insertion:
$myDiv.append( function(index_myDiv, HTML_myDiv){ //.... return child })

Check on JQuery documentation: http://api.jquery.com/append/
And here's a practical, similar, example: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_prepend_func

List<Object> and List<?>

List is an interface so you can't instanciate it. Use any of its implementatons instead e.g.

List<Object> object = new List<Object>();

About List : you can use any object as a generic param for it instance:

List<?> list = new ArrayList<String>();

or

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

While using List<Object> this declaration is invalid because it will be type missmatch.

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

If you are simply testing a local dev version of WordPress as I was an hitting timeouts when WordPress tries to update itself you can always disable updates for your local version like so: https://www.wpbeginner.com/wp-tutorials/how-to-disable-automatic-updates-in-wordpress/

Don't do this for a production site!

How to set a Javascript object values dynamically?

You can get the property the same way as you set it.

foo = {
 bar: "value"
}

You set the value foo["bar"] = "baz";

To get the value foo["bar"]

will return "baz".

How to check file MIME type with javascript before upload?

As stated in other answers, you can check the mime type by checking the signature of the file in the first bytes of the file.

But what other answers are doing is loading the entire file in memory in order to check the signature, which is very wasteful and could easily freeze your browser if you select a big file by accident or not.

_x000D_
_x000D_
/**_x000D_
 * Load the mime type based on the signature of the first bytes of the file_x000D_
 * @param  {File}   file        A instance of File_x000D_
 * @param  {Function} callback  Callback with the result_x000D_
 * @author Victor www.vitim.us_x000D_
 * @date   2017-03-23_x000D_
 */_x000D_
function loadMime(file, callback) {_x000D_
    _x000D_
    //List of known mimes_x000D_
    var mimes = [_x000D_
        {_x000D_
            mime: 'image/jpeg',_x000D_
            pattern: [0xFF, 0xD8, 0xFF],_x000D_
            mask: [0xFF, 0xFF, 0xFF],_x000D_
        },_x000D_
        {_x000D_
            mime: 'image/png',_x000D_
            pattern: [0x89, 0x50, 0x4E, 0x47],_x000D_
            mask: [0xFF, 0xFF, 0xFF, 0xFF],_x000D_
        }_x000D_
        // you can expand this list @see https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern_x000D_
    ];_x000D_
_x000D_
    function check(bytes, mime) {_x000D_
        for (var i = 0, l = mime.mask.length; i < l; ++i) {_x000D_
            if ((bytes[i] & mime.mask[i]) - mime.pattern[i] !== 0) {_x000D_
                return false;_x000D_
            }_x000D_
        }_x000D_
        return true;_x000D_
    }_x000D_
_x000D_
    var blob = file.slice(0, 4); //read the first 4 bytes of the file_x000D_
_x000D_
    var reader = new FileReader();_x000D_
    reader.onloadend = function(e) {_x000D_
        if (e.target.readyState === FileReader.DONE) {_x000D_
            var bytes = new Uint8Array(e.target.result);_x000D_
_x000D_
            for (var i=0, l = mimes.length; i<l; ++i) {_x000D_
                if (check(bytes, mimes[i])) return callback("Mime: " + mimes[i].mime + " <br> Browser:" + file.type);_x000D_
            }_x000D_
_x000D_
            return callback("Mime: unknown <br> Browser:" + file.type);_x000D_
        }_x000D_
    };_x000D_
    reader.readAsArrayBuffer(blob);_x000D_
}_x000D_
_x000D_
_x000D_
//when selecting a file on the input_x000D_
fileInput.onchange = function() {_x000D_
    loadMime(fileInput.files[0], function(mime) {_x000D_
_x000D_
        //print the output to the screen_x000D_
        output.innerHTML = mime;_x000D_
    });_x000D_
};
_x000D_
<input type="file" id="fileInput">_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Extracting Ajax return data in jQuery

You can use .filter on a jQuery object that was created from the response:

success: function(data){
    //Create jQuery object from the response HTML.
    var $response=$(data);

    //Query the jQuery object for the values
    var oneval = $response.filter('#one').text();
    var subval = $response.filter('#sub').text();
}

How to bind DataTable to Datagrid

using (SqlCeConnection con = new SqlCeConnection())
   {
   con.ConnectionString = connectionString;
   con.Open();
   SqlCeCommand com = new SqlCeCommand("SELECT S_no,Name,Father_Name")
   SqlCeDataAdapter sda = new SqlCeDataAdapter(com);
   System.Data.DataTable dt = new System.Data.DataTable();
   sda.Fill(dt);
   dataGrid1.ItemsSource = dt.DefaultView;
   dataGrid1.AutoGenerateColumns = true;
   dataGrid1.CanUserAddRows = false;
   }

Run a mySQL query as a cron job?

Try creating a shell script like the one below:

#!/bin/bash

mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7"

You can then add this to the cron

Drop shadow on a div container?

This works for me on all my browsers:

.shadow {
-moz-box-shadow: 0 0 30px 5px #999;
-webkit-box-shadow: 0 0 30px 5px #999;
}

then just give any div the shadow class, no jQuery required.

google console error `OR-IEH-01`

Recently I was also having this issue, then I contacted Google Support and they gave me this link to provide required info, I posted and within 24 hours my problem was fixed.

Link: https://support.google.com/payments/contact/alt_account_verification

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

You might want to use your local file as a last resort.

Seems as of now jQuery's own CDN does not support https. If it did you then might want to load from there first.

So here's the sequence: Google CDN => Microsoft CDN => Your local copy.

<!-- load jQuery from Google's CDN -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<!-- fallback to Microsoft's Ajax CDN -->
<script> window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js">\x3C/script>')</script> 
<!-- fallback to local file -->
<script> window.jQuery || document.write('<script src="Assets/jquery-1.8.3.min.js">\x3C/script>')</script> 

How can I convert a PFX certificate file for use with Apache on a linux server?

With OpenSSL you can convert pfx to Apache compatible format with next commands:

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain.key   

First command extracts public key to domain.cer.
Second command extracts private key to domain.key.

Update your Apache configuration file with:

<VirtualHost 192.168.0.1:443>
 ...
 SSLEngine on
 SSLCertificateFile /path/to/domain.cer
 SSLCertificateKeyFile /path/to/domain.key
 ...
</VirtualHost>

How to strip HTML tags with jQuery?

This is a example for get the url image, escape the p tag from some item.

Try this:

$('#img').attr('src').split('<p>')[1].split('</p>')[0]

Under what conditions is a JSESSIONID created?

Here is some information about one more source of the JSESSIONID cookie:

I was just debugging some Java code that runs on a tomcat server. I was not calling request.getSession() explicitly anywhere in my code but I noticed that a JSESSIONID cookie was still being set.

I finally took a look at the generated Java code corresponding to a JSP in the work directory under Tomcat.

It appears that, whether you like it or not, if you invoke a JSP from a servlet, JSESSIONID will get created!

Added: I just found that by adding the following JSP directive:

<%@ page session="false" %>

you can disable the setting of JSESSIONID by a JSP.

Comparing two hashmaps for equal values and same key sets?

Compare every key in mapB against the counterpart in mapA. Then check if there is any key in mapA not existing in mapB

public boolean mapsAreEqual(Map<String, String> mapA, Map<String, String> mapB) {

    try{
        for (String k : mapB.keySet())
        {
            if (!mapA.get(k).equals(mapB.get(k))) {
                return false;
            }
        } 
        for (String y : mapA.keySet())
        {
            if (!mapB.containsKey(y)) {
                return false;
            }
        } 
    } catch (NullPointerException np) {
        return false;
    }
    return true;
}

Convert float64 column to int64 in Pandas

You can need to pass in the string 'int64':

>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1.0, 2.0]})  # some test dataframe

>>> df['a'].astype('int64')
0    1
1    2
Name: a, dtype: int64

There are some alternative ways to specify 64-bit integers:

>>> df['a'].astype('i8')      # integer with 8 bytes (64 bit)
0    1
1    2
Name: a, dtype: int64

>>> import numpy as np
>>> df['a'].astype(np.int64)  # native numpy 64 bit integer
0    1
1    2
Name: a, dtype: int64

Or use np.int64 directly on your column (but it returns a numpy.array):

>>> np.int64(df['a'])
array([1, 2], dtype=int64)

Test if numpy array contains only zeros

I'd use np.all here, if you have an array a:

>>> np.all(a==0)

Drop all tables whose names begin with a certain string

On Oracle XE this works:

SELECT 'DROP TABLE "' || TABLE_NAME || '";'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'

Or if you want to remove the constraints and free up space as well, use this:

SELECT 'DROP TABLE "' || TABLE_NAME || '" cascade constraints PURGE;'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'

Which will generate a bunch of DROP TABLE cascade constraints PURGE statements...

For VIEWS use this:

SELECT 'DROP VIEW "' || VIEW_NAME || '";'
FROM USER_VIEWS
WHERE VIEW_NAME LIKE 'YOURVIEWPREFIX%'

Select all 'tr' except the first one

You could also use a pseudo class selector in your CSS like this:

.desc:not(:first-child) {
    display: none;
}

That will not apply the class to the first element with the class .desc.

Here's a JSFiddle with an example: http://jsfiddle.net/YYTFT/, and this is a good source to explain pseudo class selectors: http://css-tricks.com/pseudo-class-selectors/

How to subtract X day from a Date object in Java?

Simply use this to get date before 300 days, replace 300 with your days:

Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();

Here,

DateTime is org.joda.time.DateTime;

Date is java.util.Date

How to prevent caching of my Javascript file?

Configure your webserver to send caching control HTTP headers for the script.

Fake headers in the HTML documents:

  1. Aren't as well supported as real HTTP headers
  2. Apply to the HTML document, not to resources that it links to

How do I change the language of moment.js?

I am not sure what changed but importing the language file like this worked for me

import 'moment/src/locale/fr';
moment.locale('fr)

Notice the src in the import statement

Countdown timer in React

The one downside with setInterval is that it can slow down the main thread. You can do a countdown timer using requestAnimationFrame instead to prevent this. For example, this is my generic countdown timer component:

class Timer extends Component {
  constructor(props) {
    super(props)
    // here, getTimeRemaining is a helper function that returns an 
    // object with { total, seconds, minutes, hours, days }
    this.state = { timeLeft: getTimeRemaining(props.expiresAt) }
  }

  // Wait until the component has mounted to start the animation frame
  componentDidMount() {
    this.start()
  }

  // Clean up by cancelling any animation frame previously scheduled
  componentWillUnmount() {
    this.stop()
  }

  start = () => {
    this.frameId = requestAnimationFrame(this.tick)
  }

  tick = () => {
    const timeLeft = getTimeRemaining(this.props.expiresAt)
    if (timeLeft.total <= 0) {
      this.stop()
      // ...any other actions to do on expiration
    } else {
      this.setState(
        { timeLeft },
        () => this.frameId = requestAnimationFrame(this.tick)
      )
    }
  }

  stop = () => {
    cancelAnimationFrame(this.frameId)
  }

  render() {...}
}

Convert xlsx file to csv using batch

To follow up on the answer by user183038, here is a shell script to batch rename all xlsx files to csv while preserving the file names. The xlsx2csv tool needs to be installed prior to running.

for i in *.xlsx;
 do
  filename=$(basename "$i" .xlsx);
  outext=".csv" 
  xlsx2csv $i $filename$outext
done

jQuery checkbox checked state changed event

$(document).ready(function () {
    $(document).on('change', 'input[Id="chkproperty"]', function (e) {
        alert($(this).val());
    });
});

AppStore - App status is ready for sale, but not in app store

I published an update to my app yesterday noon(I have selected Manual release instead of Automatic) and Today early morning App store review was completed and after I release the build manually, the App shows Ready for sale in iTunesConect immediately. After 45mins I got the update on the App store.

django admin - add custom form fields that are not part of the model

you can always create new admin template , and do what you need in your admin_view (override the admin add url to your admin_view):

 url(r'^admin/mymodel/mymodel/add/$' , 'admin_views.add_my_special_model')

What is the equivalent to getch() & getche() in Linux?

#include <termios.h>
#include <stdio.h>

static struct termios old, current;

/* Initialize new terminal i/o settings */
void initTermios(int echo) 
{
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  current = old; /* make new settings same as old settings */
  current.c_lflag &= ~ICANON; /* disable buffered i/o */
  if (echo) {
      current.c_lflag |= ECHO; /* set echo mode */
  } else {
      current.c_lflag &= ~ECHO; /* set no echo mode */
  }
  tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void) 
{
  tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo) 
{
  char ch;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  return ch;
}

/* Read 1 character without echo */
char getch(void) 
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void) 
{
  return getch_(1);
}

/* Let's test it out */
int main(void) {
  char c;
  printf("(getche example) please type a letter: ");
  c = getche();
  printf("\nYou typed: %c\n", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("\nYou typed: %c\n", c);
  return 0;
}

Output:

(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g

Remove a cookie

You could set a session variable based on cookie values

session_start();

if(isset($_COOKIE['loggedin']) && ($_COOKIE['loggedin'] == "true") ){
$_SESSION['loggedin'] = "true";
}

echo ($_SESSION['loggedin'] == "true" ? "You are logged in" : "Please Login to continue");

No resource found that matches the given name '@style/Theme.AppCompat.Light'

If you are looking for the solution in Android Studio :

  1. Right click on your app
  2. Open Module Settings
  3. Select Dependencies tab
  4. Click on green + symbol which is on the right side
  5. Select Library Dependency
  6. Choose appcompat-v7 from list

How do I update a GitHub forked repository?

Follow the below steps. I tried them and it helped me.

Checkout to your branch

Syntax: git branch yourDevelopmentBranch
Example: git checkout master

Pull source repository branch for getting the latest code

Syntax: git pull https://github.com/tastejs/awesome-app-ideas master
Example: git pull https://github.com/ORIGINAL_OWNER/ORIGINAL_REPO.git BRANCH_NAME

Ansible: deploy on multiple hosts in the same time

As of Ansible 2.0 there seems to be an option called strategy on a playbook. When setting the strategy to free, the playbook plays tasks on each host without waiting to the others. See http://docs.ansible.com/ansible/playbooks_strategies.html.

It looks something like this (taken from the above link):

- hosts: all
  strategy: free
  tasks:
  ...

Please note that I didn't check this and I'm very new to Ansible. I was just curious about doing what you described and happened to come acroess this strategy thing.

EDIT:

It seems like this is not exactly what you're trying to do. Maybe "async tasks" is more appropriate as described here: http://docs.ansible.com/ansible/playbooks_async.html.

This includes specifying async and poll on a task. The following is taken from the 2nd link I mentioned:

- name: simulate long running op, allow to run for 45 sec, fire and forget
  command: /bin/sleep 15
  async: 45
  poll: 0

I guess you can specify longer async times if your task is lengthy. You can probably define your three concurrent task this way.

How to call a method defined in an AngularJS directive?

Assuming that the action button uses the same controller $scope as the directive, just define function updateMap on $scope inside the link function. Your controller can then call that function when the action button is clicked.

<div ng-controller="MyCtrl">
    <map></map>
    <button ng-click="updateMap()">call updateMap()</button>
</div>
app.directive('map', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function($scope, element, attrs) {
            $scope.updateMap = function() {
                alert('inside updateMap()');
            }
        }
    }
});

fiddle


As per @FlorianF's comment, if the directive uses an isolated scope, things are more complicated. Here's one way to make it work: add a set-fn attribute to the map directive which will register the directive function with the controller:

<map set-fn="setDirectiveFn(theDirFn)"></map>
<button ng-click="directiveFn()">call directive function</button>
scope: { setFn: '&' },
link: function(scope, element, attrs) {
    scope.updateMap = function() {
       alert('inside updateMap()');
    }
    scope.setFn({theDirFn: scope.updateMap});
}
function MyCtrl($scope) {
    $scope.setDirectiveFn = function(directiveFn) {
        $scope.directiveFn = directiveFn;
    };
}

fiddle

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I had a similar problem and in my case, the issue was different (I am using Django templates).

The order of JS was different (I know that's the first thing you check but I was almost sure that that was not the case, but it was). The js calling the dialog was called before jqueryUI library was called.

I am using Django, so was inheriting a template and using {{super.block}} to inherit code from the block as well to the template. I had to move {{super.block}} at the end of the block which solved the issue. The js calling the dialog was declared in the Media class in Django's admin.py. I spent more than an hour to figure it out. Hope this helps someone.

How to change default install location for pip

Open Terminal and type:

pip config set global.target /Users/Bob/Library/Python/3.8/lib/python/site-packages

except instead of

/Users/Bob/Library/Python/3.8/lib/python/site-packages

you would use whatever directory you want.

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

Put search icon near textbox using bootstrap

Adding a class with a width of 90% to your input element and adding the following input-icon class to your span would achieve what you want I think.

.input { width: 90%; }
.input-icon {
    display: inline-block;
    height: 22px;
    width: 22px;
    line-height: 22px;
    text-align: center;
    color: #000;
    font-size: 12px;
    font-weight: bold;
    margin-left: 4px;
}

EDIT Per dan's suggestion, it would not be wise to use .input as the class name, some more specific would be advised. I was simply using .input as a generic placeholder for your css

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

iOS 5 added the following style that can be added to the parent div so that scrolling works.

-webkit-overflow-scrolling:touch

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

I also struggled finding articles on how to just generate the token part. I never found one and wrote my own. So if it helps:

The things to do are:

  • Create a new web application
  • Install the following NuGet packages:
    • Microsoft.Owin
    • Microsoft.Owin.Host.SystemWeb
    • Microsoft.Owin.Security.OAuth
    • Microsoft.AspNet.Identity.Owin
  • Add a OWIN startup class

Then create a HTML and a JavaScript (index.js) file with these contents:

var loginData = 'grant_type=password&[email protected]&password=test123';

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        alert(xmlhttp.responseText);
    }
}
xmlhttp.open("POST", "/token", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(loginData);
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="index.js"></script>
</body>
</html>

The OWIN startup class should have this content:

using System;
using System.Security.Claims;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using OAuth20;
using Owin;

[assembly: OwinStartup(typeof(Startup))]

namespace OAuth20
{
    public class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public void Configuration(IAppBuilder app)
        {
            OAuthOptions = new OAuthAuthorizationServerOptions()
            {
                TokenEndpointPath = new PathString("/token"),
                Provider = new OAuthAuthorizationServerProvider()
                {
                    OnValidateClientAuthentication = async (context) =>
                    {
                        context.Validated();
                    },
                    OnGrantResourceOwnerCredentials = async (context) =>
                    {
                        if (context.UserName == "[email protected]" && context.Password == "test123")
                        {
                            ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                            context.Validated(oAuthIdentity);
                        }
                    }
                },
                AllowInsecureHttp = true,
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1)
            };

            app.UseOAuthBearerTokens(OAuthOptions);
        }
    }
}

Run your project. The token should be displayed in the pop-up.

Bootstrap 3 - How to load content in modal body via AJAX?

This is actually super simple with just a little bit of added javascript. The link's href is used as the ajax content source. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function.

JavaScript:

// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

Html (based on the official example):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal
</a>

<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Try it yourself: https://jsfiddle.net/ednon5d1/

How do I get the directory that a program is running from?

Just my two cents, but doesn't the following code portably work in C++17?

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main(int argc, char* argv[])
{
    std::cout << "Path is " << fs::path(argv[0]).parent_path() << '\n';
}

Seems to work for me on Linux at least.

Based on the previous idea, I now have:

std::filesystem::path prepend_exe_path(const std::string& filename, const std::string& exe_path = "");

With implementation:

fs::path prepend_exe_path(const std::string& filename, const std::string& exe_path)
{
    static auto exe_parent_path = fs::path(exe_path).parent_path();
    return exe_parent_path / filename;
}

And initialization trick in main():

(void) prepend_exe_path("", argv[0]);

Thanks @Sam Redway for the argv[0] idea. And of course, I understand that C++17 was not around for many years when the OP asked the question.

Convert an image (selected by path) to base64 string

Something like that

 Function imgTo64(ByVal thePath As String) As String
    Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
    Dim m As IO.MemoryStream = New IO.MemoryStream()

    img.Save(m, img.RawFormat)
    Dim imageBytes As Byte() = m.ToArray
    img.Dispose()

    Dim str64 = Convert.ToBase64String(imageBytes)
    Return str64
End Function

Python: how can I check whether an object is of type datetime.date?

If you are using freezegun package in tests you may need to have more smart isinstance checks which works well with FakeDate and original Date/Datetime beeing inside with freeze_time context:

def isinstance_date(value):
    """Safe replacement for isinstance date which works smoothly also with Mocked freezetime"""
    import datetime
    if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):
        return True
    elif type(datetime.datetime.today().date()) == type(value):
        return True
    else:
        return False


def isinstance_datetime(value):
    """Safe replacement for isinstance datetime which works smoothly also with Mocked freezetime """
    import datetime
    if isinstance(value, datetime.datetime):
        return True
    elif type(datetime.datetime.now()) == type(value):
        return True
    else:
        return False

and tests to verify the implementation

class TestDateUtils(TestCase):

    def setUp(self):
        self.date_orig = datetime.date(2000, 10, 10)
        self.datetime_orig = datetime.datetime(2000, 10, 10)

        with freeze_time('2001-01-01'):
            self.date_freezed = datetime.date(2002, 10, 10)
            self.datetime_freezed = datetime.datetime(2002, 10, 10)

    def test_isinstance_date(self):
        def check():
            self.assertTrue(isinstance_date(self.date_orig))
            self.assertTrue(isinstance_date(self.date_freezed))
            self.assertFalse(isinstance_date(self.datetime_orig))
            self.assertFalse(isinstance_date(self.datetime_freezed))
            self.assertFalse(isinstance_date(None))

        check()
        with freeze_time('2005-01-01'):
            check()

    def test_isinstance_datetime(self):
        def check():
            self.assertFalse(isinstance_datetime(self.date_orig))
            self.assertFalse(isinstance_datetime(self.date_freezed))
            self.assertTrue(isinstance_datetime(self.datetime_orig))
            self.assertTrue(isinstance_datetime(self.datetime_freezed))
            self.assertFalse(isinstance_datetime(None))

        check()
        with freeze_time('2005-01-01'):
            check()

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Use this method it under your email service it can attach any email body and attachments to Microsoft outlook

using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later

 try {
                    var officeType = Type.GetTypeFromProgID("Outlook.Application");
    
                    if(officeType == null) {//outlook is not installed
                        return new PdfErrorResponse {
                            ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
                        };
                    } else {
                        // Outlook is installed.    
                        // Continue your work.
                        Outlook.Application objApp = new Outlook.Application();
                        Outlook.MailItem mail = null;
                        mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
                        //The CreateItem method returns an object which has to be typecast to MailItem 
                        //before using it.
                        mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
                        //The parameters are explained below
                        mail.To = recipientEmailAddress;
                        //mail.CC = "[email protected]";//All the mail lists have to be separated by the ';'
    
                        //To send email:
                        //mail.Send();
                        //To show email window
                        await Task.Run(() => mail.Display());
                    }
    
                } catch(System.Exception) {
                    return new PdfErrorResponse {
                        ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
                    };
                }

How can I indent multiple lines in Xcode?

Shortcut key:

ctrl + i

NOTE: Please select codes to Re-indent and press 'control' and 'i' on your mac.

How to get a URL parameter in Express?

You can do something like req.param('tagId')

Fast ceiling of an integer division in C / C++

This works for positive or negative numbers:

q = x / y + ((x % y != 0) ? !((x > 0) ^ (y > 0)) : 0);

If there is a remainder, checks to see if x and y are of the same sign and adds 1 accordingly.

Reading output of a command into an array in Bash

The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *, ?, [...].

To get the output of a command in an array, with one line per element, there are essentially 3 ways:

  1. With Bash=4 use mapfile—it's the most efficient:

    mapfile -t my_array < <( my_command )
    
  2. Otherwise, a loop reading the output (slower, but safe):

    my_array=()
    while IFS= read -r line; do
        my_array+=( "$line" )
    done < <( my_command )
    
  3. As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:

    IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
    

    Please make sure you use exactly this form, i.e., make sure you have the following:

    • IFS=$'\n' on the same line as the read statement: this will only set the environment variable IFS for the read statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read to break the stream at the EOL character \n.
    • -r: this is important. It tells read to not interpret the backslashes as escape sequences.
    • -d '': please note the space between the -d option and its argument ''. If you don't leave a space here, the '' will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read to stop reading at the nil byte. Some people write it as -d $'\0', but it is not really necessary. -d '' is better.
    • -a my_array tells read to populate the array my_array while reading the stream.
    • You must use the printf '\0' statement after my_command, so that read returns 0; it's actually not a big deal if you don't (you'll just get an return code 1, which is okay if you don't use set -e – which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf '', which doesn't output anything. printf '\0' prints a null byte, needed by read to happily stop reading there (remember the -d '' option?).

If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.

If you want to use read, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]} in the example I gave).

Note that mapfile provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile and the options -C and -c therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).


Now I'm going to tell you why the following method:

my_array=( $( my_command) )

is broken when there are spaces:

$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!

Then some people will then recommend using IFS=$'\n' to fix it:

$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!

But now let's use another command, with globs:

$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?

That's because I have a file called t in the current directory… and this filename is matched by the glob [three four]… at this point some people would recommend using set -f to disable globbing: but look at it: you have to change IFS and use set -f to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.

$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'

here we're working with the shell!

jquery change style of a div on click

$(document).ready(function() {
  $('#div_one').bind('click', function() {
    $('#div_two').addClass('large');
  });
});

If I understood your question.

Or you can modify css directly:

var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');

Purpose of #!/usr/bin/python3 shebang

That's called a hash-bang. If you run the script from the shell, it will inspect the first line to figure out what program should be started to interpret the script.

A non Unix based OS will use its own rules for figuring out how to run the script. Windows for example will use the filename extension and the # will cause the first line to be treated as a comment.

If the path to the Python executable is wrong, then naturally the script will fail. It is easy to create links to the actual executable from whatever location is specified by standard convention.

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

In SQL Developer: Everything was working fine and I had all the permissions to login and there was no password change and I could click the table and see the data tab.

But when I run query (simple select statement) it was showing "ORA-01031: insufficient privileges" message.

The solution is simply disconnect the connection and reconnect. Note: only doing Reconnect did not work for me. SQL Developer Disconnect Snapshot

How to filter (key, value) with ng-repeat in AngularJs?

You can simply use angular.filter module, and then you can filter even by nested properties.
see: jsbin
2 Examples:

JS:

angular.module('app', ['angular.filter'])
  .controller('MainCtrl', function($scope) {
  //your example data
  $scope.items = { 
    'A2F0C7':{ secId:'12345', pos:'a20' },
    'C8B3D1':{ pos:'b10' }
  };
  //more advantage example
  $scope.nestedItems = { 
    'A2F0C7':{
      details: { secId:'12345', pos:'a20' }
    },
    'C8B3D1':{
      details: { pos:'a20' }
    },
    'F5B3R1': { secId:'12345', pos:'a20' }
  };
});

HTML:

  <b>Example1:</b>
  <p ng-repeat="item in items | toArray: true | pick: 'secId'">
    {{ item.$key }}, {{ item }}
  </p>

  <b>Example2:</b>
  <p ng-repeat="item in nestedItems | toArray: true | pick: 'secId || details.secId' ">
    {{ item.$key }}, {{ item }}
  </p> 

Reading RFID with Android phones

I recently worked on a project to read the RFID tags. The project used the Devices from manufacturers like Zebra (we were using RFD8500 ) & TSL.

More devices are from Motorola & other vendors as well!

We have to use the native SDK api's provided by the manufacturer, how it works is by pairing the device by the Bluetooth of the phones and so the data transfer between both devices take place! The programming is based on subscribe pattern where the scan should be read by the device trigger(hardware trigger) or soft trigger (from the application).

The Tag read gives us the tagId & the RSSI which is the distance factor from the RFID tags!

This is the sample app:

We get all the device paired to our Android/iOS phones :

get device list

connect

connected

Scan

String strip() for JavaScript?

Use this:

if(typeof(String.prototype.trim) === "undefined")
{
    String.prototype.trim = function() 
    {
        return String(this).replace(/^\s+|\s+$/g, '');
    };
}

The trim function will now be available as a first-class function on your strings. For example:

" dog".trim() === "dog" //true

EDIT: Took J-P's suggestion to combine the regex patterns into one. Also added the global modifier per Christoph's suggestion.

Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it. This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.

Where can I get Google developer key

First activate Google+ API, then you will get "Simple API access" box, from there you can get developer key as API key https://code.google.com/apis/console/?api=plus or read this: http://code.google.com/p/google-api-php-client/wiki/OAuth2

successful/fail message pop up box after submit?

Instead of using a submit button, try using a <button type="button">Submit</button>

You can then call a javascript function in the button, and after the alert popup is confirmed, you can manually submit the form with document.getElementById("form").submit(); ... so you'll need to name and id your form for that to work.

How to call a JavaScript function within an HTML body

Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

How can I create a self-signed cert for localhost?

you could try mkcert.

macos: brew install mkcert

Source file 'Properties\AssemblyInfo.cs' could not be found

This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.

How do I hide an element on a click event anywhere outside of the element?

$( "element" ).focusout(function() {
    //your code on element
})

Template not provided using create-react-app

Clear your npm cache first then use yarn as follows:

  • npm cache clean --force
  • npm cache verify
  • yarn create react-app my-app

I hope this helps.

EDIT

...you might want to try the following after I have looked into this problem further:

  1. npm uninstall -g create-react-app
  2. yarn global remove create-react-app
  3. which create-react-app - If it returns something (e.g. /usr/local/bin/create-react-app), then do a rm -rf /usr/local/bin/create-react-app to delete manually.
  4. npm cache clean --force
  5. npm cache verify
  6. npx create-react-app@latest

These steps should remove globally installed create-react-app installs, you then manually remove the old directories linked to the old globally installed create-react-app scripts. It's then a good idea to clear your npm cache to ensure your not using any old cached versions of create-react-app. Lastly create a new reactjs app with the @latest option like so: npx create-react-app@latest. There has been much confusion on this issue where no template is created when using npx create-react-app, if you follow the steps I have stated above (1-6) then I hope you'll have success.

p.s.

If I wanted to then create a react app in a directory called client then I would type the following command into the terminal:

npx create-react-app@latest ./client

Good luck.

Why should I use core.autocrlf=true in Git?

The only specific reasons to set autocrlf to true are:

  • avoid git status showing all your files as modified because of the automatic EOL conversion done when cloning a Unix-based EOL Git repo to a Windows one (see issue 83 for instance)
  • and your coding tools somehow depends on a native EOL style being present in your file:

Unless you can see specific treatment which must deal with native EOL, you are better off leaving autocrlf to false (git config --global core.autocrlf false).

Note that this config would be a local one (because config isn't pushed from repo to repo)

If you want the same config for all users cloning that repo, check out "What's the best CRLF handling strategy with git?", using the text attribute in the .gitattributes file.

Example:

*.vcproj    text eol=crlf
*.sh        text eol=lf

Note: starting git 2.8 (March 2016), merge markers will no longer introduce mixed line ending (LF) in a CRLF file.
See "Make Git use CRLF on its “<<<<<<< HEAD” merge lines"

Make iframe automatically adjust height according to the contents without using scrollbar?

This option will work 100%

<iframe id='iframe2' src="url.com" frameborder="0" style="overflow: hidden; height: 100%; width: 100%; position: absolute;" height="100%" width="100%"></iframe>

Adding a new SQL column with a default value

Try This :)

ALTER TABLE TABLE_NAME ADD COLUMN_NAME INT NOT NULL DEFAULT 0;

C++: Converting Hexadecimal to Decimal

This should work as well.

#include <ctype.h>
#include <string.h>

template<typename T = unsigned int>
T Hex2Int(const char* const Hexstr, bool* Overflow)
{
    if (!Hexstr)
        return false;
    if (Overflow)
        *Overflow = false;

    auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
    size_t len = strlen(Hexstr);
    T result = 0;

    for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
    {
        if (between(Hexstr[i], '0', '9'))
            result = result << 4 ^ Hexstr[i] - '0';
        else if (between(tolower(Hexstr[i]), 'a', 'f'))
            result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
        offset -= 4;
    }
    if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
        *Overflow = true;
    return result;
}

The 'Overflow' parameter is optional, so you can leave it NULL.

Example:

auto result = Hex2Int("C0ffee", NULL);
auto result2 = Hex2Int<long>("DeadC0ffe", NULL);

ORACLE IIF Statement

In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE function.

SET SERVEROUTPUT ON

DECLARE
    x   VARCHAR2(10);
BEGIN
    x := owa_util.ite('a' = 'b','T','F');
    dbms_output.put_line(x);
END;
/

F

PL/SQL procedure successfully completed.

How to sort an array of integers correctly

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

_x000D_
_x000D_
var numArray = [140000, 104, 99];_x000D_
numArray.sort(function(a, b) {_x000D_
  return a - b;_x000D_
});_x000D_
_x000D_
console.log(numArray);
_x000D_
_x000D_
_x000D_

In ES6, you can simplify this with arrow functions:

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort

Documentation:

Mozilla Array.prototype.sort() recommends this compare function for arrays that don't contain Infinity or NaN. (Because Inf - Inf is NaN, not 0).

Also examples of sorting objects by key.

How do I change the color of radio buttons?

A radio button is a native element specific to each OS/browser. There is no way to change its color/style, unless you want to implement custom images or use a custom Javascript library which includes images (e.g. this - cached link)

Generics in C#, using type of a variable as parameter

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

Add php variable inside echo statement as href link address?

Try like

HTML in PHP :

echo "<a href='".$link_address."'>Link</a>";

Or even you can try like

echo "<a href='$link_address'>Link</a>";

Or you can use PHP in HTML like

PHP in HTML :

<a href="<?php echo $link_address;?>"> Link </a>

Difference between dates in JavaScript

This answer, based on another one (link at end), is about the difference between two dates.
You can see how it works because it's simple, also it includes splitting the difference into
units of time (a function that I made) and converting to UTC to stop time zone problems.

_x000D_
_x000D_
function date_units_diff(a, b, unit_amounts) {_x000D_
    var split_to_whole_units = function (milliseconds, unit_amounts) {_x000D_
        // unit_amounts = list/array of amounts of milliseconds in a_x000D_
        // second, seconds in a minute, etc., for example "[1000, 60]"._x000D_
        time_data = [milliseconds];_x000D_
        for (i = 0; i < unit_amounts.length; i++) {_x000D_
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));_x000D_
            time_data[i] = time_data[i] % unit_amounts[i];_x000D_
        }; return time_data.reverse();_x000D_
    }; if (unit_amounts == undefined) {_x000D_
        unit_amounts = [1000, 60, 60, 24];_x000D_
    };_x000D_
    var utc_a = new Date(a.toUTCString());_x000D_
    var utc_b = new Date(b.toUTCString());_x000D_
    var diff = (utc_b - utc_a);_x000D_
    return split_to_whole_units(diff, unit_amounts);_x000D_
}_x000D_
_x000D_
// Example of use:_x000D_
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);_x000D_
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(_x000D_
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));
_x000D_
_x000D_
_x000D_

How my code above works

A date/time difference, as milliseconds, can be calculated using the Date object:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000).
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.

I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units, with this demo:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

This answer is based on this other one.

Inner Joining three tables

select *
from
    tableA a
        inner join
    tableB b
        on a.common = b.common
        inner join 
    TableC c
        on b.common = c.common

MySQL - sum column value(s) based on row from the same table

This might be seen as a little complex but does exactly what you want

SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(pl.CashAmount) AS Cash,
  SUM(pr.CashAmount) AS `Check`,
  SUM(px.CashAmount) AS `Credit Card`,
  SUM(pl.CashAmount) + SUM(pr.CashAmount) +SUM(px.CashAmount) AS Amount
FROM
  `payments` AS p 
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Cash' GROUP BY ProductID , PaymentMethod ) AS pl 
    ON pl.`PaymentMethod` = p.`PaymentMethod` AND pl.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Check' GROUP BY ProductID , PaymentMethod) AS pr 
    ON pr.`PaymentMethod` = p.`PaymentMethod` AND pr.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID, PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Credit Card' GROUP BY ProductID , PaymentMethod) AS px 
    ON px.`PaymentMethod` = p.`PaymentMethod` AND px.ProductID = p.`ProductID`
GROUP BY p.`ProductID` ;

Output

ProductID | Cash | Check | Credit Card | Amount
-----------------------------------------------
    3     | 20   |  15   |   25        |  60
    4     | 5    |  6    |   7         |  18

SQL Fiddle Demo

Include files from parent or other directory

I can't believe none of the answers pointed to the function dirname() (available since PHP 4).

Basically, it returns the full path for the referenced object. If you use a file as a reference, the function returns the full path of the file. If the referenced object is a folder, the function will return the parent folder of that folder.

https://www.php.net/manual/en/function.dirname.php

For the current folder of the current file, use $current = dirname(__FILE__);.

For a parent folder of the current folder, simply use $parent = dirname(__DIR__);.

upstream sent too big header while reading response header from upstream

Add the following to your conf file

fastcgi_buffers 16 16k; 
fastcgi_buffer_size 32k;

JQuery create a form and add elements to it programmatically

You need to append form itself to body too:

$form = $("<form></form>");
$form.append('<input type="button" value="button">');
$('body').append($form);

How do you get the currently selected <option> in a <select> via JavaScript?

The .selectedIndex of the select object has an index; you can use that to index into the .options array.

What's an Aggregate Root?

Imagine you have a Computer entity, this entity also cannot live without its Software entity and Hardware entity. These form the Computer aggregate, the mini-ecosystem for the Computer portion of the domain.

Aggregate Root is the mothership entity inside the aggregate (in our case Computer), it is a common practice to have your repository only work with the entities that are Aggregate Roots, and this entity is responsible for initializing the other entities.

Consider Aggregate Root as an Entry-Point to an Aggregate.

In C# code:

public class Computer : IEntity, IAggregateRoot
{
    public Hardware Hardware { get; set; }
    public Software Software { get; set; }
}

public class Hardware : IEntity { }
public class Software : IValueObject { }

public class Repository<T> : IRepository<T> where T : IAggregateRoot {}

Keep in mind that Hardware would likely be a ValueObject too (do not have identity on its own), consider it as an example only.

How to convert DataSet to DataTable

DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

I had the similar problem with my Eclipse Helios which debugging Junits. My problem was little different as i was able to run Junits successfully but when i was getting ClassNotFoundException while debugging the same JUNITs.

I have tried all sort of different solutions available in Stackoverflow.com and forums elsewhere, but nothing seem to work. After banging my head with these issue for close to two days, finally i figured out the solution to it.

If none of the solutions seem to work, just delete the .metadata folder created in your workspace. This would create an additional overhead of importing the projects and all sorts of configuration you have done, but these will surely solve these issue.

Hope these helps.

Most efficient way to check if a file is empty in Java on Windows

String line = br.readLine();
String[] splitted = line.split("anySplitCharacter");
if(splitted.length == 0)
    //file is empty
else
    //file is not empty

I had the same problem with my text file. Although it was empty, the value being returned by the readLine method was not null. Therefore, I tried to assign its value to the String array which I was using to access the splitted attributes of my data. It did work for me. Try this out and tell me if it works for u as well.

Capitalize the first letter of both words in a two word string

From the help page for ?toupper:

.simpleCap <- function(x) {
    s <- strsplit(x, " ")[[1]]
    paste(toupper(substring(s, 1,1)), substring(s, 2),
          sep="", collapse=" ")
}


> sapply(name, .simpleCap)

zip code         state   final count 
"Zip Code"       "State" "Final Count"

How do you run a .bat file from PHP?

When you use the exec() function, it is as though you have a cmd terminal open and are typing commands straight to it.

Use single quotes like this $str = exec('start /B Path\to\batch.bat');
The /B means the bat will be executed in the background so the rest of the php will continue after running that line, as opposed to $str = exec('start /B /C command', $result); where command is executed and then result is stored for later use.

PS: It works for both Windows and Linux.
More details are here http://www.php.net/manual/en/function.exec.php :)

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

I was getting this exception when i was pressing back button to cancel intent chooser on my map fragment activity. I resolved this by replacing the code of onResume(where i was initializing the fragment) to onstart() and the app is working fine.Hope it helps.

Reading Properties file in Java

Given the context loader.getResourceAsStream("myPackage/myProp.properties") should be used.

Leading '/' doesn't work with ClassLoader.getResourceAsStream(String) method.

Alternatively you could use Class.getResourceAsStream(String) method, which uses '/' to determine if the path is absolute or relative to the class location.

Examples:

myClass.class.getResourceAsStream("myProp.properties")
myClass.class.getResourceAsStream("/myPackage/myProp.properties")

Server did not recognize the value of HTTP Header SOAPAction

I had similar issue. To debug the problem, I've run Wireshark and capture request generated by my code. Then I used XML Spy trial to create a SOAP request (assuming you have WSDL) and compared those two.

This should give you a hint what goes wrong.

What is default list styling (CSS)?

An answer for the future: CSS 4 will probably contain the revert keyword, which reverts a property to its value from the user or user-agent stylesheet [source]. As of writing this, only Safari supports this – check here for updates on browser support.

In your case you would use:

.my_container ol, .my_container ul {
    list-style: revert;
}

See also this other answer with some more details.

How to delete an object by id with entity framework

This answer is actually taken from Scott Allen's course titled ASP.NET MVC 5 Fundamentals. I thought I'd share because I think it is slightly simpler and more intuitive than any of the answers here already. Also note according to Scott Allen and other trainings I've done, find method is an optimized way to retrieve a resource from database that can use caching if it already has been retrieved. In this code, collection refers to a DBSet of objects. Object can be any generic object type.

        var object = context.collection.Find(id);  
        context.collection.Remove(object);
        context.SaveChanges();

SELECT FOR UPDATE with SQL Server

Try using:

SELECT * FROM <tablename> WITH ROWLOCK XLOCK HOLDLOCK

This should make the lock exclusive and hold it for the duration of the transaction.

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

Fixed page header overlaps in-page anchors

<div style="position:relative; top:-45px;">
    <a name="fragment"> </a>
</div>

This code should do the trick. Swap out 45px for the height of your header bar.

EDIT: If using jQuery is an option, I've also been successful using jQuery.localScroll with an offset value set. The offset option is a part of jQuery.scrollTo, which jQuery.localScroll is built upon. A demo is available here: http://demos.flesler.com/jquery/scrollTo/ (second window, under 'offset')

Connect multiple devices to one device via Bluetooth

Bluetooth 4.0 Allows you in a Bluetooth piconet one master can communicate up to 7 active slaves, there can be some other devices up to 248 devices which sleeping.

Also you can use some slaves as bridge to participate with more devices.

Mongoose: Find, modify, save

If you want to use find, like I would for any validation you want to do on the client side.

find returns an ARRAY of objects

findOne returns only an object

Adding user = user[0] made the save method work for me.

Here is where you put it.

User.find({username: oldUsername}, function (err, user) {
    user = user[0];
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
});

How to window.scrollTo() with a smooth effect

$('html, body').animate({scrollTop:1200},'50');

You can do this!

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

ssh "permissions are too open" error

Keys need to be only readable by you:

chmod 400 ~/.ssh/id_rsa

If Keys need to be read-writable by you:

chmod 600 ~/.ssh/id_rsa

600 appears to be fine as well (in fact better in most cases, because you don't need to change file permissions later to edit it).

The relevant portion from the manpage (man ssh)

 ~/.ssh/id_rsa
         Contains the private key for authentication.  These files contain sensitive 
         data and should be readable by the user but not
         accessible by others (read/write/execute).  ssh will simply ignore a private 
         key file if it is              
         accessible by others.  It is possible to specify a
         passphrase when generating the key which will be used to encrypt the sensitive 
         part of this file using 3DES.

 ~/.ssh/identity.pub
 ~/.ssh/id_dsa.pub
 ~/.ssh/id_ecdsa.pub
 ~/.ssh/id_rsa.pub
         Contains the public key for authentication.  These files are not sensitive and 
         can (but need not) be readable by anyone.

What is meant with "const" at end of function declaration?

Function can't change its parameters via the pointer/reference you gave it.

I go to this page every time I need to think about it:

http://www.parashift.com/c++-faq-lite/const-correctness.html

I believe there's also a good chapter in Meyers' "More Effective C++".

Auto-center map with multiple markers in Google Maps API v3

To find the exact center of the map you'll need to translate the lat/lon coordinates into pixel coordinates and then find the pixel center and convert that back into lat/lon coordinates.

You might not notice or mind the drift depending how far north or south of the equator you are. You can see the drift by doing map.setCenter(map.getBounds().getCenter()) inside of a setInterval, the drift will slowly disappear as it approaches the equator.

You can use the following to translate between lat/lon and pixel coordinates. The pixel coordinates are based on a plane of the entire world fully zoomed in, but you can then find the center of that and switch it back into lat/lon.

   var HALF_WORLD_CIRCUMFERENCE = 268435456; // in pixels at zoom level 21
   var WORLD_RADIUS = HALF_WORLD_CIRCUMFERENCE / Math.PI;

   function _latToY ( lat ) {
      var sinLat = Math.sin( _toRadians( lat ) );
      return HALF_WORLD_CIRCUMFERENCE - WORLD_RADIUS * Math.log( ( 1 + sinLat ) / ( 1 - sinLat ) ) / 2;
   }

   function _lonToX ( lon ) {
      return HALF_WORLD_CIRCUMFERENCE + WORLD_RADIUS * _toRadians( lon );
   }

   function _xToLon ( x ) {
      return _toDegrees( ( x - HALF_WORLD_CIRCUMFERENCE ) / WORLD_RADIUS );
   }

   function _yToLat ( y ) {
      return _toDegrees( Math.PI / 2 - 2 * Math.atan( Math.exp( ( y - HALF_WORLD_CIRCUMFERENCE ) / WORLD_RADIUS ) ) );
   }

   function _toRadians ( degrees ) {
      return degrees * Math.PI / 180;
   }

   function _toDegrees ( radians ) {
      return radians * 180 / Math.PI;
   }

How to check if a table contains an element in Lua?

I can't think of another way to compare values, but if you use the element of the set as the key, you can set the value to anything other than nil. Then you get fast lookups without having to search the entire table.

Sending HTML email using Python

for python3, improve @taltman 's answer:

  • use email.message.EmailMessage instead of email.message.Message to construct email.
  • use email.set_content func, assign subtype='html' argument. instead of low level func set_payload and add header manually.
  • use SMTP.send_message func instead of SMTP.sendmail func to send email.
  • use with block to auto close connection.
from email.message import EmailMessage
from smtplib import SMTP

# construct email
email = EmailMessage()
email['Subject'] = 'foo'
email['From'] = '[email protected]'
email['To'] = '[email protected]'
email.set_content('<font color="red">red color text</font>', subtype='html')

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.login('foo_user', 'bar_password')
    s.send_message(email)

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

Doing it in one bulk read:

import re

textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)

Line by line:

import re

textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += reg.findall(line)
textfile.close()

But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:

import re

textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += [(reg.findall(line),offset)]
    offset += len(line)
textfile.close()

But it still just makes more sense to read the whole file in at once.

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Be sure to remember to invoke json.loads() on the contents of the file, as opposed to the file path of that JSON:

json_file_path = "/path/to/example.json"

with open(json_file_path, 'r') as j:
     contents = json.loads(j.read())

I think a lot of people are guilty of doing this every once in a while (myself included):

contents = json.loads(json_file_path)

C#: what is the easiest way to subtract time?

These can all be done with DateTime.Add(TimeSpan) since it supports positive and negative timespans.

DateTime original = new DateTime(year, month, day, 8, 0, 0);
DateTime updated = original.Add(new TimeSpan(5,0,0));

DateTime original = new DateTime(year, month, day, 17, 0, 0);
DateTime updated = original.Add(new TimeSpan(-2,0,0));

DateTime original = new DateTime(year, month, day, 17, 30, 0);
DateTime updated = original.Add(new TimeSpan(0,45,0));

Or you can also use the DateTime.Subtract(TimeSpan) method analogously.

How do I set up the database.yml file in Rails?

At first I would use http://ruby.railstutorial.org/.

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

CKEditor, Image Upload (filebrowserUploadUrl)

May be it's too late. Your code is correct so please check again your url in filebrowserUploadUrl

CKEDITOR.replace( 'editor1', {
    filebrowserUploadUrl: "upload/upload.php" 
} );

And the Upload.php file

if (file_exists("images/" . $_FILES["upload"]["name"]))
{
 echo $_FILES["upload"]["name"] . " already exists. ";
}
else
{
 move_uploaded_file($_FILES["upload"]["tmp_name"],
 "images/" . $_FILES["upload"]["name"]);
 echo "Stored in: " . "images/" . $_FILES["upload"]["name"];
}

Truncate Decimal number not Round Off

You can use Math.Round:

decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229

Or you can use ToString with the N3 numeric format.

string roundedNumber = number.ToString("N3");

EDIT: Since you don't want rounding, you can easily use Math.Truncate:

Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229

Get docker container id from container name

You can try this:

docker inspect --format="{{.Id}}" container_name

This approach is OS independent.

Count unique values in a column in Excel

Here's an elegant array formula (which I found here http://www.excel-easy.com/examples/count-unique-values.html) that does the trick nicely:

Type

=SUM(1/COUNTIF(List,List))

and confirm with CTRL-SHIFT-ENTER

Why is Android Studio reporting "URI is not registered"?

it turns out I was editing the DEBUG version of the xml, to fix it, simply close the tab that has the error and re-open it

Declare an array in TypeScript

Here are the different ways in which you can create an array of booleans in typescript:

let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();

let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();

let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];

let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();

let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();

You can access them using the index:

console.log(arr[5]);

and you add elements using push:

arr.push(true);

When creating the array you can supply the initial values:

let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);

Passing additional variables from command line to make

From the manual:

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment.

So you can do (from bash):

FOOBAR=1 make

resulting in a variable FOOBAR in your Makefile.

How to resize an image with OpenCV2.0 and Python2.6

If you wish to use CV2, you need to use the resize function.

For example, this will resize both axes by half:

small = cv2.resize(image, (0,0), fx=0.5, fy=0.5) 

and this will resize the image to have 100 cols (width) and 50 rows (height):

resized_image = cv2.resize(image, (100, 50)) 

Another option is to use scipy module, by using:

small = scipy.misc.imresize(image, 0.5)

There are obviously more options you can read in the documentation of those functions (cv2.resize, scipy.misc.imresize).


Update:
According to the SciPy documentation:

imresize is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use skimage.transform.resize instead.

Note that if you're looking to resize by a factor, you may actually want skimage.transform.rescale.

How to represent a fix number of repeats in regular expression?

The finite repetition syntax uses {m,n} in place of star/plus/question mark.

From java.util.regex.Pattern:

X{n}      X, exactly n times
X{n,}     X, at least n times
X{n,m}    X, at least n but not more than m times

All repetition metacharacter have the same precedence, so just like you may need grouping for *, +, and ?, you may also for {n,m}.

  • ha* matches e.g. "haaaaaaaa"
  • ha{3} matches only "haaa"
  • (ha)* matches e.g. "hahahahaha"
  • (ha){3} matches only "hahaha"

Also, just like *, +, and ?, you can add the ? and + reluctant and possessive repetition modifiers respectively.

    System.out.println(
        "xxxxx".replaceAll("x{2,3}", "[x]")
    ); "[x][x]"

    System.out.println(
        "xxxxx".replaceAll("x{2,3}?", "[x]")
    ); "[x][x]x"

Essentially anywhere a * is a repetition metacharacter for "zero-or-more", you can use {...} repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use * because Java doesn't officially support infinite-length lookbehind.

References

Related questions

CSS3 scrollbar styling on a div

.scroll {
   width: 200px; height: 400px;
   overflow: auto;
}

Open mvc view in new window from controller

This cannot be done from within the controller itself, but rather from your View. As I see it, you have two options:

  1. Decorate your link with the "_blank" attribute (examples using HTML helper and straight HMTL syntax)

    • @Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank"})
    • <a href="@Url.Action("Action", "Controller")" target="_blank">Link Text</a>
  2. Use Javascript to open a new window

    window.open("Link URL")

Java Ordered Map

tl;dr

To keep Map< Integer , String > in an order sorted by key, use either of the two classes implementing the SortedMap/NavigableMap interfaces:

  • TreeMap
  • ConcurrentSkipListMap

If manipulating the map within a single thread, use the first, TreeMap. If manipulating across threads, use the second, ConcurrentSkipListMap.

For details, see the table below and the following discussion.

Details

Here is a graphic table I made showing the features of the ten Map implementations bundled with Java 11.

The NavigableMap interface is what SortedMap should have been in the first place. The SortedMap logically should be removed but cannot be as some 3rd-party map implementations may be using interface.

As you can see in this table, only two classes implement the SortedMap/NavigableMap interfaces:

Both of these keep keys in sorted order, either by their natural order (using compareTo method of the Comparable(https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Comparable.html) interface) or by a Comparator implementation you pass. The difference between these two classes is that the second one, ConcurrentSkipListMap, is thread-safe, highly concurrent.

See also the Iteration order column in the table below.

  • The LinkedHashMap class returns its entries by the order in which they were originally inserted.
  • EnumMap returns entries in the order by which the enum class of the key is defined. For example, a map of which employee is covering which day of the week (Map< DayOfWeek , Person >) uses the DayOfWeek enum class built into Java. That enum is defined with Monday first and Sunday last. So entries in an iterator will appear in that order.

The other six implementations make no promise about the order in which they report their entries.

Table of map implementations in Java 11, comparing their features

Getting command-line password input in Python

Here is my code based off the code offered by @Ahmed ALaa

Features:

  • Works for passwords up to 64 characters
  • Accepts backspace input
  • Outputs * character (DEC: 42 ; HEX: 0x2A) instead of the input character

Demerits:

  • Works on Windows only

The function secure_password_input() returns the password as a string when called. It accepts a Password Prompt string, which will be displayed to the user to type the password

def secure_password_input(prompt=''):
    p_s = ''
    proxy_string = [' '] * 64
    while True:
        sys.stdout.write('\x0D' + prompt + ''.join(proxy_string))
        c = msvcrt.getch()
        if c == b'\r':
            break
        elif c == b'\x08':
            p_s = p_s[:-1]
            proxy_string[len(p_s)] = " "
        else:
            proxy_string[len(p_s)] = "*"
            p_s += c.decode()

    sys.stdout.write('\n')
    return p_s

Missing Authentication Token while accessing API Gateway?

If you enable AWS_IAM authentication you must sign your request with AWS credentials using AWS Signature Version 4.

Note: signing into the AWS console does not automatically sign your browser's requests to your API.

sql select with column name like

Blorgbeard had a great answer for SQL server. If you have a MySQL server like mine then the following will allow you to select the information from columns where the name is like some key phrase. You just have to substitute the table name, database name, and keyword.

SET @columnnames = (SELECT concat("`",GROUP_CONCAT(`COLUMN_NAME` SEPARATOR "`, `"),"`") 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='your_database' 
    AND `TABLE_NAME`='your_table'
    AND COLUMN_NAME LIKE "%keyword%");

SET @burrito = CONCAT("SELECT ",@columnnames," FROM your_table");

PREPARE result FROM @burrito;
EXECUTE result;

Batch Renaming of Files in a Directory

directoryName = "Photographs"
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"

for counter, filename in enumerate(os.listdir(directoryName)):

    filenameWithPath = os.path.join(filePathWithSlash, filename)

    os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
          str(counter).zfill(4) + ".jpg" ))

# e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"        
# The string.replace call swaps in the new filename into 
# the current filename within the filenameWitPath string. Which    
# is then used by os.rename to rename the file in place, using the  
# current (unmodified) filenameWithPath.

# os.listdir delivers the filename(s) from the directory
# however in attempting to "rename" the file using os 
# a specific location of the file to be renamed is required.

# this code is from Windows 

How do I see which version of Swift I'm using?

In case anyone is looking for quick one-to-one mapping of Swift version based on Xcode Version:

Xcode 12.3   :      Swift version 5.3.2

Xcode 12.2   :      Swift version 5.3.1

Xcode 11.6   :      Swift version 5.2.4

Xcode 11.5   :      Swift version 5.2.4

Xcode 11.4   :      Swift version 5.2

Xcode 11.3   :      Swift version 5.1.3

Xcode 11.2.1 :      Swift version 5.1.2

Xcode 11.1   :      Swift version 5.1

Obtained with running following command as mentioned on different Xcode versions:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift --version

How to push both key and value into an Array in Jquery

arr[title] = link;

You're not pushing into the array, you're setting the element with the key title to the value link. As such your array should be an object.

React : difference between <Route exact path="/" /> and <Route path="/" />

In short, if you have multiple routes defined for your app's routing, enclosed with Switch component like this;

<Switch>

  <Route exact path="/" component={Home} />
  <Route path="/detail" component={Detail} />

  <Route exact path="/functions" component={Functions} />
  <Route path="/functions/:functionName" component={FunctionDetails} />

</Switch>

Then you have to put exact keyword to the Route which it's path is also included by another Route's path. For example home path / is included in all paths so it needs to have exact keyword to differentiate it from other paths which start with /. The reason is also similar to /functions path. If you want to use another route path like /functions-detail or /functions/open-door which includes /functions in it then you need to use exact for the /functions route.

ALTER table - adding AUTOINCREMENT in MySQL

The syntax:

   ALTER TABLE `table1` CHANGE `itemId` `itemId` INT( 11 ) NOT NULL AUTO_INCREMENT 

But the table needs a defined key (ex primary key on itemId).

"No such file or directory" error when executing a binary

I think you're x86-64 install does not have the i386 runtime linker. The ENOENT is probably due to the OS looking for something like /lib/ld.so.1 or similar. This is typically part of the 32-bit glibc runtime, and while I'm not directly familiar with Ubuntu, I would assume they have some sort of 32-bit compatibility package to install. Fortunately gzip only depends on the C library, so that's probably all you'll need to install.

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

RecyclerView inside ScrollView is not working

For those people who trying to do it just for design purposes - leave it. Redesign your app and leave only RecyclerView. It will be better solution than doing ANY hardcode.

Checking that a List is not empty in Hamcrest

This works:

assertThat(list,IsEmptyCollection.empty())

Row names & column names in R

I think that using colnames and rownames makes the most sense; here's why.

Using names has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to call colnames whenever you use matrices. By calling colnames, you only have to remember one function. Finally, if you look at the code for colnames, you will see that it calls names in the case of a data frame anyway, so the output is identical.

rownames and row.names return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names, rownames will print "NULL" (as does colnames), but row.names returns it invisibly. Since there isn't much to choose between the two functions, rownames wins on the grounds of aesthetics, since it pairs more prettily withcolnames. (Also, for the lazy programmer, you save a character of typing.)

no debugging symbols found when using gdb

I know this was answered a long time ago, but I've recently spent hours trying to solve a similar problem. The setup is local PC running Debian 8 using Eclipse CDT Neon.2, remote ARM7 board (Olimex) running Debian 7. Tool chain is Linaro 4.9 using gdbserver on the remote board and the Linaro GDB on the local PC. My issue was that the debug session would start and the program would execute, but breakpoints did not work and when manually paused "no source could be found" would result. My compile line options (Linaro gcc) included -ggdb -O0 as many have suggested but still the same problem. Ultimately I tried gdb proper on the remote board and it complained of no symbols. The curious thing was that 'file' reported debug not stripped on the target executable.

I ultimately solved the problem by adding -g to the linker options. I won't claim to fully understand why this helped, but I wanted to pass this on for others just in case it helps. In this case Linux did indeed need -g on the linker options.

PowerShell array initialization

You can also rely on the default value of the constructor if you wish to create a typed array:

> $a = new-object bool[] 5
> $a
False
False
False
False
False

The default value of a bool is apparently false so this works in your case. Likewise if you create a typed int[] array, you'll get the default value of 0.

Another cool way that I use to initialze arrays is with the following shorthand:

> $a = ($false, $false, $false, $false, $false)
> $a
False
False
False
False
False

Or if you can you want to initialize a range, I've sometimes found this useful:

> $a = (1..5)   
> $a
1
2
3
4
5

Hope this was somewhat helpful!

Which command do I use to generate the build of a Vue app?

in your terminal

npm run build

and you host the dist folder. for more see this video

Fixed position but relative to container

My project is .NET ASP Core 2 MVC Angular 4 template with Bootstrap 4. Adding "sticky-top" into main app component html (i.e. app.component.html) on the first row worked, as follows:

_x000D_
_x000D_
<div class='row sticky-top'>_x000D_
    <div class='col-sm-12'>_x000D_
        <nav-menu-top></nav-menu-top>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="row">_x000D_
    <div class='col-sm-3'>_x000D_
        <nav-menu></nav-menu>_x000D_
    </div>_x000D_
    <div class='col-sm-9 body-content'>_x000D_
        <router-outlet></router-outlet>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is that the convention or did I oversimplify this?

Java List.add() UnsupportedOperationException

You must initialize your List seeAlso :

List<String> seeAlso = new Vector<String>();

or

List<String> seeAlso = new ArrayList<String>();

Differences between .NET 4.0 and .NET 4.5 in High level in .NET


.NET Framework 4


Microsoft announced the intention to ship .NET Framework 4 on 29 September 2008. The Public Beta was released on 20 May 2009.

  • Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls., are included.
  • New Visual Basic .NET and C# language features, such as implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
  • Support for Code Contracts.
  • Inclusion of new types to work with arbitrary-precision arithmetic (System.Numerics.BigInteger) and complex numbers (System.Numerics.Complex).
  • Introduce Common Language Runtime (CLR) 4.0.

After the release of the .NET Framework 4, Microsoft released a set of enhancements, named Windows Server AppFabric, for application server capabilities in the form of AppFabric Hosting and in-memory distributed caching support.


.NET Framework 4.5


.NET Framework 4.5 was released on 15 August 2012., a set of new or improved features were added into this version. The .NET Framework 4.5 is only supported on Windows Vista or later. The .NET Framework 4.5 uses Common Language Runtime 4.0, with some additional runtime features.

1. .NET for Metro style apps

Metro-style apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework is available for building Metro style apps for Windows 8 using C# or Visual Basic. This subset is called .NET APIs for apps. The version of .NET Framework, runtime and libraries, used for Metro style apps is a part of the new Windows Runtime, which is the new platform and application model for Metro style apps. It is an ecosystem that houses many platforms and languages, including .NET Framework, C++ and HTML5/JavaScript.

2. Core Features

  • Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out.
  • Ability to define the culture for an application domain.
  • Console support for Unicode (UTF-16) encoding.
  • Support for versioning of cultural string ordering and comparison data.
  • Better performance when retrieving resources.
  • Zip compression improvements to reduce the size of a compressed file.
  • Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.

3. Managed Extensibility Framework (MEF)

  • Support for generic types.
  • Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.
  • Multiple scopes.

4. Asynchronous operations

In the .NET Framework 4.5, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations.

5. ASP.NET

  • Support for new HTML5 form types.
  • Support for model binders in Web Forms. These let you bind data controls directly to data-access methods, and automatically convert user input to and from .NET Framework data types.
  • Support for unobtrusive JavaScript in client-side validation scripts.
  • Improved handling of client script through bundling and minification for improved page performance.
  • Integrated encoding routines from the AntiXSS library (previously an external library) to protect from cross-site scripting attacks.
  • Support for WebSocket protocol.
  • Support for reading and writing HTTP requests and responses asynchronously.
  • Support for asynchronous modules and handlers.
  • Support for content distribution network (CDN) fallback in the ScriptManager control.

6. Networking

  • Provides a new programming interface for HTTP applications: System.Net.Http namespace and System.Net.Http.Headers namespaces are added.
  • Other improvements: Improved internationalization and IPv6 support. RFC-compliant URI support. Support for Internationalized Domain Name (IDN) parsing. Support for Email Address Internationalization (EAI).

7. Windows Presentation Foundation (WPF)

  • The new Ribbon control, which enables you to implement a ribbon user interface that hosts a Quick Access Toolbar, Application Menu, and tabs.
  • The new INotifyDataErrorInfo interface, which supports synchronous and asynchronous data validation.
  • New features for the VirtualizingPanel and Dispatcher classes.
  • Improved performance when displaying large sets of grouped data, and by accessing collections on non-UI threads.
  • Data binding to static properties, data binding to custom types that implement the ICustomTypeProvider interface and retrieval of data binding information from a binding expression.
  • Repositioning of data as the values change (live shaping).
  • Better integration between WPF and Win32 user interface components.
  • Ability to check whether the data context for an item container is disconnected.
  • Ability to set the amount of time that should elapse between property changes and data source updates.
  • Improved support for implementing weak event patterns. Also, events can now accept markup extensions.

8. Windows Communication Foundation (WCF)

In the .NET Framework 4.5, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:

  • Simplification of generated configuration files.
  • Support for contract-first development.
  • Ability to configure ASP.NET compatibility mode more easily.
  • Changes in default transport property values to reduce the likelihood that you will have to set them.
  • Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.
  • Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.
  • New asynchronous streaming support.
  • New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).
  • Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.
  • Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.
  • Support for configuring services in code.
  • XML Editor tooltips.
  • ChannelFactory caching support.
  • Binary encoder compression support.
  • Support for a UDP transport that enables developers to write services that use "fire and forget" messaging. A client sends a message to a service and expects no response from the service.
  • Ability to support multiple authentication modes on a single WCF endpoint when using the HTTP transport and transport security.
  • Support for WCF services that use internationalized domain names (IDNs).

9. Tools

  • Resource File Generator (Resgen.exe) enables you to create a .resw file for use in Windows Store apps from a .resources file embedded in a .NET Framework assembly.
  • Managed Profile Guided Optimization (Mpgo.exe) enables you to improve application startup time, memory utilization (working set size), and throughput by optimizing native image assemblies. The command-line tool generates profile data for native image application assemblies.

For more information and access to reference links, please visit:

===========.Net 4.5 Poster=========

enter image description here

Showing percentages above bars on Excel column graph

Either

  1. Use a line series to show the %
  2. Update the data labels above the bars to link back directly to other cells

Method 2 by step

  • add data-lables
  • right-click the data lable
  • goto the edit bar and type in a refence to a cell (C4 in this example)
  • this changes the data lable from the defulat value (2000) to a linked cell with the 15%

enter image description here

add new row in gridview after binding C#, ASP.net

try using the cloning technique.

{
    DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
    // then for each of the values use a loop like below.
    int cc = yourdatagrid.Columns.Count;
    for (int i2 = 0; i < cc; i2++)
    {
        row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
    }
    yourdatagrid.Rows.Add(row);
    i++;
    }
}

This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.

C#: New line and tab characters in strings

It depends on if you mean '\n' (linefeed) or '\r\n' (carriage return + linefeed). The former is not the Windows default and will not show properly in some text editors (like Notepad).

You can do

sb.Append(Environment.NewLine);
sb.Append("\t");

or

sb.Append("\r\n\t");

Selenium Finding elements by class name in python

You can try to get the list of all elements with class = "content" by using find_elements_by_class_name:

a = driver.find_elements_by_class_name("content")

Then you can click on the link that you are looking for.

Getting a link to go to a specific section on another page

To link from a page to another section of the page, I navigate through the page depending on the page's location to the other, at the URL bar, and add the #id. So what I mean;

<a href = "../#the_part_that_you_want">This takes you #the_part_that_you_want at the page before</a>

How to change color and font on ListView

If u want to set background of the list then place the image before the < Textview>

< ImageView
android:background="@drawable/image_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

and if u want to change color then put color code on above textbox like this

 android:textColor="#ffffff"

cannot load such file -- bundler/setup (LoadError)

I ran into the same issue, but I think it was due to spring caching some gems and configurations. I fixed it by running gem pristine --all.

This restores installed gems to pristine condition from files located in the gem cache.

or you can just try for your gem like

gem pristine your_gem_name

How to count the number of lines of a string in javascript

There are three options:

Using jQuery (download from jQuery website) - jquery.com

var lines = $("#ptest").val().split("\n");
return lines.length;

Using Regex

var lines = str.split(/\r\n|\r|\n/);
return lines.length;

Or, a recreation of a for each loop

var length = 0;
for(var i = 0; i < str.length; ++i){
    if(str[i] == '\n') {
        length++;
    }
}
return length;

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

open app/build.gradle from your app-module and rewrite below line after dependencies block. This allows the plugin to determine what version of Play services you are using

apply plugin: 'com.google.gms.google-services'

I got this idea from here. In this tutorial second point is saying that above plugin line be at the bottom of your app/build.gradle file so that no dependency collisions are introduced. Hope it will help you out.

How to stop asynctask thread in android?

u can check onCancelled() once then :

protected Object doInBackground(Object... x) {

while (/* condition */) {
  if (isCancelled()) break;
}
return null;

}

Create JSON object dynamically via JavaScript (Without concate strings)

This topic, especially the answer of Xotic750 was very helpful to me. I wanted to generate a json variable to pass it to a php script using ajax. My values were stored into two arrays, and i wanted them in json format. This is a generic example:

valArray1 = [121, 324, 42, 31];
valArray2 = [232, 131, 443];
myJson = {objArray1: {}, objArray2: {}};
for (var k = 1; k < valArray1.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray1[k];
    myJson.objArray1[objName] = objValue;
}
for (var k = 1; k < valArray2.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray2[k];
    myJson.objArray2[objName] = objValue;
}
console.log(JSON.stringify(myJson));

The result in the console Log should be something like this:

{
   "objArray1": {
        "obj1": 121,
        "obj2": 324,
        "obj3": 42,
        "obj4": 31
   },
   "objArray2": {
        "obj1": 232,
        "obj2": 131,
        "obj3": 443
  }
}

TypeScript, Looping through a dictionary

There is one caveat to the key/value loop that Ian mentioned. If it is possible that the Objects may have attributes attached to their Prototype, and when you use the in operator, these attributes will be included. So you will want to make sure that the key is an attribute of your instance, and not of the prototype. Older IEs are known for having indexof(v) show up as a key.

for (const key in myDictionary) {
    if (myDictionary.hasOwnProperty(key)) {
        let value = myDictionary[key];
    }
}

How do I find an array item with TypeScript? (a modern, easier way)

If you need some es6 improvements not supported by Typescript, you can target es6 in your tsconfig and use Babel to convert your files in es5.

How to Upload Image file in Retrofit 2

Totally agree with @tir38 and @android_griezmann. This would be the version in kotlin:

interface servicesEndPoint {
@Multipart
@POST("user/updateprofile")
fun updateProfile(@Part("user_id") id:RequestBody, @Part("full_name") other:fullName, @Part image: MultipartBody.Part, @Part("other") other:RequestBody): Single<UploadPhotoResponse>

companion object {
        val API_BASE_URL = "YOUR_URL"

        fun create(): servicesPhotoEndPoint {
            val retrofit = Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(API_BASE_URL)
                .build()
            return retrofit.create(servicesPhotoEndPoint::class.java)
        }
    }
}

// pass it like this
val file = File(RealPathUtils.getRealPathFromURI_API19(context, uri))  
val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)

// MultipartBody.Part is used to send also the actual file name
val body: MultipartBody.Part = MultipartBody.Part.createFormData("image", file.name, requestFile)

// add another part within the multipart request
val fullName: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name")

servicesEndPoint.create().updateProfile(id, fullName, body, fullName)

To obtain the real path, use RealPathUtils. Check this class in the answers of @Harsh Bhavsar in this question: How to get the Full file path from URI.

To getRealPathFromURI_API19 you need permissions of READ_EXTERNAL_STORAGE

Deleting an object in C++

Your code is indeed using the normal way to create and delete a dynamic object. Yes, it's perfectly normal (and indeed guaranteed by the language standard!) that delete will call the object's destructor, just like new has to invoke the constructor.

If you weren't instantiating Object1 directly but some subclass thereof, I'd remind you that any class intended to be inherited from must have a virtual destructor (so that the correct subclass's destructor can be invoked in cases analogous to this one) -- but if your sample code is indeed representative of your actual code, this cannot be your current problem -- must be something else, maybe in the destructor code you're not showing us, or some heap-corruption in the code you're not showing within that function or the ones it calls...?

BTW, if you're always going to delete the object just before you exit the function which instantiates it, there's no point in making that object dynamic -- just declare it as a local (storage class auto, as is the default) variable of said function!

How to store Emoji Character in MySQL Database

I have updated my database and table to upgraded from utf8 to utf8mb4. But nothing works for me. Then I tried to update column datatype to blob, luckily it worked for me and data has been saved. Even my database and table both are CHARACTER SET utf8 COLLATE utf8_unicode

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

Is Tomcat running?

Here are my two cents.

I have multiple tomcat instances running on different ports for my cluster setup. I use the following command to check each processes running on different ports.

/sbin/fuser 8080/tcp

Replace the port number as per your need.

And to kill the process use -k in the above command.

  • This is much faster than the ps -ef way or any other commands where you call a command and call another grep on top of it.
  • Works well with multiple installations of tomcat ,Or any other server that uses a port as a matter of fact running on the same server.

The equivalent command on BSD operating systems is fstat

How to center body on a page?

For those that do know the width, you could do something like

div {
     max-width: ???px; //px,%
     margin-left:auto;
     margin-right:auto;
}

I also agree about not setting text-align:center on the body because it can mess up the rest of your code and you might have to individually set text-align:left on a lot of things either then or in the future.

Clone only one branch

From the announcement Git 1.7.10 (April 2012):

  • git clone learned --single-branch option to limit cloning to a single branch (surprise!); tags that do not point into the history of the branch are not fetched.

Git actually allows you to clone only one branch, for example:

git clone -b mybranch --single-branch git://sub.domain.com/repo.git

Note: Also you can add another single branch or "undo" this action.

What's causing my java.net.SocketException: Connection reset?

The Exception means that the socket was closed unexpectedly from the other side. Since you are calling a web service, this should not happen - most likely you're sending a request that triggers a bug in the web service.

Try logging the entire request in those cases, and see if you notice anything unusual. Otherwise, get in contact with the web service provider and send them your logged problematical request.

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

For anyone else with this issue that arrives here via Google, please check that the host element of the *ngFor directive is accurate. By this, I mean that I encountered this error and spent a long time researching fixes before realizing that I had put the *ngFor on an ng-template element instead of on my component I wanted to repeat.

Incorrect

<ng-template *ngFor=let group of groups$ | async" ...>
  <my-component [prop1]="group.key" ... </my-component>
<\ng-template>

Correct

<my-component *ngFor=let group of groups$ | async" [prop1]="group.key" ... </my-component>

I know this is an obvious mistake in hindsight, but I hope an answer here will save someone the headache I now have.

dll missing in JDBC

keep sqljdbc_auth.dll in your windows/system32 folder and it will work.Download sqljdbc driver from this link Unzip it and you will find sqljdbc_auth.dll.Now keep the sqljdbc_auth.dll inside system32 folder and run your program

Convert Dictionary<string,string> to semicolon separated string in c#

using System.Linq;

string s = string.Join(";", myDict.Select(x => x.Key + "=" + x.Value).ToArray());

(And if you're using .NET 4, or newer, then you can omit the final ToArray call.)

Read XML file using javascript

If you get this from a Webserver, check out jQuery. You can load it, using the Ajax load function and select the node or text you want, using Selectors.

If you don't want to do this in a http environment or avoid using jQuery, please explain in greater detail.

RichTextBox (WPF) does not have string property "Text"

There is no Text property in the WPF RichTextBox control. Here is one way to get all of the text out:

TextRange range = new TextRange(myRTB.Document.ContentStart, myRTB.Document.ContentEnd);

string allText = range.Text;

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

How to change colors of a Drawable in Android?

You can solve it using Android support compat libraries. :)

 // mutate to not share its state with any other drawable
 Drawable drawableWrap = DrawableCompat.wrap(drawable).mutate();
 DrawableCompat.setTint(drawableWrap, ContextCompat.getColor(getContext(), R.color.your_color))

Reading specific XML elements from XML file

You could use linq to xml.

    var xmlStr = File.ReadAllText("fileName.xml");


    var str = XElement.Parse(xmlStr);

    var result = str.Elements("word").
Where(x => x.Element("category").Value.Equals("verb")).ToList();

    Console.WriteLine(result);

How to install an npm package from GitHub directly?

I tried npm install git+https://github.com/visionmedia/express but that took way too long and I wasn't sure that would work.

What did work for me was - yarn add git+https://github.com/visionmedia/express.

Using C# to check if string contains a string in string array

string strName = "vernie";
string[] strNamesArray = { "roger", "vernie", "joel" };

if (strNamesArray.Any(x => x == strName))
{
   // do some action here if true...
}

How can I use UserDefaults in Swift?

Swift 4, I have used Enum for handling UserDefaults.

This is just a sample code. You can customize it as per your requirements.

For Storing, Retrieving, Removing. In this way just add a key for your UserDefaults key to the enum. Handle values while getting and storing according to dataType and your requirements.

enum UserDefaultsConstant : String {
    case AuthToken, FcmToken

    static let defaults = UserDefaults.standard


   //Store
    func setValue(value : Any) {
        switch self {
        case .AuthToken,.FcmToken:
            if let _ = value as? String {
                UserDefaults.standard.set(value, forKey: self.rawValue)
            }
            break
        }

        UserDefaults.standard.synchronize()
    }

   //Retrieve
    func getValue() -> Any? {
        switch self {
        case .AuthToken:
            if(UserDefaults.standard.value(forKey: UserDefaultsConstant.AuthToken.rawValue) != nil) {

                return "Bearer "+(UserDefaults.standard.value(forKey: UserDefaultsConstant.AuthToken.rawValue) as! String)
            }
            else {
                return ""
            }

        case .FcmToken:

            if(UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue) != nil) {
                print(UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue))
                return (UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue) as! String)
            }
            else {
                return ""
            }
        }
    }

    //Remove
    func removeValue() {
        UserDefaults.standard.removeObject(forKey: self.rawValue)
        UserDefaults.standard.synchronize()
    }
}

For storing a value in userdefaults,

if let authToken = resp.data?.token {
     UserDefaultsConstant.AuthToken.setValue(value: authToken)
    }

For retrieving a value from userdefaults,

//As AuthToken value is a string
    (UserDefaultsConstant.AuthToken.getValue() as! String)

Is it possible to save HTML page as PDF using JavaScript or jquery?

I used jsPDF and dom-to-image library to export HTML to PDF.

I post here as reference to whom concern.

$('#downloadPDF').click(function () {
    domtoimage.toPng(document.getElementById('content2'))
      .then(function (blob) {
          var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
          pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
          pdf.save("test.pdf");
      });
});

Demo: https://jsfiddle.net/viethien/md03wb21/27/

Manually Triggering Form Validation using jQuery

When there is a very complex (especially asynchronous) validation process, there is a simple workaround:

<form id="form1">
<input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" />
<input type="submit" id="form1_submit_hidden" style="display:none" />
</form>
...
<script>
function submitIfVeryComplexValidationIsOk() {
    var form1 = document.forms['form1']
    if (!form1.checkValidity()) {
        $("#form1_submit_hidden").click()
        return
    }

    if (checkForVeryComplexValidation() === 'Ok') {
         form1.submit()
    } else {
         alert('form is invalid')
    }
}
</script>

Check free disk space for current partition in bash

  1. df command : Report file system disk space usage
  2. du command : Estimate file space usage

Type df -h or df -k to list free disk space:

 $ df -h

OR

 $ df -k

du shows how much space one or more files or directories is using:

 $ du -sh

The -s option summarizes the space a directory is using and -h option provides Human-readable output.

Change Bootstrap tooltip color

BootStrap 4

When using BootStrap 4 the tooltip is appended to the bottom of the body tag. If your tooltip is a child of another tag there is no way to target the tooltip using css. The only way I've found that works is using the inserted.bs.tooltip event and adding a class to the inner div and the arrow. Then you can target the class in css.

_x000D_
_x000D_
// initialize tooltips_x000D_
$('[data-toggle="tooltip"]').tooltip(); _x000D_
_x000D_
// Add the classes to the toolip when it is created_x000D_
$('[data-toggle="tooltip"]').on('inserted.bs.tooltip',function () {_x000D_
    var thisClass = $(this).attr("class");_x000D_
    $('.tooltip-inner').addClass(thisClass);_x000D_
    $('.arrow').addClass(thisClass + "-arrow");_x000D_
});
_x000D_
/* style the tooltip box and arrow based on your class*/_x000D_
.bs-tooltip-left .redTip {_x000D_
    background-color: red !important_x000D_
}_x000D_
.bs-tooltip-left .redTip-arrow::before {_x000D_
    border-left-color: red !important_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
<p>Show a red tooltip <a href="#" class="redTip" data-toggle="tooltip" data-placement="left" title="You Did It!">Hover over me</a></p>
_x000D_
_x000D_
_x000D_