Programs & Examples On #Richtextctrl

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

How to call a MySQL stored procedure from within PHP code?

This is my solution with prepared statements and stored procedure is returning several rows not only one value.

<?php

require 'config.php';
header('Content-type:application/json');
$connection->set_charset('utf8');

$mIds = $_GET['ids'];

$stmt = $connection->prepare("CALL sp_takes_string_returns_table(?)");
$stmt->bind_param("s", $mIds);

$stmt->execute();

$result = $stmt->get_result();
$response = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($response);

$stmt->close();
$connection->close();

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

require 'date'

current_time = DateTime.now

current_time.strftime "%d/%m/%Y %H:%M"
# => "14/09/2011 17:02"

current_time.next_month.strftime "%d/%m/%Y %H:%M"
# => "14/10/2011 17:02"

In Java, can you modify a List while iterating through it?

Use Java 8's removeIf(),

To remove safely,

letters.removeIf(x -> !x.equals("A"));

Programmatically center TextView text

These two need to go together for it to work. Been scratching my head for a while.

numberView.textAlignment = View.TEXT_ALIGNMENT_CENTER
 numberView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

"Case" can return single value only, but you can use complex type:

create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;

How to download source in ZIP format from GitHub?

I've been stumped by this too. The "Download" button is to the far right, but you also need to be in the top folder in order to download what you're seeing. Go up as high as you can to the parent/root folder and then look for the download button.

Syntax error: Illegal return statement in JavaScript

where are you trying to return the value? to console in dev tools is better for debugging

<script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
  if(ask==false){
    return false;     
  } else {
    return true;
  }
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>

Dynamically Changing log4j log level

You can use following code snippet

((ch.qos.logback.classic.Logger)LoggerFactory.getLogger(packageName)).setLevel(ch.qos.logback.classic.Level.toLevel(logLevel));

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:

>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'

You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!

How to import other Python files?

the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.

this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.

Javascript date regex DD/MM/YYYY

Do the following change to the jquery.validationengine-en.js file and update the dd/mm/yyyy inline validation by including leap year:

"date": {
    // Check if date is valid by leap year
    "func": function (field) {
    //var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
    var pattern = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})$/);
    var match = pattern.exec(field.val());
    if (match == null)
    return false;

    //var year = match[1];
    //var month = match[2]*1;
    //var day = match[3]*1;
    var year = match[3];
    var month = match[2]*1;
    var day = match[1]*1;
    var date = new Date(year, month - 1, day); // because months starts from 0.

    return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in DD-MM-YYYY format"

Run a Docker image as a container

To view a list of all images on your Docker host, run:

  $ docker images
   REPOSITORY          TAG           IMAGE ID            CREATED             SIZE
   apache_snapshot     latest        13037686eac3        22 seconds ago      249MB
   ubuntu              latest        00fd29ccc6f1        3 weeks ago         111MB

Now you can run the Docker image as a container in interactive mode:

   $ docker run -it apache_snapshot /bin/bash

OR if you don't have any images locally,Search Docker Hub for an image to download:

    $ docker search ubuntu
    NAME                            DESCRIPTION             STARS  OFFICIAL  AUTOMATED
    ubuntu                          Ubuntu is a Debian...   6759   [OK]       
    dorowu/ubuntu-desktop-lxde-vnc  Ubuntu with openss...   141              [OK]
    rastasheep/ubuntu-sshd          Dockerized SSH ser...   114              [OK]
    ansible/ubuntu14.04-ansible     Ubuntu 14.04 LTS w...   88               [OK]
    ubuntu-upstart                  Upstart is an even...   80     [OK]

Pull the Docker image from a repository with the docker pull command:

     $ docker pull ubuntu

Run the Docker image as a container:

     $ docker run -it ubuntu /bin/bash

How to return a table from a Stored Procedure?

Where is your problem??

For the stored procedure, just create:

CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
   SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
   FROM dbo.Emp
   WHERE ID = @EmpID

That's all there is.

From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

DataTable tblEmployees = new DataTable();

using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
    _cmd.CommandType = CommandType.StoredProcedure;

    _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
    _cmd.Parameters["@EmpID"].Value = 42;

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);

    _dap.Fill(tblEmployees);
}

YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();

and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

Colon (:) in Python list index

: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples and strings, too.

Instagram API to fetch pictures with specific hashtags

Firstly, the Instagram API endpoint "tags" required OAuth authentication.

You can query results for a particular hashtag (snowy in this case) using the following url

It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour

https://api.instagram.com/v1/tags/snowy/media/recent

Sample response

{
  "pagination":  {
    "next_max_tag_id": "1370433362010",
    "deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
    "next_max_id": "1370433362010",
    "next_min_id": "1370443976800",
    "min_tag_id": "1370443976800",
    "next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
  },
  "meta":  {
    "code": 200
  },
  "data":  [
     {
      "attribution": null,
      "tags":  [
        "snowy"
      ],
      "type": "image",
      "location": null,
      "comments":  {
        "count": 0,
        "data":  []
      },
      "filter": null,
      "created_time": "1370418343",
      "link": "http://instagram.com/p/aK1yrGRi3l/",
      "likes":  {
        "count": 1,
        "data":  [
           {
            "username": "iri92lol",
            "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
            "id": "404174490",
            "full_name": "Iri"
          }
        ]
      },
      "images":  {
        "low_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
          "width": 306,
          "height": 306
        },
        "thumbnail":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
          "width": 150,
          "height": 150
        },
        "standard_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
          "width": 612,
          "height": 612
        }
      },
      "users_in_photo":  [],
      "caption":  {
        "created_time": "1370418353",
        "text": "#snowy",
        "from":  {
          "username": "iri92lol",
          "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
          "id": "404174490",
          "full_name": "Iri"
        },
        "id": "471425773832908504"
      },
      "user_has_liked": false,
      "id": "471425689728724453_404174490",
      "user":  {
        "username": "iri92lol",
        "website": "",
        "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
        "full_name": "Iri",
        "bio": "",
        "id": "404174490"
      }
    }
}

You can play around here :

https://apigee.com/console/instagram?req=%7B%22resource%22%3A%22get_tags_media_recent%22%2C%22params%22%3A%7B%22query%22%3A%7B%7D%2C%22template%22%3A%7B%22tag-name%22%3A%22snowy%22%7D%2C%22headers%22%3A%7B%7D%2C%22body%22%3A%7B%22attachmentFormat%22%3A%22mime%22%2C%22attachmentContentDisposition%22%3A%22form-data%22%7D%7D%2C%22verb%22%3A%22get%22%7D

You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.

All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.

python: SyntaxError: EOL while scanning string literal

I was getting this error in postgresql function. I had a long SQL which I broke into multiple lines with \ for better readability. However, that was the problem. I removed all and made them in one line to fix the issue. I was using pgadmin III.

How do I pass a variable to the layout using Laravel' Blade templating?

I was able to solve that problem by adding this to my controller method:

    $title = 'My Title Here';
    View::share('title', $title);

$this->layout->title = 'Home page'; did not work either.

What is an uber jar?

The different names are just ways of packaging java apps.

Skinny – Contains ONLY the bits you literally type into your code editor, and NOTHING else.

Thin – Contains all of the above PLUS the app’s direct dependencies of your app (db drivers, utility libraries, etc).

Hollow – The inverse of Thin – Contains only the bits needed to run your app but does NOT contain the app itself. Basically a pre-packaged “app server” to which you can later deploy your app, in the same style as traditional Java EE app servers, but with important differences.

Fat/Uber – Contains the bit you literally write yourself PLUS the direct dependencies of your app PLUS the bits needed to run your app “on its own”.

Source: Article from Dzone

Visual representation of JAR types

Reposted from: https://stackoverflow.com/a/57592130/9470346

When do we need curly braces around shell variables?

The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.

Classic Example 1) - shell variable without trailing whitespace

TIME=10

# WRONG: no such variable called 'TIMEsecs'
echo "Time taken = $TIMEsecs"

# What we want is $TIME followed by "secs" with no whitespace between the two.
echo "Time taken = ${TIME}secs"

Example 2) Java classpath with versioned jars

# WRONG - no such variable LATESTVERSION_src
CLASSPATH=hibernate-$LATESTVERSION_src.zip:hibernate_$LATEST_VERSION.jar

# RIGHT
CLASSPATH=hibernate-${LATESTVERSION}_src.zip:hibernate_$LATEST_VERSION.jar

