Programs & Examples On #Recordset

A recordset is a subset of a database table consisting of columns and rows specified by a query language

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Just answering the second part of your question about getting the name of the sheet where a table is:

Dim name as String

name = Range("Table1").Worksheet.Name

Edit:

To make things more clear: someone suggested that to use Range on a Sheet object. In this case, you need not; the Range where the table lives can be obtained using the table's name; this name is available throughout the book. So, calling Range alone works well.

Select multiple columns using Entity Framework

Indeed, the compiler doesn't know how to convert this anonymous type (the new { x.ServerName, x.ProcessID, x.Username } part) to a PInfo object.

var dataset = entities.processlists
    .Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
    .Select(x => new { x.ServerName, x.ProcessID, x.Username }).ToList();

This gives you a list of objects (of anonymous type) you can use afterwards, but you can't return that or pass that to another method.

If your PInfo object has the right properties, it can be like this :

var dataset = entities.processlists
    .Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
    .Select(x => new PInfo 
                 { 
                      ServerName = x.ServerName, 
                      ProcessID = x.ProcessID, 
                      UserName = x.Username 
                 }).ToList();

Assuming that PInfo has at least those three properties.

Both query allow you to fetch only the wanted columns, but using an existing type (like in the second query) allows you to send this data to other parts of your app.

Check if ADODB connection is open

ADO Recordset has .State property, you can check if its value is adStateClosed or adStateOpen

If Not (rs Is Nothing) Then
  If (rs.State And adStateOpen) = adStateOpen Then rs.Close
  Set rs = Nothing
End If

MSDN about State property

Edit; The reason not to check .State against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen check.

Edit2:

For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum

If Not (rs Is Nothing) Then
  If (rs.State And 1) = 1 Then rs.Close
  Set rs = Nothing
End If

Or you can define the constant yourself to make your code more readable (defining them all for a good example.)

Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.    

[...]

If Not (rs Is Nothing) Then

    ' ex. If (0001 And 0001) = 0001 (only open flag) -> true
    ' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
    '    This second example means it is open, but its value is not 1
    '    and If rs.State = 1 -> false, even though it is open
    If (rs.State And adStateOpen) = adStateOpen Then 
        rs.Close
    End If

    Set rs = Nothing
End If

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

How can VBA connect to MySQL database in Excel?

Ranjit's code caused the same error message as reported by Tin, but worked after updating Cn.open with the ODBC driver I'm running. Check the Drivers tab in the ODBC Data Source Administrator. Mine said "MySQL ODBC 5.3 Unicode Driver" so I updated accordingly.

How do I test if a recordSet is empty? isNull?

I would check the "End of File" flag:

If temp_rst1.EOF Or temp_rst2.EOF Then MsgBox "null"

Access: Move to next record until EOF

Keeping the code simple is always my advice:

If IsNull(Me.Id) = True Then
  DoCmd.GoToRecord , , acNext
Else
  DoCmd.GoToRecord , , acLast
End If

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

Does the query has more than the parameter siteID, becouse if you want to run the query one parameter still isn't filled witch gives you the error

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).

Generate a random number in the range 1 - 10

(trunc(random() * 10) % 10) + 1

How can I create an array with key value pairs?

You can create the single value array key-value as

$new_row = array($row["datasource_id"]=>$row["title"]);

inside while loop, and then use array_merge function in loop to combine the each new $new_row array.

Accessing SQL Database in Excel-VBA

Is that a proper connection string?
Where is the SQL Server instance located?

You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.

EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.

Base64 String throwing invalid character error

You say

The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything).

In fact, it does do something (it causes your code to throw a FormatException:"Invalid character in a Base-64 string") because the Convert.FromBase64String does not consider "\0" to be a valid Base64 character.

  byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
  byte[] data2 = Convert.FromBase64String("AAAA");   // Works

Solution: Get rid of the zero termination. (Maybe call .Trim("\0"))

Notes:

The MSDN docs for Convert.FromBase64String say it will throw a FormatException when

The length of s, ignoring white space characters, is not zero or a multiple of 4.

-or-

The format of s is invalid. s contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.

and that

The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'.

How to Add a Dotted Underline Beneath HTML Text

HTML5 element can give dotted underline so the beneath text will have dotted line rather than regular underline. And the title attribute creates a tool tip for the user when they hover their cursor over the element:

NOTE: The dotted border/underline is shown by default in Firefox and Opera, but IE8, Safari, and Chrome need a line of CSS:

<abbr title="Hyper Text Markup Language">HTML</abbr>

How to trim whitespace from a Bash variable?

# Strip leading and trailing white space (new line inclusive).
trim(){
    [[ "$1" =~ [^[:space:]](.*[^[:space:]])? ]]
    printf "%s" "$BASH_REMATCH"
}

OR

# Strip leading white space (new line inclusive).
ltrim(){
    [[ "$1" =~ [^[:space:]].* ]]
    printf "%s" "$BASH_REMATCH"
}

# Strip trailing white space (new line inclusive).
rtrim(){
    [[ "$1" =~ .*[^[:space:]] ]]
    printf "%s" "$BASH_REMATCH"
}

# Strip leading and trailing white space (new line inclusive).
trim(){
    printf "%s" "$(rtrim "$(ltrim "$1")")"
}

OR

# Strip leading and trailing specified characters.  ex: str=$(trim "$str" $'\n a')
trim(){
    if [ "$2" ]; then
        trim_chrs="$2"
    else
        trim_chrs="[:space:]"
    fi

    [[ "$1" =~ ^["$trim_chrs"]*(.*[^"$trim_chrs"])["$trim_chrs"]*$ ]]
    printf "%s" "${BASH_REMATCH[1]}"
}

OR

# Strip leading specified characters.  ex: str=$(ltrim "$str" $'\n a')
ltrim(){
    if [ "$2" ]; then
        trim_chrs="$2"
    else
        trim_chrs="[:space:]"
    fi

    [[ "$1" =~ ^["$trim_chrs"]*(.*[^"$trim_chrs"]) ]]
    printf "%s" "${BASH_REMATCH[1]}"
}

# Strip trailing specified characters.  ex: str=$(rtrim "$str" $'\n a')
rtrim(){
    if [ "$2" ]; then
        trim_chrs="$2"
    else
        trim_chrs="[:space:]"
    fi

    [[ "$1" =~ ^(.*[^"$trim_chrs"])["$trim_chrs"]*$ ]]
    printf "%s" "${BASH_REMATCH[1]}"
}

# Strip leading and trailing specified characters.  ex: str=$(trim "$str" $'\n a')
trim(){
    printf "%s" "$(rtrim "$(ltrim "$1" "$2")" "$2")"
}

OR

Building upon moskit's expr soulution...

# Strip leading and trailing white space (new line inclusive).
trim(){
    printf "%s" "`expr "$1" : "^[[:space:]]*\(.*[^[:space:]]\)[[:space:]]*$"`"
}

OR

# Strip leading white space (new line inclusive).
ltrim(){
    printf "%s" "`expr "$1" : "^[[:space:]]*\(.*[^[:space:]]\)"`"
}

# Strip trailing white space (new line inclusive).
rtrim(){
    printf "%s" "`expr "$1" : "^\(.*[^[:space:]]\)[[:space:]]*$"`"
}

# Strip leading and trailing white space (new line inclusive).
trim(){
    printf "%s" "$(rtrim "$(ltrim "$1")")"
}

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

MySQL's utf8 permits only the Unicode characters that can be represented with 3 bytes in UTF-8. Here you have a character that needs 4 bytes: \xF0\x90\x8D\x83 (U+10343 GOTHIC LETTER SAUIL).

If you have MySQL 5.5 or later you can change the column encoding from utf8 to utf8mb4. This encoding allows storage of characters that occupy 4 bytes in UTF-8.

You may also have to set the server property character_set_server to utf8mb4 in the MySQL configuration file. It seems that Connector/J defaults to 3-byte Unicode otherwise:

For example, to use 4-byte UTF-8 character sets with Connector/J, configure the MySQL server with character_set_server=utf8mb4, and leave characterEncoding out of the Connector/J connection string. Connector/J will then autodetect the UTF-8 setting.

Turn on torch/flash on iPhone

Here's a shorter version you can now use to turn the light on or off:

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch]) {
    [device lockForConfiguration:nil];
    [device setTorchMode:AVCaptureTorchModeOn];  // use AVCaptureTorchModeOff to turn off
    [device unlockForConfiguration];
}

UPDATE: (March 2015)

With iOS 6.0 and later, you can control the brightness or level of the torch using the following method:

- (void)setTorchToLevel:(float)torchLevel
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        if (torchLevel <= 0.0) {
            [device setTorchMode:AVCaptureTorchModeOff];
        }
        else {
            if (torchLevel >= 1.0)
                torchLevel = AVCaptureMaxAvailableTorchLevel;
            BOOL success = [device setTorchModeOnWithLevel:torchLevel   error:nil];
        }
        [device unlockForConfiguration];
    }
}

You may also want to monitor the return value (success) from setTorchModeOnWithLevel:. You may get a failure if you try to set the level too high and the torch is overheating. In that case setting the level to AVCaptureMaxAvailableTorchLevel will set the level to the highest level that is allowed given the temperature of the torch.

XAMPP Start automatically on Windows 7 startup

In addition to MR Chandru"s answer above, do these steps after configuring XAMPP:

  • open the directory where XAMPP is installed. By default it's installed at C:\xampp
  • Create Shortcut to the file xampp-control.exe, the XAMPP Control Panel
  • Paste it in

C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

or

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

The XAMPP Control Panel should now auto-start whenever you reboot Windows.

How to Refresh a Component in Angular

router.navigate['/path'] will only takes you to the specified path
use router.navigateByUrl('/path')
it reloads the whole page

What is the default Precision and Scale for a Number in Oracle?

The NUMBER type can be specified in different styles:

                Resulting  Resulting  Precision
Specification   Precision  Scale      Check      Comment
-------------------------------------------------------------------------------
NUMBER          NULL       NULL       NO         'maximum range and precision',
                                                 values are stored 'as given'
NUMBER(P, S)    P          S          YES        Error code: ORA-01438
NUMBER(P)       P          0          YES        Error code: ORA-01438
NUMBER(*, S)    38         S          NO

Where the precision is the total number of digits and scale is the number of digits right or left (negative scale) of the decimal point.

Oracle specifies ORA-01438 as

value larger than specified precision allowed for this column

As noted in the table, this integrity check is only active if the precision is explicitly specified. Otherwise Oracle silently rounds the inserted or updated value using some unspecified method.

Is it possible to format an HTML tooltip (title attribute)?

Better late than never, they always say.

Normally I'd use jQuery to solve such a situation. However, when working on a site for a client which required a javascript-less solution, I came up with the following:

<div class="hover-container">
    <div class="hover-content">
        <p>Content with<br />
        normal formatting</p>
    </div>
</div>

By using the following css, you get the same situation as with a title:

.hover-container {
    position: relative;
}

.hover-content {
    position: absolute;
    bottom: -10px;
    right: 10px;
    display: none;
}

.hover-container:hover .hover-content {
    display: block;
}

This gives you the option to style it according to your needs as well, and it works in all browsers. Even the ones where javascript is disabled.

Pros:

  • You have a lot of influence on the styling
  • It works in (nearly) all browsers

Cons:

  • It's harder to position the tooltip

Add zero-padding to a string

string strvalue="11".PadRight(4, '0');

output= 1100

string strvalue="301".PadRight(4, '0');

output= 3010

string strvalue="11".PadLeft(4, '0');

output= 0011

string strvalue="301".PadLeft(4, '0');

output= 0301

Is it better practice to use String.format over string Concatenation in Java?

I think we can go with MessageFormat.format as it should be good at both readability and also performance aspects.

I used the same program which one used by Icaro in his above answer and I enhanced it with appending code for using MessageFormat to explain the performance numbers.

  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = "Hi " + i + "; Hi to you " + i * 2;
    }
    long end = System.currentTimeMillis();
    System.out.println("Concatenation = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("Format = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("MessageFormat = " + ((end - start)) + " millisecond");
  }

Concatenation = 69 millisecond

Format = 1435 millisecond

MessageFormat = 200 millisecond

UPDATES:

As per SonarLint Report, Printf-style format strings should be used correctly (squid:S3457)

Because printf-style format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that result in the wrong strings being created. This rule statically validates the correlation of printf-style format strings to their arguments when calling the format(...) methods of java.util.Formatter, java.lang.String, java.io.PrintStream, MessageFormat, and java.io.PrintWriter classes and the printf(...) methods of java.io.PrintStream or java.io.PrintWriter classes.

I replace the printf-style with the curly-brackets and I got something interesting results as below.

Concatenation = 69 millisecond
Format = 1107 millisecond
Format:curly-brackets = 416 millisecond
MessageFormat = 215 millisecond
MessageFormat:curly-brackets = 2517 millisecond

My Conclusion:
As I highlighted above, using String.format with curly-brackets should be a good choice to get benefits of good readability and also performance.

How can I declare enums using java

public enum MyEnum
{
    ONE(1),
    TWO(2);

    private int value;

    private MyEnum(int val){
        value = val;
    }

    public int getValue(){
        return value;
    }
}

SQL: Select columns with NULL values only

You'll have to loop over the set of columns and check each one. You should be able to get a list of all columns with a DESCRIBE table command.

Pseudo-code:


foreach $column ($cols) {
   query("SELECT count(*) FROM table WHERE $column IS NOT NULL")
   if($result is zero)  {
      # $column contains only null values"
      push @onlyNullColumns, $column;
   } else {
      # $column contains non-null values
   }
}
return @onlyNullColumns;

I know this seems a little counterintuitive but SQL does not provide a native method of selecting columns, only rows.

Securely storing passwords for use in python script

Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.

How to get the size of a JavaScript object?

I believe you forgot to include 'array'.

  typeOf : function(value) {
        var s = typeof value;
        if (s === 'object')
        {
            if (value)
            {
                if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length')) && typeof value.splice === 'function')
                {
                    s = 'array';
                }
            }
            else
            {
                s = 'null';
            }
        }
        return s;
    },

   estimateSizeOfObject: function(value, level)
    {
        if(undefined === level)
            level = 0;

        var bytes = 0;

        if ('boolean' === typeOf(value))
            bytes = 4;
        else if ('string' === typeOf(value))
            bytes = value.length * 2;
        else if ('number' === typeOf(value))
            bytes = 8;
        else if ('object' === typeOf(value) || 'array' === typeOf(value))
        {
            for(var i in value)
            {
                bytes += i.length * 2;
                bytes+= 8; // an assumed existence overhead
                bytes+= estimateSizeOfObject(value[i], 1)
            }
        }
        return bytes;
    },

   formatByteSize : function(bytes)
    {
        if (bytes < 1024)
            return bytes + " bytes";
        else
        {
            var floatNum = bytes/1024;
            return floatNum.toFixed(2) + " kb";
        }
    },

How to increase scrollback buffer size in tmux?

This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.

tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000

This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.

I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:

#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000

how to set radio option checked onload with jQuery

I liked the answer by @Amc. I found the expression could be condensed further to not use a filter() call (@chaiko apparently also noticed this). Also, prop() is the way to go vs attr() for jQuery v1.6+, see the jQuery documentation for prop() for the official best practices on the subject.

Consider the same input tags from @Paolo Bergantino's answer.

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

The updated one-liner might read something like:

$('input:radio[name="gender"][value="Male"]').prop('checked', true);

Regex select all text between tags

_x000D_
_x000D_
var str = "Lorem ipsum <pre>text 1</pre> Lorem ipsum <pre>text 2</pre>";_x000D_
    str.replace(/<pre>(.*?)<\/pre>/g, function(match, g1) { console.log(g1); });
