Programs & Examples On #Arrayofstring

toBe(true) vs toBeTruthy() vs toBeTrue()

As you read through the examples below, just keep in mind this difference

true === true // true
"string" === true // false
1 === true // false
{} === true // false

But

Boolean("string") === true // true
Boolean(1) === true // true
Boolean({}) === true // true

1. expect(statement).toBe(true)

Assertion passes when the statement passed to expect() evaluates to true

expect(true).toBe(true) // pass
expect("123" === "123").toBe(true) // pass

In all other cases cases it would fail

expect("string").toBe(true) // fail
expect(1).toBe(true); // fail
expect({}).toBe(true) // fail

Even though all of these statements would evaluate to true when doing Boolean():

So you can think of it as 'strict' comparison

2. expect(statement).toBeTrue()

This one does exactly the same type of comparison as .toBe(true), but was introduced in Jasmine recently in version 3.5.0 on Sep 20, 2019

3. expect(statement).toBeTruthy()

toBeTruthy on the other hand, evaluates the output of the statement into boolean first and then does comparison

expect(false).toBeTruthy() // fail
expect(null).toBeTruthy() // fail
expect(undefined).toBeTruthy() // fail
expect(NaN).toBeTruthy() // fail
expect("").toBeTruthy() // fail
expect(0).toBeTruthy() // fail

And IN ALL OTHER CASES it would pass, for example

expect("string").toBeTruthy() // pass
expect(1).toBeTruthy() // pass
expect({}).toBeTruthy() // pass

How to compare the contents of two string objects in PowerShell

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

Detect URLs in text with JavaScript

tmp.innerText is undefined. You should use tmp.innerHTML

function strip(html) 
    {  
        var tmp = document.createElement("DIV"); 
        tmp.innerHTML = html; 
        var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   
        return tmp.innerHTML .replace(urlRegex, function(url) {     
        return '\n' + url 
    })

Is there a PowerShell "string does not contain" cmdlet or syntax?

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }

Android emulator not able to access the internet

After trying many of these solutions, I was going to just delete my current AVD and make it again, but when I clicked the down arrow on the AVD, I noticed "Cold Boot Now".

AVD Menu

On a whim I tried that. Lo and behold my emulator has internet connectivity again!

EDIT: Ok, for those saying why not just wipe data and restart. Do you reformat your PC every time you restart it? Wiping data on the emulator is just like doing a factory reset to a phone or reformatting your hard drive on your PC and reinstalling your OS. It is unnecessary unless the data is totally corrupt.

When you shut off the emulator and restart it, it is like putting your PC in hibernate or sleep mode. Memory is not wiped, it is saved.

Doing a cold boot is the same as rebooting your phone or rebooting your PC. It resets memory and lets things reload. This allows the network emulation to start with clean memory and connect properly.

So, don't wipe your data. Just cold boot. If it still doesn't work, then wipe, but save that as a last resort.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.

Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know

If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.

In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:

How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections

Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.

flutter run: No connected devices

I am facing the same issue with Flutter. But I found another way to work i.e.

  1. First run Android Emulator
  2. Then go to your Flutter Console
  3. Run the command flutter doctor & check whether your emulator is showing under connected devices tag e.g. enter image description here

  4. Now move to your Flutter project path via Flutter console e.g. for me it is D:\FlutterWorkspace\flutter_demo

  5. Then run flutter run command. e.g.

enter image description here

Wait for few moments you will see your app running into Android Emulator. enter image description here

Returning JSON from PHP to JavaScript?

You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.

It looks like :

<?php
// Include the json class
include('includes/json.php');

// Then create the PHP-Json Object to suits your needs

// Set a variable ; var name = {}
$Json = new json('var', 'name'); 
// Fire a callback ; callback({});
$Json = new json('callback', 'name'); 
// Just send a raw JSON ; {}
$Json = new json();

// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';

// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);

// Finally, send the JSON.

$Json->send();
?>

adding a datatable in a dataset

I assume that you haven't set the TableName property of the DataTable, for example via constructor:

var tbl = new DataTable("dtImage");

If you don't provide a name, it will be automatically created with "Table1", the next table will get "Table2" and so on.

Then the solution would be to provide the TableName and then check with Contains(nameOfTable).

To clarify it: You'll get an ArgumentException if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException if there's already a DataTable in the DataSet with the same name(not case-sensitive).

http://msdn.microsoft.com/en-us/library/as4zy2kc.aspx

How to add parameters to HttpURLConnection using POST using NameValuePair

You can get output stream for the connection and write the parameter query string to it.

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();

...

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

Drop shadow on a div container?

.shadow {
    -moz-box-shadow:    3px 3px 5px 6px #ccc;
    -webkit-box-shadow: 3px 3px 5px 6px #ccc;
    box-shadow:         3px 3px 5px 6px #ccc;
}

What is the right way to populate a DropDownList from a database?

You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

For example, if you wanted to use a DataTable:

ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();

EDIT - More complete example

private void LoadSubjects()
{

    DataTable subjects = new DataTable();

    using (SqlConnection con = new SqlConnection(connectionString))
    {

        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
            adapter.Fill(subjects);

            ddlSubject.DataSource = subjects;
            ddlSubject.DataTextField = "SubjectNamne";
            ddlSubject.DataValueField = "SubjectID";
            ddlSubject.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }

    }

    // Add the initial item - you can add this even if the options from the
    // db were not successfully loaded
    ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

}

To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>

You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

from the code-behind, or you'll have two "" items.

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

UnicodeDecodeError, invalid continuation byte

Use this, If it shows the error of UTF-8

pd.read_csv('File_name.csv',encoding='latin-1')

How to declare 2D array in bash

Mark Reed suggested a very good solution for 2D arrays (matrix)! They always can be converted in a 1D array (vector). Although Bash doesn't have a native support for 2D arrays, it's not that hard to create a simple ADT around the mentioned principle.

Here is a barebone example with no argument checks, etc, just to keep the solution clear: the array's size is set as two first elements in the instance (documentation for the Bash module that implements a matrix ADT, https://github.com/vorakl/bash-libs/blob/master/src.docs/content/pages/matrix.rst )

#!/bin/bash

matrix_init() {
    # matrix_init instance x y data ...

    declare -n self=$1                                                          
    declare -i width=$2 height=$3                                                
    shift 3;                                                                    

    self=(${width} ${height} "$@")                                               
}                                                                               

matrix_get() {                                                                  
    # matrix_get instance x y

    declare -n self=$1                                                          
    declare -i x=$2 y=$3                                                        
    declare -i width=${self[0]} height=${self[1]}                                

    echo "${self[2+y*width+x]}"                                                 
}                                                                               

matrix_set() {                                                                  
    # matrix_set instance x y data

    declare -n self=$1                                                          
    declare -i x=$2 y=$3                                                        
    declare data="$4"                                                           
    declare -i width=${self[0]} height=${self[1]}                                

    self[2+y*width+x]="${data}"                                                 
}                                                                               

matrix_destroy() {                                                                     
    # matrix_destroy instance

    declare -n self=$1                                                          
    unset self                                                                  
}

# my_matrix[3][2]=( (one, two, three), ("1 1" "2 2" "3 3") )
matrix_init my_matrix \                                                         
        3 2 \                                                               
        one two three \                                                     
        "1 1" "2 2" "3 3"

# print my_matrix[2][0]
matrix_get my_matrix 2 0

# print my_matrix[1][1]
matrix_get my_matrix 1 1

# my_matrix[1][1]="4 4 4"
matrix_set my_matrix 1 1 "4 4 4"                                                

# print my_matrix[1][1]
matrix_get my_matrix 1 1                                                        

# remove my_matrix
matrix_destroy my_matrix

Setting Action Bar title and subtitle

Nope! You have to do it at runtime.

If you want to make your app backwards compatible, then simply check the device API level. If it is higher than 11, then you can fiddle with the ActionBar and set the subtitle.

if(Integer.valueOf(android.os.Build.VERSION.SDK) >= 11){
    //set actionbar title
}

Implicit type conversion rules in C++ operators

In C++ operators (for POD types) always act on objects of the same type.
Thus if they are not the same one will be promoted to match the other.
The type of the result of the operation is the same as operands (after conversion).

If either is      long          double the other is promoted to      long          double
If either is                    double the other is promoted to                    double
If either is                    float  the other is promoted to                    float
If either is long long unsigned int    the other is promoted to long long unsigned int
If either is long long          int    the other is promoted to long long          int
If either is long      unsigned int    the other is promoted to long      unsigned int
If either is long               int    the other is promoted to long               int
If either is           unsigned int    the other is promoted to           unsigned int
If either is                    int    the other is promoted to                    int
Both operands are promoted to int

Note. The minimum size of operations is int. So short/char are promoted to int before the operation is done.

In all your expressions the int is promoted to a float before the operation is performed. The result of the operation is a float.

int + float =>  float + float = float
int * float =>  float * float = float
float * int =>  float * float = float
int / float =>  float / float = float
float / int =>  float / float = float
int / int                     = int
int ^ float =>  <compiler error>

how to start stop tomcat server using CMD?

Steps to start Apache Tomcat using cmd:
1. Firstly check that the JRE_HOME or JAVA_HOME is a variable available in environment variables.(If it is not create a new variable JRE_HOME or JAVA_HOME)
2. Goto cmd and change your working directory to bin path where apache is installed (or extracted).
3. Type Command -> catalina.bat start to start the server.
4. Type Command -> catalina.bat stop to stop the server.

Environment variable in Jenkins Pipeline

You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).

From the documentation:

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.

For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job enter image description here

Remove padding or margins from Google Charts

By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width to 100% and chartArea.height to 80% and moving the legend.position to bottom:

// Set chart options
var options = {'title': 'How Much Pizza I Ate Last Night',
               'width': 350,
               'height': 400,
               'chartArea': {'width': '100%', 'height': '80%'},
               'legend': {'position': 'bottom'}
    };

If you want to tune it more, try changing these values or using other properties from the link above.

How to convert a DataTable to a string in C#?

i know i'm years late xD but Here's how i did it

    public static string convertDataTableToString(DataTable dataTable)
    {
        string data = string.Empty;
        for (int i = 0; i < dataTable.Rows.Count; i++)
        {
            DataRow row = dataTable.Rows[i];
            for (int j = 0; j < dataTable.Columns.Count; j++)
            {
                data += dataTable.Columns[j].ColumnName + "~" + row[j];
                if (j == dataTable.Columns.Count - 1)
                {
                    if (i != (dataTable.Rows.Count - 1))
                        data += "$";
                }
                else
                    data += "|";
            }
        }
        return data;
    }

If someone ever optimizes this please let me know

i tried this :

    public static string convertDataTableToString(DataTable dataTable)
    {
        string data = string.Empty;
        int rowsCount = dataTable.Rows.Count;
        for (int i = 0; i < rowsCount; i++)
        {
            DataRow row = dataTable.Rows[i];
            int columnsCount = dataTable.Columns.Count;
            for (int j = 0; j < columnsCount; j++)
            {
                data += dataTable.Columns[j].ColumnName + "~" + row[j];
                if (j == columnsCount - 1)
                {
                    if (i != (rowsCount - 1))
                        data += "$";
                }
                else
                    data += "|";
            }
        }
        return data;
    }

but this answer says it's worse

Bootstrap $('#myModal').modal('show') is not working

After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.

Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using

setTimeout(() => {  $('#modalID').modal('show'); }, 500);

Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

What's the proper way to compare a String to an enum value?

My idea:

public enum SomeKindOfEnum{
    ENUM_NAME("initialValue");

    private String value;

    SomeKindOfEnum(String value){
        this.value = value;
    }

    public boolean equalValue(String passedValue){
        return this.value.equals(passedValue);
    }
}

And if u want to check Value u write:

SomeKindOfEnum.ENUM_NAME.equalValue("initialValue")

Kinda looks nice for me :). Maybe somebody will find it useful.

How to insert values into the database table using VBA in MS access

  1. Remove this line of code: For i = 1 To DatDiff. A For loop must have the word NEXT
  2. Also, remove this line of code: StrSQL = StrSQL & "SELECT 'Test'" because its making Access look at your final SQL statement like this; INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );SELECT 'Test' Notice the semicolon in the middle of the SQL statement (should always be at the end. its by the way not required. you can also omit it). also, there is no space between the semicolon and the key word SELECT

in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #

Getting JavaScript object key list

_x000D_
_x000D_
var obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  key4: 'value4'
};
var keys = [];

for (var k in obj) keys.push(k);

console.log("total " + keys.length + " keys: " + keys);
_x000D_
_x000D_
_x000D_

Passing a variable from one php include file to another: global vs. not

When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

So, in your example, since you've set a variable called $name in your front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

In other words, to do the behavior you're expecting, you will need to define it as a global.

Single TextView with multiple colored text

25 June 2020 by @canerkaseler

I would like to share Kotlin Answer :