(Fred's answer already states this but his example is a bit too abstract)

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

I think the second is "proper," but to be honest I don't think it will matter. The compiler should be smart enough to compile any of those to the exact same bytecode. I use "" myself.

word-wrap break-word does not work in this example

This combination of properties helped for me:

display: inline-block;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: normal;
line-break: strict;
hyphens: none;
-webkit-hyphens: none;
-moz-hyphens: none;

How to outline text in HTML / CSS

Try this:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
 font: Tahoma, Geneva, sans-serif;_x000D_
 font-size: 64px;_x000D_
    color: white;_x000D_
    text-shadow:_x000D_
    /* Outline */_x000D_
    -1px -1px 0 #000000,_x000D_
    1px -1px 0 #000000,_x000D_
    -1px 1px 0 #000000,_x000D_
    1px 1px 0 #000000,  _x000D_
    -2px 0 0 #000000,_x000D_
    2px 0 0 #000000,_x000D_
    0 2px 0 #000000,_x000D_
    0 -2px 0 #000000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

...and you might also want to do this too:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
 font: Tahoma, Geneva, sans-serif;_x000D_
 font-size: 64px;_x000D_
    color: white;_x000D_
    text-shadow:_x000D_
    /* Outline 1 */_x000D_
    -1px -1px 0 #000000,_x000D_
    1px -1px 0 #000000,_x000D_
    -1px 1px 0 #000000,_x000D_
    1px 1px 0 #000000,  _x000D_
    -2px 0 0 #000000,_x000D_
    2px 0 0 #000000,_x000D_
    0 2px 0 #000000,_x000D_
    0 -2px 0 #000000, _x000D_
    /* Outline 2 */_x000D_
    -2px -2px 0 #ff0000,_x000D_
    2px -2px 0 #ff0000,_x000D_
    -2px 2px 0 #ff0000,_x000D_
    2px 2px 0 #ff0000,  _x000D_
    -3px 0 0 #ff0000,_x000D_
    3px 0 0 #ff0000,_x000D_
    0 3px 0 #ff0000,_x000D_
    0 -3px 0 #ff0000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

You can do as many Outlines as you like, and there's enough scope for coming up with lots of creative ideas.

Have fun!

stdlib and colored output in C

#include <stdio.h>

#define BLUE(string) "\x1b[34m" string "\x1b[0m"
#define RED(string) "\x1b[31m" string "\x1b[0m"

int main(void)
{
    printf("this is " RED("red") "!\n");

    // a somewhat more complex ...
    printf("this is " BLUE("%s") "!\n","blue");

    return 0;
}

reading Wikipedia:

  • \x1b[0m resets all attributes
  • \x1b[31m sets foreground color to red
  • \x1b[44m would set the background to blue.
  • both : \x1b[31;44m
  • both but inversed : \x1b[31;44;7m
  • remember to reset afterwards \x1b[0m ...

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

Replace preg_replace() e modifier with preg_replace_callback

preg_replace shim with eval support

This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace function to keep your /e flag working temporarily.

/**
 * Can be used as a stopgap shim for preg_replace() calls with /e flag.
 * Is likely to fail for more complex string munging expressions. And
 * very obviously won't help with local-scope variable expressions.
 *
 * @license: CC-BY-*.*-comment-must-be-retained
 * @security: Provides `eval` support for replacement patterns. Which
 *   poses troubles for user-supplied input when paired with overly
 *   generic placeholders. This variant is only slightly stricter than
 *   the C implementation, but still susceptible to varexpression, quote
 *   breakouts and mundane exploits from unquoted capture placeholders.
 * @url: https://stackoverflow.com/q/15454220
 */
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
    # strip /e flag
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    # warn about most blatant misuses at least
    if (preg_match('/\(\.[+*]/', $pattern)) {
        trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
    }
    # run preg_replace with eval-callback
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($replacement) {
            # substitute $1/$2/… with literals from $matches[]
            $repl = preg_replace_callback(
                '/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
                function ($m) use ($matches) {
                    if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
                    return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
                },
                $replacement
            );
            # run the replacement expression
            return eval("return $repl;");
        },
        $subject,
        $limit
    );
}

In essence, you just include that function in your codebase, and edit preg_replace to preg_replace_eval wherever the /e flag was used.

Pros and cons:

  • Really just tested with a few samples from Stack Overflow.
  • Does only support the easy cases (function calls, not variable lookups).
  • Contains a few more restrictions and advisory notices.
  • Will yield dislocated and less comprehensible errors for expression failures.
  • However is still a usable temporary solution and doesn't complicate a proper transition to preg_replace_callback.
  • And the license comment is just meant to deter people from overusing or spreading this too far.

Replacement code generator

Now this is somewhat redundant. But might help those users who are still overwhelmed with manually restructuring their code to preg_replace_callback. While this is effectively more time consuming, a code generator has less trouble to expand the /e replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.

To use this function, edit any broken preg_replace call into preg_replace_eval_replacement and run it once. This will print out the according preg_replace_callback block to be used in its place.

/**
 * Use once to generate a crude preg_replace_callback() substitution. Might often
 * require additional changes in the `return …;` expression. You'll also have to
 * refit the variable names for input/output obviously.
 *
 * >>>  preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
 */
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    $replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
    $ve = "var_export";
    $bt = debug_backtrace(0, 1)[0];
    print "<pre><code>
    #----------------------------------------------------
    # replace preg_*() call in '$bt[file]' line $bt[line] with:
    #----------------------------------------------------
    \$OUTPUT_VAR = preg_replace_callback(
        {$ve($pattern, TRUE)},
        function (\$m) {
            return {$replacement};
        },
        \$YOUR_INPUT_VARIABLE_GOES_HERE
    )
    #----------------------------------------------------
    </code></pre>\n";
}

Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.

  • Specificially the $OUTPUT = assignment would have to go if the previous preg_replace call was used in an if.
  • It's best to keep temporary variables or the multiline code block structure though.

And the replacement expression may demand more readability improvements or rework.

  • For instance stripslashes() often becomes redundant in literal expressions.
  • Variable-scope lookups require a use or global reference for/within the callback.
  • Unevenly quote-enclosed "-$1-$2" capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2].

The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.

Total Number of Row Resultset getRow Method

BalusC's answer is right! but I have to mention according to the user instance variable such as:

rSet.last(); 
total = rSet.getRow();

and then which you are missing

rSet.beforeFirst();

the remaining code is same you will get your desire result.

LINQ syntax where string value is not null or empty

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077

Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL. Proposed Solution Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:

var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;

var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;

Other Reading:
1. DevArt
2. Dervalp.com
3. StackOverflow Post

Recover SVN password from local cache

For those interested in the OS X solution for apps like Intelli-J where authorizations are stored by OSX:

  1. Hit CMD+SPACE
  2. Type "keychain"
  3. Open keychain access
  4. Under "Keychains" on the left, choose "login"
  5. Under "Category" on the right, choose "All items"
  6. At the top right in the search box, type in the the host URL (e.g. svn.mycompany.com)
  7. Your keychain item will show if you chose to have your Mac remember your login credentials.
  8. Double click the item and check the "Show password" checkbox at the bottom of the dialog that pops up. You will have to enter your Mac login to reveal the password.

Much easier than having to try to decrypt a password :-)

Spark Dataframe distinguish columns with duplicated name

This might not be the best approach, but if you want to rename the duplicate columns(after join), you can do so using this tiny function.

def rename_duplicate_columns(dataframe):
    columns = dataframe.columns
    duplicate_column_indices = list(set([columns.index(col) for col in columns if columns.count(col) == 2]))
    for index in duplicate_column_indices:
        columns[index] = columns[index]+'2'
    dataframe = dataframe.toDF(*columns)
    return dataframe

How do I get PHP errors to display?

The best/easy/fast solution that you can use if it's a quick debugging, is to surround your code with catching exceptions. That's what I'm doing when I want to check something fast in production.

try {
    // Page code
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

Import/Index a JSON file into Elasticsearch

  • If you are using the elastic search 7.7 or above version then follow below command.

    curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk? pretty&refresh" --data-binary @"/Users/waseem.khan/waseem/elastic/account.json"

  • On above file path is /Users/waseem.khan/waseem/elastic/account.json.

  • If you are using elastic search 6.x version then you can use the below command.

curl -X POST localhost:9200/bank/_bulk?pretty&refresh --data-binary @"/Users/waseem.khan/waseem/elastic/account.json" -H 'Content-Type: application/json'

Note: Make sure in your .json file at the end you will add the one empty line otherwise you will be getting below exception.

"error" : {
"root_cause" : [
  {
    "type" : "illegal_argument_exception",
    "reason" : "The bulk request must be terminated by a newline [\n]"
  }
],
"type" : "illegal_argument_exception",
"reason" : "The bulk request must be terminated by a newline [\n]"
},
`enter code here`"status" : 400

Why am I getting this redefinition of class error?

You define the class gameObject in both your .cpp file and your .h file.
That is creating a redefinition error.

You should define the class, ONCE, in ONE place. (convention says the definition is in the .h, and all the implementation is in the .cpp)

Please help us understand better, what part of the error message did you have trouble with?

The first part of the error says the class has been redefined in gameObject.cpp
The second part of the error says the previous definition is in gameObject.h.

How much clearer could the message be?

How to compare DateTime in C#?

//Time compare.
private int CompareTime(string t1, string t2)
{
    TimeSpan s1 = TimeSpan.Parse(t1);
    TimeSpan s2 = TimeSpan.Parse(t2);
    return s2.CompareTo(s1);
}

Send data through routing paths in Angular

In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-

this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});

but it showing some error like below:

Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
  Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'

.

Solution: we have to write like this:

this.Router.navigate(['componentname'],{state: {customerkey:response.key}});

Create list or arrays in Windows Batch

Sometimes the array element may be very long, at that time you can create an array in this way:

set list=a
set list=%list%;b 
set list=%list%;c 
set list=%list%;d

Then show it:

@echo off
for %%a in (%list%) do ( 
 echo %%a
 echo/
)

How do I get a computer's name and IP address using VB.NET?

IP Version 4 Only ...

Imports System.Net

Module MainLine
    Sub Main()
        Dim hostName As String = Dns.GetHostName
        Console.WriteLine("Host Name: " & hostName & vbNewLine)
        Console.WriteLine("IP Version 4 Address(es):")
        For Each address In Dns.GetHostEntry(hostName).AddressList().
            Where(Function(p) p.AddressFamily = Sockets.AddressFamily.InterNetwork)
            Console.WriteLine(vbTab & address.ToString)
        Next
        Console.ReadKey()
    End Sub
End Module

Show all current locks from get_lock

Another easy way is to use:

mysqladmin debug 

This dumps a lot of information (including locks) to the error log.

When should we use Observer and Observable?

In very simple terms (because the other answers are referring you to all the official design patterns anyway, so look at them for further details):

If you want to have a class which is monitored by other classes in the ecosystem of your program you say that you want the class to be observable. I.e. there might be some changes in its state which you would want to broadcast to the rest of the program.

Now, to do this we have to call some kind of method. We don't want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn't care who it is as long as it fulfils certain criteria. (Imagine it is a radio station, it doesn't care who is listening as long as they have an FM radio tuned on their frequency). To achieve that we use an interface, referred to as the Observer.

Therefore, the Observable class will have a list of Observers (i.e. instances implementing the Observer interface methods you might have). Whenever it wants to broadcast something, it just calls the method on all the observers, one after the other.

The last thing to close the puzzle is how will the Observable class know who is interested? So the Observable class must offer some mechanism to allow Observers to register their interest. A method such as addObserver(Observer o) internally adds the Observer to the list of observers, so that when something important happens, it loops through the list and calls the respective notification method of the Observer interface of each instance in the list.

It might be that in the interview they did not ask you explicitly about the java.util.Observer and java.util.Observable but about the generic concept. The concept is a design pattern, which Java happens to provide support for directly out of the box to help you implement it quickly when you need it. So I would suggest that you understand the concept rather than the actual methods/classes (which you can look up when you need them).

UPDATE

In response to your comment, the actual java.util.Observable class offers the following facilities:

  1. Maintaining a list of java.util.Observer instances. New instances interested in being notified can be added through addObserver(Observer o), and removed through deleteObserver(Observer o).

  2. Maintaining an internal state, specifying whether the object has changed since the last notification to the observers. This is useful because it separates the part where you say that the Observable has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged(). So you just call it when you changed something to the Observable and you want the rest of the Observers to eventually know about it.

  3. Notifying all observers that the specific Observable has changed state. This is done through notifyObservers(). This checks if the object has actually changed (i.e. a call to setChanged() was made) before proceeding with the notification. There are 2 versions, one with no arguments and one with an Object argument, in case you want to pass some extra information with the notification. Internally what happens is that it just iterates through the list of Observer instances and calls the update(Observable o, Object arg) method for each of them. This tells the Observer which was the Observable object that changed (you could be observing more than one), and the extra Object arg to potentially carry some extra information (passed through notifyObservers().

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

In a nutshell, [[ is better because it doesn't fork another process. No brackets or a single bracket is slower than a double bracket because it forks another process.

finding the type of an element using jQuery

The following will return true if the element is an input:

$("#elementId").is("input") 

or you can use the following to get the name of the tag:

$("#elementId").get(0).tagName

How can I enable Assembly binding logging?

Just create a new DWORD(32) under the Fusion key. Name the DWORD to EnableLog, and set it to value 1. Then restart IIS, refresh the page giving errors, and the assembly bind logs will show in the error message.

php how to go one level up on dirname(__FILE__)

dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder

Difference between malloc and calloc?

There's no difference in the size of the memory block allocated. calloc just fills the memory block with physical all-zero-bits pattern. In practice it is often assumed that the objects located in the memory block allocated with calloc have initilial value as if they were initialized with literal 0, i.e. integers should have value of 0, floating-point variables - value of 0.0, pointers - the appropriate null-pointer value, and so on.

From the pedantic point of view though, calloc (as well as memset(..., 0, ...)) is only guaranteed to properly initialize (with zeroes) objects of type unsigned char. Everything else is not guaranteed to be properly initialized and may contain so called trap representation, which causes undefined behavior. In other words, for any type other than unsigned char the aforementioned all-zero-bits patterm might represent an illegal value, trap representation.

Later, in one of the Technical Corrigenda to C99 standard, the behavior was defined for all integer types (which makes sense). I.e. formally, in the current C language you can initialize only integer types with calloc (and memset(..., 0, ...)). Using it to initialize anything else in general case leads to undefined behavior, from the point of view of C language.

In practice, calloc works, as we all know :), but whether you'd want to use it (considering the above) is up to you. I personally prefer to avoid it completely, use malloc instead and perform my own initialization.

Finally, another important detail is that calloc is required to calculate the final block size internally, by multiplying element size by number of elements. While doing that, calloc must watch for possible arithmetic overflow. It will result in unsuccessful allocation (null pointer) if the requested block size cannot be correctly calculated. Meanwhile, your malloc version makes no attempt to watch for overflow. It will allocate some "unpredictable" amount of memory in case overflow happens.

How to create a temporary directory and get the path / file name in Python

Use the mkdtemp() function from the tempfile module:

import tempfile
import shutil

dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)

How to copy a huge table data into another table in SQL Server

I have been working with our DBA to copy an audit table with 240M rows to another database.

Using a simple select/insert created a huge tempdb file.

Using a the Import/Export wizard worked but copied 8M rows in 10min

Creating a custom SSIS package and adjusting settings copied 30M rows in 10Min

The SSIS package turned out to be the fastest and most efficent for our purposes

Earl

Tab separated values in awk

echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -v var="test" 'BEGIN { FS = "[ \t]+" } ; { print $1 "\t" var "\t" $3 }'

What is the most efficient way to deep clone an object in JavaScript?

Deep copying objects in JavaScript (I think the best and the simplest)

1. Using JSON.parse(JSON.stringify(object));

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}
var newObj = JSON.parse(JSON.stringify(obj));
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } } 