_x000D_
_x000D_
_x000D_

Since accepted answer is without javascript code, so adding that:

Regular Expression to reformat a US phone number in Javascript

_x000D_
_x000D_
var x = '301.474.4062';_x000D_
    _x000D_
x = x.replace(/\D+/g, '')_x000D_
     .replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');_x000D_
_x000D_
alert(x);
_x000D_
_x000D_
_x000D_

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

Install pip:

sudo easy_install pip

Install brew:

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

Install mysql:

brew install mysql

Install MySQLdb

sudo pip install MySQL-python

If you have compilation problems, try editing the ~/.profile file like in one of the answers here.

How to create an empty DataFrame with a specified schema?

Java version to create empty DataSet:

public Dataset<Row> emptyDataSet(){

    SparkSession spark = SparkSession.builder().appName("Simple Application")
                .config("spark.master", "local").getOrCreate();

    Dataset<Row> emptyDataSet = spark.createDataFrame(new ArrayList<>(), getSchema());

    return emptyDataSet;
}

public StructType getSchema() {

    String schemaString = "column1 column2 column3 column4 column5";

    List<StructField> fields = new ArrayList<>();

    StructField indexField = DataTypes.createStructField("column0", DataTypes.LongType, true);
    fields.add(indexField);

    for (String fieldName : schemaString.split(" ")) {
        StructField field = DataTypes.createStructField(fieldName, DataTypes.StringType, true);
        fields.add(field);
    }

    StructType schema = DataTypes.createStructType(fields);

    return schema;
}

adb shell command to make Android package uninstall dialog appear

I assume that you enable developer mode on your android device and you are connected to your device and you have shell access (adb shell).

Once this is done you can uninstall application with this command pm uninstall --user 0 <package.name>. 0 is root id -this way you don't need too root your device.

Here is an example how I did on my Huawei P110 lite

# gain shell access
$ adb shell

# check who you are
$ whoami
shell

# obtain user id
$ id
uid=2000(shell) gid=2000(shell)

# list packages
$ pm list packages | grep google                                                                                                                                                         
package:com.google.android.youtube
package:com.google.android.ext.services
package:com.google.android.googlequicksearchbox
package:com.google.android.onetimeinitializer
package:com.google.android.ext.shared
package:com.google.android.apps.docs.editors.sheets
package:com.google.android.configupdater
package:com.google.android.marvin.talkback
package:com.google.android.apps.tachyon
package:com.google.android.instantapps.supervisor
package:com.google.android.setupwizard
package:com.google.android.music
package:com.google.android.apps.docs
package:com.google.android.apps.maps
package:com.google.android.webview
package:com.google.android.syncadapters.contacts
package:com.google.android.packageinstaller
package:com.google.android.gm
package:com.google.android.gms
package:com.google.android.gsf
package:com.google.android.tts
package:com.google.android.partnersetup
package:com.google.android.videos
package:com.google.android.feedback
package:com.google.android.printservice.recommendation
package:com.google.android.apps.photos
package:com.google.android.syncadapters.calendar
package:com.google.android.gsf.login
package:com.google.android.backuptransport
package:com.google.android.inputmethod.latin

# uninstall gmail app
pm uninstall --user 0 com.google.android.gms

Reset all the items in a form

foreach (Control field in container.Controls)
            {
                if (field is TextBox)
                    ((TextBox)field).Clear();
                else if (field is ComboBox)
                    ((ComboBox)field).SelectedIndex=0;
                else
                    dgView.DataSource = null;
                    ClearAllText(field);
            }

Java - get index of key in HashMap?

I was recently learning the concepts behind Hashmap and it was clear that there was no definite ordering of the keys. To iterate you can use:

Hashmap<String,Integer> hs=new Hashmap();
for(Map.Entry<String, Integer> entry : hs.entrySet()){
      String key=entry.getKey();
      int val=entry.getValue();
      //your code block  
  }

Resolve absolute path from relative path and/or file name

Without having to have another batch file to pass arguments to (and use the argument operators), you can use FOR /F:

FOR /F %%i IN ("..\relativePath") DO echo absolute path: %%~fi

where the i in %%~fi is the variable defined at /F %%i. eg. if you changed that to /F %%a then the last part would be %%~fa.

To do the same thing right at the command prompt (and not in a batch file) replace %% with %...

Using for loop inside of a JSP

Do this

    <% for(int i = 0; i < allFestivals.size(); i+=1) { %>
        <tr>      
            <td><%=allFestivals.get(i).getFestivalName()%></td>
        </tr>
    <% } %>

Better way is to use c:foreach see link jstl for each

What is "Connect Timeout" in sql server connection string?

How a connection works in a nutshell

A connection between a program and a database server relies on a handshake.

What this means is that when a connection is opened then the thread establishing the connection will send network packets to the database server. This thread will then pause until either network packets about this connection are received from the database server or when the connection timeout expires.

The connection timeout

The connection timeout is measured in seconds from the point the connection is opened.

When the timeout expires then the thread will continue, but it will do so having reported a connection failure.

  • If there is no value specified for connection timeout in the connection string then the default value is 30.

  • A value greater than zero means how many seconds before it gives up e.g. a value of 10 means to wait 10 seconds.

  • A value of 0 means to never give up waiting for the connection

Note: A value of 0 is not advised since it is possible for either the connection request packets or the server response packets to get lost. Will you seriously be prepared to wait even a day for a response that may never come?

What should I set my Connection Timeout value to?

This setting should depend on the speed of your network and how long you are prepared to allow a thread to wait for a response.

As an example, on a task that repeats hourly during the day, I know my network has always responded within one second so I set the connection timeout to a value of 2 just to be safe. I will then try again three times before giving up and either raising a support ticket or escalating a similar existing support ticket.

Test your own network speed and consider what to do when a connection fails as a one off, and also when it fails repeatedly and sporadically.

Creating an instance using the class name and calling constructor

Very Simple way to create an object in Java using Class<?> with constructor argument(s) passing:

Case 1:- Here, is a small code in this Main class:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {

    public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        // Get class name as string.
        String myClassName = Base.class.getName();
        // Create class of type Base.
        Class<?> myClass = Class.forName(myClassName);
        // Create constructor call with argument types.
        Constructor<?> ctr = myClass.getConstructor(String.class);
        // Finally create object of type Base and pass data to constructor.
        String arg1 = "My User Data";
        Object object = ctr.newInstance(new Object[] { arg1 });
        // Type-cast and access the data from class Base.
        Base base = (Base)object;
        System.out.println(base.data);
    }

}

And, here is the Base class structure:

public class Base {

    public String data = null;

    public Base() 
    {
        data = "default";
        System.out.println("Base()");
    }

    public Base(String arg1) {
        data = arg1;
        System.out.println("Base("+arg1+")");
    }

}

Case 2:- You, can code similarly for constructor with multiple argument and copy constructor. For example, passing 3 arguments as parameter to the Base constructor will need the constructor to be created in class and a code change in above as:

Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" }); 

And here the Base class should somehow look like:

public class Base {

    public Base(String a, String b, String c){
        // This constructor need to be created in this case.
    }   
}

Note:- Don't forget to handle the various exceptions which need to be handled in the code.

Java generics - get class?

You are seeing the result of Type Erasure. From that page...

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

For instance, Box<String> is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime.

This also looks like this question which has a pretty good answer as well.

Kotlin's List missing "add", "remove", Map missing "put", etc?

You can do with create new one like this.

var list1 = ArrayList<Int>()
var list2  = list1.toMutableList()
list2.add(item)

Now you can use list2, Thank you.

Switch focus between editor and integrated terminal in Visual Studio Code

The default keybinding to toggle the integrated terminal is "Ctrl+`" according to VS Code keyboard shortcuts documentation page. If you don't like that shortcut you can change it in your keybindings file by adding something similar to:

{ "key": "ctrl+l", "command": "workbench.action.terminal.toggleTerminal" }

There does not seem to be a default keybinding for simply focusing the bottom panel. So, if you do not want to toggle the bottom panel, you will need to add something similar to the following to your keybindings file:

{ "key": "ctrl+t", "command": "workbench.action.focusPanel" }

JQuery create a form and add elements to it programmatically

The 2nd line should be written as:

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

Can linux cat command be used for writing text to file?

Here's another way -

cat > outfile.txt
>Enter text
>to save press ctrl-d

Calling Oracle stored procedure from C#?

It's basically the same mechanism as for a non query command with:

  • command.CommandText = the name of the stored procedure
  • command.CommandType = CommandType.StoredProcedure
  • As many calls to command.Parameters.Add as the number of parameters the sp requires
  • command.ExecuteNonQuery

There are plenty of examples out there, the first one returned by Google is this one

There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection

Is there a function to round a float in C or do I need to write my own?

To print a rounded value, @Matt J well answers the question.

float x = 45.592346543;
printf("%0.1f\n", x);  // 45.6

As most floating point (FP) is binary based, exact rounding to one decimal place is not possible when the mathematically correct answer is x.1, x.2, ....

To convert the FP number to the nearest 0.1 is another matter.

Overflow: Approaches that first scale by 10 (or 100, 1000, etc) may overflow for large x.

float round_tenth1(float x) {
  x = x * 10.0f;
  ...
}

Double rounding: Adding 0.5f and then using floorf(x*10.0f + 0.5f)/10.0 returns the wrong result when the intermediate sum x*10.0f + 0.5f rounds up to a new integer.

// Fails to round 838860.4375 correctly, comes up with 838860.5 
// 0.4499999880790710449 fails as it rounds to 0.5
float round_tenth2(float x) {
  if (x < 0.0) {
    return ceilf(x*10.0f + 0.5f)/10.0f;
  }
  return floorf(x*10.0f + 0.5f)/10.0f;
}

Casting to int has the obvious problem when float x is much greater than INT_MAX.


Using roundf() and family, available in <math.h> is the best approach.

float round_tenthA(float x) {
  double x10 = 10.0 * x;
  return (float) (round(x10)/10.0);
}

To avoid using double, simply test if the number needs rounding.

float round_tenthB(float x) {
  const float limit = 1.0/FLT_EPSILON;
  if (fabsf(x) < limit) {
    return roundf(x*10.0f)/10.0f;
  }
  return x;
}

Sniffing/logging your own Android Bluetooth traffic

Android 4.4 (Kit Kat) does have a new sniffing capability for Bluetooth. You should give it a try.

If you don’t own a sniffing device however, you aren’t necessarily out of luck. In many cases we can obtain positive results with a new feature introduced in Android 4.4: the ability to capture all Bluetooth HCI packets and save them to a file.

When the Analyst has finished populating the capture file by running the application being tested, he can pull the file generated by Android into the external storage of the device and analyze it (with Wireshark, for example).

Once this setting is activated, Android will save the packet capture to /sdcard/btsnoop_hci.log to be pulled by the analyst and inspected.

Type the following in case /sdcard/ is not the right path on your particular device:

adb shell echo \$EXTERNAL_STORAGE

We can then open a shell and pull the file: $adb pull /sdcard/btsnoop_hci.log and inspect it with Wireshark, just like a PCAP collected by sniffing WiFi traffic for example, so it is very simple and well supported:

screenshot of wireshark capture using Android HCI Snoop

[source]

You can enable this by going to Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log."

How exactly does binary code get converted into letters?

Assuming that by "binary code" you mean just plain old data (sequences of bits, or bytes), and that by "letters" you mean characters, the answer is in two steps. But first, some background.

  • A character is just a named symbol, like "LATIN CAPITAL LETTER A" or "GREEK SMALL LETTER PI" or "BLACK CHESS KNIGHT". Do not confuse a character (abstract symbol) with a glyph (a picture of a character).
  • A character set is a particular set of characters, each of which is associated with a special number, called its codepoint. To see the codepoint mappings in the Unicode character set, see http://www.unicode.org/Public/UNIDATA/UnicodeData.txt.

Okay now here are the two steps:

  1. The data, if it is textual, must be accompanied somehow by a character encoding, something like UTF-8, Latin-1, US-ASCII, etc. Each character encoding scheme specifies in great detail how byte sequences are interpreted as codepoints (and conversely how codepoints are encoded as byte sequences).

  2. Once the byte sequences are interpreted as codepoints, you have your characters, because each character has a specific codepoint.

A couple notes:

  • In some encodings, certain byte sequences correspond to no codepoints at all, so you can have character decoding errors.
  • In some character sets, there are codepoints that are unused, that is, they correspond to no character at all.

In other words, not every byte sequence means something as text.

getElementsByClassName not working

There are several issues:

  1. Class names (and IDs) are not allowed to start with a digit.
  2. You have to pass a class to getElementsByClassName().
  3. You have to iterate of the result set.

Example (untested):

<script type="text/javascript">
function hideTd(className){
    var elements = document.getElementsByClassName(className);
    for(var i = 0, length = elements.length; i < length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
  <tr>
    <td class="td">not empty</td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
</table>
</body>

Note that getElementsByClassName() is not available up to and including IE8.

Update:

Alternatively you can give the table an ID and use:

var elements = document.getElementById('tableID').getElementsByTagName('td');

to get all td elements.

To hide the parent row, use the parentNode property of the element:

elements[i].parentNode.style.display = "none";

How do I escape ampersands in XML so they are rendered as entities in HTML?

The & character is itself an escape character in XML so the solution is to concatenate it and a Unicode decimal equivalent for & thus ensuring that there are no XML parsing errors. That is, replace the character & with &#038;.

VSCode: How to Split Editor Vertically

The key bindings has been changed with version 1.20:

SHIFT+ALT+0 for Linux.

Presumably the same works for Windows also and CMD+OPT+0 for Mac.

Best Way to View Generated Source of Webpage?

I know this is an old post, but I just found this piece of gold. This is old (2006), but still works with IE9. I personnally added a bookmark with this.

Just copy paste this in your browser's address bar:

javascript:void(window.open("javascript:document.open(\"text/plain\");document.write(opener.document.body.parentNode.outerHTML)"))

As for firefox, web developper tool bar does the job. I usually use this, but sometimes, some dirty 3rd party asp.net controls generates differents markups based on the user agent...

EDIT

As Bryan pointed in the comment, some browser remove the javascript: part when copy/pasting in url bar. I just tested and that's the case with IE10.

Animate text change in UILabel

The system default values of 0.25 for duration and .curveEaseInEaseOut for timingFunction are often preferable for consistency across animations, and can be omitted:

let animation = CATransition()
label.layer.add(animation, forKey: nil)
label.text = "New text"

which is the same as writing this:

let animation = CATransition()
animation.duration = 0.25
animation.timingFunction = .curveEaseInEaseOut
label.layer.add(animation, forKey: nil)
label.text = "New text"

How to get base url in CodeIgniter 2.*

I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows -

$autoload['helper'] = array('url'); 

How to get UTF-8 working in Java webapps?

This is for Greek Encoding in MySql tables when we want to access them using Java:

Use the following connection setup in your JBoss connection pool (mysql-ds.xml)

<connection-url>jdbc:mysql://192.168.10.123:3308/mydatabase</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>nts</user-name>
<password>xaxaxa!</password>
<connection-property name="useUnicode">true</connection-property>
<connection-property name="characterEncoding">greek</connection-property>

If you don't want to put this in a JNDI connection pool, you can configure it as a JDBC-url like the next line illustrates:

jdbc:mysql://192.168.10.123:3308/mydatabase?characterEncoding=greek

For me and Nick, so we never forget it and waste time anymore.....

Count the number of items in my array list

You can get the number of elements in the list by calling list.size(), however some of the elements may be duplicates or null (if your list implementation allows null).

If you want the number of unique items and your items implement equals and hashCode correctly you can put them all in a set and call size on that, like this:

new HashSet<>(list).size()

If you want the number of items with a distinct itemId you can do this:

list.stream().map(i -> i.itemId).distinct().count()

Assuming that the type of itemId correctly implements equals and hashCode (which String in the question does, unless you want to do something like ignore case, in which case you could do map(i -> i.itemId.toLowerCase())).

You may need to handle null elements by either filtering them before the call to map: filter(Objects::nonNull) or by providing a default itemId for them in the map call: map(i -> i == null ? null : i.itemId).

Remove elements from collection while iterating

Old Timer Favorite (it still works):

List<String> list;

for(int i = list.size() - 1; i >= 0; --i) 
{
        if(list.get(i).contains("bad"))
        {
                list.remove(i);
        }
}

Benefits:

  1. It only iterates over the list once
  2. No extra objects created, or other unneeded complexity
  3. No problems with trying to use the index of a removed item, because... well, think about it!

CSS transition fade on hover

I recommend you to use an unordered list for your image gallery.

You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.

#photos li {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;
}

#photos li:hover {
    opacity: 1;
}