fun setTextColor(tv:TextView, startPosition:Int, endPosition:Int, color:Int){
    val spannableStr = SpannableString(tv.text)

    val underlineSpan = UnderlineSpan()
    spannableStr.setSpan(
        underlineSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val backgroundColorSpan = ForegroundColorSpan(this.resources.getColor(R.color.agreement_color))
    spannableStr.setSpan(
        backgroundColorSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val styleSpanItalic = StyleSpan(Typeface.BOLD)
    spannableStr.setSpan(
        styleSpanItalic,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    tv.text = spannableStr
}

After, call above function. You can call more than one:

setTextColor(textView, 0, 61, R.color.agreement_color)
setTextColor(textView, 65, 75, R.color.colorPrimary)

Output: You can see underline and different colors with each other.

@canerkaseler

How to remove the focus from a TextBox in WinForms?

Focusing on the label didn't work for me, doing something like label1.Focus() right? the textbox still has focus when loading the form, however trying Velociraptors answer, worked for me, setting the Form's Active control to the label like this:

private void Form1_Load(object sender, EventArgs e)  
{ 
    this.ActiveControl = label1;       
}

How can I install MacVim on OS X?

  • Step 1. Install homebrew from here: http://brew.sh
  • Step 1.1. Run export PATH=/usr/local/bin:$PATH
  • Step 2. Run brew update
  • Step 3. Run brew install vim && brew install macvim
  • Step 4. Run brew link macvim

You now have the latest versions of vim and macvim managed by brew. Run brew update && brew upgrade every once in a while to upgrade them.

This includes the installation of the CLI mvim and the mac application (which both point to the same thing).

I use this setup and it works like a charm. Brew even takes care of installing vim with the preferable options.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

The solution was to add these flags to JVM command line when Tomcat is started:

-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the "Java" tab, add the arguments to the "Java Options" box. Click "OK" and then restart the service.

If you get an error the specified service does not exist as an installed service you should run:

tomcat6w //ES//servicename

where servicename is the name of the server as viewed in services.msc

Source: orx's comment on Eric's Agile Answers.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

I had the same problem using Spring Boot 2.0.0.M7 + Spring Security + Springfox 2.8.0. And I solved the problem using the following security configuration that allows public access to Swagger UI resources.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- Swagger UI v2
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**",
            // -- Swagger UI v3 (OpenAPI)
            "/v3/api-docs/**",
            "/swagger-ui/**"
            // other public endpoints of your API may be appended to this array
    };


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                // ... here goes your custom security configuration
                authorizeRequests().
                antMatchers(AUTH_WHITELIST).permitAll().  // whitelist Swagger UI resources
                // ... here goes your custom security configuration
                antMatchers("/**").authenticated();  // require authentication for any endpoint that's not whitelisted
    }

}

Adding rows to tbody of a table using jQuery

Here is an appendTo version using the html dropdown you mentioned. It inserts another row on "change".

$('#dropdown').on( 'change', function(e) {
    $('#table').append('<tr><td>COL1</td><td>COL2</td></tr>');
});

With an example for you to play with. Best of luck!

http://jsfiddle.net/xtHaF/12/

new Image(), how to know if image 100% loaded or not?

Use the load event:

img = new Image();

img.onload = function(){
  // image  has been loaded
};

img.src = image_url;

Also have a look at:

angular ng-repeat in reverse

Im adding one answer that no one mentioned. I would try to make the server do it if you have one. Clientside filtering can be dangerous if the server returns a lot of records. Because you might be forced to add paging. If you have paging from the server then the client filter on order, would be in the current page. Which would confuse the end user. So if you have a server, then send the orderby with the call and let the server return it.

ES6 export default with multiple functions referring to each other

One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.

export function foo() { console.log('foo') }, 
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }

In this case you are export all of the functions with names, so you could do

import * as fns from './foo';

to get an object with properties for each function instead of the import you'd use for your first example:

import fns from './foo';

Javascript | Set all values of an array

It's 2019 and you should be using this:

let arr = [...Array(20)].fill(10)

So basically 20 is the length or a new instantiated Array.

Left padding a String with Zeros

String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);

Substring with reverse index

slice works just fine in IE and other browsers, it's part of the specification and it's the most efficient method too:

alert("xxx_456".slice(-3));
//-> 456

slice Method (String) - MSDN
slice - Mozilla Developer Center

diff current working copy of a file with another branch's committed copy

Also: git diff master..feature foo

Since git diff foo master:foo doesn't work on directories for me.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

For me I do this to find,

let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in ...}

Can't use

"let url = NSURL(string: urlString)

EF Code First "Invalid column name 'Discriminator'" but no inheritance

this error happen with me because I did the following

  1. I changed Column name of table in database
  2. (I did not used Update Model from database in Edmx) I Renamed manually Property name to match the change in database schema
  3. I did some refactoring to change name of the property in the class to be the same as database schema and models in Edmx

Although all of this, I got this error

so what to do

  1. I Deleted the model from Edmx
  2. Right Click and Update Model from database

this will regenerate the model, and entity framework will not give you this error

hope this help you

Echoing the last command run in Bash?

There is a racecondition between the last command ($_) and last error ( $?) variables. If you try to store one of them in an own variable, both encountered new values already because of the set command. Actually, last command hasn't got any value at all in this case.

Here is what i did to store (nearly) both informations in own variables, so my bash script can determine if there was any error AND setting the title with the last run command:

   # This construct is needed, because of a racecondition when trying to obtain
   # both of last command and error. With this the information of last error is
   # implied by the corresponding case while command is retrieved.

   if   [[ "${?}" == 0 && "${_}" != "" ]] ; then
    # Last command MUST be retrieved first.
      LASTCOMMAND="${_}" ;
      RETURNSTATUS='?' ;
   elif [[ "${?}" == 0 && "${_}" == "" ]] ; then
      LASTCOMMAND='unknown' ;
      RETURNSTATUS='?' ;
   elif [[ "${?}" != 0 && "${_}" != "" ]] ; then
    # Last command MUST be retrieved first.
      LASTCOMMAND="${_}" ;
      RETURNSTATUS='?' ;
      # Fixme: "$?" not changing state until command executed.
   elif [[ "${?}" != 0 && "${_}" == "" ]] ; then
      LASTCOMMAND='unknown' ;
      RETURNSTATUS='?' ;
      # Fixme: "$?" not changing state until command executed.
   fi

This script will retain the information, if an error occured and will obtain the last run command. Because of the racecondition i can not store the actual value. Besides, most commands actually don't even care for error noumbers, they just return something different from '0'. You'll notice that, if you use the errono extention of bash.

It should be possible with something like a "intern" script for bash, like in bash extention, but i'm not familiar with something like that and it wouldn't be compatible as well.

CORRECTION

I didn't think, that it was possible to retrieve both variables at the same time. Although i like the style of the code, i assumed it would be interpreted as two commands. This was wrong, so my answer devides down to:

   # Because of a racecondition, both MUST be retrieved at the same time.
   declare RETURNSTATUS="${?}" LASTCOMMAND="${_}" ;

   if [[ "${RETURNSTATUS}" == 0 ]] ; then
      declare RETURNSYMBOL='?' ;
   else
      declare RETURNSYMBOL='?' ;
   fi

Although my post might not get any positive rating, i solved my problem myself, finally. And this seems appropriate regarding the intial post. :)

How to open a WPF Popup when another control is clicked, using XAML markup only?

I had some issues with the MouseDown part of this, but here is some code that might get your started.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Control VerticalAlignment="Top">
            <Control.Template>
                <ControlTemplate>
                    <StackPanel>
                    <TextBox x:Name="MyText"></TextBox>
                    <Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
                        <Border Background="Red">
                            <TextBlock>Test Popup Content</TextBlock>
                        </Border>
                    </Popup>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Control.Template>
        </Control>
    </Grid>
</Window>

Convert string to ASCII value python

If you want your result concatenated, as you show in your question, you could try something like:

>>> reduce(lambda x, y: str(x)+str(y), map(ord,"hello world"))
'10410110810811132119111114108100'

What is the difference between MOV and LEA?

  • LEA means Load Effective Address
  • MOV means Load Value

In short, LEA loads a pointer to the item you're addressing whereas MOV loads the actual value at that address.

The purpose of LEA is to allow one to perform a non-trivial address calculation and store the result [for later usage]

LEA ax, [BP+SI+5] ; Compute address of value

MOV ax, [BP+SI+5] ; Load value at that address

Where there are just constants involved, MOV (through the assembler's constant calculations) can sometimes appear to overlap with the simplest cases of usage of LEA. Its useful if you have a multi-part calculation with multiple base addresses etc.

How to break a while loop from an if condition inside the while loop?

while(something.hasnext())
do something...
   if(contains something to process){
      do something...
      break;
   }
}

Just use the break statement;

For eg:this just prints "Breaking..."

while (true) {
     if (true) {
         System.out.println("Breaking...");
         break;
     }
     System.out.println("Did this print?");
}

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

Both are the same thing but many of the databases are not providing the varying char mainly postgreSQL is providing. So for the multi database like Oracle Postgre and DB2 it is good to use the Varchar

How does GPS in a mobile phone work exactly?

There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing. Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.

If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.

Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.

Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.

How could I put a border on my grid control in WPF?

<Grid x:Name="outerGrid">
    <Grid x:Name="innerGrid">
        <Border BorderBrush="#FF179AC8" BorderThickness="2" />
        <other stuff></other stuff>
        <other stuff></other stuff>
    </Grid>
</Grid>

This code Wrap a border inside the "innerGrid"

Clear Application's Data Programmatically

What I use everywhere :

 Runtime.getRuntime().exec("pm clear me.myapp");

Executing above piece of code closes application and removes all databases and shared preferences

What's a Good Javascript Time Picker?

I wasn't happy with any of the suggested time pickers, so I created my own with inspiration from Perifer's and the HTML5 spec:

http://github.com/gregersrygg/jquery.timeInput

You can either use the new html5 attributes for time input (step, min, max), or use an options object:

<input type="time" name="myTime" class="time-mm-hh" min="9:00" max="18:00" step="1800" />
<input type="time" name="myTime2" class="time-mm-hh" />

<script type="text/javascript">
    $("input[name='myTime']").timeInput(); // use default or html5 attributes
    $("input[name='myTime2']").timeInput({min: "6:00", max: "15:00", step: 900}); // 15 min intervals from 6:00 am to 3:00 pm
</script>

Validates input like this:

  • Insert ":" if missing
  • Not valid time? Replace with blank
  • Not a valid time according to step? Round up/down to closest step

The HTML5 spec doesn't allow am/pm or localized time syntax, so it only allowes the format hh:mm. Seconds is allowed according to spec, but I have not implemented it yet.

It's very "alpha", so there might be some bugs. Feel free to send me patches/pull requests. Have manually tested in IE 6&8, FF, Chrome and Opera (Latest stable on Linux for the latter ones).

How to get Linux console window width in Python

Many of the Python 2 implementations here will fail if there is no controlling terminal when you call this script. You can check sys.stdout.isatty() to determine if this is in fact a terminal, but that will exclude a bunch of cases, so I believe the most pythonic way to figure out the terminal size is to use the builtin curses package.

import curses
w = curses.initscr()
height, width = w.getmaxyx()

Turning Sonar off for certain code

I not be able to find squid number in sonar 5.6, with this annotation also works:

@SuppressWarnings({"pmd:AvoidCatchingGenericException", "checkstyle:com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck"})

Python: "Indentation Error: unindent does not match any outer indentation level"

I have this issue. This is because wrong space in my code. probably the next line.delete all space and tabs and use space.

Loop through files in a directory using PowerShell

If you need to loop inside a directory recursively for a particular kind of file, use the below command, which filters all the files of doc file type

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc

If you need to do the filteration on multiple types, use the below command.

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf

Now $fileNames variable act as an array from which you can loop and apply your business logic.

How to get the unique ID of an object which overrides hashCode()?

Just to augment the other answers from a different angle.

If you want to reuse hashcode(s) from 'above' and derive new ones using your class' immutatable state, then a call to super will work. While this may/may not cascade all the way up to Object (i.e. some ancestor may not call super), it will allow you to derive hashcodes by reuse.

@Override
public int hashCode() {
    int ancestorHash = super.hashCode();
    // now derive new hash from ancestorHash plus immutable instance vars (id fields)
}

Key Listeners in python?

keyboard

Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.

Global event hook on all keyboards (captures keys regardless of focus). Listen and sends keyboard events. Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!). Pure Python, no C modules to be compiled. Zero dependencies. Trivial to install and deploy, just copy the files. Python 2 and 3. Complex hotkey support (e.g. Ctrl+Shift+M, Ctrl+Space) with controllable timeout. Includes high level API (e.g. record and play, add_abbreviation). Maps keys as they actually are in your layout, with full internationalization support (e.g. Ctrl+ç). Events automatically captured in separate thread, doesn't block main program. Tested and documented. Doesn't break accented dead keys (I'm looking at you, pyHook). Mouse support available via project mouse (pip install mouse).

From README.md:

import keyboard

keyboard.press_and_release('shift+s, space')

keyboard.write('The quick brown fox jumps over the lazy dog.')

# Press PAGE UP then PAGE DOWN to type "foobar".
keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))

# Blocks until you press esc.
keyboard.wait('esc')

# Record events until 'esc' is pressed.
recorded = keyboard.record(until='esc')
# Then replay back at three times the speed.
keyboard.play(recorded, speed_factor=3)

# Type @@ then press space to replace with abbreviation.
keyboard.add_abbreviation('@@', '[email protected]')
# Block forever.
keyboard.wait()

There is already an open DataReader associated with this Command which must be closed first

It appears that you're calling DateLastUpdated from within an active query using the same EF context and DateLastUpdate issues a command to the data store itself. Entity Framework only supports one active command per context at a time.

You can refactor your above two queries into one like this:

return accounts.AsEnumerable()
        .Select((account, index) => new AccountsReport()
        {
          RecordNumber = FormattedRowNumber(account, index + 1),
          CreditRegistryId = account.CreditRegistryId,
          DateLastUpdated = (
                                                from h in context.AccountHistory 
                                                where h.CreditorRegistryId == creditorRegistryId 
                              && h.AccountNo == accountNo 
                                                select h.LastUpdated).Max(),
          AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)
        })
        .OrderBy(c=>c.FormattedRecordNumber)
        .ThenByDescending(c => c.StateChangeDate);