2.Using created method

function cloneObject(obj) {
    var clone = {};
    for(var i in obj) {
        if(obj[i] != null &&  typeof(obj[i])=="object")
            clone[i] = cloneObject(obj[i]);
        else
            clone[i] = obj[i];
    }
    return clone;
}

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}
var newObj = cloneObject(obj);
obj.b.c = 20;

console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } } 

3. Using Lo-Dash's _.cloneDeep link lodash

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}

var newObj = _.cloneDeep(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } } 

4. Using Object.assign() method

var obj = { 
  a: 1,
  b: 2
}

var newObj = _.clone(obj);
obj.b = 20;
console.log(obj); // { a: 1, b: 20 }
console.log(newObj); // { a: 1, b: 2 }  

BUT WRONG WHEN

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}

var newObj = Object.assign({}, obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG
// Note: Properties on the prototype chain and non-enumerable properties cannot be copied.

5.Using Underscore.js _.clone link Underscore.js

var obj = { 
  a: 1,
  b: 2
}

var newObj = _.clone(obj);
obj.b = 20;
console.log(obj); // { a: 1, b: 20 }
console.log(newObj); // { a: 1, b: 2 }  

BUT WRONG WHEN

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}

var newObj = _.cloneDeep(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG
// (Create a shallow-copied clone of the provided plain object. Any nested objects or arrays will be copied by reference, not duplicated.)

JSBEN.CH Performance Benchmarking Playground 1~3 http://jsben.ch/KVQLd Performance Deep copying objects in JavaScript

Entity Framework - Linq query with order by and group by

You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye

var groupByReference = (from m in context.Measurements
                              .GroupBy(m => m.Reference)
                              .Take(numOfEntries).AsEnumerable()
                               .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
                                             Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
                              .ThenBy(x => x.Avg)
                              .ToList() select m);

Your sql query would look similar (depending on your input) this

SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
    SELECT [t0].[Reference]
    FROM [Measurements] AS [t0]
    GROUP BY [t0].[Reference]
    ) AS [t1]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]

Kotlin: How to get and set a text to TextView in Android using Kotlin?

The top post has 'as TextView' appended on the end. You might get other compiler errors if you leave this on. The following should be fine.

val text: TextView = findViewById(R.id.android_text) as TextView

Where 'android_text' is the ID of your textView

Remove part of string after "."

You just need to escape the period:

a <- c("NM_020506.1","NM_020519.1","NM_001030297.2","NM_010281.2","NM_011419.3", "NM_053155.2")

gsub("\\..*","",a)
[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155" 

Reading values from DataTable

DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];

for (int i = 0; i < dr_art_line_2.Rows.Count; i++)
{
    QuantityInIssueUnit_value = Convert.ToInt32(dr_art_line_2.Rows[i]["columnname"]);
    //Similarly for QuantityInIssueUnit_uom.
}

How to use a table type in a SELECT FROM statement?

In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;

In package body:

initialize the table in declarations:

exch_rt exch_tbl := exch_tbl();

in order to add record to the local collection, in begin - end block you can do:

exch_rt.extend;
                                one_row.exch_rt_usd := 2;
                                one_row.exch_rt_eur := 1;
                                one_row.currency_cd := 'dollar';
                                exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop 

in order to get data from this table , inside package body you can use:

select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)

enjoy!

P.S. sorry for a late answer :D

Best Practices: working with long, multiline strings in PHP?

you can also use:

<?php
ob_start();
echo "some text";
echo "\n";

// you can also use: 
?> 
some text can be also written here, or maybe HTML:
<div>whatever<\div>
<?php
echo "you can basically write whatever you want";
// and then: 
$long_text = ob_get_clean();

html button to send email

This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...

HTML:

<form id="fr1">
    <input type="text" id="tb1" />
    <input type="text" id="tb2" />
    <input type="button" id="bt1" value="click" />
</form>

JavaScript (with jQuery):

$(document).ready(function() {
    $('#bt1').click(function() {
        $('#fr1').attr('action',
                       'mailto:[email protected]?subject=' +
                       $('#tb1').val() + '&body=' + $('#tb2').val());
        $('#fr1').submit();
    });
});

Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit type, it's just a button type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.

It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.

HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.

Showing Difference between two datetime values in hours

I think you're confused because you haven't declared a TimeSpan you've declared a TimeSpan? which is a nullable TimeSpan. Either remove the question mark if you don't need it to be nullable or use variable.Value.TotalHours.

How to get the connection String from a database

If one uses the tool Linqpad, after one connects to a target database from the connections one can get a connection string to use.

  1. Right click on the database connection.
  2. Select Properties
  3. Select Advanced
  4. Select Copy Full Connection String to Clipboard

Result: Data Source=.\jabberwocky;Integrated Security=SSPI;Initial Catalog=Rasa;app=LINQPad

enter image description here


Remove the app=LinqPad depending on the drivers and other items such as Server instead of source, you may need to adjust the driver to suit the target operation; but it gives one a launching pad.

How can I implement prepend and append with regular JavaScript?

You can also use unshift() to prepend to a list

How to print strings with line breaks in java

private static final String mText = "SHOP MA" + "\n" +
        + "----------------------------" + "\n" +
        + "Pannampitiya" + newline +
        + "09-10-2012 harsha  no: 001" + "\n" +
        + "No  Item  Qty  Price  Amount" + "\n" +
        + "1 Bread 1 50.00  50.00" + "\n" +
        + "____________________________" + "\n";

This should work.

Counting the number of files in a directory using Java

Unfortunately, I believe that is already the best way (although list() is slightly better than listFiles(), since it doesn't construct File objects).

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

Child element click event trigger the parent click event

Without jQuery : DEMO

 <div id="parentDiv" onclick="alert('parentDiv');">
   <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
     AAA
   </div>   
</div>

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Do the following:

Dim dataTable1 As New DataTable
                dataTable1.Columns.Add("FECHA")
                dataTable1.Columns.Add("TT")
                dataTable1.Columns.Add("DESCRIPCION")
                dataTable1.Columns.Add("No. DOC")
                dataTable1.Columns.Add("DEBE")
                dataTable1.Columns.Add("HABER")
                dataTable1.Columns.Add("SALDO")

For Each line As String In System.IO.File.ReadAllLines(objetos.url)
                    dataTable1.Rows.Add(line.Split(","))
                Next

npm - EPERM: operation not permitted on Windows

For me, It was an issue with the .npmrc file. Which is present in C:\Users\myname.npmrc Somehow the content of .npmrc file got changed. I have changed the content by comparing with my colleagues laptop. So it solved.

For reference, I am adding the content of .npmrc file too

 ;;;;
 ;npm userconfig file
 ;this is a simple ini-formatted file
 ;lines that start with semi-colons are comments.
 ;read `npm help config` for help on the various options
 ;;;;

 //registry.npmjs.org/:_authToken=95632bcf-3056-4538-b57d-38426736e3a0
 scope=true
 @true:registry=https://registry.npmjs.org/

 ;;;;
 ;all options with default values
 ;;;;
 ;access=null

 ;allow-same-version=false

 ;always-auth=false

 ;also=null

 ;audit=true

 ;audit-level=low

 ;auth-type=legacy

 ;before=null

 ;bin-links=true

 ;browser=null

 ;ca=null

 ;cafile=undefined

 ;cache=C:\Users\myname\AppData\Roaming\npm-cache

 ;cache-lock-stale=60000

 ;cache-lock-retries=10

 ;cache-lock-wait=10000

 ;cache-max=null

 ;cache-min=10

 ;cert=null

 ;cidr=null

 ;color=true

 ;depth=null

 ;description=true

 ;dev=false

 ;dry-run=false

 ;editor=notepad.exe

 ;engine-strict=false

 ;force=false

 ;fetch-retries=2

 ;fetch-retry-factor=10

 ;fetch-retry-mintimeout=10000

 ;fetch-retry-maxtimeout=60000

 ;git=git

 ;git-tag-version=true

 ;commit-hooks=true

 ;global=false

 ;globalconfig=C:\Users\myname\AppData\Roaming\npm\etc\npmrc

 ;global-style=false

 ;group=0

 ;ham-it-up=false

 ;heading=npm

 ;if-present=false

 ;ignore-prepublish=false

 ;ignore-scripts=false

 ;init-module=C:\Users\myname\.npm-init.js

 ;init-author-name=

 ;init-author-email=

 ;init-author-url=

 ;init-version=1.0.0

 ;init-license=ISC

 ;json=false

 ;key=null

 ;legacy-bundling=false

 ;link=false

 ;local-address=undefined

 ;loglevel=notice

 ;logs-max=10

 ;long=false

 ;maxsockets=50

 ;message=%s

 ;metrics-registry=null

 ;node-options=null

 ;node-version=10.15.2

 ;offline=false

 ;onload-script=null

 ;only=null

 ;optional=true

 ;otp=null

 ;package-lock=true

 ;package-lock-only=false

 ;parseable=false

 ;prefer-offline=false

 ;prefer-online=false

 ;prefix=C:\Program Files\nodejs

 ;preid=

 ;production=false

 ;progress=true

 ;proxy=null

 ;https-proxy=null

 ;noproxy=null

 ;user-agent=npm/{npm-version} node/{node-version} {platform} {arch}

 ;read-only=false

 ;rebuild-bundle=true

 ;registry=https://registry.npmjs.org/

 ;rollback=true

 ;save=true

 ;save-bundle=false

 ;save-dev=false

 ;save-exact=false

 ;save-optional=false

 ;save-prefix=^

 ;save-prod=false

 ;scope=

 ;script-shell=null

 ;scripts-prepend-node-path=warn-only

 ;searchopts=

 ;searchexclude=null

 ;searchlimit=20

 ;searchstaleness=900

 ;send-metrics=false

 ;shell=C:\windows\system32\cmd.exe

 ;shrinkwrap=true

 ;sign-git-commit=false

 ;sign-git-tag=false

 ;sso-poll-frequency=500

 ;sso-type=oauth

 ;strict-ssl=true

 ;tag=latest

 ;tag-version-prefix=v

 ;timing=false

 ;tmp=C:\Users\myname\AppData\Local\Temp

 ;unicode=false

 ;unsafe-perm=true

 ;update-notifier=true

 ;usage=false

 ;user=0

 ;userconfig=C:\Users\myname\.npmrc

 ;umask=0

 ;version=false

 ;versions=false

 ;viewer=browser

 ;_exit=true

 ;globalignorefile=C:\Users\myname\AppData\Roaming\npm\etc\npmignore

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

Compatible with all SDK versions (android.permission.ACCESS_FINE_LOCATION became dangerous permission in Android M and requires user to manually grant it).

In Android versions below Android M ContextCompat.checkSelfPermission(...) always returns true if you add these permission(s) in AndroidManifest.xml)