How to make a drop down list in yii2?

If you made it to the bottom of the list. Save some php code and just bring everything back from the DB as you need like this:

 $items = Standard::find()->select(['name'])->indexBy('s_id')->column();

Inserting data to table (mysqli insert)

In mysqli_query(first parameter should be connection,your sql statement) so

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');

but best practice is

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);

Localhost : 404 not found

open D:\xampp\apache\conf\extra\httpd-vhosts.conf

ServerName localhost DocumentRoot "D:\xampp\htdocs" SetEnv APPLICATION_ENV "development"
DirectoryIndex index.php AllowOverride FileInfo Require all granted

Restart Apache server

and then refresh your given url

How do I line up 3 divs on the same row?

here are two samples: http://jsfiddle.net/H5q5h/1/

one uses float:left and a wrapper with overflow:hidden. the wrapper ensures the sibling of the wrapper starts below the wrapper.

the 2nd one uses the more recent display:inline-block and wrapper can be disregarded. but this is not generally supported by older browsers so tread lightly on this one. also, any white space between the items will cause an unnecessary "margin-like" white space on the left and right of the item divs.

What is your single most favorite command-line trick using Bash?

As an extension to CTRL-r to search backwards, you can auto-complete your current input with your history if you bind 'history-search-backward'. I typically bind it to the same key that it is in tcsh: ESC-p. You can do this by putting the following line in your .inputrc file:

"\M-p": history-search-backward

E.g. if you have previously executed 'make some_really_painfully_long_target' you can type:

> make <ESC p>

and it will give you

> make some_really_painfully_long_target

C# Creating an array of arrays

This loops vertically but might work for you.

int rtn = 0;    
foreach(int[] L in lists){
    for(int i = 0; i<L.Length;i++){
          rtn = L[i];
      //Do something with rtn
    }
}

How to write trycatch in R

Here goes a straightforward example:

# Do something, or tell me why it failed
my_update_function <- function(x){
    tryCatch(
        # This is what I want to do...
        {
        y = x * 2
        return(y)
        },
        # ... but if an error occurs, tell me what happened: 
        error=function(error_message) {
            message("This is my custom message.")
            message("And below is the error message from R:")
            message(error_message)
            return(NA)
        }
    )
}

If you also want to capture a "warning", just add warning= similar to the error= part.

How can I enter latitude and longitude in Google Maps?

for higher precision. this format:

45 11.735N,004 34.281E

and this

45 23.623, 5 38.77

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

http://help.github.com/forking/

Best way to make a shell script daemon?

Just backgrounding your script (./myscript &) will not daemonize it. See http://www.faqs.org/faqs/unix-faq/programmer/faq/, section 1.7, which describes what's necessary to become a daemon. You must disconnect it from the terminal so that SIGHUP does not kill it. You can take a shortcut to make a script appear to act like a daemon;

nohup ./myscript 0<&- &>/dev/null &

will do the job. Or, to capture both stderr and stdout to a file:

nohup ./myscript 0<&- &> my.admin.log.file &

However, there may be further important aspects that you need to consider. For example:

  • You will still have a file descriptor open to the script, which means that the directory it's mounted in would be unmountable. To be a true daemon you should chdir("/") (or cd / inside your script), and fork so that the parent exits, and thus the original descriptor is closed.
  • Perhaps run umask 0. You may not want to depend on the umask of the caller of the daemon.

For an example of a script that takes all of these aspects into account, see Mike S' answer.

CSS 3 slide-in from left transition

I liked @mate64's answer so I am going to reuse that with slight modifications to create a slide down and up animations below:

_x000D_
_x000D_
var $slider = document.getElementById('slider');_x000D_
var $toggle = document.getElementById('toggle');_x000D_
_x000D_
$toggle.addEventListener('click', function() {_x000D_
    var isOpen = $slider.classList.contains('slide-in');_x000D_
_x000D_
    $slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');_x000D_
});
_x000D_
#slider {_x000D_
    position: absolute;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background: blue;_x000D_
    transform: translateY(-100%);_x000D_
    -webkit-transform: translateY(-100%);_x000D_
}_x000D_
_x000D_
.slide-in {_x000D_
    animation: slide-in 0.5s forwards;_x000D_
    -webkit-animation: slide-in 0.5s forwards;_x000D_
}_x000D_
_x000D_
.slide-out {_x000D_
    animation: slide-out 0.5s forwards;_x000D_
    -webkit-animation: slide-out 0.5s forwards;_x000D_
}_x000D_
    _x000D_