I also noticed you're calling functions like FormattedAccountNumber and FormattedRecordNumber in the queries. Unless these are stored procs or functions you've imported from your database into the entity data model and mapped correct, these will also throw excepts as EF will not know how to translate those functions in to statements it can send to the data store.

Also note, calling AsEnumerable doesn't force the query to execute. Until the query execution is deferred until enumerated. You can force enumeration with ToList or ToArray if you so desire.

Rename Oracle Table or View

One can rename indexes the same way:

alter index owner.index_name rename to new_name;

Size of Matrix OpenCV

cv:Mat mat;
int rows = mat.rows;
int cols = mat.cols;

cv::Size s = mat.size();
rows = s.height;
cols = s.width;

Also note that stride >= cols; this means that actual size of the row can be greater than element size x cols. This is different from the issue of continuous Mat and is related to data alignment.

Javascript get Object property Name

If you want to get the key name of myVar object then you can use Object.keys() for this purpose.

var result = Object.keys(myVar); 

alert(result[0]) // result[0] alerts typeA

Where IN clause in LINQ

This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.

Problem:

Let say we have document table. Schema as follows schema : document(name,version,auther,modifieddate) composite Keys : name,version

So we need to get latest versions of all documents.

soloution

 var result = (from t in Context.document
                          where ((from tt in Context.document where t.Name == tt.Name
                                orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
                          select t).ToList();

How to sort an ArrayList?

If you have to sort object based on its id in the ArrayList , then use java8 stream.

 List<Person> personList = new ArrayList<>();

    List<Person> personListSorted =
                personList.stream()
                  .sorted(Comparator.comparing(Person::getPersonId))
                  .collect(Collectors.toList());

What is the difference between "::" "." and "->" in c++

In C++ you can access fields or methods, using different operators, depending on it's type:

  • ClassName::FieldName : class public static field and methods
  • ClassInstance.FieldName : accessing a public field (or method) through class reference
  • ClassPointer->FieldName : accessing a public field (or method) dereferencing a class pointer

Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.

class AClass{
public:
static int static_field;
int instance_field;

static void static_method();
void method();
};

then you access this way:

AClass instance;
AClass *pointer = new AClass();

instance.instance_field; //access instance_field through a reference to AClass
instance.method();

pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();

AClass::static_field;  
AClass::static_method();

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

Getting DOM node from React child element

this.props.children should either be a ReactElement or an array of ReactElement, but not components.

To get the DOM nodes of the children elements, you need to clone them and assign them a new ref.

render() {
  return (
    <div>
      {React.Children.map(this.props.children, (element, idx) => {
        return React.cloneElement(element, { ref: idx });
      })}
    </div>
  );
}

You can then access the child components via this.refs[childIdx], and retrieve their DOM nodes via ReactDOM.findDOMNode(this.refs[childIdx]).

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

How do I lock the orientation to portrait mode in a iPhone Web Application?

This is a pretty hacky solution, but it's at least something(?). The idea is to use a CSS transform to rotate the contents of your page to quasi-portrait mode. Here's JavaScript (expressed in jQuery) code to get you started:

$(document).ready(function () {
  function reorient(e) {
    var portrait = (window.orientation % 180 == 0);
    $("body > div").css("-webkit-transform", !portrait ? "rotate(-90deg)" : "");
  }
  window.onorientationchange = reorient;
  window.setTimeout(reorient, 0);
});

The code expects the entire contents of your page to live inside a div just inside the body element. It rotates that div 90 degrees in landscape mode - back to portrait.

Left as an exercise to the reader: the div rotates around its centerpoint, so its position will probably need to be adjusted unless it's perfectly square.

Also, there's an unappealing visual problem. When you change orientation, Safari rotates slowly, then the top-level div snaps to 90degrees different. For even more fun, add

body > div { -webkit-transition: all 1s ease-in-out; }

to your CSS. When the device rotates, then Safari does, then the content of your page does. Beguiling!

Visualizing branch topology in Git

I've tried --simplify-by-decoration but all my merges are not shown. So I instead just prune off lines with no "\" and "/" symbols at the headers, while always keeping lines with "(" indicating branches immediately after that. When showing branch history I'm in general uninterested in commit comments, so I remove them too. I end up with the following shell alias.

gbh () { 
    git log --graph --oneline --decorate "$@" | grep '^[^0-9a-f]*[\\/][^0-9a-f]*\( [0-9a-f]\|$\)\|^[^0-9a-f]*[0-9a-f]*\ (' | sed -e 's/).*/)/'
}

C# "internal" access modifier when doing unit testing

Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.

Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.

One thing to consider might be a "ForTest" suffix:

internal void DoThisForTest(string name)
{
    DoThis(name);
}

private void DoThis(string name)
{
    // Real implementation
}

Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

If you're running Windows 10 Creators Update (1703) and are comfortable navigating around a Unix terminal, you could potentially achieve this using the native Feature Bash on Ubuntu on Windows (aka Bash/WSL)

This was originally introduced on the launch of Build 2016 but many additions and bug fixes were addressed at the Creators update but please be warned this is still in Beta.

To enable simply navigate to Control Panel\All Control Panel Items\Programs and Features\Turn Windows features on or off

Then select the Windows Subsystem for Linux (Beta) as below Bash on Windows Feature

Facebook OAuth "The domain of this URL isn't included in the app's domain"

Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

I had this issue today, I find the Facebook documentation and SDK disrespectful and arogant towards other developers to say the least.

Besides having the "app domains" in two different locations without much information (3 if you add a "web" platform), you also need to go to app products / facebook login / settings and add your redirect URL under Valid OAuth Redirect URIs

The error says NOTHING about the oauth settings.

How to add external library in IntelliJ IDEA?

Intellij IDEA 15: File->Project Structure...->Project Settings->Libraries

android:layout_height 50% of the screen size

You should do something like that:

<LinearLayout
    android:id="@+id/widget34"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_below="@+id/tv_scanning_for"
    android:layout_centerHorizontal="true">

    <ListView
        android:id="@+id/lv_events"
        android:textSize="18sp"         
        android:cacheColorHint="#00000000"
        android:layout_height="1"
        android:layout_width="fill_parent"
        android:layout_weight="0dp"
        android:layout_below="@+id/tv_scanning_for"
        android:layout_centerHorizontal="true"
        />

</LinearLayout>

Also use dp instead px or read about it here.

What is the Auto-Alignment Shortcut Key in Eclipse?

The answer that the OP accepted is wildly different from the question I thought was asked. I thought the OP wanted a way to auto-align = signs or + signs, similar to the tabularize plugin for vim.

For this task, I found the Columns4Eclipse plugin to be just what I needed.

Why em instead of px?

Pixel is an absolute unit whereas rem/em are relative units. For more: https://drafts.csswg.org/css-values-3/

You should use the relative unit when you want the font-size to be adaptive according to the system's font size because the system provides the font-size value to the root element which is the HTML element.

In this case, where the webpage is open in google chrome, the font-size to the HTML element is set by chrome, try changing it to see the effect on webpages with fonts of rem/ em units.

enter image description here

If you use px as the unit for fonts, the fonts will not resize whereas the fonts with rem/ em unit will resize when you change the system's font size.

So use px when you want the size to be fixed and use rem/ em when you want the size to be adaptive/ dynamic to the size of the system.

Inheritance and Overriding __init__ in python

The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.

It looks like this nowadays:

class FileInfo(dict):
    """store file metadata"""
    def __init__(self, filename=None):
        super(FileInfo, self).__init__()
        self["name"] = filename

Note the following:

  1. We can directly subclass built-in classes, like dict, list, tuple, etc.

  2. The super function handles tracking down this class's superclasses and calling functions in them appropriately.

Call a method of a controller from another controller using 'scope' in AngularJS

Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

HTML

<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

<my-component ng-model="message"></my-component>

JS

var myModule = angular.module('myModule', []);

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };

    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

How do I fix "Expected to return a value at the end of arrow function" warning?

_x000D_
_x000D_
class Blog extends Component{_x000D_
 render(){_x000D_
  const posts1 = this.props.posts;_x000D_
  //console.log(posts)_x000D_
  const sidebar = (_x000D_
   <ul>_x000D_
    {posts1.map((post) => {_x000D_
     //Must use return to avoid this error._x000D_
          return(_x000D_
      <li key={post.id}>_x000D_
       {post.title} - {post.content}_x000D_
      </li>_x000D_
     )_x000D_
    })_x000D_
   }_x000D_
   _x000D_
   </ul>_x000D_
  );_x000D_
  const maincontent = this.props.posts.map((post) => {_x000D_
   return(_x000D_
    <div key={post.id}>_x000D_
     <h3>{post.title}</h3>_x000D_
     <p>{post.content}</p>_x000D_
    </div>_x000D_
   )_x000D_
  })_x000D_
  return(_x000D_
   <div>{sidebar}<hr/>{maincontent}</div>_x000D_
  );_x000D_
 }_x000D_
}_x000D_
const posts = [_x000D_
  {id: 1, title: 'Hello World', content: 'Welcome to learning React!'},_x000D_
  {id: 2, title: 'Installation', content: 'You can install React from npm.'}_x000D_
];_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Blog posts={posts} />,_x000D_
  document.getElementById('root')_x000D_
);
_x000D_
_x000D_
_x000D_

iPhone 6 and 6 Plus Media Queries

iPhone X

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 812px) 
  and (-webkit-min-device-pixel-ratio: 3)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

iPhone 6+, 7+ and 8+

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 414px) 
  and (max-device-width: 736px) 
  and (-webkit-min-device-pixel-ratio: 3)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

iPhone 6, 6S, 7 and 8

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 667px) 
  and (-webkit-min-device-pixel-ratio: 2)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

Source: Media Queries for Standard Devices

WCF, Service attribute value in the ServiceHost directive could not be found

I also ran into this issue trying the Microsoft.ServiceModel.Samples.Calculator WCF sample. I am using IIS 5.1. I resolved it by ensuring that the website that was auto-generated (servicemodelsamples) was not an application. Right-click the folder, click "Properties" and click the "Create" button.

How to tell if tensorflow is using gpu acceleration from inside python shell?

I found below snippet is very handy to test the gpu ..

Tensorflow 2.0 Test

import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
with tf.device('/gpu:0'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
    c = tf.matmul(a, b)

with tf.Session() as sess:
    print (sess.run(c))

Tensorflow 1 Test

import tensorflow as tf
with tf.device('/gpu:0'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
    c = tf.matmul(a, b)

with tf.Session() as sess:
    print (sess.run(c))

How do I format date and time on ssrs report?

If the date and time is in its own cell (aka textbox), then you should look at applying the format to the entire textbox. This will create cleaner exports to other formats; in particular, the value will export as a datetime value to Excel instead of a string.

Use the properties pane or dialog to set the format for the textbox to "MM/dd/yyyy hh:mm tt"

I would only use Ian's answer if the datetime is being concatenated with another string.

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

You probably just need to see the ASCII and EXTENDED ASCII character sets. As far as I know any of these are allowed in a char/varchar field.

If you use nchar/nvarchar then it's pretty much any character in any unicode set in the world.

enter image description here

enter image description here

How to set order of repositories in Maven settings.xml

Also, consider to use a repository manager such as Nexus and configure all your repositories there.

JavaScript hashmap equivalent

According to ECMAScript 2015 (ES6), standard JavaScript has a Map implementation. More about which could be found here.

Basic usage:

var myMap = new Map();
var keyString = "a string",
    keyObj = {},
    keyFunc = function () {};

// Setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

// Getting the values
myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

How to trigger button click in MVC 4

yo can try this code

@using (Html.BeginForm("SignUp", "Account", FormMethod.Post)){<fieldset>
    <legend>Sign Up</legend>
    <table>
        <tr>
            <td>
                @Html.Label("User Name")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Username)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Email")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Email)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Password")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Password)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Confirm Password")
            </td>
            <td>
                @Html.Password("txtPassword")
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" name="btnSubmit" value="Sign Up" />
            </td>
        </tr>
    </table>
</fieldset>}

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

Instead of gdb, run gdbtui. Or run gdb with the -tui switch. Or press C-x C-a after entering gdb. Now you're in GDB's TUI mode.

Enter layout asm to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish etc. are abbreviated to a single key, allowing you to walk through your program very quickly.

   +---------------------------------------------------------------------------+
B+>|0x402670 <main>         push   %r15                                        |
   |0x402672 <main+2>       mov    %edi,%r15d                                  |
   |0x402675 <main+5>       push   %r14                                        |
   |0x402677 <main+7>       push   %r13                                        |
   |0x402679 <main+9>       mov    %rsi,%r13                                   |
   |0x40267c <main+12>      push   %r12                                        |
   |0x40267e <main+14>      push   %rbp                                        |
   |0x40267f <main+15>      push   %rbx                                        |
   |0x402680 <main+16>      sub    $0x438,%rsp                                 |
   |0x402687 <main+23>      mov    (%rsi),%rdi                                 |
   |0x40268a <main+26>      movq   $0x402a10,0x400(%rsp)                       |
   |0x402696 <main+38>      movq   $0x0,0x408(%rsp)                            |
   |0x4026a2 <main+50>      movq   $0x402510,0x410(%rsp)                       |
   +---------------------------------------------------------------------------+
child process 21518 In: main                            Line: ??   PC: 0x402670
(gdb) file /opt/j64-602/bin/jconsole
Reading symbols from /opt/j64-602/bin/jconsole...done.
(no debugging symbols found)...done.
(gdb) layout asm
(gdb) start
(gdb)

How to add "required" attribute to mvc razor viewmodel text input editor

A newer way to do this in .NET Core is with TagHelpers.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro

Building on these examples (MaxLength, Label), you can extend the existing TagHelper to suit your needs.