public void onSomeButtonClick() {
    ...
    if (!permissionsGranted()) {
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
    } else doLocationAccessRelatedJob();
    ...
}

private Boolean permissionsGranted() {
    return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 123) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted.
            doLocationAccessRelatedJob();
        } else {
            // User refused to grant permission. You can add AlertDialog here
            Toast.makeText(this, "You didn't give permission to access device location", Toast.LENGTH_LONG).show();
            startInstalledAppDetailsActivity();
        }
    }
}

private void startInstalledAppDetailsActivity() {
    Intent i = new Intent();
    i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    i.addCategory(Intent.CATEGORY_DEFAULT);
    i.setData(Uri.parse("package:" + getPackageName()));
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}

in AndroidManifest.xml:

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

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

I've also seen this error in solutions where I have multiple projects (usually netTiers projects where I've updated one or more of the sub-projects to target the 4.0 framework). It can be problematic to remove. Oftentimes it can be resolved, however, by first fixing all other errors in sub-projects (eg, any missing references), individually rebuilding those sub-projects, then removing/adding back any references to those sub-projects in Visual Studio. Personally, I've had little luck resolving this error by cleaning the solution alone.

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

Try installing the 32 bit version of Java 6. This works for version Install4J 4.0.5. Should fire right up, or allow you to re-run the installer.

Any newer version or the 64-bit version of 6 will fail, complaining that the java.exe is damaged.

How to do a num_rows() on COUNT query in codeigniter?

This will only return 1 row, because you're just selecting a COUNT(). you will use mysql_num_rows() on the $query in this case.

If you want to get a count of each of the ID's, add GROUP BY id to the end of the string.

Performance-wise, don't ever ever ever use * in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *. This is because * has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.

Vue v-on:click does not work on component

From the documentation:

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
  2. When you modify the length of the array, e.g. vm.items.length = newLength

In my case i stumbled on this problem when migrating from Angular to VUE. Fix was quite easy, but really difficult to find:

setValue(index) {
    Vue.set(this.arr, index, !this.arr[index]);
    this.$forceUpdate(); // Needed to force view rerendering
}

Can two applications listen to the same port?

Yes Definitely. As far as i remember From kernel version 3.9 (Not sure on the version) onwards support for the SO_REUSEPORT was introduced. SO_RESUEPORT allows binding to the exact same port and address, As long as the first server sets this option before binding its socket.

It works for both TCP and UDP. Refer to the link for more details: SO_REUSEPORT

Note: Accepted answer no longer holds true as per my opinion.

Android Overriding onBackPressed()

Override the onBackPressed() method as per the example by codeMagic, and remove the call to super.onBackPressed(); if you do not want the default action (finishing the current activity) to be executed.

Traverse all the Nodes of a JSON Object Tree with JavaScript

             var localdata = [{''}]// Your json array
              for (var j = 0; j < localdata.length; j++) 
               {$(localdata).each(function(index,item)
                {
                 $('#tbl').append('<tr><td>' + item.FirstName +'</td></tr>);
                 }

How to set up Spark on Windows?

You can use following ways to setup Spark:

  • Building from Source
  • Using prebuilt release

Though there are various ways to build Spark from Source.
First I tried building Spark source with SBT but that requires hadoop. To avoid those issues, I used pre-built release.

Instead of Source,I downloaded Prebuilt release for hadoop 2.x version and ran it. For this you need to install Scala as prerequisite.

I have collated all steps here :
How to run Apache Spark on Windows7 in standalone mode

Hope it'll help you..!!!

How to style the parent element when hovering a child element?

Well, this question is asked many times before, and the short typical answer is: It cannot be done by pure CSS. It's in the name: Cascading Style Sheets only supports styling in cascading direction, not up.

But in most circumstances where this effect is wished, like in the given example, there still is the possibility to use these cascading characteristics to reach the desired effect. Consider this pseudo markup:

<parent>
    <sibling></sibling>
    <child></child>
</parent>

The trick is to give the sibling the same size and position as the parent and to style the sibling instead of the parent. This will look like the parent is styled!

Now, how to style the sibling?

When the child is hovered, the parent is too, but the sibling is not. The same goes for the sibling. This concludes in three possible CSS selector paths for styling the sibling:

parent sibling { }
parent sibling:hover { }
parent:hover sibling { }

These different paths allow for some nice possibilities. For instance, unleashing this trick on the example in the question results in this fiddle:

div {position: relative}
div:hover {background: salmon}
div p:hover {background: white}
div p {padding-bottom: 26px}
div button {position: absolute; bottom: 0}

Style parent image example

Obviously, in most cases this trick depends on the use of absolute positioning to give the sibling the same size as the parent, ánd still let the child appear within the parent.

Sometimes it is necessary to use a more qualified selector path in order to select a specific element, as shown in this fiddle which implements the trick multiple times in a tree menu. Quite nice really.

Aesthetics must either be length one, or the same length as the dataProblems

I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:

ggplot(df, aes(x="", y = y, fill=grp))

because df was empty.

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

Jquery change <p> text programmatically

"saving" is something wholly different from changing paragraph content with jquery.

If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").

Judging by your question, this is a topic on which you will have to do MUCH more research.

Input page (input.html):

<form action="/saveMyParagraph.php">
    <input name="pContent" type="text"></input>
</form>

Saving page (saveMyParagraph.php) and Ouput page (output.php):

Inserting Data Into a MySQL Database using PHP

List to array conversion to use ravel() function

I wanted a way to do this without using an extra module. First turn list to string, then append to an array:

dataset_list = ''.join(input_list)
dataset_array = []
for item in dataset_list.split(';'): # comma, or other
    dataset_array.append(item)

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

For the people like myself, who started recently: The loaders keyword is replaced with rules; even though it still represents the concept of loaders. So my webpack.config.js, for a React app, is as follows:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');

var config = {
  entry: APP_DIR + '/index.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  module : {
    rules : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        loader : 'babel-loader'
      }
    ]
  }
};

module.exports = config;

How permission can be checked at runtime without throwing SecurityException?

Like Google documentation:

// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

C# list.Orderby descending

Sure:

var newList = list.OrderByDescending(x => x.Product.Name).ToList();

Doc: OrderByDescending(IEnumerable, Func).

In response to your comment:

var newList = list.OrderByDescending(x => x.Product.Name)
                  .ThenBy(x => x.Product.Price)
                  .ToList();

Javascript change font color

Html code

<div id="coloredBy">
    Colored By Santa
</div>

javascript code

document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff

I think this is very easy to use

How to get on scroll events?

// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {
  ...
}

or

<div (scroll)="onScroll($event)"></div>

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

Try it like,

<?php 
    $name='your name';
    echo '<table>
       <tr><th>Name</th></tr>
       <tr><td>'.$name.'</td></tr>
    </table>';
?>

Updated

<?php 
    echo '<table>
       <tr><th>Rst</th><th>Marks</th></tr>
       <tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
    </table>';
?>

How to show full column content in a Spark Dataframe?

results.show(false) will show you the full column content.

Show method by default limit to 20, and adding a number before false will show more rows.

Parallel foreach with asynchronous lambda

You can use the ParallelForEachAsync extension method from AsyncEnumerator NuGet Package:

using Dasync.Collections;

var bag = new ConcurrentBag<object>();
await myCollection.ParallelForEachAsync(async item =>
{
  // some pre stuff
  var response = await GetData(item);
  bag.Add(response);
  // some post stuff
}, maxDegreeOfParallelism: 10);
var count = bag.Count;

How to print the contents of RDD?

There are probably many architectural differences between myRDD.foreach(println) and myRDD.collect().foreach(println) (not only 'collect', but also other actions). One the differences I saw is when doing myRDD.foreach(println), the output will be in a random order. For ex: if my rdd is coming from a text file where each line has a number, the output will have a different order. But when I did myRDD.collect().foreach(println), order remains just like the text file.

Error inflating class android.support.v7.widget.Toolbar?

The solution to the problem for me was found in the XML document for my Main Activity. Originally my toolbar was <android.support.v7.widget.Toolbar. To resolve this I changed it to <android.widget.Toolbar. I do not know why this worked though. Does anyone have any insight as to why?

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

How do I encode and decode a base64 string?

A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:

using System;

namespace Service.Support
{
    public static class Base64
    {
        public static string ToBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return Convert.ToBase64String(textAsBytes);
        }

        public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
        {
            if (encodedText == null)
            {
                decodedText = null;
                return false;
            }

            try
            {
                byte[] textAsBytes = Convert.FromBase64String(encodedText);
                decodedText = encoding.GetString(textAsBytes);
                return true;
            }
            catch (Exception)
            {
                decodedText = null;
                return false;   
            }
        }
    }
}

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

For all those still affected by this.

I've been getting the error...

OLEDB error "The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine."

...as described by the OP, Shailesh Sahu.

I have 64bit Windows 7.

My problem is within PowerShell scripts, but is using a connection string, similar to the OP's post, so hopefully my findings can be applied to C#, PowerShell and any other language relying on the "Microsoft.ACE.OLEDB" driver.

I followed instructions on this MS forum thread: http://goo.gl/h73RmI

I first tried installing the 64bit version, then installing the 32bit version of the AccessDatabaseEngine.exe from this page http://www.microsoft.com/en-us/download/details.aspx?id=13255

But still no joy.