@keyframes slide-in {_x000D_
    100% { transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-in {_x000D_
    100% { -webkit-transform: translateY(0%); }_x000D_
}_x000D_
    _x000D_
@keyframes slide-out {_x000D_
    0% { transform: translateY(0%); }_x000D_
    100% { transform: translateY(-100%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-out {_x000D_
    0% { -webkit-transform: translateY(0%); }_x000D_
    100% { -webkit-transform: translateY(-100%); }_x000D_
}
_x000D_
<div id="slider" class="slide-in">_x000D_
    <ul>_x000D_
        <li>Lorem</li>_x000D_
        <li>Ipsum</li>_x000D_
        <li>Dolor</li>_x000D_
    </ul>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
_x000D_
_x000D_

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

How to simulate "Press any key to continue?"

This works on a Windows Platform: It Uses the Microprocessor registers directly and can be used to check key press or mousebutton

    #include<stdio.h>
    #include<conio.h>
    #include<dos.h>
    void main()
    {
     clrscr();
     union REGS in,out;
     in.h.ah=0x00;
     printf("Press any key : ");

     int86(0x16,&in,&out);
     printf("Ascii : %d\n",out.h.al);
     char ch = out.h.al;
     printf("Charcter Pressed : %c",&ch);
     printf("Scan code : %d",out.h.ah);
     getch();
    }

Java Multithreading concept and join() method

First of all, when you create ob1 then constructor is called and it starts execution. At that time t.start() also runs in separate thread. Remember when a new thread is created, it runs parallely to main thread. And thats why main start execution again with next statement.

And Join() statement is used to prevent the child thread from becoming orphan. Means if you did'nt call join() in your main class, then main thread will exit after its execution and child thread will be still there executing the statements. Join() will wait until all child thread complete its execution and then only main method will exit.

Go through this article, helps a lot.

Apply CSS Style to child elements

Here is some code that I recently wrote. I think that it provides a basic explanation of combining class/ID names with pseudoclasses.

_x000D_
_x000D_
.content {_x000D_
  width: 800px;_x000D_
  border: 1px solid black;_x000D_
  border-radius: 10px;_x000D_
  box-shadow: 0 0 5px 2px grey;_x000D_
  margin: 30px auto 20px auto;_x000D_
  /*height:200px;*/_x000D_
_x000D_
}_x000D_
p.red {_x000D_
  color: red;_x000D_
}_x000D_
p.blue {_x000D_
  color: blue;_x000D_
}_x000D_
p#orange {_x000D_
  color: orange;_x000D_
}_x000D_
p#green {_x000D_
  color: green;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Class practice</title>_x000D_
  <link href="wrench_favicon.ico" rel="icon" type="image/x-icon" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="content">_x000D_
    <p id="orange">orange</p>_x000D_
    <p id="green">green</p>_x000D_
    <p class="red">red</p>_x000D_
    <p class="blue">blue</p>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I Convert HTML to Text in C#?

What you are looking for is a text-mode DOM renderer that outputs text, much like Lynx or other Text browsers...This is much harder to do than you would expect.

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

It's as simple as that:

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1
}

function isWindows() {
  return navigator.platform.indexOf('Win') > -1
}

You can do funny things then like:

var isMac = isMacintosh();
var isPC = !isMacintosh();

AngularJS Multiple ng-app within a page

I have modified your jsfiddle, can make top most module as rootModule for rest of the modules. Below Modifications updated on your jsfiddle.

  1. Second Module can injected in RootModule.
  2. In Html second defined ng-app placed inside the Root ng-app.

Updated JsFiddle: http://jsfiddle.net/ep2sQ/1011/

Conda: Installing / upgrading directly from github

The answers are outdated. You simply have to conda install pip and git. Then you can use pip normally:

  1. Activate your conda environment source activate myenv

  2. conda install git pip

  3. pip install git+git://github.com/scrappy/scrappy@master

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

When you start playing around with custom request headers you will get a CORS preflight. This is a request that uses the HTTP OPTIONS verb and includes several headers, one of which being Access-Control-Request-Headers listing the headers the client wants to include in the request.

You need to reply to that CORS preflight with the appropriate CORS headers to make this work. One of which is indeed Access-Control-Allow-Headers. That header needs to contain the same values the Access-Control-Request-Headers header contained (or more).

https://fetch.spec.whatwg.org/#http-cors-protocol explains this setup in more detail.

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

Submit form without reloading page

You can use jQuery serialize function along with get/post as follows:

$.get('server.php?' + $('#theForm').serialize())

$.post('server.php', $('#theform').serialize())

jQuery Serialize Documentation: http://api.jquery.com/serialize/

Simple AJAX submit using jQuery:

// this is the id of the submit button
$("#submitButtonId").click(function() {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

HTML table: keep the same width for columns

In your case, since you are only showing 3 columns:

Name    Value       Business
  or
Name    Business    Ecommerce Pro

why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.

MySQL "incorrect string value" error when save unicode string in Django

If it's a new project, I'd just drop the database, and create a new one with a proper charset:

CREATE DATABASE <dbname> CHARACTER SET utf8;

configure Git to accept a particular self-signed server certificate for a particular https remote

On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755

How to get HQ youtube thumbnails?

Depending on the resolution you need, you can use a different URL:

Default Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

High Quality Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

Medium Quality

http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

Standard Definition

http://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

Maximum Resolution

http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

Note: it's a work-around if you don't want to use the YouTube Data API. Furthermore not all videos have the thumbnail images set, so the above method doesn’t work.

Show or hide element in React

This is a nice way to make use of the virtual DOM:

class Toggle extends React.Component {
  state = {
    show: true,
  }

  toggle = () => this.setState((currentState) => ({show: !currentState.show}));

  render() {
    return (
      <div>
        <button onClick={this.toggle}>
          toggle: {this.state.show ? 'show' : 'hide'}
        </button>    
        {this.state.show && <div>Hi there</div>}
      </div>
     );
  }
}

Example here

Using React hooks:

const Toggle = () => {
  const [show, toggleShow] = React.useState(true);

  return (
    <div>
      <button
        onClick={() => toggleShow(!show)}
      >
        toggle: {show ? 'show' : 'hide'}
      </button>    
      {show && <div>Hi there</div>}
    </div>
  )
}

Example here

Is it possible to decompile a compiled .pyc file into a .py file?

Uncompyle6 works for Python 3.x and 2.7 - recommended option as it's most recent tool, aiming to unify earlier forks and focusing on automated unit testing. The GitHub page has more details.

  • if you use Python 3.7+, you could also try decompile3, a fork of Uncompyle6 focusing on 3.7 and higher.
  • do raise GitHub issues on these projects if needed - both run unit test suites on a range of Python versions

With these tools, you get your code back including variable names and docstrings, but without the comments.

The older Uncompyle2 supports Python 2.7 only. This worked well for me some time ago to decompile the .pyc bytecode into .py, whereas unpyclib crashed with an exception.

Facebook development in localhost

There is ! My solution works when you create an app, but you want to use facebook authentification on your website. This solution below is NOT needed when you want to create an app integrated to FB page.

The thing is that you can't put "localhost" as a domain in the facebook configuration page of your app. Security reasons ?

You need to go to your host file, in OSX / Linux etc/hosts and add the following line : 127.0.0.1 dev.yourdomain.com

The domain you put whatever you want. One mistake is to add this line : localhost dev.yourdomain.com (at least on osx snow leopard in doesnt work).

Then you have to clear your dns cache. On OSX : type dscacheutil -flushcache in the terminal. Finally, go back to the online facebook developer website, and in the configuration page of your app, you can add the domain "dev.yourdomain.com".

If you use a program such as Mamp, Easyphp or whatever, make sure the port for Apache is 80.

This solution should work for Windows because it also has a hosts file. Nevertheless, as far as I remember Windows 7 doesnt use this file anymore, but this trick should work if you find a way to force windows to use a hosts file.

How can I backup a remote SQL Server database to a local drive?

I use Redgate backup pro 7 tools for this purpose. you can create mirror from backup file in create tile on other location. and can copy backup file after create on network and on host storage automatically.

How to get the Power of some Integer in Swift language?

If you really want an 'Int only' implementation and don't want to coerce to/from Double, you'll need to implement it. Here is a trivial implementation; there are faster algorithms but this will work:

func pow (_ base:Int, _ power:UInt) -> Int {
  var answer : Int = 1
  for _ in 0..<power { answer *= base }
  return answer
}

> pow (2, 4)
$R3: Int = 16
> pow (2, 8)
$R4: Int = 256
> pow (3,3)
$R5: Int = 27

In a real implementation you'd probably want some error checking.

How to iterate through range of Dates in Java?

public static final void generateRange(final Date dateFrom, final Date dateTo)
{
    final Calendar current = Calendar.getInstance();
    current.setTime(dateFrom);

    while (!current.getTime().after(dateTo))
    {
        // TODO

        current.add(Calendar.DATE, 1);
    }
}

How do I import a sql data file into SQL Server?

If you are talking about an actual database (an mdf file) you would Attach it

.sql files are typically run using SQL Server Management Studio. They are basically saved SQL statements, so could be anything. You don't "import" them. More precisely, you "execute" them. Even though the script may indeed insert data.

Also, to expand on Jamie F's answer, don't run a SQL file against your database unless you know what it is doing. SQL scripts can be as dangerous as unchecked exe's

How to use JQuery with ReactJS

To install it, just run the command

npm install jquery

or

yarn add jquery

then you can import it in your file like

import $ from 'jquery';

check all socket opened in linux OS

/proc/net/tcp -a list of open tcp sockets

/proc/net/udp -a list of open udp sockets

/proc/net/raw -a list all the 'raw' sockets

These are the files, use cat command to view them. For example:

cat /proc/net/tcp

You can also use the lsof command.

lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

XPath to fetch SQL XML value

I think the xpath query you want goes something like this:

/xml/box[@stepId="$stepId"]/components/component[@id="$componentId"]/variables/variable[@nom="Enabled" and @valeur="Yes"]

This should get you the variables that are named "Enabled" with a value of "Yes" for the specified $stepId and $componentId. This is assuming that your xml starts with an tag like you show, and not

If the SQL Server 2005 XPath stuff is pretty straightforward (I've never used it), then the above query should work. Otherwise, someone else may have to help you with that.

How do I strip all spaces out of a string in PHP?

If you know the white space is only due to spaces, you can use:

$string = str_replace(' ','',$string); 

But if it could be due to space, tab...you can use:

$string = preg_replace('/\s+/','',$string);

How to check if multiple array keys exists

If you have something like this:

$stuff = array();
$stuff[0] = array('story' => 'A story', 'message' => 'in a bottle');
$stuff[1] = array('story' => 'Foo');

You could simply count():

foreach ($stuff as $value) {
  if (count($value) == 2) {
    // story and message
  } else {
    // only story
  }
}

This only works if you know for sure that you ONLY have these array keys, and nothing else.

Using array_key_exists() only supports checking one key at a time, so you will need to check both seperately:

foreach ($stuff as $value) {
  if (array_key_exists('story', $value) && array_key_exists('message', $value) {
    // story and message
  } else {
    // either one or both keys missing
  }
}

array_key_exists() returns true if the key is present in the array, but it is a real function and a lot to type. The language construct isset() will almost do the same, except if the tested value is NULL:

foreach ($stuff as $value) {
  if (isset($value['story']) && isset($value['message']) {
    // story and message
  } else {
    // either one or both keys missing
  }
}

Additionally isset allows to check multiple variables at once:

foreach ($stuff as $value) {
  if (isset($value['story'], $value['message']) {
    // story and message
  } else {
    // either one or both keys missing
  }
}

Now, to optimize the test for stuff that is set, you'd better use this "if":

foreach ($stuff as $value) {
  if (isset($value['story']) {
    if (isset($value['message']) {
      // story and message
    } else {
      // only story
    }
  } else {
    // No story - but message not checked
  }
}

What does "export" do in shell programming?

Well, it generally depends on the shell. For bash, it marks the variable as "exportable" meaning that it will show up in the environment for any child processes you run.

Non-exported variables are only visible from the current process (the shell).

From the bash man page:

export [-fn] [name[=word]] ...
export -p

The supplied names are marked for automatic export to the environment of subsequently executed commands.

If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed.

The -n option causes the export property to be removed from each name.

If a variable name is followed by =word, the value of the variable is set to word.

export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function.

You can also set variables as exportable with the typeset command and automatically mark all future variable creations or modifications as such, with set -a.

Generate Java classes from .XSD files...?

If you want to start coding Java to XML and XML to Java in less than 5 minutes, try Simple XML Serialization. Don't spend hours learning the JAXB API http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php

However, if you are really keen on learning JAXB, here's an excellent tutorial http://blogs.oracle.com/teera/entry/jaxb_for_simple_java_xml

Contents of tutorial:

JAXB for simple Java-XML serialization

There're a number of way to do XML serialization in Java. If you want fine-grained control over parsing and serialization you can go for SAX, DOM, or Stax for better performance. Yet, what I often want to do is a simple mapping between POJOs and XML. However, creating Java classes to do XML event parsing manually is not trivial. I recently found JAXB to be a quick and convenient Java-XML mapping or serialization.

JAXB contains a lot of useful features, you can check out the reference implementation here. Kohsuke's Blog is also a good resource to learn more about JAXB. For this blog entry, I'll show you how to do a simple Java-XML serialization with JAXB.

POJO to XML

Let's say I have an Item Java object. I want to serialize an Item object to XML format. What I have to do first is to annotate this POJO with a few XML annotation from javax.xml.bind.annotation.* package. See code listing 1 for Item.java

From the code

  • @XmlRootElement(name="Item") indicates that I want to be the root element.
  • @XmlType(propOrder = {"name", "price"}) indicates the order that I want the element to be arranged in XML output.
  • @XmlAttribute(name="id", ...) indicates that id is an attribute to root element.
  • @XmlElement(....) indicates that I want price and name to be element within Item.

My Item.java is ready. I can then go ahead and create JAXB script for marshaling Item.

//creating Item data object
Item item = new Item();
item.setId(2);
item.setName("Foo");
item.setPrice(200);
.....

JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
//I want to save the output file to item.xml
marshaller.marshal(item, new FileWriter("item.xml"));

For complete code Listing please see Code Listing 2 main.java. The output Code Listing 3 item.xml file is created. It looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:item ns1:id="2" xmlns:ns1="http://blogs.sun.com/teera/ns/item">
  <ns1:itemName>Foo</ns1:itemName>
  <ns1:price>200</ns1:price>
</ns1:item>

Easy right? You can alternatively channel the output XML as text String, Stream, Writer, ContentHandler, etc by simply change the parameter of the marshal(...) method like

...
JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
// save xml output to the OutputStream instance
marshaller.marshal(item, <java.io.OutputStream instance>);

...
JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
//save to StringWriter, you can then call sw.toString() to get java.lang.String
marshaller.marshal(item, sw);

XML to POJO

Let's reverse the process. Assume that I now have a piece of XML string data and I want to turn it into Item.java object. XML data (Code listing 3) looks like

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:item ns1:id="2" xmlns:ns1="http://blogs.sun.com/teera/ns/item">
  <ns1:itemName>Bar</ns1:itemName>
  <ns1:price>80</ns1:price>
</ns1:item>

I can then unmarshal this xml code to Item object by

...
ByteArrayInputStream xmlContentBytes = new ByteArrayInputStream (xmlContent.getBytes());
JAXBContext context = JAXBContext.newInstance(Item.getClass());
Unmarshaller unmarshaller = context.createUnmarshaller();
//note: setting schema to null will turn validator off
unmarshaller.setSchema(null);
Object xmlObject = Item.getClass().cast(unmarshaller.unmarshal(xmlContentBytes));
return xmlObject;
...

For complete code Listing please see Code Listing 2 (main.java). The XML source can come in many forms both from Stream and file. The only difference, again, is the method parameter:

...
unmarshaller.unmarshal(new File("Item.xml")); // reading from file
...
// inputStream is an instance of java.io.InputStream, reading from stream
unmarshaller.unmarshal(inputStream);

Validation with XML Schema

Last thing I want to mention here is validating input XML with schema before unmarshalling to Java object. I create an XML schema file called item.xsd. For complete code Listing please see Code Listing 4 (Item.xsd). Now what I have to do is register this schema for validation.

...
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
.newSchema(new File("Item.xsd"));
unmarshaller.setSchema(schema); //register item.xsd shcema for validation
...

When I try to unmarshal XML data to POJO, if the input XML is not conformed to the schema, exception will be caught. For complete code Listing please see Code Listing 5 (invalid_item.xml).

javax.xml.bind.UnmarshalException
- with linked exception:
javax.xml.bind.JAXBException caught: null
[org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: 'item1' is
                                not a valid value for 'integer'.]

Here I change the 'id' attribute to string instead of integer.

If XML input is valid against the schema, the XML data will be unmarshalled to Item.java object successfully.

Oracle query execution time

I'd recommend looking at consistent gets/logical reads as a better proxy for 'work' than run time. The run time can be skewed by what else is happening on the database server, how much stuff is in the cache etc.

But if you REALLY want SQL executing time, the V$SQL view has both CPU_TIME and ELAPSED_TIME.

how to set start page in webconfig file in asp.net c#

I think this will help

    <directoryBrowse enabled="false" />
    <defaultDocument>
      <files>
        <clear />
        <add value="index.aspx" />
        <add value="Default.htm" />
        <add value="Default.asp" />
        <add value="index.htm" />
        <add value="index.html" />
        <add value="iisstart.htm" />
        <add value="default.aspx" />
        <add value="index.php" />
      </files>
    </defaultDocument>
  </system.webServer>

Split string based on a regular expression

When you use re.split and the split pattern contains capturing groups, the groups are retained in the output. If you don't want this, use a non-capturing group instead.

Android MediaPlayer Stop and Play

I may have not got your answer correct, but you can try this:

public void MusicController(View view) throws IOException{
    switch (view.getId()){
        case R.id.play: mplayer.start();break;
        case R.id.pause: mplayer.pause(); break;
        case R.id.stop:
            if(mplayer.isPlaying()) {
                mplayer.stop();
                mplayer.prepare(); 
            }
            break;

    }// where mplayer is defined in  onCreate method}

as there is just one thread handling all, so stop() makes it die so we have to again prepare it If your intent is to start it again when your press start button(it throws IO Exception) Or for better understanding of MediaPlayer you can refer to Android Media Player

PHP: How do I display the contents of a textfile on my page?

For just reading file and outputting it the best one would be readfile.

How to show the text on a ImageButton?

As you can't use android:text I recommend you to use a normal button and use one of the compound drawables. For instance:

<Button 
    android:id="@+id/buttonok" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/buttonok"
    android:text="OK"/>

You can put the drawable wherever you want by using: drawableTop, drawableBottom, drawableLeft or drawableRight.

UPDATE

For a button this too works pretty fine. Putting android:background is fine!

<Button
    android:id="@+id/fragment_left_menu_login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_bg"
    android:text="@string/login_string" />

I just had this issue and is working perfectly.

Rotate camera in Three.js with mouse

Take a look at THREE.PointerLockControls

How to display a readable array - Laravel

You can use var_dump or print_r functions on Blade themplate via Controller functions :

class myController{

   public function showView(){
     return view('myView',["myController"=>$this]);
   }
   public function myprint($obj){
     echo "<pre>";
     print_r($obj);
     echo "</pre>";
   }
}

And use your blade themplate :

$myController->myprint($users);

Why is $$ returning the same id as the parent process?

  1. Parentheses invoke a subshell in Bash. Since it's only a subshell it might have the same PID - depends on implementation.
  2. The C program you invoke is a separate process, which has its own unique PID - doesn't matter if it's in a subshell or not.
  3. $$ is an alias in Bash to the current script PID. See differences between $$ and $BASHPID here, and right above that the additional variable $BASH_SUBSHELL which contains the nesting level.

What is the OR operator in an IF statement

|| is the conditional OR operator in C#

You probably had a hard time finding it because it's difficult to search for something whose name you don't know. Next time try doing a Google search for "C# Operators" and look at the logical operators.

Here is a list of C# operators.

My code is:

if (title == "User greeting" || "User name") {do stuff};

and my error is:

Error 1 Operator '||' cannot be applied to operands of type 'bool' and 'string' C:\Documents and Settings\Sky View Barns\My Documents\Visual Studio 2005\Projects\FOL Ministry\FOL Ministry\Downloader.cs 63 21 FOL Ministry

You need to do this instead:

if (title == "User greeting" || title == "User name") {do stuff};

The OR operator evaluates the expressions on both sides the same way. In your example, you are operating on the expression title == "User greeting" (a bool) and the expression "User name" (a string). These can't be combined directly without a cast or conversion, which is why you're getting the error.

In addition, it is worth noting that the || operator uses "short-circuit evaluation". This means that if the first expression evaluates to true, the second expression is not evaluated because it doesn't have to be - the end result will always be true. Sometimes you can take advantage of this during optimization.

One last quick note - I often write my conditionals with nested parentheses like this:

if ((title == "User greeting") || (title == "User name")) {do stuff};

This way I can control precedence and don't have to worry about the order of operations. It's probably overkill here, but it's especially useful when the logic gets complicated.

Load external css file like scripts in jquery which is compatible in ie also

Here is a function that will load CSS files with a success or failure callback. The failure callback will be called just once, if one or more resources fail to load. I think this approach is better than some of the other solutions because inserting a element into the DOM with an HREF causes an additional browser request (albeit, the request will likely come from cache, depending on response headers).

function loadCssFiles(urls, successCallback, failureCallback) {

    $.when.apply($,
        $.map(urls, function(url) {
            return $.get(url, function(css) {
                $("<style>" + css + "</style>").appendTo("head");
            });
        })
    ).then(function() {
        if (typeof successCallback === 'function') successCallback();
    }).fail(function() {
        if (typeof failureCallback === 'function') failureCallback();
    });

}

Usage as so:

loadCssFiles(["https://test.com/style1.css", "https://test.com/style2.css",],
    function() {
    alert("All resources loaded");
}, function() {
    alert("One or more resources failed to load");
});

Here is another function that will load both CSS and javascript files:

function loadJavascriptAndCssFiles(urls, successCallback, failureCallback) {

    $.when.apply($,
        $.map(urls, function(url) {
            if(url.endsWith(".css")) {
                return $.get(url, function(css) {
                    $("<style>" + css + "</style>").appendTo("head");
                });
            } else {
                return $.getScript(url);
            }
        })
    ).then(function() {
        if (typeof successCallback === 'function') successCallback();
    }).fail(function() {
        if (typeof failureCallback === 'function') failureCallback();
    });

}

Direct casting vs 'as' operator?

If you already know what type it can cast to, use a C-style cast:

var o = (string) iKnowThisIsAString; 

Note that only with a C-style cast can you perform explicit type coercion.

If you don't know whether it's the desired type and you're going to use it if it is, use as keyword:

var s = o as string;
if (s != null) return s.Replace("_","-");

//or for early return:
if (s==null) return;

Note that as will not call any type conversion operators. It will only be non-null if the object is not null and natively of the specified type.

Use ToString() to get a human-readable string representation of any object, even if it can't cast to string.

python: How do I know what type of exception occurred?

Here's how I'm handling my exceptions. The idea is to do try solving the issue if that's easy, and later add a more desirable solution if possible. Don't solve the issue in the code that generates the exception, or that code loses track of the original algorithm, which should be written to-the-point. However, pass what data is needed to solve the issue, and return a lambda just in case you can't solve the problem outside of the code that generates it.

path = 'app.p'

def load():
    if os.path.exists(path):
        try:
            with open(path, 'rb') as file:
                data = file.read()
                inst = pickle.load(data)
        except Exception as e:
            inst = solve(e, 'load app data', easy=lambda: App(), path=path)()
    else:
        inst = App()
    inst.loadWidgets()

# e.g. A solver could search for app data if desc='load app data'
def solve(e, during, easy, **kwargs):
    class_name = e.__class__.__name__
    print(class_name + ': ' + str(e))
    print('\t during: ' + during)
    return easy

For now, since I don't want to think tangentially to my app's purpose, I haven't added any complicated solutions. But in the future, when I know more about possible solutions (since the app is designed more), I could add in a dictionary of solutions indexed by during.

In the example shown, one solution might be to look for app data stored somewhere else, say if the 'app.p' file got deleted by mistake.

For now, since writing the exception handler is not a smart idea (we don't know the best ways to solve it yet, because the app design will evolve), we simply return the easy fix which is to act like we're running the app for the first time (in this case).

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

Change the following line

$(document).ready(function() {

To

jQuery.noConflict();
jQuery(document).ready(function($) {

What is the difference between .yaml and .yml extension?

As @David Heffeman indicates the recommendation is to use .yaml when possible, and the recommendation has been that way since September 2006.

That some projects use .yml is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).

The best way to approach this is to be rigorous when creating new files (i.e. use .yaml) and be permissive when accepting input (i.e. allow .yml when you encounter it), possible automatically upgrading/correcting these errors when possible.

The other recommendation I have is to document the argument(s) why you have to use .yml, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml has more pages than .yaml" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml extension instead of the correct .yaml, but I think you will be hard pressed to do so.

Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose used .yml, but in later versions started to use .yaml, although they still support .yml). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml instead of appveyor.yml for building the windows wheels of my YAML parser for Python).


On the other hand:

The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.

So it seems fitting that they also use a subset of the recommended extension.

How can I view array structure in JavaScript with alert()?

If what you want is to show with an alert() the content of an array of objects, i recomend you to define in the object the method toString() so with a simple alert(MyArray); the full content of the array will be shown in the alert.

Here is an example:

//-------------------------------------------------------------------
// Defininf the Point object
function Point(CoordenadaX, CoordenadaY) {
    // Sets the point coordinates depending on the parameters defined
    switch (arguments.length) {
        case 0:
            this.x = null;
            this.y = null;
            break;
        case 1:
            this.x = CoordenadaX;
            this.y = null;
            break;
        case 2:
            this.x = CoordenadaX;
            this.y = CoordenadaY;
            break;
    }
    // This adds the toString Method to the point object so the 
    // point can be printed using alert();
    this.toString = function() {
        return " (" + this.x + "," + this.y + ") ";
    };
 }

Then if you have an array of points:

var MyArray = [];
MyArray.push ( new Point(5,6) );
MyArray.push ( new Point(7,9) );

You can print simply calling:

alert(MyArray);

Hope this helps!

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

hi,that maybe the project's problem,

chose the project and setting you eclipse:

project -> clean... 

ImportError: No module named PyQt4.QtCore

I had the "No module named PyQt4.QtCore" error and installing the python-qt4 package fixed it only partially: I could run

from PyQt4.QtCore import SIGNAL

from a python interpreter but only without activating my virtualenv.

The only solution I've found till now to use a virtualenv is to copy the PyQt4 folder and the sip.so file into my virtualenv as explained here: Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?

How do you sort a dictionary by value?

The easiest way to get a sorted Dictionary is to use the built in SortedDictionary class:

//Sorts sections according to the key value stored on "sections" unsorted dictionary, which is passed as a constructor argument
System.Collections.Generic.SortedDictionary<int, string> sortedSections = null;
if (sections != null)
{
    sortedSections = new SortedDictionary<int, string>(sections);
}

sortedSections will contain the sorted version of sections

Read/write to file using jQuery

Use javascript's execCommand('SaveAs', false, filename); functionality

Edit: No longer works. This Javascript function used to work across all browsers, but now only on IE, due to browser security considerations. It presented a "Save As" Dialog to the user who runs this function through their browser, the user presses OK and the file is saved by javascript on the server side.

Now this code is an rare antique zero day collectible.

// content is the data (a string) you'll write to file.
// filename is a string filename to write to on server side.
// This function uses iFrame as a buffer, it fills it up with your content
// and prompts the user to save it out.
function save_content_to_file(content, filename){
    var dlg = false;
    with(document){
     ir=createElement('iframe');
     ir.id='ifr';
     ir.location='about.blank';
     ir.style.display='none';
     body.appendChild(ir);
      with(getElementById('ifr').contentWindow.document){
           open("text/plain", "replace");
           charset = "utf-8";
           write(content);
           close();
           document.charset = "utf-8";
           dlg = execCommand('SaveAs', false, filename);
       }
       body.removeChild(ir);
     }
    return dlg;
}

Invoke the function like this:

msg =  "I am the president of tautology club.";
save_content_to_file(msg, "C:\\test");

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Full binary tree are a complete binary tree but reverse is not possible, and if the depth of the binary is n the no. of nodes in the full binary tree is ( 2^n-1 ). It is not necessary in the binary tree that it have two child but in the full binary it every node have no or two child.

R: invalid multibyte string

This happened to me because I had the 'copyright' symbol in one of my strings! Once it was removed, problem solved.

A good rule of thumb, make sure that characters not appearing on your keyboard are removed if you are seeing this error.

Ignore self-signed ssl cert using Jersey Client

Okay, I'd like to just add my class only because there might be some dev out there in the future that wants to connect to a Netbackup server (or something similar) and do stuff from Java while ignoring the SSL cert. This worked for me and we use windows active directory for auth to the Netbackup server.

public static void main(String[] args) throws Exception {
    SSLContext sslcontext = null;
    try {
        sslcontext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        }}, new java.security.SecureRandom());
    } catch (KeyManagementException ex) {
        Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
    }
    //HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().credentials(username, password).build();
    ClientConfig clientConfig = new ClientConfig();
    //clientConfig.register(feature);
    Client client = ClientBuilder.newBuilder().withConfig(clientConfig)
            .sslContext(sslcontext)
            .hostnameVerifier((s1, s2) -> true)
            .build();

    //String the_url = "https://the_server:1556/netbackup/security/cacert";
    String the_token;
    {
        String the_url = "https://the_server:1556/netbackup/login";
        WebTarget webTarget = client.target(the_url);

        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
        String jsonString = new JSONObject()
                .put("domainType", "NT")
                .put("domainName", "XX")
                .put("userName", "the username")
                .put("password", "the password").toString();
        System.out.println(jsonString);
        Response response = invocationBuilder.post(Entity.json(jsonString));
        String data = response.readEntity(String.class);
        JSONObject jo = new JSONObject(data);
        the_token = jo.getString("token");
        System.out.println("token is:" + the_token);

    }
    {
        String the_url = "https://the_server:1556/netbackup/admin/jobs/1122012"; //job id 1122012 is an example
        WebTarget webTarget = client.target(the_url);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, the_token).header(HttpHeaders.ACCEPT, "application/vnd.netbackup+json;version=1.0");
        Response response = invocationBuilder.get();
        System.out.println("response status:" + response.getStatus());
        String data = response.readEntity(String.class);
        //JSONObject jo = new JSONObject(data);
        System.out.println(data);
    }
}

I know it can be considered off-topic, but I bet the dev that tries to connect to a Netbackup server will probably end up here. By the way many thanks to all the answers in this question! The spec I'm talking about is here and their code samples are (currently) missing a Java example.

***This is of course unsafe since we ignore the cert!

Error "can't load package: package my_prog: found packages my_prog and main"

Yes, each package must be defined in its own directory.

The source structure is defined in How to Write Go Code.

A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

What does '<?=' mean in PHP?

<?=$a; ?>

is a shortcut for:

<?php echo $a; ?>

Git push failed, "Non-fast forward updates were rejected"

Add --force to your command line if you are sure you want to push. E.g. use git push origin --force (I recommend the command line as you will find much more support from other users with the command line. Also this may not be possible with SmartGit.) See this site for more information: http://help.github.com/remotes/

Java 8 LocalDate Jackson format

annotation in Pojo without using additional dependencies

@DateTimeFormat (pattern = "yyyy/MM/dd", iso = DateTimeFormat.ISO.DATE)
private LocalDate enddate;

contenteditable change events

The onchange event doesn't fires when an element with the contentEditable attribute is changed, a suggested approach could be to add a button, to "save" the edition.

Check this plugin which handles the issue in that way:

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

On a tuple/mapping object for multiple argument format

The following is excerpt from the documentation:

Given format % values, % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language.

If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).

References


On str.format instead of %

A newer alternative to % operator is to use str.format. Here's an excerpt from the documentation:

str.format(*args, **kwargs)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

This method is the new standard in Python 3.0, and should be preferred to % formatting.

References


Examples

Here are some usage examples:

>>> '%s for %s' % ("tit", "tat")
tit for tat

>>> '{} and {}'.format("chicken", "waffles")
chicken and waffles

>>> '%(last)s, %(first)s %(last)s' % {'first': "James", 'last': "Bond"}
Bond, James Bond

>>> '{last}, {first} {last}'.format(first="James", last="Bond")
Bond, James Bond

See also

<hr> tag in Twitter Bootstrap not functioning correctly?

It is because Bootstrap's DEFAULT CSS for <hr /> is ::

hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eeeeee;
}

it creates 40px gap between those two lines

so if you want to change any particular <hr /> margin style in your page you may try something like this ::

<hr style="margin-bottom:5px !important; margin-top:5px !important; " />

if you want to change appearance/other styles of any particular <hr /> in your page like color and border type or thickness the you may try something like :

<hr style="border-top: 1px dotted #000000 !important; " />

for all <hr /> in your page

<style>
   hr {
       border-top: 1px dotted #000000 !important;
       margin-bottom:5px !important; 
       margin-top:5px !important;
   }
</style>

box-shadow on bootstrap 3 container

You should give the container an id and use that in your custom css file (which should be linked after the bootstrap css):

#container { box-shadow: values }

Convert IQueryable<> type object to List<T> type?

System.Linq has ToList() on IQueryable<> and IEnumerable<>. It will cause a full pass through the data to put it into a list, though. You loose your deferred invoke when you do this. Not a big deal if it is the consumer of the data.

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

If else embedding inside html

You will find multiple different methods that people use and they each have there own place.

<?php if($first_condition): ?>
  /*$first_condition is true*/
<?php elseif ($second_condition): ?>
  /*$first_condition is false and $second_condition is true*/
<?php else: ?>
  /*$first_condition and $second_condition are false*/
<?php endif; ?>

If in your php.ini attribute short_open_tag = true (this is normally found on line 141 of the default php.ini file) you can replace your php open tag from <?php to <?. This is not advised as most live server environments have this turned off (including many CMS's like Drupal, WordPress and Joomla). I have already tested short hand open tags in Drupal and confirmed that it will break your site, so stick with <?php. short_open_tag is not on by default in all server configurations and must not be assumed as such when developing for unknown server configurations. Many hosting companies have short_open_tag turned off.

A quick search of short_open_tag in stackExchange shows 830 results. https://stackoverflow.com/search?q=short_open_tag That's a lot of people having problems with something they should just not play with.

with some server environments and applications, short hand php open tags will still crash your code even with short_open_tag set to true.

short_open_tag will be removed in PHP6 so don't use short hand tags.

all future PHP versions will be dropping short_open_tag

"It's been recommended for several years that you not use the short tag "short cut" and instead to use the full tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them." – Jelmer Sep 25 '12 at 9:00 php: "short_open_tag = On" not working

and

Normally you write PHP like so: . However if allow_short_tags directive is enabled you're able to use: . Also sort tags provides extra syntax: which is equal to .

Short tags might seem cool but they're not. They causes only more problems. Oh... and IIRC they'll be removed from PHP6. Crozin answered Aug 24 '10 at 22:12 php short_open_tag problem

and

To answer the why part, I'd quote Zend PHP 5 certification guide: "Short tags were, for a time, the standard in the PHP world; however, they do have the major drawback of conflicting with XML headers and, therefore, have somewhat fallen by the wayside." – Fluffy Apr 13 '11 at 14:40 Are PHP short tags acceptable to use?

You may also see people use the following example:

<?php if($first_condition){ ?>
  /*$first_condition is true*/
<?php }else if ($second_condition){ ?>
  /*$first_condition is false and $second_condition is true*/
<?php }else{ ?>
  /*$first_condition and $second_condition are false*/
<?php } ?>

This will work but it is highly frowned upon as it's not considered as legible and is not what you would use this format for. If you had a PHP file where you had a block of PHP code that didn't have embedded tags inside, then you would use the bracket format.

The following example shows when to use the bracket method

<?php
if($first_condition){
   /*$first_condition is true*/
}else if ($second_condition){
   /*$first_condition is false and $second_condition is true*/
}else{
   /*$first_condition and $second_condition are false*/
}
?>

If you're doing this code for yourself you can do what you like, but if your working with a team at a job it is advised to use the correct format for the correct circumstance. If you use brackets in embedded html/php scripts that is a good way to get fired, as no one will want to clean up your code after you. IT bosses will care about code legibility and college professors grade on legibility.

UPDATE

based on comments from duskwuff its still unclear if shorthand is discouraged (by the php standards) or not. I'll update this answer as I get more information. But based on many documents found on the web about shorthand being bad for portability. I would still personally not use it as it gives no advantage and you must rely on a setting being on that is not on for every web host.

Mac OS X - EnvironmentError: mysql_config not found

This answer is for MacOS users who did not install from brew but rather from the official .dmg/.pkg. That installer fails to edit your PATH, causing things to break out of the box:

  1. All MySQL commands like mysql, mysqladmin, mysql_config, etc cannot be found, and as a result:
  2. the "MySQL Preference Pane" fails to appear in System Preferences, and
  3. you cannot install any API that communicates with MySQL, including mysqlclient

What you have to do is appending the MySQL bin folder (typically /usr/local/mysql/bin in your PATH by adding this line in your ~/.bash_profile file:

export PATH="/usr/local/mysql/bin/:$PATH"

You should then reload your ~/.bash_profile for the change to take effect in your current Terminal session:

source ~/.bash_profile

Before installing mysqlclient, however, you need to accept the XcodeBuild license:

sudo xcodebuild -license

Follow their directions to sign away your family, after which you should be able to install mysqlclient without issue:

pip install mysqlclient

After installing that, you must do one more thing to fix a runtime bug that ships with MySQL (Dynamic Library libmysqlclient.dylib not found), by adding this line to your system dynamic libraries path:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/:$DYLD_LIBRARY_PATH

Get File Path (ends with folder)

Use Application.GetSaveAsFilename() in the same way that you used Application.GetOpenFilename()

onNewIntent() lifecycle and registered listeners

Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.

OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.

You can invoke onNewIntent always by putting it into onCreate method like

@Override
public void onCreate(Bundle savedState){
    super.onCreate(savedState);
    onNewIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  //code
}

Get current category ID of the active page

I use the get_queried_object function to get the current category on a category.php template page.

$current_category = get_queried_object();

Jordan Eldredge is right, get_the_category is not suitable here.

How to get the Android Emulator's IP address?

Just to clarify: from within your app, you can simply refer to the emulator as 'localhost' or 127.0.0.1.

Web traffic is routed through your development machine, so the emulator's external IP is whatever IP has been assigned to that machine by your provider. The development machine can always be reached from your device at 10.0.2.2.

Since you were asking only about the emulator's IP, what is it you're trying to do?

How do I make a burn down chart in Excel?

Why not graph the percentage complete. If you include the last date as a 100% complete value you can force the chart to show the linear trend as well as the actual data. This should give you a reasonable idea of whether you are above or below the line.

I would include a screenshot but not enough rep. Here is a link to one I prepared earlier. Burn Down Chart.

Unable to load DLL 'SQLite.Interop.dll'

In the Nuget package of SQLLite Core there is a the file System.Data.SQLite.Core.targets . Just include this in all projects that use the this library and all libraries that used your library.

In yours .csproj or .vbproj files add: Every time you compile in your bin will added x86 and x64 directory with the SQLite.Interop.dll file.

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

I had practically the same problem. in the log file I found this:

110903  9:09:39  InnoDB: 1.1.4 started; log sequence number 1595675
110903  9:09:40 [ERROR] Fatal error: Can't open and lock privilege tables: Incorrect key file for table 'user'; try to repair it

Apparently the user table has been corrupted. I replaced it with another copy (user.frm ; user.MYD ; user.MYI in mysql\data\mysql)
and thats works for me.

ps: am using xampp.

Calculate date from week number

One of the biggest problems I found was to convert from weeks to dates, and then from dates to weeks.

The main problem is when trying to get the correct week year from a date that belongs to a week of the previous year. Luckily System.Globalization.ISOWeek.GetYear handles this.

Here is my solution:

public class WeekOfYear
{
    public static (int Year, int Week) DateToWeekOfYear(DateTime date) =>
        (ISOWeek.GetYear(date), ISOWeek.GetWeekOfYear(date));

    public static bool ValidYearAndWeek(int year, int week) =>
           year >= 1 && year <= 9999 && week >= 1 && week <= 53 // bounds of year/week
        && !(year <= 1 && week <= 1) && !(year >= 9999 && week >= 53); // bounds of DateTime

    public int Year { get; }
    public int Week { get; }
    public virtual DateTime StartOfWeek { get; protected set; }
    public virtual DateTime EndOfWeek { get; protected set; }

    public virtual IEnumerable<DateTime> DaysInWeek =>
        Enumerable.Range(1, 10).Select(i => StartOfWeek.AddDays(i));

    public WeekOfYear(int year, int week)
    {
        if (!ValidYearAndWeek(year, week))
            throw new ArgumentException($"DateTime can't represent {week} of year {year}.");

        Year = year;
        Week = week;
        StartOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Monday);
        EndOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Sunday).AddDays(1).AddTicks(-1);
    }

    public WeekOfYear((int Year, int Week) week) : this(week.Year, week.Week) { }
    public WeekOfYear(DateTime date) : this(DateToWeekOfYear(date)) { }
}

The second biggest problem was the preference for weeks starting on Sundays in the US.

The solution I cam up with subclasses WeekOfYear from above, and manages the offset of the in the constructor (which converts week to dates) and DateToWeekOfYear (which converts from date to week).

public class UsWeekOfYear : WeekOfYear
{
    public static new (int Year, int Week) DateToWeekOfYear(DateTime date)
    {
        // if date is a sunday, return the next week
        if (date.DayOfWeek == DayOfWeek.Sunday) date = date.AddDays(1);
        return WeekOfYear.DateToWeekOfYear(date);
    }

    public UsWeekOfYear(int year, int week) : base(year, week)
    {
        StartOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Monday).AddDays(-1);
        EndOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Sunday).AddTicks(-1);
    }

    public UsWeekOfYear((int Year, int Week) week) : this(week.Year, week.Week) { }
    public UsWeekOfYear(DateTime date) : this(DateToWeekOfYear(date)) { }
}

Here is some test code:

public static void Main(string[] args)
{
    Console.WriteLine("== Last Week / First Week");
    Log(new WeekOfYear(2020, 53));
    Log(new UsWeekOfYear(2020, 53));

    Log(new WeekOfYear(2021, 1));
    Log(new UsWeekOfYear(2021, 1));

    Console.WriteLine("\n== Year Crossover (iso)");
    var start = new DateTime(2020, 12, 26);
    var i = 0;
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-26 - Sat
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-27 - Sun
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-28 - Mon
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-29 - Tue
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-30 - Wed
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-30 - Thu
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-01 - Fri
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-02 - Sat
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-03 - Sun
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-04 - Mon
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-05 - Tue
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-06 - Wed

    Console.WriteLine("\n== Year Crossover (us)");
    i = 0;
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-26 - Sat
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-27 - Sun
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-28 - Mon
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-29 - Tue
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-30 - Wed
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-30 - Thu
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-01 - Fri
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-02 - Sat
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-03 - Sun
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-04 - Mon
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-05 - Tue
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-06 - Wed

    var x = new UsWeekOfYear(2020, 53) as WeekOfYear;
}

public static void Log(WeekOfYear week)
{
    Console.WriteLine($"{week} - {week.StartOfWeek:yyyy-MM-dd} ({week.StartOfWeek:ddd}) - {week.EndOfWeek:yyyy-MM-dd} ({week.EndOfWeek:ddd})");
}

public static void Log(DateTime date, WeekOfYear week)
{
    Console.WriteLine($"{date:yyyy-MM-dd (ddd)} - {week} - {week.StartOfWeek:yyyy-MM-dd (ddd)} - {week.EndOfWeek:yyyy-MM-dd (ddd)}");
}

offsetTop vs. jQuery.offset().top

I think you are right by saying that people cannot click half pixels, so personally, I would use rounded jQuery offset...

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

It's in this package (Ubuntu 19.04):

  sudo apt install g++-6

How can I call a shell command in my Perl script?

How to run a shell script from a Perl program

1. Using system system($command, @arguments);

For example:

system("sh", "script.sh", "--help" );

system("sh script.sh --help");

System will execute the $command with @arguments and return to your script when finished. You may check $! for certain errors passed to the OS by the external application. Read the documentation for system for the nuances of how various invocations are slightly different.

2. Using exec

This is very similar to the use of system, but it will terminate your script upon execution. Again, read the documentation for exec for more.

3. Using backticks or qx//

my $output = `script.sh --option`;

my $output = qx/script.sh --option/;

The backtick operator and it's equivalent qx//, excute the command and options inside the operator and return that commands output to STDOUT when it finishes.

There are also ways to run external applications through creative use of open, but this is advanced use; read the documentation for more.

What's a good (free) visual merge tool for Git? (on windows)

I don't know a good free tool but winmerge is ok(ish). I've been using the beyond compare tools since 1999 and can't rate it enough - it costs about 50 USD and this investment has paid for it self in time savings more than I can possible imagine.

Sometimes tools should be paid for if they are very very good.

How to add two edit text fields in an alert dialog

 LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1);
final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);             
input1.setText("DefaultValue", TextView.BufferType.EDITABLE);
input2.setText("DefaultValue", TextView.BufferType.EDITABLE);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);

alert.setIcon(R.drawable.icon)
     .setTitle("Enter the Text:")
     .setView(textEntryView)
     .setPositiveButton("Save", 
         new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int whichButton) {
                    Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
                    Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString());
                    /* User clicked OK so do some stuff */
             }
         })
     .setNegativeButton("Cancel",
         new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog,
                    int whichButton) {
             }
         });