RequiredTagHelper.cs

using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;

namespace ProjectName.TagHelpers
{
    [HtmlTargetElement("input", Attributes = "asp-for")]
    public class RequiredTagHelper : TagHelper
    {
        public override int Order
        {
            get { return int.MaxValue; }
        }

        [HtmlAttributeName("asp-for")]
        public ModelExpression For { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output); 

            if (context.AllAttributes["required"] == null)
            {
                var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
                if (isRequired)
                {
                    var requiredAttribute = new TagHelperAttribute("required");
                    output.Attributes.Add(requiredAttribute);
                }
            }
        }
    }
}

You'll then need to add it to be used in your views:

_ViewImports.cshtml

@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"

Given the following model:

Foo.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace ProjectName.Models
{
    public class Foo
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "Full Name")]
        public string Name { get; set; }
    }
}

and view (snippet):

New.cshtml

<label asp-for="Name"></label>
<input asp-for="Name"/>

Will result in this HTML:

<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>

I hope this is helpful to anyone with same question but using .NET Core.

Selecting multiple columns in a Pandas dataframe

In the latest version of Pandas there is an easy way to do exactly this. Column names (which are strings) can be sliced in whatever manner you like.

columns = ['b', 'c']
df1 = pd.DataFrame(df, columns=columns)

How to duplicate a git repository? (without forking)

If you just want to create a new repository using all or most of the files from an existing one (i.e., as a kind of template), I find the easiest approach is to make a new repo with the desired name etc, clone it to your desktop, then just add the files and folders you want in it.

You don't get all the history etc, but you probably don't want that in this case.

How to use \n new line in VB msgbox() ...?

The message box must end with a text and not with a variable

How to discard all changes made to a branch?

If you don't want any changes in design and definitely want it to just match a remote's branch, you can also just delete the branch and recreate it:

# Switch to some branch other than design
$ git br -D design
$ git co -b design origin/design            # Will set up design to track origin's design branch

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

Error: Specified cast is not valid. (SqlManagerUI)

Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?

RESTORE VERIFYONLY FROM DISK = N'd:\yourbackup.bak'

if it gives error like:

Msg 3241, Level 16, State 13, Line 2 The media family on device 'd:\alibaba.bak' is incorrectly formed. SQL Server cannot process this media family. Msg 3013, Level 16, State 1, Line 2 VERIFY DATABASE is terminating abnormally.

Check it further:

RESTORE HEADERONLY FROM DISK = N'd:\yourbackup.bak'

BackupName is "* INCOMPLETE *", Position is "1", other fields are "NULL".

Means either your backup is corrupt or taken from newer version.

Why can't I make a vector of references?

Ion Todirel already mentioned an answer YES using std::reference_wrapper. Since C++11 we have a mechanism to retrieve object from std::vector and remove the reference by using std::remove_reference. Below is given an example compiled using g++ and clang with option
-std=c++11 and executed successfully.

#include <iostream>
#include <vector>
#include<functional>

class MyClass {
public:
    void func() {
        std::cout << "I am func \n";
    }

    MyClass(int y) : x(y) {}

    int getval()
    {
        return x;
    }

private: 
        int x;
};

int main() {
    std::vector<std::reference_wrapper<MyClass>> vec;

    MyClass obj1(2);
    MyClass obj2(3);

    MyClass& obj_ref1 = std::ref(obj1);
    MyClass& obj_ref2 = obj2;

    vec.push_back(obj_ref1);
    vec.push_back(obj_ref2);

    for (auto obj3 : vec)
    {
        std::remove_reference<MyClass&>::type(obj3).func();      
        std::cout << std::remove_reference<MyClass&>::type(obj3).getval() << "\n";
    }             
}

Parsing arguments to a Java command line program

Simple code for command line in java:

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

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

Passing arguments to require (when loading module)

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {
  ...
};

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

How can I get the source directory of a Bash script from within the script itself?

How to obtain the full file path, full directory, and base filename of any script being run itself

For many cases, all you need to acquire is the full path to the script you just called. This can be easily accomplished using realpath. Note that realpath is part of GNU coreutils. If you don't have it already installed (it comes default on Ubuntu), you can install it with sudo apt update && sudo apt install coreutils.

get_script_path.sh:

#!/bin/bash

FULL_PATH_TO_SCRIPT="$(realpath "$0")"

# You can then also get the full path to the directory, and the base
# filename, like this:
SCRIPT_DIRECTORY="$(dirname "$FULL_PATH_TO_SCRIPT")"
SCRIPT_FILENAME="$(basename "$FULL_PATH_TO_SCRIPT")"

# Now print it all out
echo "FULL_PATH_TO_SCRIPT = \"$FULL_PATH_TO_SCRIPT\""
echo "SCRIPT_DIRECTORY    = \"$SCRIPT_DIRECTORY\""
echo "SCRIPT_FILENAME     = \"$SCRIPT_FILENAME\""

Example output:

~/GS/dev/eRCaGuy_hello_world/bash$ ./get_script_path.sh 
FULL_PATH_TO_SCRIPT = "/home/gabriel/GS/dev/eRCaGuy_hello_world/bash/get_script_path.sh"
SCRIPT_DIRECTORY    = "/home/gabriel/GS/dev/eRCaGuy_hello_world/bash"
SCRIPT_FILENAME     = "get_script_path.sh"

Note that realpath also successfully walks down symbolic links to determine and point to their targets rather than pointing to the symbolic link.

The code above is now part of my eRCaGuy_hello_world repo in this file here: bash/get_script_path.sh.

References:

  1. How to retrieve absolute path given relative

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

Python - Count elements in list

len()

>>> someList=[]
>>> print len(someList)
0

How do I print bold text in Python?

Use this:

print '\033[1m' + 'Hello'

And to change back to normal:

print '\033[0m'

This page is a good reference for printing in colors and font-weights. Go to the section that says 'Set graphics mode:'

And note this won't work on all operating systems but you don't need any modules.

Good way to encapsulate Integer.parseInt()

What about forking the parseInt method?

It's easy, just copy-paste the contents to a new utility that returns Integer or Optional<Integer> and replace throws with returns. It seems there are no exceptions in the underlying code, but better check.

By skipping the whole exception handling stuff, you can save some time on invalid inputs. And the method is there since JDK 1.0, so it is not likely you will have to do much to keep it up-to-date.

Error: "an object reference is required for the non-static field, method or property..."

You just need to make the siprimo and volteado methods static.

private static bool siprimo(long a)

and

private static long volteado(long a)

How to remove listview all items

use any one of the bellow options which suites your requirement

listview.removeViews(1,listview.getChildCount());

or

listview.removeViewInLayout(your view);

initialize a const array in a class initializer in C++

Where I've a constant array, it's always been done as static. If you can accept that, this code should compile and run.

#include <stdio.h>
#include <stdlib.h>

class a {
        static const int b[2];
public:
        a(void) {
                for(int i = 0; i < 2; i++) {
                        printf("b[%d] = [%d]\n", i, b[i]);
                }
        }
};

const int a::b[2] = { 4, 2 };

int main(int argc, char **argv)
{
        a foo;
        return 0;
}

Remove the last chars of the Java String variable

path = path.substring(0, path.length() - 5);

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

python's re: return True if string contains regex pattern

import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print 'matched'

Is there a constraint that restricts my generic method to numeric types?

The .NET numeric primitive types do not share any common interface that would allow them to be used for calculations. It would be possible to define your own interfaces (e.g. ISignedWholeNumber) which would perform such operations, define structures which contain a single Int16, Int32, etc. and implement those interfaces, and then have methods which accept generic types constrained to ISignedWholeNumber, but having to convert numeric values to your structure types would likely be a nuisance.