I then ran the code below in PowerShell (from SQL Panda's site http://goo.gl/A3Hu96)

(New-Object system.data.oledb.oledbenumerator).GetElements() | select SOURCES_NAME, SOURCES_DESCRIPTION 

...which gave me this result (I've removed other data sources for brevity)...

SOURCES_NAME              SOURCES_DESCRIPTION                                                                       
------------              -------------------                                                                       
Microsoft.ACE.OLEDB.15.0  Microsoft Office 15.0 Access Database Engine OLE DB Provider

As you can see, I have Microsoft.ACE.OLEDB.15.0 (fifteen) not Microsoft.ACE.OLEDB.12.0 (twelve)

So, I amended my connection string to 15 and it worked.

So, a quick PowerShell snippet to demonstrate how to soft-code the version...

$AceVersion = ((New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Where-Object { $_.SOURCES_NAME -like "Microsoft.ACE.OLEDB*" } | Sort-Object SOURCES_NAME -Descending | Select-Object -First 1 SOURCES_NAME).SOURCES_NAME

$connString = "Provider=$AceVersion;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=NO`";"

amended to pick the latest ACE version, if more than one

Hopefully, anyone finding this can now check to see what OLEDB version is installed and use the appropriate version number.

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

Still Reachable Leak detected by Valgrind

Here is a proper explanation of "still reachable":

"Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.

Local variables that are assigned allocations and not free'd are almost always leaks.

Here is an example

int foo(void)
{
    static char *working_buf = NULL;
    char *temp_buf;
    if (!working_buf) {
         working_buf = (char *) malloc(16 * 1024);
    }
    temp_buf = (char *) malloc(5 * 1024);

    ....
    ....
    ....

}

Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".

How do I iterate over a JSON structure?

mootools example:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});

How to write UTF-8 in a CSV file

A very simple hack is to use the json import instead of csv. For example instead of csv.writer just do the following:

    fd = codecs.open(tempfilename, 'wb', 'utf-8')  
    for c in whatever :
        fd.write( json.dumps(c) [1:-1] )   # json dumps writes ["a",..]
        fd.write('\n')
    fd.close()

Basically, given the list of fields in correct order, the json formatted string is identical to a csv line except for [ and ] at the start and end respectively. And json seems to be robust to utf-8 in python 2.*

javascript: calculate x% of a number

var result = (35.8 / 100) * 10000;

(Thank you jball for this change of order of operations. I didn't consider it).

How to play YouTube video in my Android application?

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watchv=cxLG2wtE7TM"));
startActivity(intent);

Including non-Python files with setup.py

Figured out a workaround: I renamed my lgpl2.1_license.txt to lgpl2.1_license.txt.py, and put some triple quotes around the text. Now I don't need to use the data_files option nor to specify any absolute paths. Making it a Python module is ugly, I know, but I consider it less ugly than specifying absolute paths.

CSS Float: Floating an image to the left of the text

Just need to float both elements left:

.post-container{
    margin: 20px 20px 0 0;  
    border:5px solid #333;
}

.post-thumb img {
    float: left;
}

.post-content {
    float: left;
}

Edit: actually, you do not need the width, just float both left

Wrap long lines in Python

I'm surprised no one mentioned the implicit style above. My preference is to use parens to wrap the string while lining the string lines up visually. Personally I think this looks cleaner and more compact than starting the beginning of the string on a tabbed new line.

Note that these parens are not part of a method call — they're only implicit string literal concatenation.

Python 2:

def fun():
    print ('{0} Here is a really '
           'long sentence with {1}').format(3, 5)

Python 3 (with parens for print function):

def fun():
    print(('{0} Here is a really '
           'long sentence with {1}').format(3, 5))

Personally I think it's cleanest to separate concatenating the long string literal from printing it:

def fun():
    s = ('{0} Here is a really '
         'long sentence with {1}').format(3, 5)
    print(s)

Return JSON for ResponseEntity<String>

public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
    JSONObject resp = new JSONObject();
    resp.put("status", 0);
    resp.put("id", id);

    return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}

How to create a popup windows in javafx

Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

How do I specify the JDK for a GlassFish domain?

Adding the actual content from dbf's link in order to keep the solution within stackoverflow.

It turns out that when I first installed Glassfish on my Windows system I had JDK 6 installed, and recently I had to downgrade to JDK 5 to compile some code for another project.

Apparently when Glassfish is installed it hard-codes its reference to your JDK location, so to fix this problem I ended up having to edit a file named asenv.bat. In short, I edited this file:

C:\glassfish\config\asenv.bat:

and I commented out the reference to JDK 6 and added a new reference to JDK 5, like this:

REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16

Although the path doesn't appear to be case sensitive, I've spent hours debugging an issue around JMS Destination object not found due to my replacement path's case being incorrect.

Anonymous method in Invoke call

I like to use Action in place of MethodInvoker, it is shorter and looks cleaner.

Invoke((Action)(() => {
    DoSomething();
}));

// OR

Invoke((Action)delegate {
    DoSomething();
});

Eg.

// Thread-safe update on a form control
public void DisplayResult(string text){
    if (txtResult.InvokeRequired){
        txtResult.Invoke((Action)delegate {
            DisplayResult(text);
        });
        return;
    }

    txtResult.Text += text + "\r\n";
}

How do I start PowerShell from Windows Explorer?

New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
if(-not (Test-Path -Path "HKCR:\Directory\shell\$KeyName"))
{
    Try
    {
        New-Item -itemType String "HKCR:\Directory\shell\$KeyName" -value "Open PowerShell in this Folder" -ErrorAction Stop
        New-Item -itemType String "HKCR:\Directory\shell\$KeyName\command" -value "$env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command Set-Location '%V'" -ErrorAction Stop
        Write-Host "Successfully!"
     }
     Catch
     {
         Write-Error $_.Exception.Message
     }
}
else
{
    Write-Warning "The specified key name already exists. Type another name and try again."
}

You can download detail script from how to start PowerShell from Windows Explorer

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

How to detect DataGridView CheckBox event change?

I have found a simpler answer to this problem. I simply use reverse logic. The code is in VB but it is not much different than C#.

 Private Sub DataGridView1_CellContentClick(sender As Object, e As 
 DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick

    Dim _ColumnIndex As Integer = e.ColumnIndex
    Dim _RowIndex As Integer = e.RowIndex

    'Uses reverse logic for current cell because checkbox checked occures 
     'after click
    'If you know current state is False then logic dictates that a click 
     'event will set it true
    'With these 2 check boxes only one can be true while both can be off

    If DataGridView1.Rows(_RowIndex).Cells("Column2").Value = False And 
       DataGridView1.Rows(_RowIndex).Cells("Column3").Value = True Then
        DataGridView1.Rows(_RowIndex).Cells("Column3").Value = False
    End If

    If DataGridView1.Rows(_RowIndex).Cells("Column3").Value = False And 
    DataGridView1.Rows(_RowIndex).Cells("Column2").Value = True Then
        DataGridView1.Rows(_RowIndex).Cells("Column2").Value = False
    End If


End Sub

One of the best things about this is no need for multiple events.

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob
WHERE NOT EXISTS (
    SELECT *
    FROM files
    WHERE id=blob.id
)

How to remove item from list in C#?

You don't specify what kind of list, but the generic List can use either the RemoveAt(index) method, or the Remove(obj) method:

// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);

// RemoveAt(index)
resultList.RemoveAt(1);

How to get first element in a list of tuples?

This is what operator.itemgetter is for.

>>> a = [(1, u'abc'), (2, u'def')]
>>> import operator
>>> b = map(operator.itemgetter(0), a)
>>> b
[1, 2]

The itemgetter statement returns a function that returns the index of the element you specify. It's exactly the same as writing

>>> b = map(lambda x: x[0], a)

But I find that itemgetter is a clearer and more explicit.

This is handy for making compact sort statements. For example,

>>> c = sorted(a, key=operator.itemgetter(0), reverse=True)
>>> c
[(2, u'def'), (1, u'abc')]

how to sync windows time from a ntp time server in command

If you just need to resync windows time, open an elevated command prompt and type:

w32tm /resync

C:\WINDOWS\system32>w32tm /resync 
Sending resync command to local computer 
The command completed successfully.

Port 443 in use by "Unable to open process" with PID 4

Similarly, I experienced this: Port 443 in use by "Unable to open process" with PID 6012! When starting XAMPP Control Panel v3.2.1 for the first time.

In Task Manager I found that PID 6012 was Apache web server. A copy of it was running in the background without the GUI, and when I invoked the GUI it was trying to start another copy. Killed the phantom copy and then XAMPP started up fine.

I didn't have to change any port settings.

How to convert enum names to string in c

I usually do this:

#define COLOR_STR(color)                            \
    (RED       == color ? "red"    :                \
     (BLUE     == color ? "blue"   :                \
      (GREEN   == color ? "green"  :                \
       (YELLOW == color ? "yellow" : "unknown"))))   

How do you express binary literals in Python?

I've tried this in Python 3.6.9

Convert Binary to Decimal

>>> 0b101111
47

>>> int('101111',2)
47

Convert Decimal to binary

>>> bin(47)
'0b101111'

Place a 0 as the second parameter python assumes it as decimal.

>>> int('101111',0)
101111

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

Make scrollbars only visible when a Div is hovered over?

Answer by @Calvin Froedge is the shortest answer but have an issue also mentioned by @kizu. Due to inconsistent width of the div the div will flick on hover. To solve this issue add minus margin to the right on hover

#div { 
     overflow:hidden;
     height:whatever px; 
}
#div:hover { 
     overflow-y:scroll; 
     margin-right: -15px; // adjust according to scrollbar width  
}

VBA macro that search for file in multiple subfolders

This sub will populate a Collection with all files matching the filename or pattern you pass in.

Sub GetFiles(StartFolder As String, Pattern As String, _
             DoSubfolders As Boolean, ByRef colFiles As Collection)

    Dim f As String, sf As String, subF As New Collection, s
    
    If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
    
    f = Dir(StartFolder & Pattern)
    Do While Len(f) > 0
        colFiles.Add StartFolder & f
        f = Dir()
    Loop
    
    If DoSubfolders then
        sf = Dir(StartFolder, vbDirectory)
        Do While Len(sf) > 0
            If sf <> "." And sf <> ".." Then
                If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
                        subF.Add StartFolder & sf
                End If
            End If
            sf = Dir()
        Loop
    
        For Each s In subF
            GetFiles CStr(s), Pattern, True, colFiles
        Next s
    End If

End Sub

Usage:

Dim colFiles As New Collection

GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
    'work with found files
End If

Carriage return and Line feed... Are both required in C#?

A carriage return \r moves the cursor to the beginning of the current line. A newline \n causes a drop to the next line and possibly the beginning of the next line; That's the platform dependent part that Alexei notes above (on a *nix system \n gives you both a carriage return and a newline, in windows it doesn't)

What you use depends on what you're trying to do. If I wanted to make a little spinning thing on a console I would do str = "|\r/\r-\r\\\r"; for example.

Get the decimal part from a double

the best of the best way is:

var floatNumber = 12.5523;

var x = floatNumber - Math.Truncate(floatNumber);

result you can convert however you like

How can I get my webapp's base URL in ASP.NET MVC?

In Code:

Url.Content("~/");

MVC3 Razor Syntax:

@Url.Content("~/")

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
    // ... 
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
  // \o/
}

Can't find System.Windows.Media namespace?

Add PresentationCore.dll to your references. This dll url in my pc - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\PresentationCore.dll

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can't solve it. Simply answer1.sum()==0, and you can't perform a division by zero.

This happens because answer1 is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.

nan is returned in this case because of the division by zero.

Now to solve your problem you could:

  • go for a library for high-precision mathematics, like mpmath. But that's less fun.
  • as an alternative to a bigger weapon, do some math manipulation, as detailed below.
  • go for a tailored scipy/numpy function that does exactly what you want! Check out @Warren Weckesser answer.

Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:

exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
                = exp(log(exp(-x)*[1+exp(-y+x)]))
                = exp(log(exp(-x) + log(1+exp(-y+x)))
                = exp(-x + log(1+exp(-y+x)))

where above x=3* 1089 and y=3* 1093. Now, the argument of this exponential is

-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06

For the denominator you could proceed similarly but obtain that log(1+exp(-z+k)) is already rounded to 0, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000. You then have that your result is

exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x)) 
                                   = exp(-266.99999385580668)

which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089 in the numerator and the first number 1000 at the denominator):

exp(3*(1089-1000))=exp(-267)

For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):

Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523

The difference between this number and the exponent above is +1.7053025658242404e-13, so the approximation we made at the denominator was fine.

The final result is

'exp(-266.99999385580668) = 1.1050349147204485e-116

From wolfram alpha is (link)

1.105034914720621496.. × 10^-116 # Wolfram alpha.

and again, it is safe to use numpy here too.

How to filter files when using scp to copy dir recursively?

There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:

rsync -av --exclude '*.svn' user@server:/my/dir .

(this line copy rsync from distant folder to current one)

Recent versions of rsync tunnel over an ssh connection automatically by default.

How to compile without warnings being treated as errors?

Solution:

CFLAGS=-Wno-error ./configure

Embed YouTube Video with No Ads

For whom can help, nowadays in 2018, youtube have options for this:

(Example in Catalan, sorry :)

enter image description here

Translation of the 3 arrows : "Share" - "Embed" - "Show suggested videos when the video is finished"

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

This is basically the same solution as @andy-wilkinson provided, but as of Spring Boot 1.0 the customize(...) method has a ConfigurableEmbeddedServletContainer parameter.

Another thing that is worth mentioning is that Tomcat only compresses content types of text/html, text/xml and text/plain by default. Below is an example that supports compression of application/json as well:

@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
    return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer servletContainer) {
            ((TomcatEmbeddedServletContainerFactory) servletContainer).addConnectorCustomizers(
                    new TomcatConnectorCustomizer() {
                        @Override
                        public void customize(Connector connector) {
                            AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
                            httpProtocol.setCompression("on");
                            httpProtocol.setCompressionMinSize(256);
                            String mimeTypes = httpProtocol.getCompressableMimeTypes();
                            String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE;
                            httpProtocol.setCompressableMimeTypes(mimeTypesWithJson);
                        }
                    }
            );
        }
    };
}

Making RGB color in Xcode

Color picker plugin for Interface Builder

There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/

Xcode plugin

This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go

Objective-C

UIColor *color = [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0];

Swift

let color = UIColor(red: 160/255, green: 97/255, blue: 5/255, alpha: 1.0)

Pods and libraries

There's a nice pod named MPColorTools: https://github.com/marzapower/MPColorTools

Split string by single spaces

You could used simple strtok() function (*)From here. Note that tokens are created on delimiters

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This is a string";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

How to get the background color of an HTML element?

With jQuery:

jQuery('#myDivID').css("background-color");

With prototype:

$('myDivID').getStyle('backgroundColor'); 

With pure JS:

document.getElementById("myDivID").style.backgroundColor

How to count the number of set bits in a 32-bit integer?

There are many algorithm to count the set bits; but i think the best one is the faster one! You can see the detailed on this page:

Bit Twiddling Hacks

I suggest this one:

Counting bits set in 14, 24, or 32-bit words using 64-bit instructions

unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v

// option 1, for at most 14-bit values in v:
c = (v * 0x200040008001ULL & 0x111111111111111ULL) % 0xf;

// option 2, for at most 24-bit values in v:
c =  ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) 
     % 0x1f;

// option 3, for at most 32-bit values in v:
c =  ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) % 
     0x1f;
c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;

This method requires a 64-bit CPU with fast modulus division to be efficient. The first option takes only 3 operations; the second option takes 10; and the third option takes 15.

AlertDialog.Builder with custom layout and EditText; cannot access view

editText is a part of alertDialog layout so Just access editText with reference of alertDialog

EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);

Update:

Because in code line dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));

inflater is Null.

update your code like below, and try to understand the each code line

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);

EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Update 2:

As you are using View object created by Inflater to update UI components else you can directly use setView(int layourResId) method of AlertDialog.Builder class, which is available from API 21 and onwards.

How to delete a file from SD card?

Recursively delete all children of the file ...

public static void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) {
        for (File child : fileOrDirectory.listFiles()) {
            DeleteRecursive(child);
        }
    }

    fileOrDirectory.delete();
}

What is the maximum length of a table name in Oracle?

Teach a man to fish

Notice the data-type and size

>describe all_tab_columns

VIEW all_tab_columns

Name                                      Null?    Type                        
 ----------------------------------------- -------- ----------------------------
 OWNER                                     NOT NULL VARCHAR2(30)                
 TABLE_NAME                                NOT NULL VARCHAR2(30)                
 COLUMN_NAME                               NOT NULL VARCHAR2(30)                
 DATA_TYPE                                          VARCHAR2(106)               
 DATA_TYPE_MOD                                      VARCHAR2(3)                 
 DATA_TYPE_OWNER                                    VARCHAR2(30)                
 DATA_LENGTH                               NOT NULL NUMBER                      
 DATA_PRECISION                                     NUMBER                      
 DATA_SCALE                                         NUMBER                      
 NULLABLE                                           VARCHAR2(1)                 
 COLUMN_ID                                          NUMBER                      
 DEFAULT_LENGTH                                     NUMBER                      
 DATA_DEFAULT                                       LONG                        
 NUM_DISTINCT                                       NUMBER                      
 LOW_VALUE                                          RAW(32)                     
 HIGH_VALUE                                         RAW(32)                     
 DENSITY                                            NUMBER                      
 NUM_NULLS                                          NUMBER                      
 NUM_BUCKETS                                        NUMBER                      
 LAST_ANALYZED                                      DATE                        
 SAMPLE_SIZE                                        NUMBER                      
 CHARACTER_SET_NAME                                 VARCHAR2(44)                
 CHAR_COL_DECL_LENGTH                               NUMBER                      
 GLOBAL_STATS                                       VARCHAR2(3)                 
 USER_STATS                                         VARCHAR2(3)                 
 AVG_COL_LEN                                        NUMBER                      
 CHAR_LENGTH                                        NUMBER                      
 CHAR_USED                                          VARCHAR2(1)                 
 V80_FMT_IMAGE                                      VARCHAR2(3)                 
 DATA_UPGRADED                                      VARCHAR2(3)                 
 HISTOGRAM                                          VARCHAR2(15)                

Changing column names of a data frame

The error is caused by the "smart-quotes" (or whatever they're called). The lesson here is, "don't write your code in an 'editor' that converts quotes to smart-quotes".

names(newprice)[1]<-paste(“premium”)  # error
names(newprice)[1]<-paste("premium")  # works

Also, you don't need paste("premium") (the call to paste is redundant) and it's a good idea to put spaces around <- to avoid confusion (e.g. x <- -10; if(x<-3) "hi" else "bye"; x).

Combining two expressions (Expression<Func<T, bool>>)

Well, you can use Expression.AndAlso / OrElse etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression in expr1 and expr2? If so, it is easier:

var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]);

This also works well to negate a single operation:

static Expression<Func<T, bool>> Not<T>(
    this Expression<Func<T, bool>> expr)
{
    return Expression.Lambda<Func<T, bool>>(
        Expression.Not(expr.Body), expr.Parameters[0]);
}

Otherwise, depending on the LINQ provider, you might be able to combine them with Invoke:

// OrElse is very similar...
static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> left,
    Expression<Func<T, bool>> right)
{
    var param = Expression.Parameter(typeof(T), "x");
    var body = Expression.AndAlso(
            Expression.Invoke(left, param),
            Expression.Invoke(right, param)
        );
    var lambda = Expression.Lambda<Func<T, bool>>(body, param);
    return lambda;
}

Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for Invoke, but it is quite lengthy (and I can't remember where I left it...)


Generalized version that picks the simplest route:

static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> expr1,
    Expression<Func<T, bool>> expr2)
{
    // need to detect whether they use the same
    // parameter instance; if not, they need fixing
    ParameterExpression param = expr1.Parameters[0];
    if (ReferenceEquals(param, expr2.Parameters[0]))
    {
        // simple version
        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(expr1.Body, expr2.Body), param);
    }
    // otherwise, keep expr1 "as is" and invoke expr2
    return Expression.Lambda<Func<T, bool>>(
        Expression.AndAlso(
            expr1.Body,
            Expression.Invoke(expr2, param)), param);
}

Starting from .NET 4.0, there is the ExpressionVisitor class which allows you to build expressions that are EF safe.

    public static Expression<Func<T, bool>> AndAlso<T>(
        this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var parameter = Expression.Parameter(typeof (T));

        var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
        var left = leftVisitor.Visit(expr1.Body);

        var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
        var right = rightVisitor.Visit(expr2.Body);

        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(left, right), parameter);
    }



    private class ReplaceExpressionVisitor
        : ExpressionVisitor
    {
        private readonly Expression _oldValue;
        private readonly Expression _newValue;

        public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
        {
            _oldValue = oldValue;
            _newValue = newValue;
        }

        public override Expression Visit(Expression node)
        {
            if (node == _oldValue)
                return _newValue;
            return base.Visit(node);
        }
    }

Git merge errors

git commit -m "Merged master fixed conflict."

Inserting the iframe into react component

If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution

var Iframe = React.createClass({     
  render: function() {
    return(         
      <div>          
        <iframe src={this.props.src} height={this.props.height} width={this.props.width}/>         
      </div>
    )
  }
});

ReactDOM.render(
  <Iframe src="http://plnkr.co/" height="500" width="500"/>,
  document.getElementById('example')
);

here live demo is available Demo

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

How do I set the rounded corner radius of a color drawable using xml?

mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).

I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Comment the following lines in the web.config file.

<modules>
    <!--<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>-->
</modules>

<handlers>
    <remove name="WebServiceHandlerFactory-ISAPI-2.0"/>
    <!--<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    <add name="ScriptResource" verb="GET" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>-->
</handlers>

This will work.

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

As can be seen by the many answers here, there are lots of problems that can result in this error message when you start the MySQL service. The thing is, MySQL will generally tell you exactly what's wrong, if you just look in the appropriate log file.

For example, on Ubuntu, you should check /var/log/syslog. Since lots of other things might also be logging to this file, you probably want to use grep to look at mysql messages, and tail to look at only the most recent. All together, that might look like:

grep mysql /var/log/syslog | tail -50

Don't blindly make changes to your configuration because someone else said 'This worked for my system.' Figure out what is actually wrong with your system and you'll get a better result much faster.

Is it possible to open a Windows Explorer window from PowerShell?

You have a few options:

Examples:

PS C:\> explorer
PS C:\> explorer .
PS C:\> explorer /n
PS C:\> Invoke-Item c:\path\
PS C:\> ii c:\path\
PS C:\> Invoke-Item c:\windows\explorer.exe
PS C:\> ii c:\windows\explorer.exe
PS C:\> [diagnostics.process]::start("explorer.exe")

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

If you can live without tools.jar and it's only included as a chained dependency, you can exclude it from the offending project:

<dependency>
    <groupId>org.apache.ambari</groupId>
    <artifactId>ambari-metrics-common</artifactId>
    <version>2.1.0.0</version>
    <exclusions>
        <exclusion>
            <artifactId>jdk.tools</artifactId>
            <groupId>jdk.tools</groupId>
        </exclusion>
    </exclusions>
</dependency>

How to change the colors of a PNG image easily?

If you are like me and Photoshop is out of your price range or just overkill for what you need. Acorn 5 is a much cheaper version of Photoshop with a lot of the same features. One of those features being a color change option. You can import all of the basic image formats including SVG and PNG. The color editing software works great and allows for basic color selection, RBG selection, hex code, or even a color grabber if you do not know the color. These color features, plus a whole lot image editing features, is definitely worth the $30. The only downside is that is currently only available on Mac.

XCOPY switch to create specified directory if it doesn't exist?

Try /E

To get a full list of options: xcopy /?

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

MySQL's now() +1 day

INSERT INTO `table` ( `data` , `date` ) VALUES('".$data."',NOW()+INTERVAL 1 DAY);

How to picture "for" loop in block representation of algorithm

Here's a flow chart that illustrates a for loop:

Flow Chart For Loop

The equivalent C code would be

for(i = 2; i <= 6; i = i + 2) {
    printf("%d\t", i + 1);
}

I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.

Check list of words in another string

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

How do I get an animated gif to work in WPF?

I modified Mike Eshva's code,And I made it work better.You can use it with either 1frame jpg png bmp or mutil-frame gif.If you want bind a uri to the control,bind the UriSource properties or you want bind any in-memory stream that you bind the Source propertie which is a BitmapImage.

    /// <summary> 