alert.show();

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

.map() a Javascript ES6 Map?

You can use this function:

function mapMap(map, fn) {
  return new Map(Array.from(map, ([key, value]) => [key, fn(value, key, map)]));
}

usage:

var map1 = new Map([["A", 2], ["B", 3], ["C", 4]]);

var map2 = mapMap(map1, v => v * v);

console.log(map1, map2);
/*
Map { A ? 2, B ? 3, C ? 4 }
Map { A ? 4, B ? 9, C ? 16 }
*/

How to make the first option of <select> selected with jQuery

$("#target").val($("#target option:first").val());

How to ssh connect through python Paramiko with ppk public key

To create a valid DSA format private key supported by Paramiko in Puttygen.

Click on Conversions then Export OpenSSH Key

enter image description here

javascript set cookie with expire time

I've set the time to 1000*36000.

function display() { 
  var now = new Date();
  var time = now.getTime();
  var expireTime = time + 1000*36000;
  now.setTime(expireTime);
  document.cookie = 'cookie=ok;expires='+now.toUTCString()+';path=/';
  //console.log(document.cookie);  // 'Wed, 31 Oct 2012 08:50:17 UTC'
}

expiration

How do I install PyCrypto on Windows?

For Windows 7:

To install Pycrypto in Windows,

Try this in Command Prompt,