An alternative approach would be to define static class Int64Converter<T> with a static property bool Available {get;}; and static delegates for Int64 GetInt64(T value), T FromInt64(Int64 value), bool TryStoreInt64(Int64 value, ref T dest). The class constructor could use be hard-coded to load delegates for known types, and possibly use Reflection to test whether type T implements methods with the proper names and signatures (in case it's something like a struct which contains an Int64 and represents a number, but has a custom ToString() method). This approach would lose the advantages associated with compile-time type-checking, but would still manage to avoid boxing operations and each type would only have to be "checked" once. After that, operations associated with that type would be replaced with a delegate dispatch.

oracle diff: how to compare two tables?

In addition to some of the other answers provided, if you wanted to look at the differences in table structure with a table that might have the similar but differing structure, you could do this in multiple ways:

First - If using Oracle SQL Developer, you could run a describe on both tables to compare them:

descr TABLE_NAME1
descr TABLE_NAME2

Second - The first solution may not be ideal for larger tables with a lot of columns. If you only want to see the differences in the data between the two tables, then as mentioned by several others, using the SQL Minus operator should do the job.

Third - If you are using Oracle SQL Developer, and you want to compare the table structure of two tables using different schemas you can do the following:

  1. Select "Tools"
  2. Select "Database Diff"
  3. Select "Source Connection"
  4. Select "Destination Connection"
  5. Select the "Standard Object Types" you want to compare
  6. Enter the "Table Name"
  7. Click "Next" until you reach "Finish"
  8. Click "Finish"
  9. NOTE: In steps 3 & 4 is where you would select the differing schemas in which the objects exist that you want to compare.

Fourth - If the tables two tables you wish to compare have more columns, are in the same schema, have no need to compare more than two tables and are unappealing to compare visually using the DESCR command you can use the following to compare the differences in the table structure:

select 
     a.column_name    || ' | ' || b.column_name, 
     a.data_type      || ' | ' || b.data_type, 
     a.data_length    || ' | ' || b.data_length, 
     a.data_scale     || ' | ' || b.data_scale, 
     a.data_precision || ' | ' || b.data_precision
from 
     user_tab_columns a,
     user_tab_columns b
where 
     a.table_name = 'TABLE_NAME1' 
and  b.table_name = 'TABLE_NAME2'
and  ( 
       a.data_type      <> b.data_type     or 
       a.data_length    <> b.data_length   or 
       a.data_scale     <> b.data_scale    or 
       a.data_precision <> b.data_precision
     )
and a.column_name = b.column_name;

Android WebView style background-color:transparent ignored on android 2.2

I had the same issue with 2.2 and also in 2.3. I solved the problem by giving the alpa value in html not in android. I tried many things and what I found out is setBackgroundColor(); color doesnt work with alpha value. webView.setBackgroundColor(Color.argb(128, 0, 0, 0)); will not work.

so here is my solution, worked for me.

      String webData = StringHelper.addSlashes("<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
      "content=\"text/html; charset=utf-8\"> </head><body><div style=\"background-color: rgba(10,10,10,0.5); " +
      "padding: 20px; height: 260px; border-radius: 8px;\"> $$$ Content Goes Here ! $$$ </div> </body></html>");

And in Java,

    webView = (WebView) findViewById(R.id.webview);
    webView.setBackgroundColor(0);
    webView.loadData(webData, "text/html", "UTF-8");

And here is the Output screenshot below.enter image description here

Check if a variable is between two numbers with Java

public static boolean between(int i, int minValueInclusive, int maxValueInclusive) {
    if (i >= minValueInclusive && i <= maxValueInclusive)
        return true;
    else
        return false;
}

https://alvinalexander.com/java/java-method-integer-is-between-a-range

QtCreator: No valid kits found

Though OP is asking about Windows, this error also occurs on Ubuntu Linux and Google lists this result first when you search for the error"QtCreator: No valid kits found".

On Ubuntu this is solved by running:

For Qt5:

sudo apt-get install qt5-default

For Qt4:

sudo apt-get install qt4-dev-tools libqt4-dev libqt4-core libqt4-gui

This question is answered here and here, though those entries are less SEO-friendly...

selecting rows with id from another table

SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

How to send string from one activity to another?

Intents are intense.

Intents are useful for passing data around the android framework. You can communicate with your own Activities and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.

How to get the first five character of a String

string str = "GoodMorning"

string strModified = str.Substring(0,5);

How to decrypt an encrypted Apple iTunes iPhone backup?

Security researchers Jean-Baptiste Bédrune and Jean Sigwald presented how to do this at Hack-in-the-box Amsterdam 2011.

Since then, Apple has released an iOS Security Whitepaper with more details about keys and algorithms, and Charlie Miller et al. have released the iOS Hacker’s Handbook, which covers some of the same ground in a how-to fashion. When iOS 10 first came out there were changes to the backup format which Apple did not publicize at first, but various people reverse-engineered the format changes.

Encrypted backups are great

The great thing about encrypted iPhone backups is that they contain things like WiFi passwords that aren’t in regular unencrypted backups. As discussed in the iOS Security Whitepaper, encrypted backups are considered more “secure,” so Apple considers it ok to include more sensitive information in them.

An important warning: obviously, decrypting your iOS device’s backup removes its encryption. To protect your privacy and security, you should only run these scripts on a machine with full-disk encryption. While it is possible for a security expert to write software that protects keys in memory, e.g. by using functions like VirtualLock() and SecureZeroMemory() among many other things, these Python scripts will store your encryption keys and passwords in strings to be garbage-collected by Python. This means your secret keys and passwords will live in RAM for a while, from whence they will leak into your swap file and onto your disk, where an adversary can recover them. This completely defeats the point of having an encrypted backup.

How to decrypt backups: in theory

The iOS Security Whitepaper explains the fundamental concepts of per-file keys, protection classes, protection class keys, and keybags better than I can. If you’re not already familiar with these, take a few minutes to read the relevant parts.

Now you know that every file in iOS is encrypted with its own random per-file encryption key, belongs to a protection class, and the per-file encryption keys are stored in the filesystem metadata, wrapped in the protection class key.

To decrypt:

  1. Decode the keybag stored in the BackupKeyBag entry of Manifest.plist. A high-level overview of this structure is given in the whitepaper. The iPhone Wiki describes the binary format: a 4-byte string type field, a 4-byte big-endian length field, and then the value itself.

    The important values are the PBKDF2 ITERations and SALT, the double protection salt DPSL and iteration count DPIC, and then for each protection CLS, the WPKY wrapped key.

  2. Using the backup password derive a 32-byte key using the correct PBKDF2 salt and number of iterations. First use a SHA256 round with DPSL and DPIC, then a SHA1 round with ITER and SALT.

    Unwrap each wrapped key according to RFC 3394.

  3. Decrypt the manifest database by pulling the 4-byte protection class and longer key from the ManifestKey in Manifest.plist, and unwrapping it. You now have a SQLite database with all file metadata.

  4. For each file of interest, get the class-encrypted per-file encryption key and protection class code by looking in the Files.file database column for a binary plist containing EncryptionKey and ProtectionClass entries. Strip the initial four-byte length tag from EncryptionKey before using.

    Then, derive the final decryption key by unwrapping it with the class key that was unwrapped with the backup password. Then decrypt the file using AES in CBC mode with a zero IV.

How to decrypt backups: in practice

First you’ll need some library dependencies. If you’re on a mac using a homebrew-installed Python 2.7 or 3.7, you can install the dependencies with:

CFLAGS="-I$(brew --prefix)/opt/openssl/include" \
LDFLAGS="-L$(brew --prefix)/opt/openssl/lib" \    
    pip install biplist fastpbkdf2 pycrypto

In runnable source code form, here is how to decrypt a single preferences file from an encrypted iPhone backup:

#!/usr/bin/env python3.7
# coding: UTF-8

from __future__ import print_function
from __future__ import division

import argparse
import getpass
import os.path
import pprint
import random
import shutil
import sqlite3
import string
import struct
import tempfile
from binascii import hexlify

import Crypto.Cipher.AES # https://www.dlitz.net/software/pycrypto/
import biplist
import fastpbkdf2
from biplist import InvalidPlistException


def main():
    ## Parse options
    parser = argparse.ArgumentParser()
    parser.add_argument('--backup-directory', dest='backup_directory',
                    default='testdata/encrypted')
    parser.add_argument('--password-pipe', dest='password_pipe',
                        help="""\
Keeps password from being visible in system process list.
Typical use: --password-pipe=<(echo -n foo)
""")
    parser.add_argument('--no-anonymize-output', dest='anonymize',
                        action='store_false')
    args = parser.parse_args()
    global ANONYMIZE_OUTPUT
    ANONYMIZE_OUTPUT = args.anonymize
    if ANONYMIZE_OUTPUT:
        print('Warning: All output keys are FAKE to protect your privacy')

    manifest_file = os.path.join(args.backup_directory, 'Manifest.plist')
    with open(manifest_file, 'rb') as infile:
        manifest_plist = biplist.readPlist(infile)
    keybag = Keybag(manifest_plist['BackupKeyBag'])
    # the actual keys are unknown, but the wrapped keys are known
    keybag.printClassKeys()

    if args.password_pipe:
        password = readpipe(args.password_pipe)
        if password.endswith(b'\n'):
            password = password[:-1]
    else:
        password = getpass.getpass('Backup password: ').encode('utf-8')

    ## Unlock keybag with password
    if not keybag.unlockWithPasscode(password):
        raise Exception('Could not unlock keybag; bad password?')
    # now the keys are known too
    keybag.printClassKeys()

    ## Decrypt metadata DB
    manifest_key = manifest_plist['ManifestKey'][4:]
    with open(os.path.join(args.backup_directory, 'Manifest.db'), 'rb') as db:
        encrypted_db = db.read()

    manifest_class = struct.unpack('<l', manifest_plist['ManifestKey'][:4])[0]
    key = keybag.unwrapKeyForClass(manifest_class, manifest_key)
    decrypted_data = AESdecryptCBC(encrypted_db, key)

    temp_dir = tempfile.mkdtemp()
    try:
        # Does anyone know how to get Python’s SQLite module to open some
        # bytes in memory as a database?
        db_filename = os.path.join(temp_dir, 'db.sqlite3')
        with open(db_filename, 'wb') as db_file:
            db_file.write(decrypted_data)
        conn = sqlite3.connect(db_filename)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        # c.execute("select * from Files limit 1");
        # r = c.fetchone()
        c.execute("""
            SELECT fileID, domain, relativePath, file
            FROM Files
            WHERE relativePath LIKE 'Media/PhotoData/MISC/DCIM_APPLE.plist'
            ORDER BY domain, relativePath""")
        results = c.fetchall()
    finally:
        shutil.rmtree(temp_dir)

    for item in results:
        fileID, domain, relativePath, file_bplist = item

        plist = biplist.readPlistFromString(file_bplist)
        file_data = plist['$objects'][plist['$top']['root'].integer]
        size = file_data['Size']

        protection_class = file_data['ProtectionClass']
        encryption_key = plist['$objects'][
            file_data['EncryptionKey'].integer]['NS.data'][4:]

        backup_filename = os.path.join(args.backup_directory,
                                    fileID[:2], fileID)
        with open(backup_filename, 'rb') as infile:
            data = infile.read()
            key = keybag.unwrapKeyForClass(protection_class, encryption_key)
            # truncate to actual length, as encryption may introduce padding
            decrypted_data = AESdecryptCBC(data, key)[:size]

        print('== decrypted data:')
        print(wrap(decrypted_data))
        print()

        print('== pretty-printed plist')
        pprint.pprint(biplist.readPlistFromString(decrypted_data))

##
# this section is mostly copied from parts of iphone-dataprotection
# http://code.google.com/p/iphone-dataprotection/

CLASSKEY_TAGS = [b"CLAS",b"WRAP",b"WPKY", b"KTYP", b"PBKY"]  #UUID
KEYBAG_TYPES = ["System", "Backup", "Escrow", "OTA (icloud)"]
KEY_TYPES = ["AES", "Curve25519"]
PROTECTION_CLASSES={
    1:"NSFileProtectionComplete",
    2:"NSFileProtectionCompleteUnlessOpen",
    3:"NSFileProtectionCompleteUntilFirstUserAuthentication",
    4:"NSFileProtectionNone",
    5:"NSFileProtectionRecovery?",

    6: "kSecAttrAccessibleWhenUnlocked",
    7: "kSecAttrAccessibleAfterFirstUnlock",
    8: "kSecAttrAccessibleAlways",
    9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
    10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
    11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
}
WRAP_DEVICE = 1
WRAP_PASSCODE = 2

class Keybag(object):
    def __init__(self, data):
        self.type = None
        self.uuid = None
        self.wrap = None
        self.deviceKey = None
        self.attrs = {}
        self.classKeys = {}
        self.KeyBagKeys = None #DATASIGN blob
        self.parseBinaryBlob(data)

    def parseBinaryBlob(self, data):
        currentClassKey = None

        for tag, data in loopTLVBlocks(data):
            if len(data) == 4:
                data = struct.unpack(">L", data)[0]
            if tag == b"TYPE":
                self.type = data
                if self.type > 3:
                    print("FAIL: keybag type > 3 : %d" % self.type)
            elif tag == b"UUID" and self.uuid is None:
                self.uuid = data
            elif tag == b"WRAP" and self.wrap is None:
                self.wrap = data
            elif tag == b"UUID":
                if currentClassKey:
                    self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
                currentClassKey = {b"UUID": data}
            elif tag in CLASSKEY_TAGS:
                currentClassKey[tag] = data
            else:
                self.attrs[tag] = data
        if currentClassKey:
            self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey

    def unlockWithPasscode(self, passcode):
        passcode1 = fastpbkdf2.pbkdf2_hmac('sha256', passcode,
                                        self.attrs[b"DPSL"],
                                        self.attrs[b"DPIC"], 32)
        passcode_key = fastpbkdf2.pbkdf2_hmac('sha1', passcode1,
                                            self.attrs[b"SALT"],
                                            self.attrs[b"ITER"], 32)
        print('== Passcode key')
        print(anonymize(hexlify(passcode_key)))
        for classkey in self.classKeys.values():
            if b"WPKY" not in classkey:
                continue
            k = classkey[b"WPKY"]
            if classkey[b"WRAP"] & WRAP_PASSCODE:
                k = AESUnwrap(passcode_key, classkey[b"WPKY"])
                if not k:
                    return False
                classkey[b"KEY"] = k
        return True

    def unwrapKeyForClass(self, protection_class, persistent_key):
        ck = self.classKeys[protection_class][b"KEY"]
        if len(persistent_key) != 0x28:
            raise Exception("Invalid key length")
        return AESUnwrap(ck, persistent_key)

    def printClassKeys(self):
        print("== Keybag")
        print("Keybag type: %s keybag (%d)" % (KEYBAG_TYPES[self.type], self.type))
        print("Keybag version: %d" % self.attrs[b"VERS"])
        print("Keybag UUID: %s" % anonymize(hexlify(self.uuid)))
        print("-"*209)
        print("".join(["Class".ljust(53),
                    "WRAP".ljust(5),
                    "Type".ljust(11),
                    "Key".ljust(65),
                    "WPKY".ljust(65),
                    "Public key"]))
        print("-"*208)
        for k, ck in self.classKeys.items():
            if k == 6:print("")

            print("".join(
                [PROTECTION_CLASSES.get(k).ljust(53),
                str(ck.get(b"WRAP","")).ljust(5),
                KEY_TYPES[ck.get(b"KTYP",0)].ljust(11),
                anonymize(hexlify(ck.get(b"KEY", b""))).ljust(65),
                anonymize(hexlify(ck.get(b"WPKY", b""))).ljust(65),
            ]))
        print()

def loopTLVBlocks(blob):
    i = 0
    while i + 8 <= len(blob):
        tag = blob[i:i+4]
        length = struct.unpack(">L",blob[i+4:i+8])[0]
        data = blob[i+8:i+8+length]
        yield (tag,data)
        i += 8 + length

def unpack64bit(s):
    return struct.unpack(">Q",s)[0]
def pack64bit(s):
    return struct.pack(">Q",s)

def AESUnwrap(kek, wrapped):
    C = []
    for i in range(len(wrapped)//8):
        C.append(unpack64bit(wrapped[i*8:i*8+8]))
    n = len(C) - 1
    R = [0] * (n+1)
    A = C[0]

    for i in range(1,n+1):
        R[i] = C[i]

    for j in reversed(range(0,6)):
        for i in reversed(range(1,n+1)):
            todec = pack64bit(A ^ (n*j+i))
            todec += pack64bit(R[i])
            B = Crypto.Cipher.AES.new(kek).decrypt(todec)
            A = unpack64bit(B[:8])
            R[i] = unpack64bit(B[8:])

    if A != 0xa6a6a6a6a6a6a6a6:
        return None
    res = b"".join(map(pack64bit, R[1:]))
    return res

ZEROIV = "\x00"*16
def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
    if len(data) % 16:
        print("AESdecryptCBC: data length not /16, truncating")
        data = data[0:(len(data)/16) * 16]
    data = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(data)
    if padding:
        return removePadding(16, data)
    return data

##
# here are some utility functions, one making sure I don’t leak my
# secret keys when posting the output on Stack Exchange

anon_random = random.Random(0)
memo = {}
def anonymize(s):
    if type(s) == str:
        s = s.encode('utf-8')
    global anon_random, memo
    if ANONYMIZE_OUTPUT:
        if s in memo:
            return memo[s]
        possible_alphabets = [
            string.digits,
            string.digits + 'abcdef',
            string.ascii_letters,
            "".join(chr(x) for x in range(0, 256)),
        ]
        for a in possible_alphabets:
            if all((chr(c) if type(c) == int else c) in a for c in s):
                alphabet = a
                break
        ret = "".join([anon_random.choice(alphabet) for i in range(len(s))])
        memo[s] = ret
        return ret
    else:
        return s

def wrap(s, width=78):
    "Return a width-wrapped repr(s)-like string without breaking on \’s"
    s = repr(s)
    quote = s[0]
    s = s[1:-1]
    ret = []
    while len(s):
        i = s.rfind('\\', 0, width)
        if i <= width - 4: # "\x??" is four characters
            i = width
        ret.append(s[:i])
        s = s[i:]
    return '\n'.join("%s%s%s" % (quote, line ,quote) for line in ret)

def readpipe(path):
    if stat.S_ISFIFO(os.stat(path).st_mode):
        with open(path, 'rb') as pipe:
            return pipe.read()
    else:
        raise Exception("Not a pipe: {!r}".format(path))

if __name__ == '__main__':
    main()

Which then prints this output:

Warning: All output keys are FAKE to protect your privacy
== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES                                                                         4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES                                                                         09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES                                                                         e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES                                                                         902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES                                                                         a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES                                                                         09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES                                                                         0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES                                                                         b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES                                                                         417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES                                                                         b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES                                                                         9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== Passcode key
ee34f5bb635830d698074b1e3e268059c590973b0f1138f1954a2a4e1069e612

== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES        64e8fc94a7b670b0a9c4a385ff395fe9ba5ee5b0d9f5a5c9f0202ef7fdcb386f 4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES        22a218c9c446fbf88f3ccdc2ae95f869c308faaa7b3e4fe17b78cbf2eeaf4ec9 09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES        1004c6ca6e07d2b507809503180edf5efc4a9640227ac0d08baf5918d34b44ef e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES        2e809a0cd1a73725a788d5d1657d8fd150b0e360460cb5d105eca9c60c365152 902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES        9a078d710dcd4a1d5f70ea4062822ea3e9f7ea034233e7e290e06cf0d80c19ca a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES        606e5328816af66736a69dfe5097305cf1e0b06d6eb92569f48e5acac3f294a4 09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES        6a4b5292661bac882338d5ebb51fd6de585befb4ef5f8ffda209be8ba3af1b96 0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES        c0ed717947ce8d1de2dde893b6026e9ee1958771d7a7282dd2116f84312c2dd2 b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES        80d8c7be8d5103d437f8519356c3eb7e562c687a5e656cfd747532f71668ff99 417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES        a875a15e3ff901351c5306019e3b30ed123e6c66c949bdaa91fb4b9a69a3811e b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES        1e7756695d337e0b06c764734a9ef8148af20dcc7a636ccfea8b2eb96a9e9373 9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== decrypted data:
'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD '
'PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist versi'
'on="1.0">\n<dict>\n\t<key>DCIMLastDirectoryNumber</key>\n\t<integer>100</integ'
'er>\n\t<key>DCIMLastFileNumber</key>\n\t<integer>3</integer>\n</dict>\n</plist'
'>\n'

== pretty-printed plist
{'DCIMLastDirectoryNumber': 100, 'DCIMLastFileNumber': 3}

Extra credit

The iphone-dataprotection code posted by Bédrune and Sigwald can decrypt the keychain from a backup, including fun things like saved wifi and website passwords:

$ python iphone-dataprotection/python_scripts/keychain_tool.py ...

--------------------------------------------------------------------------------------
|                              Passwords                                             |
--------------------------------------------------------------------------------------
|Service           |Account          |Data           |Access group  |Protection class|
--------------------------------------------------------------------------------------
|AirPort           |Ed’s Coffee Shop |<3FrenchRoast  |apple         |AfterFirstUnlock|
...

That code no longer works on backups from phones using the latest iOS, but there are some golang ports that have been kept up to date allowing access to the keychain.

Java JSON serialization - best practice

Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection.

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }

How to insert an item into a key/value pair object?

You could use an OrderedDictionary, but I would question why you would want to do that.

Regex: ignore case sensitivity

Depends on implementation but I would use

(?i)G[a-b].

VARIATIONS:

(?i) case-insensitive mode ON    
(?-i) case-insensitive mode OFF

Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?im) in the middle of the regex then the modifier only applies to the part of the regex to the right of the modifier. With these flavors, you can turn off modes by preceding them with a minus sign (?-i).