/// ??????? ?????????? "???????????", ?????????????? ????????????? GIF. 
/// </summary> 
public class AnimatedImage : Image
{
    static AnimatedImage()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(AnimatedImage), new FrameworkPropertyMetadata(typeof(AnimatedImage)));
    }

    #region Public properties

    /// <summary> 
    /// ????????/????????????? ????? ???????? ?????. 
    /// </summary> 
    public int FrameIndex
    {
        get { return (int)GetValue(FrameIndexProperty); }
        set { SetValue(FrameIndexProperty, value); }
    }

    /// <summary>
    /// Get the BitmapFrame List.
    /// </summary>
    public List<BitmapFrame> Frames { get; private set; }

    /// <summary>
    /// Get or set the repeatBehavior of the animation when source is gif formart.This is a dependency object.
    /// </summary>
    public RepeatBehavior AnimationRepeatBehavior
    {
        get { return (RepeatBehavior)GetValue(AnimationRepeatBehaviorProperty); }
        set { SetValue(AnimationRepeatBehaviorProperty, value); }
    }

    public new BitmapImage Source
    {
        get { return (BitmapImage)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }

    public Uri UriSource
    {
        get { return (Uri)GetValue(UriSourceProperty); }
        set { SetValue(UriSourceProperty, value); }
    }

    #endregion

    #region Protected interface

    /// <summary> 
    /// Provides derived classes an opportunity to handle changes to the Source property. 
    /// </summary> 
    protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs e)
    {
        ClearAnimation();
        BitmapImage source;
        if (e.NewValue is Uri)
        {
            source = new BitmapImage();
            source.BeginInit();
            source.UriSource = e.NewValue as Uri;
            source.CacheOption = BitmapCacheOption.OnLoad;
            source.EndInit();
        }
        else if (e.NewValue is BitmapImage)
        {
            source = e.NewValue as BitmapImage;
        }
        else
        {
            return;
        }
        BitmapDecoder decoder;
        if (source.StreamSource != null)
        {
            decoder = BitmapDecoder.Create(source.StreamSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
        }
        else if (source.UriSource != null)
        {
            decoder = BitmapDecoder.Create(source.UriSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
        }
        else
        {
            return;
        }
        if (decoder.Frames.Count == 1)
        {
            base.Source = decoder.Frames[0];
            return;
        }

        this.Frames = decoder.Frames.ToList();

        PrepareAnimation();
    }

    #endregion

    #region Private properties

    private Int32Animation Animation { get; set; }
    private bool IsAnimationWorking { get; set; }

    #endregion

    #region Private methods

    private void ClearAnimation()
    {
        if (Animation != null)
        {
            BeginAnimation(FrameIndexProperty, null);
        }

        IsAnimationWorking = false;
        Animation = null;
        this.Frames = null;
    }

    private void PrepareAnimation()
    {
        Animation =
            new Int32Animation(
                0,
                this.Frames.Count - 1,
                new Duration(
                    new TimeSpan(
                        0,
                        0,
                        0,
                        this.Frames.Count / 10,
                        (int)((this.Frames.Count / 10.0 - this.Frames.Count / 10) * 1000))))
            {
                RepeatBehavior = RepeatBehavior.Forever
            };

        base.Source = this.Frames[0];
        BeginAnimation(FrameIndexProperty, Animation);
        IsAnimationWorking = true;
    }

    private static void ChangingFrameIndex
        (DependencyObject dp, DependencyPropertyChangedEventArgs e)
    {
        AnimatedImage animatedImage = dp as AnimatedImage;

        if (animatedImage == null || !animatedImage.IsAnimationWorking)
        {
            return;
        }

        int frameIndex = (int)e.NewValue;
        ((Image)animatedImage).Source = animatedImage.Frames[frameIndex];
        animatedImage.InvalidateVisual();
    }

    /// <summary> 
    /// Handles changes to the Source property. 
    /// </summary> 
    private static void OnSourceChanged
        (DependencyObject dp, DependencyPropertyChangedEventArgs e)
    {
        ((AnimatedImage)dp).OnSourceChanged(e);
    }

    #endregion

    #region Dependency Properties

    /// <summary> 
    /// FrameIndex Dependency Property 
    /// </summary> 
    public static readonly DependencyProperty FrameIndexProperty =
        DependencyProperty.Register(
            "FrameIndex",
            typeof(int),
            typeof(AnimatedImage),
            new UIPropertyMetadata(0, ChangingFrameIndex));

    /// <summary> 
    /// Source Dependency Property 
    /// </summary> 
    public new static readonly DependencyProperty SourceProperty =
        DependencyProperty.Register(
            "Source",
            typeof(BitmapImage),
            typeof(AnimatedImage),
            new FrameworkPropertyMetadata(
                null,
                FrameworkPropertyMetadataOptions.AffectsRender |
                FrameworkPropertyMetadataOptions.AffectsMeasure,
                OnSourceChanged));

    /// <summary>
    /// AnimationRepeatBehavior Dependency Property
    /// </summary>
    public static readonly DependencyProperty AnimationRepeatBehaviorProperty =
        DependencyProperty.Register(
        "AnimationRepeatBehavior",
        typeof(RepeatBehavior),
        typeof(AnimatedImage),
        new PropertyMetadata(null));

    public static readonly DependencyProperty UriSourceProperty =
        DependencyProperty.Register(
        "UriSource",
        typeof(Uri),
        typeof(AnimatedImage),
                new FrameworkPropertyMetadata(
                null,
                FrameworkPropertyMetadataOptions.AffectsRender |
                FrameworkPropertyMetadataOptions.AffectsMeasure,
                OnSourceChanged));

    #endregion
}

This is a custom control. You need to create it in WPF App Project,and delete the Template override in style.

JOptionPane Yes or No window

You are always checking for a true condition, hence your message will always show.

You should replace your if (true) statement with if ( n == JOptionPane.YES_OPTION)

When one of the showXxxDialog methods returns an integer, the possible values are:

YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION

From here

Send email from localhost running XAMMP in PHP using GMAIL mail server

Don't forget to generate a second password for your Gmail account. You will use this new password in your code. Read this:

https://support.google.com/accounts/answer/185833

Under the section "How to generate an App password" click on "App passwords", then under "Select app" choose "Mail", select your device and click "Generate". Your second password will be printed on the screen.

AngularJs ReferenceError: $http is not defined

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];

Changing Fonts Size in Matlab Plots

To change the default property for your entire MATLAB session, see the documentation on how default properties are handled.

As an example:

set(0,'DefaultAxesFontSize',22)
x=1:200; y=sin(x);
plot(x,y)
title('hello'); xlabel('x'); ylabel('sin(x)')

how to change background image of button when clicked/focused?

To change the button background we can follow 2 methods

  1. In the button OnClick, just add this code:

     public void onClick(View v) {
         if(v == buttonName) {
            buttonName.setBackgroundDrawable
             (getResources().getDrawable(R.drawable.imageName_selected));
          }
    
           }
    

    2.Create button_background.xml in the drawable folder.(using xml)

    res -> drawable -> button_background.xml

       <?xml version="1.0" encoding="UTF-8"?>
        <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
             <item android:state_selected="true"
                   android:drawable="@drawable/tabs_selected" /> <!-- selected-->
             <item android:state_pressed="true"
                   android:drawable="@drawable/tabs_selected" /> <!-- pressed-->
             <item  android:drawable="@drawable/tabs_selected"/>
        </selector>
    

    Now set the above file in button's background file.

         <Button
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:background="@drawable/button_background"/>
    
                              (or)
    
             Button tiny = (Button)findViewById(R.id.tiny);
                   tiny.setBackgroundResource(R.drawable.abc);
    

    2nd method is better for setting the background fd button

PHP __get and __set magic methods

I'd recommend to use an array for storing all values via __set().

class foo {

    protected $values = array();

    public function __get( $key )
    {
        return $this->values[ $key ];
    }

    public function __set( $key, $value )
    {
        $this->values[ $key ] = $value;
    }

}

This way you make sure, that you can't access the variables in another way (note that $values is protected), to avoid collisions.

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

Differences between ConstraintLayout and RelativeLayout

The only difference i've noted is that things set in a relative layout via drag and drop automatically have their dimensions relative to other elements inferred, so when you run the app what you see is what you get. However in the constraint layout even if you drag and drop an element in the design view, when you run the app things may be shifted around. This can easily be fixed by manually setting the constraints or, a more risky move being to right click the element in the component tree, selecting the constraint layout sub menu, then clicking 'infer constraints'. Hope this helps

Select query with date condition

The semicolon character is used to terminate the SQL statement.

You can either use # signs around a date value or use Access's (ACE, Jet, whatever) cast to DATETIME function CDATE(). As its name suggests, DATETIME always includes a time element so your literal values should reflect this fact. The ISO date format is understood perfectly by the SQL engine.

Best not to use BETWEEN for DATETIME in Access: it's modelled using a floating point type and anyhow time is a continuum ;)

DATE and TABLE are reserved words in the SQL Standards, ODBC and Jet 4.0 (and probably beyond) so are best avoided for a data element names:

Your predicates suggest open-open representation of periods (where neither its start date or the end date is included in the period), which is arguably the least popular choice. It makes me wonder if you meant to use closed-open representation (where neither its start date is included but the period ends immediately prior to the end date):

SELECT my_date
  FROM MyTable
 WHERE my_date >= #2008-09-01 00:00:00#
       AND my_date < #2010-09-01 00:00:00#;

Alternatively:

SELECT my_date
  FROM MyTable
 WHERE my_date >= CDate('2008-09-01 00:00:00')
       AND my_date < CDate('2010-09-01 00:00:00'); 

Python: Select subset from list based on index set

Matlab and Scilab languages offer a simpler and more elegant syntax than Python for the question you're asking, so I think the best you can do is to mimic Matlab/Scilab by using the Numpy package in Python. By doing this the solution to your problem is very concise and elegant:

from numpy import *
property_a = array([545., 656., 5.4, 33.])
property_b = array([ 1.2,  1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]

Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.

Visibility of global variables in imported modules

Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static.)

There are different ways to solve this, depending on your actual use case.


Before even going down this path, ask yourself whether this really needs to be global. Maybe you really want a class, with f as an instance method, rather than just a free function? Then you could do something like this:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

If you really do want a global, but it's just there to be used by module1, set it in that module.

import module1
module1.a=3
module1.f()

On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

… and, in module1.py:

import shared_stuff
def f():
    print shared_stuff.a

Don't use a from import unless the variable is intended to be a constant. from shared_stuff import a would create a new a variable initialized to whatever shared_stuff.a referred to at the time of the import, and this new a variable would not be affected by assignments to shared_stuff.a.


Or, in the rare case that you really do need it to be truly global everywhere, like a builtin, add it to the builtin module. The exact details differ between Python 2.x and 3.x. In 3.x, it works like this:

import builtins
import module1
builtins.a = 3
module1.f()

Detect IF hovering over element with jQuery

It does not work in jQuery 1.9. Made this plugin based on user2444818's answer.

jQuery.fn.mouseIsOver = function () {
    return $(this).parent().find($(this).selector + ":hover").length > 0;
}; 

http://jsfiddle.net/Wp2v4/1/

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I dont know if you solved this issue, but i had same issue, if the instance is local you must check the permission to access the file, but if you are accessing from your computer to a server (remote access) you have to specify the path in the server, so that means to include the file in a server directory, that solved my case