Set path=C:\Python27\Scripts (i.e path where easy_install is located)

Then execute the following,

easy_install pycrypto

For Ubuntu:

Try this,

Download Pycrypto from "https://pypi.python.org/pypi/pycrypto"

Then change your current path to downloaded path using your terminal and user should be root:

Eg: root@xyz-virtual-machine:~/pycrypto-2.6.1#

Then execute the following using the terminal:

python setup.py install

It's worked for me. Hope works for all..

Android set bitmap to Imageview

this code works with me

 ImageView carView = (ImageView) v.findViewById(R.id.car_icon);

                            byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
                            InputStream input=new ByteArrayInputStream(decodedString);
                            Bitmap ext_pic = BitmapFactory.decodeStream(input);
                            carView.setImageBitmap(ext_pic);

iText - add content to existing PDF file

iText has more than one way of doing this. The PdfStamper class is one option. But I find the easiest method is to create a new PDF document then import individual pages from the existing document into the new PDF.

// Create output PDF
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();

// Load existing PDF
PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1); 

// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);

// Add your new data / text here
// for example...
document.add(new Paragraph("my timestamp")); 

document.close();

This will read in a PDF from templateInputStream and write it out to outputStream. These might be file streams or memory streams or whatever suits your application.

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

Clone contents of a GitHub repository (without the folder itself)

If the current directory is empty, you can do that with:

git clone git@github:me/name.git .

(Note the . at the end to specify the current directory.) Of course, this also creates the .git directory in your current folder, not just the source code from your project.

This optional [directory] parameter is documented in the git clone manual page, which points out that cloning into an existing directory is only allowed if that directory is empty.

How to make CSS width to fill parent?

So after research the following is discovered:

For a div#bar setting display:block; width: auto; causes the equivalent of outerWidth:100%;

For a table#bar you need to wrap it in a div with the rules stated below. So your structure becomes:

<div id="foo">
 <div id="barWrap" style="border....">
  <table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">

This way the table takes up the parent div 100%, and #barWrap is used to add borders/margin/padding to the #bar table. Note that you will need to set the background of the whole thing in #barWrap and have #bar's background be transparent or the same as #barWrap.

For textarea#bar and input#bar you need to do the same thing as table#bar, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.

base64 encoded images in email signatures

Recently I had the same problem to include QR image/png in email. The QR image is a byte array which is generated using ZXing. We do not want to save it to a file because saving/reading from a file is too expensive (slow). So both of the answers above do not work for me. Here's what I did to solve this problem:

import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.mail.ImageHtmlEmail;
...
ImageHtmlEmail email = new ImageHtmlEmail();
byte[] qrImageBytes = createQRCode(); // get your image byte array
ByteArrayDataSource qrImageDataSource = new ByteArrayDataSource(qrImageBytes, "image/png");
String contentId = email.embed(qrImageDataSource, "QR Image");

Let's say the contentId is "111122223333", then your HTML part should have this:

<img src="cid: 111122223333">

There's no need to convert the byte array to Base64 because Commons Mail does the conversion for you automatically. Hope this helps.

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

How do I set up a simple delegate to communicate between two view controllers?

Following solution is very basic and simple approach to send data from VC2 to VC1 using delegate .

PS: This solution is made in Xcode 9.X and Swift 4

Declared a protocol and created a delegate var into ViewControllerB

    import UIKit

    //Declare the Protocol into your SecondVC
    protocol DataDelegate {
        func sendData(data : String)
    }

    class ViewControllerB : UIViewController {

    //Declare the delegate property in your SecondVC
        var delegate : DataDelegate?
        var data : String = "Send data to ViewControllerA."
        override func viewDidLoad() {
            super.viewDidLoad()
        }

        @IBAction func btnSendDataPushed(_ sender: UIButton) {
                // Call the delegate method from SecondVC
                self.delegate?.sendData(data:self.data)
                dismiss(animated: true, completion: nil)
            }
        }

ViewControllerA confirms the protocol and expected to receive data via delegate method sendData

    import UIKit
        // Conform the  DataDelegate protocol in ViewControllerA
        class ViewControllerA : UIViewController , DataDelegate {
        @IBOutlet weak var dataLabel: UILabel!

        override func viewDidLoad() {
            super.viewDidLoad()
        }

        @IBAction func presentToChild(_ sender: UIButton) {
            let childVC =  UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"ViewControllerB") as! ViewControllerB
            //Registered delegate
            childVC.delegate = self
            self.present(childVC, animated: true, completion: nil)
        }

        // Implement the delegate method in ViewControllerA
        func sendData(data : String) {
            if data != "" {
                self.dataLabel.text = data
            }
        }
    }

Get JSON Data from URL Using Android?

If you get the server response as a String, without using a third party library you can do

JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");

Here is the documentation

Otherwise to parse json you can use Gson or Jackson

EDIT without libraries (not tested)

class retrievedata extends AsyncTask<Void, Void, String>{
    @Override
    protected String doInBackground(Void... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        URL url;
        try {
            url = new URL("http://myurlhere.com");
            urlConnection.setRequestMethod("GET"); //Your method here 
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null)
                buffer.append(line + "\n");

            if (buffer.length() == 0)
                return null;

            return buffer.toString();
        } catch (IOException e) {
            Log.e(TAG, "IO Exception", e);
            exception = e;
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    exception = e;
                    Log.e(TAG, "Error closing stream", e);
                }
            }
        }
    }

    @Override
    protected void onPostExecute(String response) {
        if(response != null) {
            JSONObject json = new JSONObject(response);
            JSONObject jsonResponse = json.getJSONObject("response");
            String team = jsonResponse.getString("Team");
        }
    }
}

How to make overlay control above all other controls?

This is a common function of Adorners in WPF. Adorners typically appear above all other controls, but the other answers that mention z-order may fit your case better.

How do I install boto?

Best way to install boto in my opinion is to use:

pip install boto-1.6 

This ensures you'll have the boto glacier code.

starting file download with JavaScript

Reading the answers - including the accepted one I'd like to point out the security implications of passing a path directly to readfile via GET.

It may seem obvious to some but some may simply copy/paste this code:

<?php 
   header("Content-Type: application/octet-stream");
   header("Content-Disposition: attachment; filename=".$_GET['path']);
   readfile($_GET['path']);
?>

So what happens if I pass something like '/path/to/fileWithSecrets' to this script? The given script will happily send any file the webserver-user has access to.

Please refer to this discussion for information how to prevent this: How do I make sure a file path is within a given subdirectory?

Map a network drive to be used by a service

You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.

The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:

  • The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)

  • Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.

How to debug when Kubernetes nodes are in 'Not Ready' state

Steps to debug:-

In case you face any issue in kubernetes, first step is to check if kubernetes self applications are running fine or not.

Command to check:- kubectl get pods -n kube-system

If you see any pod is crashing, check it's logs

if getting NotReady state error, verify network pod logs.

if not able to resolve with above, follow below steps:-

  1. kubectl get nodes # Check which node is not in ready state

  2. kubectl describe node nodename #nodename which is not in readystate

  3. ssh to that node

  4. execute systemctl status kubelet # Make sure kubelet is running

  5. systemctl status docker # Make sure docker service is running

  6. journalctl -u kubelet # To Check logs in depth

Most probably you will get to know about error here, After fixing it reset kubelet with below commands:-

  1. systemctl daemon-reload
  2. systemctl restart kubelet

In case you still didn't get the root cause, check below things:-

  1. Make sure your node has enough space and memory. Check for /var directory space especially. command to check: -df -kh, free -m

  2. Verify cpu utilization with top command. and make sure any process is not taking an unexpected memory.

Select <a> which href ends with some string

   $('a[href$="ABC"]')...

Selector documentation can be found at http://docs.jquery.com/Selectors

For attributes:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

Tomcat 8 is not able to handle get request with '|' in query parameters?

This behavior is introduced in all major Tomcat releases:

  • Tomcat 7.0.73, 8.0.39, 8.5.7