Description is from the page: https://www.regular-expressions.info/modifiers.html

What's an easy way to read random line from a file in Unix command line?

#!/bin/bash

IFS=$'\n' wordsArray=($(<$1))

numWords=${#wordsArray[@]}
sizeOfNumWords=${#numWords}

while [ True ]
do
    for ((i=0; i<$sizeOfNumWords; i++))
    do
        let ranNumArray[$i]=$(( ( $RANDOM % 10 )  + 1 ))-1
        ranNumStr="$ranNumStr${ranNumArray[$i]}"
    done
    if [ $ranNumStr -le $numWords ]
    then
        break
    fi
    ranNumStr=""
done

noLeadZeroStr=$((10#$ranNumStr))
echo ${wordsArray[$noLeadZeroStr]}

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

The Philippe solution but cleaner:

My subtraction data is: '2018-09-22T11:05:00.000Z'

import datetime
import pandas as pd

df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)

How to set margin of ImageView using code, not xml

Here is an example to add 8px Margin on left, top, right, bottom.


ImageView imageView = new ImageView(getApplicationContext());

ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(
    ViewGroup.MarginLayoutParams.MATCH_PARENT,
    ViewGroup.MarginLayoutParams.WRAP_CONTENT
);

marginLayoutParams.setMargins(8, 8, 8, 8);

imageView.setLayoutParams(marginLayoutParams);

Algorithm to return all combinations of k elements from n

C# simple algorithm. (I'm posting it since I've tried to use the one you guys uploaded, but for some reason I couldn't compile it - extending a class? so I wrote my own one just in case someone else is facing the same problem I did). I'm not much into c# more than basic programming by the way, but this one works fine.

public static List<List<int>> GetSubsetsOfSizeK(List<int> lInputSet, int k)
        {
            List<List<int>> lSubsets = new List<List<int>>();
            GetSubsetsOfSizeK_rec(lInputSet, k, 0, new List<int>(), lSubsets);
            return lSubsets;
        }

public static void GetSubsetsOfSizeK_rec(List<int> lInputSet, int k, int i, List<int> lCurrSet, List<List<int>> lSubsets)
        {
            if (lCurrSet.Count == k)
            {
                lSubsets.Add(lCurrSet);
                return;
            }

            if (i >= lInputSet.Count)
                return;

            List<int> lWith = new List<int>(lCurrSet);
            List<int> lWithout = new List<int>(lCurrSet);
            lWith.Add(lInputSet[i++]);

            GetSubsetsOfSizeK_rec(lInputSet, k, i, lWith, lSubsets);
            GetSubsetsOfSizeK_rec(lInputSet, k, i, lWithout, lSubsets);
        }

USAGE: GetSubsetsOfSizeK(set of type List<int>, integer k)

You can modify it to iterate over whatever you are working with.

Good luck!

How to open a new form from another form

In my opinion the main form should be responsible for opening both child form. Here is some pseudo that explains what I would do:

// MainForm
private ChildForm childForm;
private MoreForm moreForm;

ButtonThatOpenTheFirstChildForm_Click()
{
    childForm = CreateTheChildForm();
    childForm.MoreClick += More_Click;
    childForm.Show();
}

More_Click()
{
    childForm.Close();
    moreForm = new MoreForm();
    moreForm.Show();
}

You will just need to create a simple event MoreClick in the first child. The main benefit of this approach is that you can replicate it as needed and you can very easily model some sort of basic workflow.

Register DLL file on Windows Server 2008 R2

That's the error you get when the DLL itself requires another COM server to be registered first or has a dependency on another DLL that's not available. The Regsvr32.exe tool does very little, it calls LoadLibrary() to load the DLL that's passed in the command line argument. Then GetProcAddress() to find the DllRegisterServer() entry point in the DLL. And calls it to leave it up to the COM server to register itself.

What that code does is fairly unguessable. The diagnostic you got is however pretty self-evident from the error code, for some reason this COM server needs another one to be registered first. The error message is crappy, it doesn't tell you what other server it needs. A sad side-effect of the way COM error handling works.

To troubleshoot this, use SysInternals' ProcMon tool. It shows you what registry keys Regsvr32.exe (actually: the COM server) is opening to find the server. Look for accesses to the CLSID key. That gives you a hint what {guid} it is looking for. That still doesn't quite tell you the server DLL, you should compare the trace with one you get from a machine that works. The InprocServer32 key has the DLL path.

Animate visibility modes, GONE and VISIBLE

You can use the expandable list view explained in API demos to show groups

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList1.html.

To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.

Background position, margin-top?

 background-image: url(/images/poster.png);
 background-position: center;
 background-position-y: 50px;
 background-repeat: no-repeat;

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

If using a where clause be sure to include .First() if you do not want a IQueryable object.

Circle drawing with SVG's arc path

These answers are much too complicated.

A simpler way to do this without creating two arcs or convert to different coordinate systems..

This assumes your canvas area has width w and height h.

`M${w*0.5 + radius},${h*0.5}
 A${radius} ${radius} 0 1 0 ${w*0.5 + radius} ${h*0.5001}`

Just use the "long arc" flag, so the full flag is filled. Then make the arcs 99.9999% the full circle. Visually it is the same. Avoid the sweep flag by just starting the circle at the rightmost point in the circle (one radius directly horizontal from the center).

Redirect to Action by parameter mvc

Try this,

return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });

Here i mention you are pass multiple values or model also. That's why here i mention that.

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

Resource from src/main/resources not found after building with maven

You can replace the src/main/resources/ directly by classpath:

So for your example you will replace this line:

new BufferedReader(new FileReader(new File("src/main/resources/config.txt")));

By this line:

new BufferedReader(new FileReader(new File("classpath:config.txt")));

Error "initializer element is not constant" when trying to initialize variable with const

Just for illustration by compare and contrast The code is from http://www.geeksforgeeks.org/g-fact-80/ /The code fails in gcc and passes in g++/

#include<stdio.h>
int initializer(void)
{
    return 50;
}

int main()
{
    int j;
    for (j=0;j<10;j++)
    {
        static int i = initializer();
        /*The variable i is only initialized to one*/
        printf(" value of i = %d ", i);
        i++;
    }
    return 0;
}

Calling a Sub and returning a value

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

How to reload a div without reloading the entire page?

Use this.

$('#mydiv').load(document.URL +  ' #mydiv');

Note, include a space before the hastag.

How to define a preprocessor symbol in Xcode

It's under "GCC 4.2 Preprocessing" (or just put "prepro" in the search box)...

...however, for the life of me I can't get it to work.

I have my standard Debug and Release configurations, and I want to define DEBUG=1 in the debugging configuration. But after adding it as a value:

(in the settings window) > Preprocessor Macros : DEBUG=1

#if DEBUG
    printf("DEBUG is set!");
#endif 

...never prints/gets called. It's driving me crazy...

How to change time in DateTime?

here is a ghetto way, but it works :)

DateTime dt = DateTime.Now; //get a DateTime variable for the example
string newSecondsValue = "00";
dt = Convert.ToDateTime(dt.ToString("MM/dd/yyyy hh:mm:" + newSecondsValue));

increase the java heap size permanently?

For Windows users, you can add a system environment variable named _JAVA_OPTIONS, and set the heap size values there. The JVM should be able to grab the virtual machine options from _JAVA_OPTIONS.

OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
... 
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/os.py", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
... 
>>> os.execl('./a', './a')

It executes exit 0 without any errors.


On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys
print(sys.argv)

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST

produces:

['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

What Vim command(s) can be used to quote/unquote words?

If you use the vim plugin https://github.com/tpope/vim-surround (or use VSCode Vim plugin, which comes with vim-surround pre-installed), its pretty convinient!

add

ysiw' // surround in word `'`

drop

ds' // drop surround `'`

change

cs'" // change surround from `'` to `"`

It even works for html tags!

cst<em> // change surround from current tag to `<em>`

check out the readme on github for better examples

Sorting HashMap by values

package SortedSet;

import java.util.*;

public class HashMapValueSort {
public static void main(String[] args){
    final Map<Integer, String> map = new HashMap<Integer,String>();
    map.put(4,"Mango");
    map.put(3,"Apple");
    map.put(5,"Orange");
    map.put(8,"Fruits");
    map.put(23,"Vegetables");
    map.put(1,"Zebra");
    map.put(5,"Yellow");
    System.out.println(map);
    final HashMapValueSort sort = new HashMapValueSort();
    final Set<Map.Entry<Integer, String>> entry = map.entrySet();
    final Comparator<Map.Entry<Integer, String>> comparator = new Comparator<Map.Entry<Integer, String>>() {
        @Override
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
            String value1 = o1.getValue();
            String value2 = o2.getValue();
            return value1.compareTo(value2);
        }
    };
    final SortedSet<Map.Entry<Integer, String>> sortedSet = new TreeSet(comparator);
    sortedSet.addAll(entry);
    final Map<Integer,String> sortedMap =  new LinkedHashMap<Integer, String>();
    for(Map.Entry<Integer, String> entry1 : sortedSet ){
        sortedMap.put(entry1.getKey(),entry1.getValue());
    }
    System.out.println(sortedMap);
}
}

Download File Using jQuery

  • Using jQuery function

        var valFileDownloadPath = 'http//:'+'your url';
    
       window.open(valFileDownloadPath , '_blank');
    

Integer to IP Address - C

#include "stdio.h"

void print_ip(int ip) {
   unsigned char bytes[4];
   int i;
   for(i=0; i<4; i++) {
      bytes[i] = (ip >> i*8) & 0xFF;
   }
   printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);
}

int main() {
   int ip = 0xDEADBEEF;
   print_ip(ip);   
}

How do I move an existing Git submodule within a Git repository?

I just went through this ordeal yesterday and this answer worked perfectly. Here are my steps, for clarity:

  1. Ensure that submodule is checked in and pushed to its server. You also need to know what branch its on.
  2. You need the URL of your submodule! Use more .gitmodules because once you delete the submodule it's not going to be around
  3. Now you can use deinit, rm and then submodule add

EXAMPLE

COMMANDS

    git submodule deinit Classes/lib/mustIReally
    git rm foo
    git submodule add http://developer.audiob.us/download/SDK.git lib/AudioBus

    # do your normal commit and push
    git commit -a 

NOTE: git mv doesn't do this. At all.

How to get database structure in MySQL via query

In the following example,

playground is the database name and equipment is the table name

Another way is using SHOW-COLUMNS:5.5 (available also for 5.5>)

$ mysql -uroot -p<password> -h<host> -P<port> -e \
    "SHOW COLUMNS FROM playground.equipment"

And the output:

mysql: [Warning] Using a password on the command line interface can be insecure.
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| type  | varchar(50) | YES  |     | NULL    |                |
| quant | int(11)     | YES  |     | NULL    |                |
| color | varchar(25) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

One can also use mysqlshow-client (also available for 5.5>) like following:

$ mysqlshow -uroot -p<password> -h<host> -P<port> \
    playground equipment

And the output:

mysqlshow: [Warning] Using a password on the command line interface can be insecure.
Database: playground  Table: equipment
+-------+-------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field | Type        | Collation         | Null | Key | Default | Extra          | Privileges                      | Comment |
+-------+-------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
| id    | int(11)     |                   | NO   | PRI |         | auto_increment | select,insert,update,references |         |
| type  | varchar(50) | latin1_swedish_ci | YES  |     |         |                | select,insert,update,references |         |
| quant | int(11)     |                   | YES  |     |         |                | select,insert,update,references |         |
| color | varchar(25) | latin1_swedish_ci | YES  |     |         |                | select,insert,update,references |         |
+-------+-------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+

post checkbox value

In your form tag, rather than

name="booking.php"

use

action="booking.php"

And then, in booking.php use

$checkValue = $_POST['booking-check'];

Also, you'll need a submit button in there

<input type='submit'>

How to mention C:\Program Files in batchfile

Surround the script call with "", generally it's good practices to do so with filepath.

"C:\Program Files"

Although for this particular name you probably should use environment variable like this :

"%ProgramFiles%\batch.cmd"

or for 32 bits program on 64 bit windows :

"%ProgramFiles(x86)%\batch.cmd"

Regex to match any character including new lines

Add the s modifier to your regex to cause . to match newlines:

$string =~ /(START)(.+?)(END)/s;

How do I get the current absolute URL in Ruby on Rails?

If you're using Rails 3.2 or Rails 4 you should use request.original_url to get the current URL.


Documentation for the method is at http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url but if you're curious the implementation is:

def original_url
  base_url + original_fullpath
end

Android Left to Right slide animation

If you want to apply the animation on "activity" start. then write below code.

startActivity(intent);
overridePendingTransition(R.anim.opening_anim, R.anim.closing_anim);

If you want to apply the animation on "dialog" then firstly add below code in styles.xml file

<style name="my_style”> 
 <item 
  name="@android:windowEnterAnimation">@anim/opening_anim</item> 
 <item 
 name="@android:windowExitAnimation">@anim/closing_anim</item>
</style>

Use this style as I defined below.

final Dialog dialog = new Dialog(activity);
dialog.getWindow().getAttributes().windowAnimations = R.style.my_style;

If you want to apply the animation on "view" then write below code

txtMessage = (TextView) findViewById(R.id.txtMessage);
     
// load the animation
Animation animFadein = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.animation); 

// start the animation
txtMessage.startAnimation(animFadein);

Below, I have mentioned most of the animation .xml code.

appear - make it just appear.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="1"
           android:fromAlpha="1.0"
           android:toAlpha="1.0"/>
</set>

===========================================

make it slowly fades into view.xml

<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator" 
        android:duration="300"
        android:repeatCount="0" />
</set>

==========================================

fadeout - make it slowly fade out of view.xml

<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:fromAlpha="1.0"
        android:toAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator" 
        android:duration="300"
        android:repeatCount="0" />
</set>

==========================================

push_down_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromYDelta="-100%p" android:toYDelta="0" android:duration="400"/>
</set>

==========================================

push_down_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="400"/>
</set>

==========================================

push_left_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="300"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>

==========================================

push_left_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="300"/>
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>

==========================================

push_right_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="300"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>

==========================================

push_right_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="100%p" android:duration="300"/>
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>

==========================================

push_up_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="300"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>

==========================================

push_up_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromYDelta="0" android:toYDelta="-100%p" android:duration="300"/>
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>

==========================================

rotation.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate
 xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="-90"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="0" android:fillAfter="true">
</rotate>

==========================================

scale_from_corner.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale android:fromYScale="0" android:toYScale="1.0"
        android:fromXScale="0" android:toXScale="1.0" 
        android:duration="500" android:pivotX="100%"
        android:pivotY="100%" />
</set>

==========================================

scale_torwards_corner.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale android:fromYScale="1.0" android:toYScale="0"
        android:fromXScale="1.0" android:toXScale="0" 
        android:duration="500"/>
</set>

==========================================

shrink_and_rotate_a(exit).xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
    android:fromXScale="1.0" android:toXScale="0.8"
    android:fromYScale="1.0" android:toYScale="0.8"
    android:pivotX="50%p" android:pivotY="50%p"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="100"
/>
<scale
    android:fromXScale="1.0" android:toXScale="0.0"
    android:fromYScale="1.0" android:toYScale="1.0"
    android:pivotX="50%p" android:pivotY="50%p"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="150"
    android:startOffset="100"
/>

==========================================

shrink_and_rotate_b(entrance).xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
    android:fromXScale="0.0" android:toXScale="1.0"
    android:fromYScale="1.0" android:toYScale="1.0"
    android:pivotX="50%p" android:pivotY="50%p"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="150"
    android:startOffset="250"
/>

<scale
    android:fromXScale="0.8" android:toXScale="1.0"
    android:fromYScale="0.8" android:toYScale="1.0"
    android:pivotX="50%p" android:pivotY="50%p"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="100"
    android:startOffset="400"
/>

========================================

blink.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="0.0"
      android:toAlpha="1.0"
      android:interpolator="@android:anim/accelerate_interpolator"
      android:duration="800"
      android:repeatMode="reverse"
      android:repeatCount="infinite"/>
</set>

========================================

ZoomIn.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:fillAfter="true" >
    <scale
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:duration="1000"
       android:fromXScale="1"
       android:fromYScale="1"
       android:pivotX="50%"
       android:pivotY="50%"
       android:toXScale="3"
       android:toYScale="3" >
    </scale>
</set>

========================================

ZoomOut.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:fillAfter="true" >
    <scale
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:duration="1000"
       android:fromXScale="1.0"
       android:fromYScale="1.0"
       android:pivotX="50%"
       android:pivotY="50%"
       android:toXScale="0.5"
       android:toYScale="0.5" >
    </scale>
</set>

========================================

FadeIn.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:fillAfter="true" >
    <alpha
       android:duration="1000"
       android:fromAlpha="0.0"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:toAlpha="1.0" />
</set>

========================================

FadeOut.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:fillAfter="true" >
    <alpha
       android:duration="1000"
       android:fromAlpha="1.0"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:toAlpha="0.0" />
</set>

========================================

Move.xml

<?xml version="1.0" encoding="utf-8"?>
<set
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/linear_interpolator"
   android:fillAfter="true">
   <translate
       android:fromXDelta="0%p"
       android:toXDelta="80%p"
       android:duration="1000" />
</set>

========================================

SlideDown.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:fillAfter="true">
    <scale
       android:duration="800"
       android:fromXScale="1.0"
       android:fromYScale="0.0"
       android:interpolator="@android:anim/linear_interpolator"
       android:toXScale="1.0"
       android:toYScale="1.0" />
</set>

========================================

SlideUp.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:fillAfter="true" >
    <scale
       android:duration="800"
       android:fromXScale="1.0"
       android:fromYScale="1.0"
       android:interpolator="@android:anim/linear_interpolator"
       android:toXScale="1.0"
       android:toYScale="0.0" />
</set>

========================================

Bounce.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:fillAfter="true"
   android:interpolator="@android:anim/bounce_interpolator">
    <scale
       android:duration="800"
       android:fromXScale="1.0"
       android:fromYScale="0.0"
       android:toXScale="1.0"
       android:toYScale="1.0" />
</set>

Automatically deleting related rows in Laravel (Eloquent ORM)

I would iterate through the collection detaching everything before deleting the object itself.

here's an example:

try {
        $user = User::findOrFail($id);
        if ($user->has('photos')) {
            foreach ($user->photos as $photo) {

                $user->photos()->detach($photo);
            }
        }
        $user->delete();
        return 'User deleted';
    } catch (Exception $e) {
        dd($e);
    }

I know it is not automatic but it is very simple.

Another simple approach would be to provide the model with a method. Like this:

public function detach(){
       try {
            
            if ($this->has('photos')) {
                foreach ($this->photos as $photo) {
    
                    $this->photos()->detach($photo);
                }
            }
           
        } catch (Exception $e) {
            dd($e);
        }
}

Then you can simply call this where you need:

$user->detach();
$user->delete();

Searching if value exists in a list of objects using Linq

zvolkov's answer is the perfect one to find out if there is such a customer. If you need to use the customer afterwards, you can do:

Customer customer = list.FirstOrDefault(cus => cus.FirstName == "John");
if (customer != null)
{
    // Use customer
}

I know this isn't what you were asking, but I thought I'd pre-empt a follow-on question :) (Of course, this only finds the first such customer... to find all of them, just use a normal where clause.)

Maximum number of threads per process in Linux?

For anyone looking at this now, on systemd systems (in my case, specifically Ubuntu 16.04) there is another limit enforced by the cgroup pids.max parameter.

This is set to 12,288 by default, and can be overriden in /etc/systemd/logind.conf

Other advice still applies including pids_max, threads-max, max_maps_count, ulimits, etc.

How to change button color with tkinter

Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after method and binding a change method allows you to change color and do other operations.

Label.destroy is another example of the after method.

    def export_win():
        //Some Operation
        orig_color = export_finding_graph.cget("background")
        export_finding_graph.configure(background = "green")

        tt = "Exported"
        label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
        label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)

        def change(orig_color):
            export_finding_graph.configure(background = orig_color)

        tab1_closed_observations.after(1000, lambda: change(orig_color))
        tab1_closed_observations.after(500, label.destroy)


    export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
    export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)

You can also revert to the original color.

Using NSLog for debugging

Try this piece of code:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@", digit);

The message means that you have incorrect syntax for using the digit variable. If you're not sending it any message - you don't need any brackets.

Empty or Null value display in SSRS text boxes

I couldn't get IsNothing() to behave and I didn't want to create dummy rows in my dataset (e.g. for a given list of customers create a dummy order per month displayed) and noticed that null values were displaying as -247192.

Lo and behold using that worked to suppress it (at least until MSFT changes SSRS for the better from 08R2) so forgive me but:

=iif(Fields!Sales_Diff.Value = -247192,"",Fields!Sales_Diff.Value)

LAST_INSERT_ID() MySQL

We only have one person entering records, so I execute the following query immediately following the insert:

$result = $conn->query("SELECT * FROM corex ORDER BY id DESC LIMIT 1");

while ($row = $result->fetch_assoc()) {

            $id = $row['id'];

}

This retrieves the last id from the database.

How to set the JDK Netbeans runs on?

All the other answers have described how to explicitly specify the location of the java platform, which is fine if you really want to use a specific version of java. However, if you just want to use the most up-to-date version of jdk, and you have that installed in a "normal" place for your operating system, then the best solution is to NOT specify a jdk location. Instead, let the Netbeans launcher search for jdk every time you start it up.

To do this, do not specify jdkhome on the command line, and comment out the line setting netbeans_jdkhome variable in any netbeans.conf files. (See other answers for where to look for these files.)

If you do this, when you install a new version of java, your netbeans will automagically use it. In most cases, that's probably exactly what you want.

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

jquery - fastest way to remove all rows from a very large table

if you want to remove only fast.. you can do like below..

$( "#tableId tbody tr" ).each( function(){
  this.parentNode.removeChild( this ); 
});

but, there can be some event-binded elements in table,

in that case,

above code is not prevent memory leak in IE... T-T and not fast in FF...

sorry....

jquery: how to get the value of id attribute?

To match the title of this question, the value of the id attribute is:

var myId = $(this).attr('id');
alert( myId );

BUT, of course, the element must already have the id element defined, as:

<option id="opt7" class='select_continent' value='7'>Antarctica</option>

In the OP post, this was not the case.


IMPORTANT:

Note that plain js is faster (in this case):

var myId = this.id
alert(  myId  );

That is, if you are just storing the returned text into a variable as in the above example. No need for jQuery's wonderfulness here.

How to avoid "RuntimeError: dictionary changed size during iteration" error?

I would try to avoid inserting empty lists in the first place, but, would generally use:

d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty

If prior to 2.7:

d = dict( (k, v) for k,v in d.iteritems() if v )

or just:

empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:
    del[k]

Get single row result with Doctrine NativeQuery

You can use $query->getSingleResult(), which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)

There's also the less famous $query->getOneOrNullResult() which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)

jQuery Get Selected Option From Dropdown

Probably your best bet with this kind of scenario is to use jQuery's change method to find the currently selected value, like so:

$('#aioConceptName').change(function(){

   //get the selected val using jQuery's 'this' method and assign to a var
   var selectedVal = $(this).val();

   //perform the rest of your operations using aforementioned var

});

I prefer this method because you can then perform functions for each selected option in a given select field.

Hope that helps!

Android: Background Image Size (in Pixel) which Support All Devices

I looked around the internet for correct dimensions for these densities for square images, but couldn't find anything reliable.

If it's any consolation, referring to Veerababu Medisetti's answer I used these dimensions for SQUARES :)

xxxhdpi: 1280x1280 px
xxhdpi: 960x960 px
xhdpi: 640x640 px
hdpi: 480x480 px
mdpi: 320x320 px
ldpi: 240x240 px

display html page with node.js

but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display.

That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.

You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391

Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js

Doctrine - How to print out the real sql, not just the prepared statement?

My solution:

 /**
 * Get SQL from query
 * 
 * @author Yosef Kaminskyi 
 * @param QueryBilderDql $query
 * @return int
 */