example:

BULK INSERT Table
FROM 'C:\bulk\usuarios_prueba.csv' -- This is server path not local
WITH 
  (
     FIELDTERMINATOR =',',
     ROWTERMINATOR ='\n'
  );

how to bind img src in angular 2 in ngFor?

I hope i am understanding your question correctly, as the above comment says you need to provide more information.

In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.

<div *ngFor="let student of students">  
 {{student.id}}
 {{student.name}}

 <img [src]="student.image">

</div>  

How to align flexbox columns left and right?

There are different ways but simplest would be to use the space-between see the example at the end

#container {    
    border: solid 1px #000;
    display: flex;    
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    height: 50px;
}

.item {
    width: 20%;
    border: solid 1px #000;
    text-align: center;
}

see the example

How to log SQL statements in Spring Boot?

Log in to standard output

Add to application.properties

### to enable
spring.jpa.show-sql=true
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

This the simplest way to print the SQL queries though it doesn't log the parameters of prepared statements. And its is not recommended since its not such as optimized logging framework.

Using Logging Framework

Add to application.properties

### logs the SQL queries
logging.level.org.hibernate.SQL=DEBUG
### logs the prepared statement parameters
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

By specifying above properties, logs entries will be sent to the configured log appender such as log-back or log4j.

How to get file name when user select a file via <input type="file" />?

just tested doing this and it seems to work in firefox & IE

<html>
    <head>
        <script type="text/javascript">
            function alertFilename()
            {
                var thefile = document.getElementById('thefile');
                alert(thefile.value);
            }
        </script>
    </head>
    <body>
        <form>
            <input type="file" id="thefile" onchange="alertFilename()" />
            <input type="button" onclick="alertFilename()" value="alert" />
        </form>
    </body>
</html>

How to replace all dots in a string using JavaScript

For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.

You could try this :

"okay.this.is.a.string".split(".").join("")

Greetings

"unary operator expected" error in Bash if condition

You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.

It goes by this syntax: ${VARIABLE:-default}.

The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.

If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".

How to install the current version of Go in Ubuntu Precise

You can also use the update-golang script:

update-golang is a script to easily fetch and install new Golang releases with minimum system intrusion

git clone https://github.com/udhos/update-golang
cd update-golang
sudo ./update-golang.sh

Split string based on regex

You could use a lookahead:

re.split(r'[ ](?=[A-Z]+\b)', input)

This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.

Note that the square brackets are only for readability and could as well be omitted.

If it is enough that the first letter of a word is upper case (so if you would want to split in front of Hello as well) it gets even easier:

re.split(r'[ ](?=[A-Z])', input)

Now this splits at every space followed by any upper-case letter.

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Very good question. The Java Language specification confirms your suggestion.

For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

move_uploaded_file gives "failed to open stream: Permission denied" error

This is because images and tmp_file_upload are only writable by root user. For upload to work we need to make the owner of those folders same as httpd process owner OR make them globally writable (bad practice).

  1. Check apache process owner: $ps aux | grep httpd. The first column will be the owner typically it will be nobody
  2. Change the owner of images and tmp_file_upload to be become nobody or whatever the owner you found in step 1.

    $sudo chown nobody /var/www/html/mysite/images/
    
    $sudo chown nobody /var/www/html/mysite/tmp_file_upload/
    
  3. Chmod images and tmp_file_upload now to be writable by the owner, if needed [Seems you already have this in place]. Mentioned in @Dmitry Teplyakov answer.

    $ sudo chmod -R 0755 /var/www/html/mysite/images/
    
    $ sudo chmod -R 0755 /var/www/html/mysite/tmp_file_upload/
    
  4. For more details why this behavior happend, check the manual http://php.net/manual/en/ini.core.php#ini.upload-tmp-dir , note that it also talking about open_basedir directive.

How to bring a window to the front?

Here's a method that REALLY works (tested on Windows Vista) :D

   frame.setExtendedState(JFrame.ICONIFIED);
   frame.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);

The fullscreen variable indicates if you want the app to run full screen or windowed.

This does not flash the task bar, but bring the window to front reliably.

is there a tool to create SVG paths from an SVG file?

Gimp can be used to convert SVGs with primitives (e.g. rects, circles, etc.) into a single path which can be used within HTML5.

  1. First download Gimp: https://www.gimp.org/downloads/
  2. Export your SVG as a .svg file with any tool of choice e.g. Illustrator. Don't worry if the SVG output is messy for now, Gimp will clean it up
  3. Import the SVG file into Gimp with File -> Open, and the following (or similar) dialog should show up:

Gimp SVG Open Dialog

Check both the Import Paths and Merge imported paths options

  1. Then go to Windows->Dockable Dialogues->Paths
  2. Right-click on the single path which says Imported Path and you should see the following dialog:

enter image description here

  1. Click Export Path... and save this text file to a location of your choice
  2. Locate and open up this file with a text editor of your choice e.g Notepad, TextEdit
  3. Copy the text within the <path d="copy this text here" />
  4. Since Gimp formats the text with lots of spaces, you may need to re-format it, by removing some of the spaces to paste it into your HTML in a single line

How to increase font size in NeatBeans IDE?

In OS X, Netbeans 8.0

  1. Use Command + , to open the options
  2. Select Fonts & Colors tab
  3. Click the button in the Font section (button is next to the Font textbox)
  4. Change the Font, style and size as needed

enter image description here

Python: How to pip install opencv2 with specific version 2.4.9?

you can try this

pip install opencv==2.4.9

Highlight Bash/shell code in Markdown files

I found a good description at Markdown Cheatsheet:

Code blocks are part of the Markdown spec, but syntax highlighting isn't.

However, many renderers -- like GitHub's and Markdown Here -- support syntax highlighting. Which languages are supported and how those language names should be written will vary from renderer to renderer. Markdown Here supports highlighting for dozens of languages (and not-really-languages, like diffs and HTTP headers); to see the complete list, and how to write the language names, see the highlight.js demo page.

Although I could not find any official GitHub documentation about using highlight.js, I've tested lots of languages and seemed to be working

To see list of languages I used https://github.com/highlightjs/highlight.js/blob/master/SUPPORTED_LANGUAGES.md

Some shell samples:

Shell:      console, shell
Bash:       bash, sh, zsh
PowerShell: powershell, ps
DOS:        dos, bat, cmd

Example:

```bat
cd \
copy a b
ping 192.168.0.1
```

How to set Android camera orientation properly?

From the Javadocs for setDisplayOrientation(int) (Requires API level 9):

 public static void setCameraDisplayOrientation(Activity activity,
         int cameraId, android.hardware.Camera camera) {
     android.hardware.Camera.CameraInfo info =
             new android.hardware.Camera.CameraInfo();
     android.hardware.Camera.getCameraInfo(cameraId, info);
     int rotation = activity.getWindowManager().getDefaultDisplay()
             .getRotation();
     int degrees = 0;
     switch (rotation) {
         case Surface.ROTATION_0: degrees = 0; break;
         case Surface.ROTATION_90: degrees = 90; break;
         case Surface.ROTATION_180: degrees = 180; break;
         case Surface.ROTATION_270: degrees = 270; break;
     }

     int result;
     if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
         result = (info.orientation + degrees) % 360;
         result = (360 - result) % 360;  // compensate the mirror
     } else {  // back-facing
         result = (info.orientation - degrees + 360) % 360;
     }
     camera.setDisplayOrientation(result);
 }

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

var x = function() vs. function x() — Function declaration syntax

(function(){})() — IIFE (Immediately Invoked Function Expression)

someFunction()() — Functions which return other functions

=> — Equal sign, greater than: arrow function expression syntax

|> — Pipe, greater than: Pipeline operator

function*, yield, yield* — Star after function or yield: generator functions

[], Array() — Square brackets: array notation

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value} — Curly brackets: object literal syntax (not to be confused with blocks)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}` — Backticks, dollar sign with curly brackets: template literals

// — Slashes: regular expression literals

$ — Dollar sign in regex replace patterns: $$, $&, $`, $', $n

() — Parentheses: grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"] — Square brackets or dot: property accessors

?., ?.[], ?.() — Question mark, dot: optional chaining operator

:: — Double colon: bind operator

new operator

...iter — Three dots: spread syntax; rest parameters


Increment and decrement

++, -- — Double plus or minus: pre- / post-increment / -decrement operators


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

void operator

+, - — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

|, &, ^, ~ — Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

% — Percent sign: remainder operator

&&, ||, ! — Double ampersand, double pipe, exclamation point: logical operators

?? — Double question mark: nullish-coalescing operator

** — Double star: power operator (exponentiation)


Equality operators

==, === — Equal signs: equality operators

!=, !== — Exclamation point and equal signs: inequality operators


Bit shift operators

<<, >>, >>> — Two or three angle brackets: bit shift operators


Conditional operator

?:… — Question mark and colon: conditional (ternary) operator


Assignment operators

= — Equal sign: assignment operator

%= — Percent equals: remainder assignment

+= — Plus equals: addition assignment operator

&&=, ||=, ??= — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

Destructuring


Comma operator

, — Comma operator


Control flow

{} — Curly brackets: blocks (not to be confused with object literal syntax)

Declarations

var, let, const — Declaring variables


Label

label: — Colon: labels


# — Hash (number sign): Private methods or private fields

Determining whether an object is a member of a collection in VBA

Isn't it good enough?

Public Function Contains(col As Collection, key As Variant) As Boolean
Dim obj As Variant
On Error GoTo err
    Contains = True
    obj = col(key)
    Exit Function
err:

    Contains = False
End Function

Download pdf file using jquery ajax

For those looking a more modern approach, you can use the fetch API. The following example shows how to download a PDF file. It is easily done with the following code.

fetch(url, {
    body: JSON.stringify(data),
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
})
.then(response => response.blob())
.then(response => {
    const blob = new Blob([response], {type: 'application/pdf'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "file.pdf";
    document.body.appendChild(a);
    a.click();
})

I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].

Important: In this example I am sending a JSON request to a server listening on the given url. This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8, as to let the server know the type of request it will receive.

How to get the 'height' of the screen using jquery

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

As documented here: http://api.jquery.com/height/

Amazon Interview Question: Design an OO parking lot

In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".

Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.

The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)

License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.

How to include Javascript file in Asp.Net page

Probably the file is not in the path specified. '../../../' will move 3 step up to the directory in which the page is located and look for the js file in a folder named JS.

Also the language attribute is Deprecated.

See Scripts:

18.2.1 The SCRIPT element

language = cdata [CI]

Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.

Edit

Try changing

<script src="../../../JS/Registration.js" language="javascript" type="text/javascript" /> 

to

<script src="../../../JS/Registration.js" language="javascript" type="text/javascript"></script>

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

What does android:layout_weight mean?

Combining both answers from

Flo & rptwsthi and roetzi,

Do remember to change your layout_width=0dp/px, else the layout_weight behaviour will act reversely with biggest number occupied the smallest space and lowest number occupied the biggest space.

Besides, some weights combination will caused some layout cannot be shown (since it over occupied the space).

Beware of this.

Objective-C : BOOL vs bool

I go against convention here. I don't like typedef's to base types. I think it's a useless indirection that removes value.

  1. When I see the base type in your source I will instantly understand it. If it's a typedef I have to look it up to see what I'm really dealing with.
  2. When porting to another compiler or adding another library their set of typedefs may conflict and cause issues that are difficult to debug. I just got done dealing with this in fact. In one library boolean was typedef'ed to int, and in mingw/gcc it's typedef'ed to a char.

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))

If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals("en")