To fix, do one of the following:

  • set relaxedQueryChars to allow this character (recommended, see Lincoln's answer)
  • set requestTargetAllow option (deprecated in Tomcat 8.5) (see Jérémie's answer).
  • you can downgrade to one of older versions (not recommended - security)

Based on changelog, those changes could affect this behavior:

Tomcat 8.5.3:

Ensure that requests with HTTP method names that are not tokens (as required by RFC 7231) are rejected with a 400 response

Tomcat 8.5.7:

Add additional checks for valid characters to the HTTP request line parsing so invalid request lines are rejected sooner.


The best option (following the standard) - you want to encode your URL on client:

encodeURI("http://localhost:8080/app/handleResponse?msg=name|id|")
> http://localhost:8080/app/handleResponse?msg=name%7Cid%7C

or just query string:

encodeURIComponent("msg=name|id|")
> msg%3Dname%7Cid%7C

It will secure you from other problematic characters (list of invalid URI characters).

How to make asynchronous HTTP requests in PHP

Well, the timeout can be set in milliseconds, see "CURLOPT_CONNECTTIMEOUT_MS" in http://www.php.net/manual/en/function.curl-setopt

Process escape sequences in a string in Python

The actually correct and convenient answer for python 3:

>>> import codecs
>>> myString = "spam\\neggs"
>>> print(codecs.escape_decode(bytes(myString, "utf-8"))[0].decode("utf-8"))
spam
eggs
>>> myString = "naïve \\t test"
>>> print(codecs.escape_decode(bytes(myString, "utf-8"))[0].decode("utf-8"))
naïve    test

Details regarding codecs.escape_decode:

  • codecs.escape_decode is a bytes-to-bytes decoder
  • codecs.escape_decode decodes ascii escape sequences, such as: b"\\n" -> b"\n", b"\\xce" -> b"\xce".
  • codecs.escape_decode does not care or need to know about the byte object's encoding, but the encoding of the escaped bytes should match the encoding of the rest of the object.

Background:

  • @rspeer is correct: unicode_escape is the incorrect solution for python3. This is because unicode_escape decodes escaped bytes, then decodes bytes to unicode string, but receives no information regarding which codec to use for the second operation.
  • @Jerub is correct: avoid the AST or eval.
  • I first discovered codecs.escape_decode from this answer to "how do I .decode('string-escape') in Python3?". As that answer states, that function is currently not documented for python 3.

How to build a RESTful API?

I know that this question is accepted and has a bit of age but this might be helpful for some people who still find it relevant. Although the outcome is not a full RESTful API the API Builder mini lib for PHP allows you to easily transform MySQL databases into web accessible JSON APIs.

How to find the length of an array in shell?

In the Fish Shell the length of an array can be found with:

$ set a 1 2 3 4
$ count $a
4

Xcode error "Could not find Developer Disk Image"

This error is shown when your Xcode installation is too old and the related device you are using is updated to latest version.

There are multiple ways to solve this issues.

1. Update your Xcode installation.

This is by far the simplest method. Just update your Xcode installation to the latest stable version and things would start working again.

Note: Please update your OS as well if Xcode doesn't support your current OS. Which brings us to...

2. Manually copying Device Disk Image. No update needed.

This is the clever way around. You don't have to update your Xcode installation or your OS for this.

First open the XCode.dmg and select Show Package Contents.

Phase 1: Getting the downloaded Xcode ready.

Steps:

  1. Download the latest Xcode.dmg from Developer portal.
  2. Select the downloaded Xcode.dmg and right click on it.
  3. In the options, select Open With ? DiskImageMounter.
  4. Now in Finder, open the Xcode disk.
  5. In the disk, right click on Xcode.
  6. Select Show Package Contents.

Now, a new finder window opens. Follow the instructions below to copy the disk image.

Phase 2: Copying the Developer Disk Image.

Steps:

  1. In the new finder, go to Contents.
  2. Inside Contents, Go to Developer.
  3. Inside Developer, go to Platform.
    Now select the desired platform. For our purpose, we are going to update iOS disk image only.
  4. Inside Platform, go to Device Support.
  5. Inside Device Support, you'll find a lot of disk images. This includes the latest device disk images as well.
  6. Copy all the folders inside Device Support. Select all and then copy.

Note: For step 6, You can copy the disk image you want to copy as well, i.e. copy the latest only. It's the last folder in the hierarchy here.

This ends the Phase 2, Copying the disk image. Now in the next phase, we will update the developer disk image of our Xcode installed on our device.

Phase 3: Upadting the Xcode's developer disk image.

Now, close all the finder windows for faster operation and less confusion.

We are now going to update our Xcode's disk image for iOS Platform.

Steps:

  1. Close the Xcode application if it is open.
  2. Open a new finder window.
  3. Select the primary partition if you have multiple partitions.
  4. Go to Applications.
  5. Find XCode and right click on it.
  6. Select Show Package Contents.

Finder window updates or opens a new window with Contents as the main directory.

  1. Select Contents.
  2. Inside Contents, select Developer.
  3. Now, select Platforms.
    1. Now, select iPhoneOS.platform.
    2. Inside iPhoneOS.platform, go to Device Support.
    3. Inside Device Support, select all the files and Move to Trash.

Note: SKIP step 12 if you copied only the latest disk image i.e. the last folder in the hierarchy.


Now, Paste the developer disk image we copied from Phase 2 here.

  1. Final Step, right click and Paste here.

If everything worked properly, your Xcode has new developer disk image. Close the finder now, and open Xcode. The error should be gone by now.

Reminder: Don't forget to unmount the Xcode now from finder as well.

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper div:

.dimmed {
  position: relative;
}

.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
}

I'm using rgba here, but of course you can use other transparency methods if you like.

What's the best strategy for unit-testing database-driven applications?

Even if there are tools that allow you to mock your database in one way or another (e.g. jOOQ's MockConnection, which can be seen in this answer - disclaimer, I work for jOOQ's vendor), I would advise not to mock larger databases with complex queries.

Even if you just want to integration-test your ORM, beware that an ORM issues a very complex series of queries to your database, that may vary in

  • syntax
  • complexity
  • order (!)

Mocking all that to produce sensible dummy data is quite hard, unless you're actually building a little database inside your mock, which interprets the transmitted SQL statements. Having said so, use a well-known integration-test database that you can easily reset with well-known data, against which you can run your integration tests.

What are the advantages of Sublime Text over Notepad++ and vice-versa?

Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.

Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.

Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.

Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?

What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.

Using Address Instead Of Longitude And Latitude With Google Maps API

Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...

_x000D_
_x000D_
var addressesArray = [_x000D_
  'Address Str.No, Postal Area/city',_x000D_
  //follow this structure_x000D_
]_x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
  center: {_x000D_
    lat: 12.7826,_x000D_
    lng: 105.0282_x000D_
  },_x000D_
  zoom: 6,_x000D_
  gestureHandling: 'cooperative'_x000D_
});_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
for (i = 0; i < addressArray.length; i++) {_x000D_
  var address = addressArray[i];_x000D_
  geocoder.geocode({_x000D_
    'address': address_x000D_
  }, function(results, status) {_x000D_
    if (status === 'OK') {_x000D_
      var marker = new google.maps.Marker({_x000D_
        map: map,_x000D_
        position: results[0].geometry.location,_x000D_
        center: {_x000D_
          lat: 12.7826,_x000D_
          lng: 105.0282_x000D_
        },_x000D_
      });_x000D_
    } else {_x000D_
      alert('Geocode was not successful for the following reason: ' + status);_x000D_
    }_x000D_
  });_x000D_
}
_x000D_
_x000D_
_x000D_

Setting the filter to an OpenFileDialog to allow the typical image formats?

To filter images files, use this code sample.

//Create a new instance of openFileDialog
OpenFileDialog res = new OpenFileDialog();

//Filter
res.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.gif;*.tif;...";

//When the user select the file
if (res.ShowDialog() == DialogResult.OK)
{
   //Get the file's path
   var filePath = res.FileName;
   //Do something
   ....
}

Is there a difference between x++ and ++x in java?

Yes, the value returned is the value after and before the incrementation, respectively.

class Foo {
    public static void main(String args[]) {
        int x = 1;
        int a = x++;
        System.out.println("a is now " + a);
        x = 1;
        a = ++x;
        System.out.println("a is now " + a);
    }
}

$ java Foo
a is now 1
a is now 2

Jquery in React is not defined

I just want to receive ajax request, but the problem is that jQuery is not defined in React.

Then don't use it. Use Fetch and have a look at Fetch polyfill in React not completely working in IE 11 to see example of alternative ways to get it running

Something like this

const that = this; 
fetch('http://jsonplaceholder.typicode.com/posts') 
  .then(function(response) { return response.json(); }) 
  .then(function(myJson) { 
     that.setState({data: myJson}); // for example
  });

Homebrew install specific version of formula?

TLDR: brew install [email protected] See answer below for more details.


*(I’ve re-edited my answer to give a more thorough workflow for installing/using older software versions with homebrew. Feel free to add a note if you found the old version better.)

Let’s start with the simplest case:

1) Check, whether the version is already installed (but not activated)

When homebrew installs a new formula, it puts it in a versioned directory like /usr/local/Cellar/postgresql/9.3.1. Only symbolic links to this folder are then installed globally. In principle, this makes it pretty easy to switch between two installed versions. (*)

If you have been using homebrew for longer and never removed older versions (using, for example brew cleanup), chances are that some older version of your program may still be around. If you want to simply activate that previous version, brew switch is the easiest way to do this.

Check with brew info postgresql (or brew switch postgresql <TAB>) whether the older version is installed:

$ brew info postgresql
postgresql: stable 9.3.2 (bottled)
http://www.postgresql.org/
Conflicts with: postgres-xc
/usr/local/Cellar/postgresql/9.1.5 (2755 files, 37M)
  Built from source
/usr/local/Cellar/postgresql/9.3.2 (2924 files, 39M) *
  Poured from bottle
From: https://github.com/Homebrew/homebrew/commits/master/Library/Formula/postgresql.rb
# … and some more

We see that some older version is already installed. We may activate it using brew switch:

$ brew switch postgresql 9.1.5
Cleaning /usr/local/Cellar/postgresql/9.1.5
Cleaning /usr/local/Cellar/postgresql/9.3.2
384 links created for /usr/local/Cellar/postgresql/9.1.5

Let’s double-check what is activated:

$ brew info postgresql
postgresql: stable 9.3.2 (bottled)
http://www.postgresql.org/
Conflicts with: postgres-xc
/usr/local/Cellar/postgresql/9.1.5 (2755 files, 37M) *
  Built from source
/usr/local/Cellar/postgresql/9.3.2 (2924 files, 39M)
  Poured from bottle
From: https://github.com/Homebrew/homebrew/commits/master/Library/Formula/postgresql.rb
# … and some more

Note that the star * has moved to the newly activated version

(*) Please note that brew switch only works as long as all dependencies of the older version are still around. In some cases, a rebuild of the older version may become necessary. Therefore, using brew switch is mostly useful when one wants to switch between two versions not too far apart.

2) Check, whether the version is available as a tap

Especially for larger software projects, it is very probably that there is a high enough demand for several (potentially API incompatible) major versions of a certain piece of software. As of March 2012, Homebrew 0.9 provides a mechanism for this: brew tap & the homebrew versions repository.

That versions repository may include backports of older versions for several formulae. (Mostly only the large and famous ones, but of course they’ll also have several formulae for postgresql.)

brew search postgresql will show you where to look:

$ brew search postgresql
postgresql
homebrew/versions/postgresql8    homebrew/versions/postgresql91
homebrew/versions/postgresql9    homebrew/versions/postgresql92

We can simply install it by typing

$ brew install homebrew/versions/postgresql8
Cloning into '/usr/local/Library/Taps/homebrew-versions'...
remote: Counting objects: 1563, done.
remote: Compressing objects: 100% (943/943), done.
remote: Total 1563 (delta 864), reused 1272 (delta 620)
Receiving objects: 100% (1563/1563), 422.83 KiB | 339.00 KiB/s, done.
Resolving deltas: 100% (864/864), done.
Checking connectivity... done.
Tapped 125 formula
==> Downloading http://ftp.postgresql.org/pub/source/v8.4.19/postgresql-8.4.19.tar.bz2
# …

Note that this has automatically tapped the homebrew/versions tap. (Check with brew tap, remove with brew untap homebrew/versions.) The following would have been equivalent:

$ brew tap homebrew/versions
$ brew install postgresql8

As long as the backported version formulae stay up-to-date, this approach is probably the best way to deal with older software.

3) Try some formula from the past

The following approaches are listed mostly for completeness. Both try to resurrect some undead formula from the brew repository. Due to changed dependencies, API changes in the formula spec or simply a change in the download URL, things may or may not work.

Since the whole formula directory is a git repository, one can install specific versions using plain git commands. However, we need to find a way to get to a commit where the old version was available.

a) historic times

Between August 2011 and October 2014, homebrew had a brew versions command, which spat out all available versions with their respective SHA hashes. As of October 2014, you have to do a brew tap homebrew/boneyard before you can use it. As the name of the tap suggests, you should probably only do this as a last resort.

E.g.

$ brew versions postgresql
Warning: brew-versions is unsupported and may be removed soon.
Please use the homebrew-versions tap instead:
  https://github.com/Homebrew/homebrew-versions
9.3.2    git checkout 3c86d2b Library/Formula/postgresql.rb
9.3.1    git checkout a267a3e Library/Formula/postgresql.rb
9.3.0    git checkout ae59e09 Library/Formula/postgresql.rb
9.2.4    git checkout e3ac215 Library/Formula/postgresql.rb
9.2.3    git checkout c80b37c Library/Formula/postgresql.rb
9.2.2    git checkout 9076baa Library/Formula/postgresql.rb
9.2.1    git checkout 5825f62 Library/Formula/postgresql.rb
9.2.0    git checkout 2f6cbc6 Library/Formula/postgresql.rb
9.1.5    git checkout 6b8d25f Library/Formula/postgresql.rb
9.1.4    git checkout c40c7bf Library/Formula/postgresql.rb
9.1.3    git checkout 05c7954 Library/Formula/postgresql.rb
9.1.2    git checkout dfcc838 Library/Formula/postgresql.rb
9.1.1    git checkout 4ef8fb0 Library/Formula/postgresql.rb
9.0.4    git checkout 2accac4 Library/Formula/postgresql.rb
9.0.3    git checkout b782d9d Library/Formula/postgresql.rb

As you can see, it advises against using it. Homebrew spits out all versions it can find with its internal heuristic and shows you a way to retrieve the old formulae. Let’s try it.

# First, go to the homebrew base directory
$ cd $( brew --prefix )
# Checkout some old formula
$ git checkout 6b8d25f Library/Formula/postgresql.rb
$ brew install postgresql
# … installing

Now that the older postgresql version is installed, we can re-install the latest formula in order to keep our repository clean:

$ git checkout -- Library/Formula/postgresql.rb

brew switch is your friend to change between the old and the new.

b) prehistoric times

For special needs, we may also try our own digging through the homebrew repo.

$ cd Library/Taps/homebrew/homebrew-core && git log -S'8.4.4' -- Formula/postgresql.rb

git log -S looks for all commits in which the string '8.4.4' was either added or removed in the file Library/Taps/homebrew/homebrew-core/Formula/postgresql.rb. We get two commits as a result.

commit 7dc7ccef9e1ab7d2fc351d7935c96a0e0b031552
Author: Aku Kotkavuo
Date:   Sun Sep 19 18:03:41 2010 +0300

    Update PostgreSQL to 9.0.0.

    Signed-off-by: Adam Vandenberg

commit fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422
Author: David Höppner
Date:   Sun May 16 12:35:18 2010 +0200

    postgresql: update version to 8.4.4

Obviously, fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422 is the commit we’re interested in. As this commit is pretty old, we’ll try to downgrade the complete homebrew installation (that way, the formula API is more or less guaranteed to be valid):

$ git checkout -b postgresql-8.4.4 fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422
$ brew install postgresql
$ git checkout master
$ git branch -d postgresql-8.4.4

You may skip the last command to keep the reference in your git repository.

One note: When checking out the older commit, you temporarily downgrade your homebrew installation. So, you should be careful as some commands in homebrew might be different to the most recent version.

4) Manually write a formula

It’s not too hard and you may then upload it to your own repository. Used to be Homebrew-Versions, but that is now discontinued.

A.) Bonus: Pinning

If you want to keep a certain version of, say postgresql, around and stop it from being updated when you do the natural brew update; brew upgrade procedure, you can pin a formula:

$ brew pin postgresql

Pinned formulae are listed in /usr/local/Library/PinnedKegs/ and once you want to bring in the latest changes and updates, you can unpin it again:

$ brew unpin postgresql

Create Excel file in Java

To create a spreadsheet and format a cell using POI, see the Working with Fonts example, and use:

font.setBoldweight(Font.BOLDWEIGHT_BOLD);