public function getFullSQL($query)
{
    $sql = $query->getSql();
    $paramsList = $this->getListParamsByDql($query->getDql());
    $paramsArr =$this->getParamsArray($query->getParameters());
    $fullSql='';
    for($i=0;$i<strlen($sql);$i++){
        if($sql[$i]=='?'){
            $nameParam=array_shift($paramsList);

            if(is_string ($paramsArr[$nameParam])){
                $fullSql.= '"'.addslashes($paramsArr[$nameParam]).'"';
             }
            elseif(is_array($paramsArr[$nameParam])){
                $sqlArr='';
                foreach ($paramsArr[$nameParam] as $var){
                    if(!empty($sqlArr))
                        $sqlArr.=',';

                    if(is_string($var)){
                        $sqlArr.='"'.addslashes($var).'"';
                    }else
                        $sqlArr.=$var;
                }
                $fullSql.=$sqlArr;
            }elseif(is_object($paramsArr[$nameParam])){
                switch(get_class($paramsArr[$nameParam])){
                    case 'DateTime':
                             $fullSql.= "'".$paramsArr[$nameParam]->format('Y-m-d H:i:s')."'";
                          break;
                    default:
                        $fullSql.= $paramsArr[$nameParam]->getId();
                }

            }
            else                     
                $fullSql.= $paramsArr[$nameParam];

        }  else {
            $fullSql.=$sql[$i];
        }
    }
    return $fullSql;
}

 /**
 * Get query params list
 * 
 * @author Yosef Kaminskyi <[email protected]>
 * @param  Doctrine\ORM\Query\Parameter $paramObj
 * @return int
 */
protected function getParamsArray($paramObj)
{
    $parameters=array();
    foreach ($paramObj as $val){
        /* @var $val Doctrine\ORM\Query\Parameter */
        $parameters[$val->getName()]=$val->getValue();
    }

    return $parameters;
}
 public function getListParamsByDql($dql)
{
    $parsedDql = preg_split("/:/", $dql);
    $length = count($parsedDql);
    $parmeters = array();
    for($i=1;$i<$length;$i++){
        if(ctype_alpha($parsedDql[$i][0])){
            $param = (preg_split("/[' ' )]/", $parsedDql[$i]));
            $parmeters[] = $param[0];
        }
    }

    return $parmeters;}

Example of usage:

$query = $this->_entityRepository->createQueryBuilder('item');
$query->leftJoin('item.receptionUser','users');
$query->where('item.customerid = :customer')->setParameter('customer',$customer)
->andWhere('item.paymentmethod = :paymethod')->setParameter('paymethod',"Bonus");
echo $this->getFullSQL($query->getQuery());

How to connect mySQL database using C++

Found here:

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
   AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
  /* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column fata by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  }
  delete res;
  delete stmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " »
     << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}

Does a "Find in project..." feature exist in Eclipse IDE?

Ctrl+H is very handy here. I mostly search in the current project, not the whole workspace. To find all occurences in the whole project of a string that is in your current buffer, just select the string press Ctrl+H and hit enter. Easy as that!

Use Resource Filters! Eclipse will restrict the search result using the Resource Filters defined for your project (eg. right click on you project name and select Properties -> Resource -> Resource Filters). So if you keep getting search hits from parts of your project that your not interested in you could make Eclipse skip those by adding a Resource Filter for them. This is especially useful if you have build files or logs or other temporary files that are part of your projects directory structure, but you only want to search amongst the source code. You should also be aware of that files/directories matched for exclusion in the Resource Filters will not show up in the Package Explorer either, so you might not always want this.

How can I append a query parameter to an existing URL?

Use the URI class.

Create a new URI with your existing String to "break it up" to parts, and instantiate another one to assemble the modified url:

URI u = new URI("http://[email protected]&name=John#fragment");

// Modify the query: append your new parameter
StringBuilder sb = new StringBuilder(u.getQuery() == null ? "" : u.getQuery());
if (sb.length() > 0)
    sb.append('&');
sb.append(URLEncoder.encode("paramName", "UTF-8"));
sb.append('=');
sb.append(URLEncoder.encode("paramValue", "UTF-8"));

// Build the new url with the modified query:
URI u2 = new URI(u.getScheme(), u.getAuthority(), u.getPath(),
    sb.toString(), u.getFragment());

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.

Private Sub Open_multiple_sub_pages_from_main_page()


Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object


' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True

' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"

' Wait while IE loading...
While IE.Busy
        DoEvents
Wend


Set objCollection = IE.Document.getElementsByTagName("input")

i = 0
While i < objCollection.Length
    If objCollection(i).Name = "txtUserName" Then
        ' Set text for search
        objCollection(i).Value = "1234"
    End If
    If objCollection(i).Name = "txtPwd" Then
        ' Set text for search
        objCollection(i).Value = "password"
    End If

    If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
        Set objElement = objCollection(i)
    End If
    i = i + 1
Wend
objElement.Click    ' click button to load page

' Wait while IE re-loading...
While IE.Busy
        DoEvents
Wend

' Show IE
IE.Visible = True
Set Doc = IE.Document

Dim links, link

Dim j As Integer                                                                    'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n                                    'loop to go thru all "a" item so it loads next page
    links(j).Click
    While IE.Busy
        DoEvents
    Wend
    '-------------Do stuff here:  copy field value and paste in excel sheet.  Will post another question for this------------------------
    IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click              'save
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click            'close
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
    j = j + 2
Wend    
End Sub

How to parse a date?

The problem is that you have a date formatted like this:

Thu Jun 18 20:56:02 EDT 2009

But are using a SimpleDateFormat that is:

yyyy-MM-dd

The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:

EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009

Check the JavaDoc page I linked to and see how the characters are used.

How to use JNDI DataSource provided by Tomcat in Spring?

I found this solution very helpful in a clean way to remove xml configuration entirely.

Please check this db configuration using JNDI and spring framework. http://www.unotions.com/design/how-to-create-oracleothersql-db-configuration-using-spring-and-maven/

By this article, it explain how easy to create a db confguration based on database jndi(db/test) configuration. once you are done with configuration then all the db repositories are loaded using this jndi. I did find useful. If @Pierre has issue with this then let me know. It's complete solution to write db configuration.

'App not Installed' Error on Android

I also faced the same issue. In my application had services in it. The services was running in the background even after the application was uninstalled, after doing a force stop of the application, got a message saying the application was uninstalled. Then I installed the application with out any problem.

Web.Config Debug/Release

It is possible using ConfigTransform build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/

All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.

The same applies to "app.*.config" transform files in non-web projects.

and then adding the following target to your *.csproj.

<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
    <TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>

Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.

Windows batch script to move files

You can try this:

:backup move C:\FilesToBeBackedUp\*.* E:\BackupPlace\ timeout 36000 goto backup

If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.

How to flush output after each `echo` call?

Anti-virus software may also be interfering with output flushing. In my case, Kaspersky Anti-Virus 2013 was holding data chunks before sending it to the browser, even though I was using an accepted solution.

Space between Column's children in Flutter

You can also use a helper function to add spacing after each child.

List<Widget> childrenWithSpacing({
  @required List<Widget> children,
  double spacing = 8,
}) {
  final space = Container(width: spacing, height: spacing);
  return children.expand((widget) => [widget, space]).toList();
}

So then, the returned list may be used as a children of a column

Column(
  children: childrenWithSpacing(
    spacing: 14,
    children: [
      Text('This becomes a text with an adjacent spacing'),
      if (true == true) Text('Also, makes it easy to add conditional widgets'),
    ],
  ),
);

I'm not sure though if it's wrong or have a performance penalty to run the children through a helper function for the same goal?

Getting the array length of a 2D array in Java

It was really hard to remember that

    int numberOfColumns = arr.length;
    int numberOfRows = arr[0].length;

Let's understand why this is so and how we can figure this out when we're given an array problem. From the below code we can see that rows = 4 and columns = 3:

    int[][] arr = { {1, 1, 1, 1}, 

                    {2, 2, 2, 2}, 

                    {3, 3, 3, 3} };

arr has multiple arrays in it, and these arrays can be arranged in a vertical manner to get the number of columns. To get the number of rows, we need to access the first array and consider its length. In this case, we access [1, 1, 1, 1] and thus, the number of rows = 4. When you're given a problem where you can't see the array, you can visualize the array as a rectangle with n X m dimensions and conclude that we can get the number of rows by accessing the first array then its length. The other one (arr.length) is for the columns.

Execute multiple command lines with the same process using .NET

You can redirect standard input and use a StreamWriter to write to it:

        Process p = new Process();
        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = "cmd.exe";
        info.RedirectStandardInput = true;
        info.UseShellExecute = false;

        p.StartInfo = info;
        p.Start();

        using (StreamWriter sw = p.StandardInput)
        {
            if (sw.BaseStream.CanWrite)
            {
                sw.WriteLine("mysql -u root -p");
                sw.WriteLine("mypassword");
                sw.WriteLine("use mydb;");
            }
        }

Where can I find MySQL logs in phpMyAdmin?

In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.

Change background colour for Visual Studio

One line answer, F1 -> search for "Color Theme" -> select the color you like

Convert List to Pandas Dataframe Column

Example:

['Thanks You',
 'Its fine no problem',
 'Are you sure']

code block:

import pandas as pd
df = pd.DataFrame(lst)

Output:

    0
0   Thanks You
1   Its fine no problem
2   Are you sure

It is not recommended to remove the column names of the panda dataframe. but if you still want your data frame without header(as per the format you posted in the question) you can do this:

df = pd.DataFrame(lst)    
df.columns = ['']

Output will be like this:

0   Thanks You
1   Its fine no problem
2   Are you sure

or

df = pd.DataFrame(lst).to_string(header=False)

But the output will be a list instead of a dataframe:

0           Thanks You
1  Its fine no problem
2         Are you sure

Hope this helps!!

Best practices with STDIN in Ruby?

Something like this perhaps?

#/usr/bin/env ruby

if $stdin.tty?
  ARGV.each do |file|
    puts "do something with this file: #{file}"
  end
else
  $stdin.each_line do |line|
    puts "do something with this line: #{line}"
  end
end

Example:

> cat input.txt | ./myprog.rb
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb < input.txt 
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb arg1 arg2 arg3
do something with this file: arg1
do something with this file: arg2
do something with this file: arg3

How to read a file into vector in C++?

Just to expand on juanchopanza's answer a bit...

for (int i=0; i=((Main.size())-1); i++) {
    cout << Main[i] << '\n';
}

does this:

  1. Create i and set it to 0.
  2. Set i to Main.size() - 1. Since Main is empty, Main.size() is 0, and i gets set to -1.
  3. Main[-1] is an out-of-bounds access. Kaboom.

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

I think I did encounter the same issue as yours. I created a simple mvn project and used "mvn eclipse:eclipse" to setup a eclipse project.

For example, my source file "Router.java" locates in "java/main/org/jhoh/mvc". And Router.java wants to read file "routes" which locates in "java/main/org/jhoh/mvc/resources"

I run "Router.java" in eclipse, and eclipse's console got NullPointerExeption. I set pom.xml with this setting to make all *.class java bytecode files locate in build directory.

<build>
    <defaultGoal>package</defaultGoal>
    <directory>${basedir}/build</directory>
<build>

I went to directory "build/classes/org/jhoh/mvc/resources", and there is no "routes". Eclipse DID NOT copy "routes" to "build/classes/org/jhoh/mvc/resources"

I think you can copy your "install.xml" to your *.class bytecode directory, NOT in your source code directory.

How to check if Receiver is registered in Android?

Just check NullPointerException. If receiver does not exist, then...

try{
    Intent i = new Intent();
    i.setAction("ir.sss.smsREC");
    context.sendBroadcast(i);
    Log.i("...","broadcast sent");
}
catch (NullPointerException e)
{
    e.getMessage();
}

Can we pass parameters to a view in SQL?

No you can't, as Mladen Prajdic said. Think of a view as a "static filter" on a table or a combination of tables. For example: a view may combine tables Order and Customer so you get a new "table" of rows from Order along with new columns containing the customer's name and the customer number (combination of tables). Or you might create a view that selects only unprocessed orders from the Order table (static filter).

You'd then select from the view like you would select from any other "normal" table - all "non-static" filtering must be done outside the view (like "Get all the orders for customers called Miller" or "Get unprocessed orders that came in on Dec 24th").

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

Solving sslv3 alert handshake failure when trying to use a client certificate

The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.

Once changing this value to DEFAULT, run the following command:

/usr/bin/update-crypto-policies --set DEFAULT

Rerun the curl command and it should work.

How to call a vue.js function on page load

you can also do this using mounted

https://vuejs.org/v2/guide/migration.html#ready-replaced

....
methods:{
    getUnits: function() {...}
},
mounted: function(){
    this.$nextTick(this.getUnits)
}
....

Django ChoiceField

First I recommend you as @ChrisHuang-Leaver suggested to define a new file with all the choices you need it there, like choices.py:

STATUS_CHOICES = (
    (1, _("Not relevant")),
    (2, _("Review")),
    (3, _("Maybe relevant")),
    (4, _("Relevant")),
    (5, _("Leading candidate"))
)
RELEVANCE_CHOICES = (
    (1, _("Unread")),
    (2, _("Read"))
)

Now you need to import them on the models, so the code is easy to understand like this(models.py):

from myApp.choices import * 

class Profile(models.Model):
    user = models.OneToOneField(User)    
    status = models.IntegerField(choices=STATUS_CHOICES, default=1)   
    relevance = models.IntegerField(choices=RELEVANCE_CHOICES, default=1)

And you have to import the choices in the forms.py too:

forms.py:

from myApp.choices import * 

class CViewerForm(forms.Form):

    status = forms.ChoiceField(choices = STATUS_CHOICES, label="", initial='', widget=forms.Select(), required=True)
    relevance = forms.ChoiceField(choices = RELEVANCE_CHOICES, required=True)

Anyway you have an issue with your template, because you're not using any {{form.field}}, you generate a table but there is no inputs only hidden_fields.

When the user is staff you should generate as many input fields as users you can manage. I think django form is not the best solution for your situation.

I think it will be better for you to use html form, so you can generate as many inputs using the boucle: {% for user in users_list %} and you generate input with an ID related to the user, and you can manage all of them in the view.

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.