POI works very well. There are some things you can't do (e.g. create VBA macros), but it'll read/write spreadsheets with macros, so you can create a suitable template sheet, read it and manipulate it with POI, and then write it out.

Angular.js directive dynamic templateURL

I have an example about this.

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  </head>

  <body>
    <div class="container-fluid body-content" ng-controller="formView">
        <div class="row">
            <div class="col-md-12">
                <h4>Register Form</h4>
                <form class="form-horizontal" ng-submit="" name="f" novalidate>
                    <div ng-repeat="item in elements" class="form-group">
                        <label>{{item.Label}}</label>
                        <element type="{{item.Type}}" model="item"></element>
                    </div>
                    <input ng-show="f.$valid" type="submit" id="submit" value="Submit" class="" />
                </form>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
    <script src="app.js"></script>
  </body>

</html>

angular.module('app', [])
    .controller('formView', function ($scope) {
        $scope.elements = [{
            "Id":1,
            "Type":"textbox",
            "FormId":24,
            "Label":"Name",
            "PlaceHolder":"Place Holder Text",
            "Max":20,
            "Required":false,
            "Options":null,
            "SelectedOption":null
          },
          {
            "Id":2,
            "Type":"textarea",
            "FormId":24,
            "Label":"AD2",
            "PlaceHolder":"Place Holder Text",
            "Max":20,
            "Required":true,
            "Options":null,
            "SelectedOption":null
        }];
    })
    .directive('element', function () {
        return {
            restrict: 'E',
            link: function (scope, element, attrs) {
                scope.contentUrl = attrs.type + '.html';
                attrs.$observe("ver", function (v) {
                    scope.contentUrl = v + '.html';
                });
            },
            template: '<div ng-include="contentUrl"></div>'
        }
    })

MVVM: Tutorial from start to finish?

I read Josh Smith's article and found it very difficult. Once understood, I wrote a very simple one that should get you really started on it. Get it here.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I tested "jenv" and other things like setting "JAVA_HOME" without success. Now i and endet up with following solution

function setJava {
    export JAVA_HOME="$(/usr/libexec/java_home -v $1)"
    launchctl setenv JAVA_HOME $JAVA_HOME
    sudo ln -nsf "$(dirname ${JAVA_HOME})/MacOS" /Library/Java/MacOS 
    java -version
}

(added to ~/.bashrc or ~/.bash.profile or ~/.zshrc)

And calling like that:

setJava 1.8

java_home will handle the wrong input. so you can't do something wrong. Maven and other stuff will pick up the right version now.

Facebook Post Link Image

If you used any plugin for seo then Check 1st your seo plugin settings.Then find out Noindex setting if Enable Media for Noindex then disable it.

How do I get the Git commit count?

Use git shortlog just like this

git shortlog -sn

Or create an alias (for ZSH based terminal)

# show contributors by commits alias gcall="git shortlog -sn"

json call with C#

In your code you don't get the HttpResponse, so you won't see what the server side sends you back.

you need to get the Response similar to the way you get (make) the Request. So

public static bool SendAnSMSMessage(string message)
{
  var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
  httpWebRequest.ContentType = "text/json";
  httpWebRequest.Method = "POST";

  using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
  {
    string json = "{ \"method\": \"send\", " +
                      "  \"params\": [ " +
                      "             \"IPutAGuidHere\", " +
                      "             \"[email protected]\", " +
                      "             \"MyTenDigitNumberWasHere\", " +
                      "             \"" + message + "\" " +
                      "             ] " +
                      "}";

    streamWriter.Write(json);
  }
  var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  {
    var responseText = streamReader.ReadToEnd();
    //Now you have your response.
    //or false depending on information in the response
    return true;        
  }
}

I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.

Generating Fibonacci Sequence

Yet another answer would be to use es6 generator functions.

function* fib() {
  var current = a = b = 1;

  yield 1;

  while (true) {
    current = b;

    yield current;

    b = a + b;
    a = current;
  }
}

sequence = fib();
sequence.next(); // 1
sequence.next(); // 1
sequence.next(); // 2
// ...

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

tl;dr

The answer is NEVER! (unless you really know what you're doing)

9/10 times the solution can be resolved with a proper understanding of encoding/decoding.

1/10 people have an incorrectly defined locale or environment and need to set:

PYTHONIOENCODING="UTF-8"  

in their environment to fix console printing problems.

What does it do?

sys.setdefaultencoding("utf-8") (struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:

str(u"\u20AC")
unicode("€")
"{}".format(u"\u20AC") 

In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

(My console is configured as UTF-8, so "€" = '\xe2\x82\xac', hence exception on \xe2)

or

UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)

sys.setdefaultencoding("utf-8") will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into code

Console

sys.setdefaultencoding("utf-8") also has a side effect of appearing to fix sys.stdout.encoding, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING to fix the console encoding.

Example:

$ export LANG=en_GB.gibberish
$ python
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> print u"\u20AC"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
>>> exit()

$ PYTHONIOENCODING=UTF-8 python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print u"\u20AC"
€

What's so bad with sys.setdefaultencoding("utf-8")?

People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.

From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/

def welcome_message(byte_string):
    try:
        return u"%s runs your business" % byte_string
    except UnicodeError:
        return u"%s runs your business" % unicode(byte_string,
            encoding=detect_encoding(byte_string))

print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))

Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.

Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.

Example problem

While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte

fetch from origin with deleted remote branches?

From http://www.gitguys.com/topics/adding-and-removing-remote-branches/

After someone deletes a branch from a remote repository, git will not automatically delete the local repository branches when a user does a git pull or git fetch. However, if the user would like to have all tracking branches removed from their local repository that have been deleted in a remote repository, they can type:

git remote prune origin

As a note, the -p param from git fetch -p actually means "prune".
Either way you chose, the non-existing remote branches will be deleted from your local repository.

Call to a member function fetch_assoc() on boolean in <path>

The query method can return false instead of a result set in case there is an error. That is why you get the error on the fetch_assoc method call, which obviously does not exist when $result is false.

This means you have an error in your SELECT statement. To get that error displayed, do this:

 $result = $conn->query($sql) or die($conn->error);

Most probably you have a wrong spelling for the table name or a column name. Maybe when moving to the host you did not create that table correctly, and made a spelling mistake there.

You should in fact see the same error when executing the same query via phpAdmin.

Also, replace this line:

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

with just:

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

You could also add this for debugging:

echo "number of rows: " . $result->num_rows;

Secondary axis with twinx(): how to add to legend?

I found an following official matplotlib example that uses host_subplot to display multiple y-axes and all the different labels in one legend. No workaround necessary. Best solution I found so far. http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
                                    axes=par2,
                                    offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

plt.draw()
plt.show()

How to access parent scope from within a custom directive *with own scope* in AngularJS?

Accessing controller method means accessing a method on parent scope from directive controller/link/scope.

If the directive is sharing/inheriting the parent scope then it is quite straight forward to just invoke a parent scope method.

Little more work is required when you want to access parent scope method from Isolated directive scope.

There are few options (may be more than listed below) to invoke a parent scope method from isolated directives scope or watch parent scope variables (option#6 specially).

Note that I used link function in these examples but you can use a directive controller as well based on requirement.

Option#1. Through Object literal and from directive html template

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChanged({selectedItems:selectedItems})" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]

});

working plnkr: http://plnkr.co/edit/rgKUsYGDo9O3tewL6xgr?p=preview

Option#2. Through Object literal and from directive link/scope

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html",
    link: function (scope, element, attrs){
      scope.selectedItemsChangedDir = function(){
        scope.selectedItemsChanged({selectedItems:scope.selectedItems});  
      }
    }
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/BRvYm2SpSpBK9uxNIcTa?p=preview

Option#3. Through Function reference and from directive html template

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-change="selectedItemsChanged()(selectedItems)" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems:'=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/Jo6FcYfVXCCg3vH42BIz?p=preview

Option#4. Through Function reference and from directive link/scope

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html",
    link: function (scope, element, attrs){
      scope.selectedItemsChangedDir = function(){
        scope.selectedItemsChanged()(scope.selectedItems);  
      }
    }
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]

});

working plnkr: http://plnkr.co/edit/BSqx2J1yCY86IJwAnQF1?p=preview

Option#5: Through ng-model and two way binding, you can update parent scope variables.. So, you may not require to invoke parent scope functions in some cases.

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter ng-model="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=ngModel'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/hNui3xgzdTnfcdzljihY?p=preview

Option#6: Through $watch and $watchCollection It is two way binding for items in all above examples, if items are modified in parent scope, items in directive would also reflect the changes.

If you want to watch other attributes or objects from parent scope, you can do that using $watch and $watchCollection as given below

html

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>Hello {{user}}!</p>
  <p>directive is watching name and current item</p>
  <table>
    <tr>
      <td>Id:</td>
      <td>
        <input type="text" ng-model="id" />
      </td>
    </tr>
    <tr>
      <td>Name:</td>
      <td>
        <input type="text" ng-model="name" />
      </td>
    </tr>
    <tr>
      <td>Model:</td>
      <td>
        <input type="text" ng-model="model" />
      </td>
    </tr>
  </table>

  <button style="margin-left:50px" type="buttun" ng-click="addItem()">Add Item</button>

  <p>Directive Contents</p>
  <sd-items-filter ng-model="selectedItems" current-item="currentItem" name="{{name}}" selected-items-changed="selectedItemsChanged" items="items"></sd-items-filter>

  <P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}}</p>
</body>

</html>

script app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@',
      currentItem: '=',
      items: '=',
      selectedItems: '=ngModel'
    },
    template: '<select ng-model="selectedItems" multiple="multiple" style="height: 140px; width: 250px;"' +
      'ng-options="item.id as item.name group by item.model for item in items | orderBy:\'name\'">' +
      '<option>--</option> </select>',
    link: function(scope, element, attrs) {
      scope.$watchCollection('currentItem', function() {
        console.log(JSON.stringify(scope.currentItem));
      });
      scope.$watch('name', function() {
        console.log(JSON.stringify(scope.name));
      });
    }
  }
})

 app.controller('MainCtrl', function($scope) {
  $scope.user = 'World';

  $scope.addItem = function() {
    $scope.items.push({
      id: $scope.id,
      name: $scope.name,
      model: $scope.model
    });
    $scope.currentItem = {};
    $scope.currentItem.id = $scope.id;
    $scope.currentItem.name = $scope.name;
    $scope.currentItem.model = $scope.model;
  }

  $scope.selectedItems = ["allItems"];

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
  }]
});

You can always refer AngularJs documentation for detailed explanations about directives.

How do I use the Tensorboard callback of Keras?

You should check out Losswise (https://losswise.com), it has a plugin for Keras that's easier to use than Tensorboard and has some nice extra features. With Losswise you'd just use from losswise.libs import LosswiseKerasCallback and then callback = LosswiseKerasCallback(tag='my fancy convnet 1') and you're good to go (see https://docs.losswise.com/#keras-plugin).

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Instead of thinking of it as 'extracting', I like to think of it as 'isolating'. Once the desired bits are isolated, you can do what you will with them.

To isolate any set of bits, apply an AND mask.

If you want the last X bits of a value, there is a simple trick that can be used.

unsigned  mask;
mask = (1 << X) - 1;
lastXbits = value & mask;

If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...

unsigned  mask;
mask = ((1 << X) - 1) << startBit;
isolatedXbits = value & mask;

Hope this helps.

tar: Error is not recoverable: exiting now

Try to get your archive using wget, I had the same issue when I was downloading archive through browser. Than I just copy archive link and in terminal use the command:

wget http://PATH_TO_ARCHIVE

Stratified Train/Test-split in scikit-learn

In addition to the accepted answer by @Andreas Mueller, just want to add that as @tangy mentioned above:

StratifiedShuffleSplit most closely resembles train_test_split(stratify = y) with added features of:

  1. stratify by default
  2. by specifying n_splits, it repeatedly splits the data

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

If you want to make a change global to the whole notebook:

import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]

500 Internal Server Error for php file not for html

Google guides me here but it didn't fix mine, this is a very general question and there are various causes, so I post my problem and solution here for reference in case anyone might read this later.

Another possible cause of 500 error is syntax error in header(...) function, like this one:

header($_SERVER['SERVER_PROTOCOL'] . '200 OK');

Be aware there should be space between server protocol and status code, so it should be:

header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');

So I suggest check your http header call if you have it in your code.

Git push hangs when pushing to Github?

I had the same issue. Stop worrying and searching endless complicated solutions, just remove git and reinstall it.

sudo apt-get purge git
sudo apt-get autoremove
sudo apt-get install git

Thats it. It should work now

Adjust table column width to content size

maybe problem with margin?

width:auto;
padding: 0px;
margin: 0px

Combining C++ and C - how does #ifdef __cplusplus work?

extern "C" doesn't really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration).

What extern "C" does is affect linkage. C++ functions, when compiled, have their names mangled -- this is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names.

Code inside an extern "C" is still C++ code. There are limitations on what you can do in an extern "C" block, but they're all about linkage. You can't define any new symbols that can't be built with C linkage. That means no classes or templates, for example.

extern "C" blocks nest nicely. There's also extern "C++" if you find yourself hopelessly trapped inside of extern "C" regions, but it isn't such a good idea from a cleanliness perspective.

Now, specifically regarding your numbered questions:

Regarding #1: __cplusplus will stay defined inside of extern "C" blocks. This doesn't matter, though, since the blocks should nest neatly.

Regarding #2: __cplusplus will be defined for any compilation unit that is being run through the C++ compiler. Generally, that means .cpp files and any files being included by that .cpp file. The same .h (or .hh or .hpp or what-have-you) could be interpreted as C or C++ at different times, if different compilation units include them. If you want the prototypes in the .h file to refer to C symbol names, then they must have extern "C" when being interpreted as C++, and they should not have extern "C" when being interpreted as C -- hence the #ifdef __cplusplus checking.

To answer your question #3: functions without prototypes will have C++ linkage if they are in .cpp files and not inside of an extern "C" block. This is fine, though, because if it has no prototype, it can only be called by other functions in the same file, and then you don't generally care what the linkage looks like, because you aren't planning on having that function be called by anything outside the same compilation unit anyway.

For #4, you've got it exactly. If you are including a header for code that has C linkage (such as code that was compiled by a C compiler), then you must extern "C" the header -- that way you will be able to link with the library. (Otherwise, your linker would be looking for functions with names like _Z1hic when you were looking for void h(int, char)

5: This sort of mixing is a common reason to use extern "C", and I don't see anything wrong with doing it this way -- just make sure you understand what you are doing.

Memory errors and list limits?

First off, see How Big can a Python Array Get? and Numpy, problem with long arrays

Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:

  1. If you are running on an older OS or one that forces processes to use a limited amount of memory, you may need to increase the amount of memory the Python process has access to.
  2. Break the list apart using chunking. For example, do the first 1000 elements of the list, pickle and save them to disk, and then do the next 1000. To work with them, unpickle one chunk at a time so that you don't run out of memory. This is essentially the same technique that databases use to work with more data than will fit in RAM.

Playing .mp3 and .wav in Java?

The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29

Here is the code for the class

public class SimplePlayer {

    public SimplePlayer(){

        try{

             FileInputStream fis = new FileInputStream("File location.");
             Player playMP3 = new Player(fis);

             playMP3.play();

        }  catch(Exception e){
             System.out.println(e);
           }
    } 
}

and here are the imports

import javazoom.jl.player.*;
import java.io.FileInputStream;

HTML Input Box - Disable

<input type="text" disabled="disabled" />

See the W3C HTML Specification on the input tag for more information.

Select every Nth element in CSS

Try this

div:nth-child(4n+4)