Programs & Examples On #Vertex shader

Vertex shaders are executable programs that execute as part of the programmable geometry pipeline in modern graphics APIs such as e.g. Direct3D or OpenGL. Vertex shaders are usually hardware accelerated on consumer hardware nowadays. The vertex shader processes one vertex at a time, followed by primitive assembly, optionally geometry shader and transform feedback, clipping, and finally rasterization and fragment processing.

How to add label in chart.js for pie chart

Rachel's solution is working fine, although you need to use the third party script from raw.githubusercontent.com

By now there is a feature they show on the landing page when advertisng the "modular" script. You can see a legend there with this structure:

<div class="labeled-chart-container">
    <div class="canvas-holder">
        <canvas id="modular-doughnut" width="250" height="250" style="width: 250px; height: 250px;"></canvas>
    </div>

<ul class="doughnut-legend">
    <li><span style="background-color:#5B90BF"></span>Core</li>
    <li><span style="background-color:#96b5b4"></span>Bar</li>
    <li><span style="background-color:#a3be8c"></span>Doughnut</li>
    <li><span style="background-color:#ab7967"></span>Radar</li>
    <li><span style="background-color:#d08770"></span>Line</li>
    <li><span style="background-color:#b48ead"></span>Polar Area</li>
</ul>
</div>

To achieve this they use the chart configuration option legendTemplate

legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"

You can find the doumentation here on chartjs.org This works for all the charts although it is not part of the global chart configuration.

Then they create the legend and add it to the DOM like this:

var legend = myPie.generateLegend();
$("#legend").html(legend);

Sample See also my JSFiddle sample

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

Font-awesome, input type 'submit'

use button type="submit" instead of input

<button type="submit" class="btn btn-success">
    <i class="fa fa-arrow-circle-right fa-lg"></i> Next
</button>

for Font Awesome 3.2.0 use

<button type="submit" class="btn btn-success">
    <i class="icon-circle-arrow-right icon-large"></i> Next
</button>

Angular 5, HTML, boolean on checkbox is checked

You can use this:

<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">

Here, record is the model for current row and status is boolean value.

Floating point vs integer calculations on modern hardware

For example (lesser numbers are faster),

64-bit Intel Xeon X5550 @ 2.67GHz, gcc 4.1.2 -O3

short add/sub: 1.005460 [0]
short mul/div: 3.926543 [0]
long add/sub: 0.000000 [0]
long mul/div: 7.378581 [0]
long long add/sub: 0.000000 [0]
long long mul/div: 7.378593 [0]
float add/sub: 0.993583 [0]
float mul/div: 1.821565 [0]
double add/sub: 0.993884 [0]
double mul/div: 1.988664 [0]

32-bit Dual Core AMD Opteron(tm) Processor 265 @ 1.81GHz, gcc 3.4.6 -O3

short add/sub: 0.553863 [0]
short mul/div: 12.509163 [0]
long add/sub: 0.556912 [0]
long mul/div: 12.748019 [0]
long long add/sub: 5.298999 [0]
long long mul/div: 20.461186 [0]
float add/sub: 2.688253 [0]
float mul/div: 4.683886 [0]
double add/sub: 2.700834 [0]
double mul/div: 4.646755 [0]

As Dan pointed out, even once you normalize for clock frequency (which can be misleading in itself in pipelined designs), results will vary wildly based on CPU architecture (individual ALU/FPU performance, as well as actual number of ALUs/FPUs available per core in superscalar designs which influences how many independent operations can execute in parallel -- the latter factor is not exercised by the code below as all operations below are sequentially dependent.)

Poor man's FPU/ALU operation benchmark:

#include <stdio.h>
#ifdef _WIN32
#include <sys/timeb.h>
#else
#include <sys/time.h>
#endif
#include <time.h>
#include <cstdlib>

double
mygettime(void) {
# ifdef _WIN32
  struct _timeb tb;
  _ftime(&tb);
  return (double)tb.time + (0.001 * (double)tb.millitm);
# else
  struct timeval tv;
  if(gettimeofday(&tv, 0) < 0) {
    perror("oops");
  }
  return (double)tv.tv_sec + (0.000001 * (double)tv.tv_usec);
# endif
}

template< typename Type >
void my_test(const char* name) {
  Type v  = 0;
  // Do not use constants or repeating values
  //  to avoid loop unroll optimizations.
  // All values >0 to avoid division by 0
  // Perform ten ops/iteration to reduce
  //  impact of ++i below on measurements
  Type v0 = (Type)(rand() % 256)/16 + 1;
  Type v1 = (Type)(rand() % 256)/16 + 1;
  Type v2 = (Type)(rand() % 256)/16 + 1;
  Type v3 = (Type)(rand() % 256)/16 + 1;
  Type v4 = (Type)(rand() % 256)/16 + 1;
  Type v5 = (Type)(rand() % 256)/16 + 1;
  Type v6 = (Type)(rand() % 256)/16 + 1;
  Type v7 = (Type)(rand() % 256)/16 + 1;
  Type v8 = (Type)(rand() % 256)/16 + 1;
  Type v9 = (Type)(rand() % 256)/16 + 1;

  double t1 = mygettime();
  for (size_t i = 0; i < 100000000; ++i) {
    v += v0;
    v -= v1;
    v += v2;
    v -= v3;
    v += v4;
    v -= v5;
    v += v6;
    v -= v7;
    v += v8;
    v -= v9;
  }
  // Pretend we make use of v so compiler doesn't optimize out
  //  the loop completely
  printf("%s add/sub: %f [%d]\n", name, mygettime() - t1, (int)v&1);
  t1 = mygettime();
  for (size_t i = 0; i < 100000000; ++i) {
    v /= v0;
    v *= v1;
    v /= v2;
    v *= v3;
    v /= v4;
    v *= v5;
    v /= v6;
    v *= v7;
    v /= v8;
    v *= v9;
  }
  // Pretend we make use of v so compiler doesn't optimize out
  //  the loop completely
  printf("%s mul/div: %f [%d]\n", name, mygettime() - t1, (int)v&1);
}

int main() {
  my_test< short >("short");
  my_test< long >("long");
  my_test< long long >("long long");
  my_test< float >("float");
  my_test< double >("double");

  return 0;
}

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

Hide the browse button on a input type=file

the best way for it

<input type="file" id="file">
<label for="file" class="file-trigger">Click Me</label> 

And you can style your "label" element

#file { 
   display: none;
}
.file-trigger {
/* your style */
}

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

Use the following excellent npm package: to-arraybuffer.

Or, you can implement it yourself. If your buffer is called buf, do this:

buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)

'uint32_t' identifier not found error

This type is defined in the C header <stdint.h> which is part of the C++11 standard but not standard in C++03. According to the Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.

In the meantime, you could probably fake up your own version of the header by adding typedefs that map Microsoft's custom integer types to the types expected by C. For example:

typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */

Hope this helps!

Limit file format when using <input type="file">?

You can use "accept" attribute as a filter in the file select box. Using "accept" help you filter input files base on their "suffix" or their "meme type"

1.Filter based on suffix: Here "accept" attribute just allow to select files with .jpeg extension.

<input type="file" accept=".jpeg" />

2.Filter based on "file type" Here "accept" attribute just allow to select file with "image/jpeg" type.

<input type="file" accept="image/jpeg" />

Important: We can change or delete the extension of a file, without changing the meme type. For example it is possible to have a file without extension, but the type of this file can be "image/jpeg". So this file can not pass the accept=".jpeg" filter. but it can pass accept="image/jpeg".

3.We can use * to select all kind of a file type. For example below code allow to select all kind of images. for example "image/png" or "image/jpeg" or ... . All of them are allowed.

<input type="file" accept="image/*" /> 

4.We can use cama ( , ) as an "or operator" in select attribute. For example to allow all kind of images or pdf files we can use this code:

<input type="file" accept="image/* , application/pdf" />

Count how many rows have the same value

FOR SPECIFIC NUM:

SELECT COUNT(1) FROM YOUR_TABLE WHERE NUM = 1

FOR ALL NUM:

SELECT NUM, COUNT(1) FROM YOUR_TABLE GROUP BY NUM

Cache busting via params

Another similar approach is to use htaccess mod_rewrite to ignore part of the path when serving the files. Your never-cached index page references the latest path to the files.

From a development perspective it's as easy as using params for the version number, but it's as robust as the filename approach.

Use the ignored part of the path for the version number, and the server just ignores it and serves the uncached file.

1.2.3/css/styles.css serves the same file as css/styles.css since the first directory is stripped and ignored by the htaccess file

Including versioned files

<?php
  $version = "1.2.3";
?>

<html>
  <head>
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />
    <link rel="stylesheet" type="text/css" href="<?php echo $version ?>/css/styles.css">
  </head>
  <body>
    <script src="<?php echo $version ?>/js/main.js"></script>
  </body>
</html>

Note that this approach means you need to disable caching of your index page - Using <meta> tags to turn off caching in all browsers?

.htaccess file

RewriteEngine On

# if you're requesting a file that exists, do nothing
RewriteCond %{REQUEST_FILENAME} !-f 
# likewise if a directory that exists, do nothing
RewriteCond %{REQUEST_FILENAME} !-d 

# otherwise, rewrite foo/bar/baz to bar/baz - ignore the first directory
RewriteRule ^[^/]+/(.+)$ $1 [L] 

You could take the same approach on any server platform that allows url rewriting

(rewrite condition adapted from mod_rewrite - rewrite directory to query string except /#!/)

... and if you need cache busting for your index page / site entry point, you could always use JavaSript to refresh it.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);

Digital Certificate: How to import .cer file in to .truststore file using?

Instead of using sed to filter out the certificate, you can also pipe the openssl s_client output through openssl x509 -out certfile.txt, for example:

echo "" | openssl s_client -connect my.server.com:443 -showcerts 2>/dev/null | openssl x509 -out certfile.txt

Auto line-wrapping in SVG text

This functionality can also be added using JavaScript. Carto.net has an example:

http://old.carto.net/papers/svg/textFlow/

Something else that also might be useful to are you are editable text areas:

http://old.carto.net/papers/svg/gui/textbox/

Where is Ubuntu storing installed programs?

to find the program you want you can run this command at terminal:

find / usr-name "your_program"

How to upgrade rubygems

You can update all gems by just performing:

sudo gem update

#define in Java

Comment space too small, so here is some more information for you on the use of static final. As I said in my comment to the Andrzej's answer, only primitive and String are compiled directly into the code as literals. To demonstrate this, try the following:

You can see this in action by creating three classes (in separate files):

public class DisplayValue {
    private String value;

    public DisplayValue(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }
}

public class Constants {
    public static final int INT_VALUE = 0;
    public static final DisplayValue VALUE = new DisplayValue("A");
}

public class Test {
    public static void main(String[] args) {
        System.out.println("Int   = " + Constants.INT_VALUE);
        System.out.println("Value = " + Constants.VALUE);
    }
}

Compile these and run Test, which prints:

Int    = 0
Value  = A

Now, change Constants to have a different value for each and just compile class Constants. When you execute Test again (without recompiling the class file) it still prints the old value for INT_VALUE but not VALUE. For example:

public class Constants {
    public static final int INT_VALUE = 2;
    public static final DisplayValue VALUE = new DisplayValue("X");
}

Run Test without recompiling Test.java:

Int    = 0
Value  = X

Note that any other type used with static final is kept as a reference.

Similar to C/C++ #if/#endif, a constant literal or one defined through static final with primitives, used in a regular Java if condition and evaluates to false will cause the compiler to strip the byte code for the statements within the if block (they will not be generated).

private static final boolean DEBUG = false;

if (DEBUG) {
    ...code here...
}

The code at "...code here..." would not be compiled into the byte code. But if you changed DEBUG to true then it would be.

jquery validate check at least one checkbox

It's highly probable that you want to have a text next to the checkbox. In that case, you can put the checkbox inside a label like I do below:

<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="72" aria-required="true" class="error"> All Over</label>
<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="73" aria-required="true" class="error"> All Over X2</label>

The problem is that when the error message is displayed, it's going to be inserted after the checkbox but before the text, making it unreadable. In order to fix that, I changed the error placement function:

if (element.is(":checkbox")) {
    error.insertAfter(element.parent().parent());
}
else {
    error.insertAfter(element);
}

It depends on your layout but what I did is to have a special error placement for checkbox controls. I get the parent of the checkbox, which is a label, and then I get the parent of it, which is a div in my case. This way, the error is placed below the list of checkbox controls.

How to select the first row for each group in MySQL?

I based my answer on the title of your post only, as I don't know C# and didn't understand the given query. But in MySQL I suggest you try subselects. First get a set of primary keys of interesting columns then select data from those rows:

SELECT somecolumn, anothercolumn 
  FROM sometable 
 WHERE id IN (
               SELECT min(id) 
                 FROM sometable 
                GROUP BY somecolumn
             );

How to plot two columns of a pandas data frame using points?

Pandas uses matplotlib as a library for basic plots. The easiest way in your case will using the following:

import pandas as pd
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
df.plot(x='col_name_1', y='col_name_2', style='o')

enter image description here

However, I would recommend to use seaborn as an alternative solution if you want have more customized plots while not going into the basic level of matplotlib. In this case you the solution will be following:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df)

enter image description here

Latex - Change margins of only a few pages

A slight modification of this to change the \voffset works for me:

\newenvironment{changemargin}[1]{
  \begin{list}{}{
    \setlength{\voffset}{#1}
  }
  \item[]}{\end{list}}

And then put your figures in a \begin{changemargin}{-1cm}...\end{changemargin} environment.

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

How to convert a String to Bytearray

The easiest way in 2018 should be TextEncoder but the returned element is not byte array, it is Uint8Array. (And not all browsers support it)

let utf8Encode = new TextEncoder();
utf8Encode.encode("eee")
> Uint8Array [ 101, 101, 101 ]

Bootstrap table without stripe / borders

Don’t add the .table class to your <table> tag. From the Bootstrap docs on tables:

For basic styling—light padding and only horizontal dividers—add the base class .table to any <table>. It may seem super redundant, but given the widespread use of tables for other plugins like calendars and date pickers, we've opted to isolate our custom table styles.

Iterate through Nested JavaScript Objects

Here is a concise breadth-first iterative solution, which I prefer to recursion:

const findCar = function(car) {
    const carSearch = [cars];

      while(carSearch.length) {
          let item = carSearch.shift();
          if (item.label === car) return true;
          carSearch.push(...item.subs);
      }

      return false;
}

How do I view the SQL generated by the Entity Framework?

I've just done this:

IQueryable<Product> query = EntitySet.Where(p => p.Id == id);
Debug.WriteLine(query);

And the result shown in the Output:

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Code] AS [Code], 
    [Extent1].[Name] AS [Name], 
    [Extent2].[Id] AS [Id1], 
    [Extent2].[FileName] AS [FileName], 
    FROM  [dbo].[Products] AS [Extent1]
    INNER JOIN [dbo].[PersistedFiles] AS [Extent2] ON [Extent1].[PersistedFileId] = [Extent2].[Id]
    WHERE [Extent1].[Id] = @p__linq__0

How to delete Project from Google Developers Console

Go to Google Cloud Console, select the project then IAM and Admin and Settings

enter image description here

now SHUT DOWN

enter image description here

Then you have to wait for the project deletion.

enter image description here

enter image description here

Remove border from IFrame

If the doctype of the page you are placing the iframe on is HTML5 then you can use the seamless attribute like so:

<iframe src="..." seamless="seamless"></iframe>

Mozilla docs on the seamless attribute

Array to Hash Ruby

Enumerator includes Enumerable. Since 2.1, Enumerable also has a method #to_h. That's why, we can write :-

a = ["item 1", "item 2", "item 3", "item 4"]
a.each_slice(2).to_h
# => {"item 1"=>"item 2", "item 3"=>"item 4"}

Because #each_slice without block gives us Enumerator, and as per the above explanation, we can call the #to_h method on the Enumerator object.

Read specific columns with pandas or other python module

Above answers are in python2. So for python 3 users I am giving this answer. You can use the bellow code:

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
print(df.star_name)

Set attribute without value

You can do it without jQuery!

Example:

_x000D_
_x000D_
document.querySelector('button').setAttribute('disabled', '');
_x000D_
<button>My disabled button!</button>
_x000D_
_x000D_
_x000D_

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

From MDN Element.setAttribute()

How do you represent a JSON array of strings?

I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.

A valid JSON always starts with either curly braces { or square brackets [, nothing else.

{ will start an object:

left brace followed by a key string (a name that can't be repeated, in quotes), colon and a value (valid types shown below), followed by an optional comma to add more pairs of string and value at will and finished with a right brace

{ "key": value, "another key": value }

Hint: although javascript accepts single quotes ', JSON only takes double ones ".

[ will start an array:

left bracket followed by value, optional comma to add more value at will and finished with a right bracket

[value, value]

Hint: spaces among elements are always ignored by any JSON parser.

And value is an object, array, string, number, bool or null:

Image showing the 6 types a JSON value can be: string, number, JSON object, Array/list, boolean, and null

So yeah, ["a", "b"] is a perfectly valid JSON, like you could try on the link Manish pointed.

Here are a few extra valid JSON examples, one per block:

{}

[0]

{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}

[{   "why":null} ]

{
  "not true": [0, false],
  "true": true,
  "not null": [0, 1, false, true, {
    "obj": null
  }, "a string"]
}

HTML/CSS--Creating a banner/header

Height is missing a p from its value.

Should be height:200*p*x

Is there a real solution to debug cordova apps

Here's the solution using Phonegap Build. Add the following to your config.xml to be able to inspect with Chrome Remote Webview Debugging.

First, make sure your widget tag contains xmlns:android="http://schemas.android.com/apk/res/android"

<widget 
    xmlns="http://www.w3.org/ns/widgets" 
    xmlns:gap="http://phonegap.com/ns/1.0" 
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="me.app.id" 
    version="1.0.0">

Then add the following

<gap:config-file platform="android" parent="/manifest">
     <application android:debuggable="true" />
</gap:config-file>

It works for me on Nexus 5, Phonegap 3.7.0.

<preference name="phonegap-version" value="3.7.0" />

Build the app in Phonegap Build, install the APK, connect the phone to the USB, enable USB debugging on you phone then visit chrome://inspect.

Source: https://www.genuitec.com/products/gapdebug/learning-center/configuration/

how to query LIST using linq

var persons = new List<Person>
    {
        new Person {ID = 1, Name = "jhon", Salary = 2500},
        new Person {ID = 2, Name = "Sena", Salary = 1500},
        new Person {ID = 3, Name = "Max", Salary = 5500},
        new Person {ID = 4, Name = "Gen", Salary = 3500}
    };

var acertainperson = persons.Where(p => p.Name == "jhon").First();
Console.WriteLine("{0}: {1} points",
    acertainperson.Name, acertainperson.Salary);

jhon: 2500 points

var doingprettywell = persons.Where(p => p.Salary > 2000);
            foreach (var person in doingprettywell)
            {
                Console.WriteLine("{0}: {1} points",
                    person.Name, person.Salary);
            }

jhon: 2500 points
Max: 5500 points
Gen: 3500 points

        var astupidcalc = from p in persons
                          where p.ID > 2
                          select new
                                     {
                                         Name = p.Name,
                                         Bobos = p.Salary*p.ID,
                                         Bobotype = "bobos"
                                     };
        foreach (var person in astupidcalc)
        {
            Console.WriteLine("{0}: {1} {2}",
                person.Name, person.Bobos, person.Bobotype);
        }

Max: 16500 bobos
Gen: 14000 bobos

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case there was a corrupted character in one of the named params ("-StorageAccountName" for cmdlet "Get-AzureStorageKey") which showed as perfectly normal in my editor (SublimeText) but Windows Powershell couldn't parse it.

To get to the bottom of it, I moved the offending lines from the error message into another .ps1 file, ran that, and the error now showed a botched character at the beginning of my "-StorageAccountName" parameter.

Deleting the character (again which looks normal in the actual editor) and re-typing it fixes this issue.

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

I found that when mixed with PCL libraries the above problem presented itself, and whilst it is true that the WindowsBase library contains System.IO.Packaging I was using the OpenXMLSDK-MOT 2.6.0.0 library which itself provides it's own copy of the physical System.IO.Packaging library. The reference that was missing for me could be found as follows in the csharp project

<Reference Include="System.IO.Packaging, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
  <HintPath>..\..\..\..\packages\OpenXMLSDK-MOT.2.6.0.0\lib\System.IO.Packaging.dll</HintPath>
  <Private>True</Private>
</Reference>

I downgraded my version of the XMLSDK to 2.6 which then seemed to fix this problem up for me. But you can see there is a physical assembly System.IO.Packaging.dll

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

Maybe try simply

@(Model.AuditDate.HasValue ? Model.AuditDate.ToString("mm/dd/yyyy") : String.Empty)

also you can use many type of string format like .ToString("dd MMM, yyyy") .ToString("d") etc

pandas three-way joining multiple dataframes on columns

Simple Solution:

If the column names are similar:

 df1.merge(df2,on='col_name').merge(df3,on='col_name')

If the column names are different:

df1.merge(df2,left_on='col_name1', right_on='col_name2').merge(df3,left_on='col_name1', right_on='col_name3').drop(columns=['col_name2', 'col_name3']).rename(columns={'col_name1':'col_name'})

CodeIgniter Disallowed Key Characters

The problem is you are using characters not included in the standard Regex. Use this:

!preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\@\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)

As per the comments (and personal experience) you should not modify they Input.php file — rather, you should create/use your own MY_Input.php as follows:

<?php

class MY_Input extends CI_Input {

    /**
     * Clean Keys
     *
     * This is a helper function. To prevent malicious users
     * from trying to exploit keys we make sure that keys are
     * only named with alpha-numeric text and a few other items.
     * 
     * Extended to allow: 
     *      - '.' (dot), 
     *      - '[' (open bracket),
     *      - ']' (close bracket)
     * 
     * @access  private
     * @param   string
     * @return  string
     */
    function _clean_input_keys($str) {
        // UPDATE: Now includes comprehensive Regex that can process escaped JSON
        if (!preg_match("/^[a-z0-9\:\;\.\,\?\!\@\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)) {
            /**
             * Check for Development enviroment - Non-descriptive 
             * error so show me the string that caused the problem 
             */
            if (getenv('ENVIRONMENT') && getenv('ENVIRONMENT') == 'DEVELOPMENT') {
                var_dump($str);
            }
            exit('Disallowed Key Characters.');
        }

        // Clean UTF-8 if supported
        if (UTF8_ENABLED === TRUE) {
            $str = $this->uni->clean_string($str);
        }

        return $str;
    }

}

// /?/> /* Should never close php file - if you have a space after code, it can mess your life up */

++Chinese Character Support

// NOTE: \x{4e00}-\x{9fa5} = allow chinese characters
// NOTE: 'i' — case insensitive
// NOTE: 'u' — UTF-8 mode
if (!preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\@\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str) { ... }

// NOTE: When Chinese characters are provided in a URL, they are not 'really' there; the browser/OS
//   handles the copy/paste -> unicode conversion, eg:
//        ???  -->  xn--4gqsa60b   
//   'punycode' converts these codes according to RFC 3492 and RFC 5891.
//   https://github.com/bestiejs/punycode.js ---  $ bower install punycode

Why is Visual Studio 2010 not able to find/open PDB files?

I'm pretty sure those are warnings, not errors. Your project should still run just fine.

However, since you should always try to fix compiler warnings, let's see what we can discover. I'm not at all familiar with OpenCV, and you don't link to the wiki tutorial that you're following. But it looks to me like the problem is that you're running a 64-bit version of Windows (as evidenced by the "SysWOW64" folder in the path to the DLL files), but the OpenCV stuff that you're trying is built for a 32-bit platform. So you might need to rebuild the project using CMake, as explained here.

More specifically, the files that are listed are Windows system files. PDB files contain debugging information that Visual Studio uses to allow you to step into and debug compiled code. You don't actually need the PDB files for system libraries to be able to debug your own code. But if you want, you can download the symbols for the system libraries as well. Go to the "Debug" menu, click on "Options and Settings", and scroll down the listbox on the right until you see "Enable source server support". Make sure that option is checked. Then, in the treeview to the left, click on "Symbols", and make sure that the "Microsoft Symbol Servers" option is selected. Click OK to dismiss the dialog, and then try rebuilding.

How to change the height of a <br>?

This did the trick for me when I couldn't get the style spacing to work from the span tag:

        <p style='margin-bottom: 5px' >
            <span>I Agree</span>
        </p>
        <span>I Don't Agree</span>

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

Actually I took a closer look at the user table in mysql database, turns out someone prior to me edited the ssl_type field for user root to SSL.

I edited that field and restarted mysql and it worked like a charm.

Thanks.

Working with $scope.$emit and $scope.$on

Scope(s) can be used to propagate, dispatch event to the scope children or parent.

$emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.

example index.html:

<div ng-app="appExample" ng-controller="EventCtrl">
      Root(Parent) scope count: {{count}}
  <div>
      <button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
      <button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button><br>

      Childrent scope count: {{count}} 
  </div>
</div>

example app.js:

angular.module('appExample', [])
.controller('EventCtrl', ['$scope', function($scope) {
  $scope.count = 0;
  $scope.$on('MyEvent', function() {
    $scope.count++;
  });
}]);

Here u can test code: http://jsfiddle.net/zp6v0rut/41/

Question mark and colon in statement. What does it mean?

It means if "OperationURL[1]" evaluates to "GET" then return "GetRequestSignature()" else return "". I'm guessing "GetRequestSignature()" here returns a string. The syntax CONDITION ? A : B basically stands for an if-else where A is returned when CONDITION is true and B is returned when CONDITION is false.

Length of the String without using length() method

Just to complete this with the most stupid method I can come up with: Generate all possible strings of length 1, use equals to compare them to the original string; if they are equal, the string length is 1. If no string matches, generate all possible strings of length 2, compare them, for string length 2. Etc. Continue until you find the string length or the universe ends, whatever happens first.

JavaScript is in array

Best way to do it in 2019 is by using .includes()

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false

First parameter is what you are searching for. Second parameter is the index position in this array at which to begin searching.

If you need to be crossbrowsy here - there are plenty of legacy answers.

Good PHP ORM Library?

Brazilian ORM: http://www.hufersil.com.br/lumine. It works with PHP 5.2+. In my opinion, it is the best choice for Portuguese and Brazilian people, because it has easy-to-understand documentation and a lot of examples for download.

static linking only some libraries

gcc objectfiles -o program -Wl,-Bstatic -ls1 -ls2 -Wl,-Bdynamic -ld1 -ld2

you can also use: -static-libgcc -static-libstdc++ flags for gcc libraries

keep in mind that if libs1.so and libs1.a both exists, the linker will pick libs1.so if it's before -Wl,-Bstatic or after -Wl,-Bdynamic. Don't forget to pass -L/libs1-library-location/ before calling -ls1.

Oracle Age calculation from Date of birth and Today

Age (full years) of the Person:

SELECT
  TRUNC(months_between(sysdate, per.DATE_OF_BIRTH) / 12) AS "Age"
FROM PD_PERSONS per

Alert after page load

If you can use jquery then you can put the alert inside the $(document).ready() function. it would look something like this:

<script>
  $(document).ready(function(){
    alert('<%: TempData["Resultat"]%>');
  });
</script>

To include jQuery, include the following in the <head> tag of your code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

Here's a quick example in jsFiddle: http://jsfiddle.net/ChaseWest/3AaAx/

Cannot find java. Please use the --jdkhome switch

  1. Go to the netbeans installation directory
  2. Find configuration file [installation-directory]/etc/netbeans.conf
  3. towards the end find the line netbeans_jdkhome=...
  4. comment this line line using '#'
  5. now run netbeans. launcher will find jdk itself (from $JDK_HOME/$JAVA_HOME) environment variable

example:

sudo vim /usr/local/netbeans-8.2/etc/netbeans.conf

How do I pass JavaScript variables to PHP?

Here's how I did it (I needed to insert a local timezone into PHP:

<?php
    ob_start();
?>

<script type="text/javascript">

    var d = new Date();
    document.write(d.getTimezoneOffset());
</script>

<?php
    $offset = ob_get_clean();
    print_r($offset);

Ruby/Rails: converting a Date to a UNIX timestamp

Solution for Ruby 1.8 when you have an arbitrary DateTime object:

1.8.7-p374 :001 > require 'date'
 => true 
1.8.7-p374 :002 > DateTime.new(2012, 1, 15).strftime('%s')
 => "1326585600"

Eliminating NAs from a ggplot

Try remove_missing instead with vars = the_variable. It is very important that you set the vars argument, otherwise remove_missing will remove all rows that contain an NA in any column!! Setting na.rm = TRUE will suppress the warning message.

ggplot(data = remove_missing(MyData, na.rm = TRUE, vars = the_variable),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
       geom_bar(stat="bin") 

How to embed images in html email

This is the code I'm using to embed images into HTML mail and PDF documents.

<?php
$logo_path = 'http://localhost/img/logo.jpg';
$type = pathinfo($logo_path, PATHINFO_EXTENSION);
$image_contents = file_get_contents($logo_path);
$image64 = 'data:image/' . $type . ';base64,' . base64_encode($image_contents);

echo '<img src="' . $image64 .'" />';
?>

Draw on HTML5 Canvas using a mouse

A super short version, here, without position:absolute in vanilla JavaScript. The main idea is to move the canvas' context to the right coordinates and draw a line. Uncomment click handler and comment mousedown & mousemove handlers below to get a feel for how it is working.

<!DOCTYPE html>
<html>
<body>

<p style="margin: 50px">Just some padding in y direction</p>

<canvas id="myCanvas" width="300" height="300" style="background: #000; margin-left: 100px;">Your browser does not support the HTML5 canvas tag.</canvas>

<script>
    const c = document.getElementById("myCanvas");
    // c.addEventListener("click", penTool); // fires after mouse left btn is released
    c.addEventListener("mousedown", setLastCoords); // fires before mouse left btn is released
    c.addEventListener("mousemove", freeForm);


    const ctx = c.getContext("2d");

    function setLastCoords(e) {
        const {x, y} = c.getBoundingClientRect();
        lastX = e.clientX - x;
        lastY = e.clientY - y;
    }

    function freeForm(e) {
        if (e.buttons !== 1) return; // left button is not pushed yet
        penTool(e);
    }

    function penTool(e) {
        const {x, y} = c.getBoundingClientRect();
        const newX = e.clientX - x;
        const newY = e.clientY - y;

        ctx.beginPath();
        ctx.lineWidth = 5;
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(newX, newY);
        ctx.strokeStyle = 'white';
        ctx.stroke();
        ctx.closePath();

        lastX = newX;
        lastY = newY;
    }

    let lastX = 0;
    let lastY = 0;  
</script>

</body>
</html>

Embed a PowerPoint presentation into HTML

The 'actual answer' is that you cannot do it directly. You have to convert your PowerPoint presentation to something that the browser can process. You can save each page of the PowerPoint presentation as a JPEG image and then display as a series of images. You can save the PowerPoint presentation as HTML. Both of these solutions will render only static pages, without any of the animations of PowerPoint. You can use a tool to convert your PowerPoint presentation to Flash (.swf) and embed it that way. This will preserve any animations and presumably allow you to do an automatic slideshow without the need for writing special code to change the images.

Some dates recognized as dates, some dates not recognized. Why?

Here is what worked for me. I highlighted the column with all my dates. Under the Data tab, I selected 'text to columns' and selected the 'Delimited' box, I hit next and finish. Although it didn't seem like anything changed, Excel now read the column as dates and I was able to sort by dates.

Image resizing in React Native

Ran into the same problem and was able to tweak the resize mode until I found something I was happy with. Alternative approaches include:

  • Reduce the size of the Static Resource using an image editor
  • Add a transparent border to the static resource using an image editor
  • Use a Network Resource at the expense of UX

To prevent loss of quality while tweaking images consider working with vector graphics so you can experiment with different sizes easily. Inkscape is free tool and works well for this purpose.

What value could I insert into a bit type column?

Generally speaking, for boolean or bit data types, you would use 0 or 1 like so:

UPDATE tbl SET bitCol = 1 WHERE bitCol = 0

See also:

How to debug Apache mod_rewrite

One trick is to turn on the rewrite log. To turn it on, try this line in your apache main config or current virtual host file (not in .htaccess):

LogLevel alert rewrite:trace6

Before Apache httpd 2.4 mod_rewrite, such a per-module logging configuration did not exist yet, instead you could use the following logging settings:

RewriteEngine On
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

Tricks to manage the available memory in an R session

I quite like the improved objects function developed by Dirk. Much of the time though, a more basic output with the object name and size is sufficient for me. Here's a simpler function with a similar objective. Memory use can be ordered alphabetically or by size, can be limited to a certain number of objects, and can be ordered ascending or descending. Also, I often work with data that are 1GB+, so the function changes units accordingly.

showMemoryUse <- function(sort="size", decreasing=FALSE, limit) {

  objectList <- ls(parent.frame())

  oneKB <- 1024
  oneMB <- 1048576
  oneGB <- 1073741824

  memoryUse <- sapply(objectList, function(x) as.numeric(object.size(eval(parse(text=x)))))

  memListing <- sapply(memoryUse, function(size) {
        if (size >= oneGB) return(paste(round(size/oneGB,2), "GB"))
        else if (size >= oneMB) return(paste(round(size/oneMB,2), "MB"))
        else if (size >= oneKB) return(paste(round(size/oneKB,2), "kB"))
        else return(paste(size, "bytes"))
      })

  memListing <- data.frame(objectName=names(memListing),memorySize=memListing,row.names=NULL)

  if (sort=="alphabetical") memListing <- memListing[order(memListing$objectName,decreasing=decreasing),] 
  else memListing <- memListing[order(memoryUse,decreasing=decreasing),] #will run if sort not specified or "size"

  if(!missing(limit)) memListing <- memListing[1:limit,]

  print(memListing, row.names=FALSE)
  return(invisible(memListing))
}

And here is some example output:

> showMemoryUse(decreasing=TRUE, limit=5)
      objectName memorySize
       coherData  713.75 MB
 spec.pgram_mine  149.63 kB
       stoch.reg  145.88 kB
      describeBy    82.5 kB
      lmBandpass   68.41 kB

How do I set Tomcat Manager Application User Name and Password for NetBeans?

Netbeans Problem: For apache Tomcat server Authentication required dialog box requesting user name and password

This dialog box appear If a user role and his credentials are not set or is incorrect for Tomcat startup via NetBeans IDE,

OR when user/pass set in IDE is not matches with user/pass in "canf/tomcat-user.xml" file

1..Need to check user name and password set in IDE tools-->server

2..Check \CATALINA_BASE\conf\tomcat-users.xml. whether user and his role is defined or not. If not add these lines

<user username="ide" password="EiWnNlBG" roles="manager-script,admin"/>
</tomcat-users>

3.. set the same user/pass in IDE tools->server

  1. restart your server to get effect of changes

Source: http://ohmjavaclasses.blogspot.com/2011/12/netbeans-problem-for-apache-tomcat.html

PHP, get file name without file extension

This return only filename without any extension in 1 row:

$path = "/etc/sudoers.php";    
print array_shift(explode(".", basename($path)));
// will print "sudoers"

$file = "file_name.php";    
print array_shift(explode(".", basename($file)));
// will print "file_name"

Moving items around in an ArrayList

Moving element with respect to each other is something I needed a lot in a project of mine. So I wrote a small util class that moves an element in an list to a position relative to another element. Feel free to use (and improve upon ;))

import java.util.List;

public class ListMoveUtil
{
    enum Position
    {
        BEFORE, AFTER
    };

    /**
     * Moves element `elementToMove` to be just before or just after `targetElement`.
     *
     * @param list
     * @param elementToMove
     * @param targetElement
     * @param pos
     */
    public static <T> void moveElementTo( List<T> list, T elementToMove, T targetElement, Position pos )
    {
        if ( elementToMove.equals( targetElement ) )
        {
            return;
        }
        int srcIndex = list.indexOf( elementToMove );
        int targetIndex = list.indexOf( targetElement );
        if ( srcIndex < 0 )
        {
            throw new IllegalArgumentException( "Element: " + elementToMove + " not in the list!" );
        }
        if ( targetIndex < 0 )
        {
            throw new IllegalArgumentException( "Element: " + targetElement + " not in the list!" );
        }
        list.remove( elementToMove );

        // if the element to move is after the targetelement in the list, just remove it
        // else the element to move is before the targetelement. When we removed it, the targetindex should be decreased by one
        if ( srcIndex < targetIndex )
        {
            targetIndex -= 1;
        }
        switch ( pos )
        {
            case AFTER:
                list.add( targetIndex + 1, elementToMove );
                break;
            case BEFORE:
                list.add( targetIndex, elementToMove );
                break;
        }
    }

How can I read the client's machine/computer name from the browser?

Erm is there any reason why you can't just use the HttpRequest? This would be on the server side but you could pass it to the javascript if you needed to?

Page.Request.UserHostName

HttpRequest.UserHostName

The one problem with this is it would only really work in an Intranet environment otherwise it would just end up picking up the users Router or Proxy address...

How to rotate portrait/landscape Android emulator?

Officially it's Ctrl+F11 & Ctrl+F12 or KEYPAD 7 & KEYPAD 9.

In practise it's a bit quirky.

  1. Specifically it's Left Ctrl+F11 and Left Ctrl+F12 to switch to previous orientation and next orientation respectively.

  2. You have to release Ctrl before you can rotate again.

  3. KEYPAD 7 and KEYPAD 9 only work with Num Lock OFF (so they're acting as Home & PageUp rather than 7 & 9).

  4. The only orientations are vertically upright and rotated one quarter-turn anti-clockwise.

Maybe a bit too much info for such a simple question, but it drove me half-mad finding this out.

Note: This was tested on Android SDK R16 and a very old keyboard, modern keyboards may behave differently.

Simple Pivot Table to Count Unique Values

If you have the data sorted.. i suggest using the following formula

=IF(OR(A2<>A3,B2<>B3),1,0)

This is faster as it uses less cells to calculate.

Pyspark replace strings in Spark dataframe column

For scala

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))

Fill Combobox from database

To use the Combobox in the way you intend, you could pass in an object to the cmbTripName.Items.Add method.

That object should have FleetID and FleetName properties:

while (drd.Read())
{
    cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

The Fleet Class:

class Fleet
{
     public Fleet(string fleetId, string fleetName)
     {
           FleetId = fleetId;
           FleetName = fleetName
     }
     public string FleetId {get;set;}
     public string FleetName {get;set;}
}

Or, You could probably do away with the need for a Fleet class completely by using an anonymous type...

while (drd.Read())
{
    cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

SQL join: selecting the last records in a one-to-many relationship

Try this, It will help.

I have used this in my project.

SELECT 
*
FROM
customer c
OUTER APPLY(SELECT top 1 * FROM purchase pi 
WHERE pi.customer_id = c.Id order by pi.Id desc) AS [LastPurchasePrice]

Hibernate, @SequenceGenerator and allocationSize

I too faced this issue in Hibernate 5:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
@SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE)
private Long titId;

Got a warning like this below:

Found use of deprecated [org.hibernate.id.SequenceHiLoGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead. See Hibernate Domain Model Mapping Guide for details.

Then changed my code to SequenceStyleGenerator:

@Id
@GenericGenerator(name="cmrSeq", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @Parameter(name = "sequence_name", value = "SEQUENCE")}
)
@GeneratedValue(generator = "sequence_name")
private Long titId;

This solved my two issues:

  1. The deprecated warning is fixed
  2. Now the id is generated as per the oracle sequence.

Get path to execution directory of Windows Forms application

This could help;

Path.GetDirectoryName(Application.ExecutablePath);

also here is the reference

How to configure the web.config to allow requests of any length

It will also generate error when you pass large string in ajax call parameter.

so for that alway use type post in ajax will resolve your issue 100% and no need to set the length in web.config.

// var UserId= array of 1000 userids

$.ajax({ global: false, url: SitePath + "/User/getAussizzMembersData", "data": { UserIds: UserId}, "type": "POST", "dataType": "JSON" }}

Ignore .pyc files in git repository

Put it in .gitignore. But from the gitignore(5) man page:

  ·   If the pattern does not contain a slash /, git treats it as a shell
       glob pattern and checks for a match against the pathname relative
       to the location of the .gitignore file (relative to the toplevel of
       the work tree if not from a .gitignore file).

  ·   Otherwise, git treats the pattern as a shell glob suitable for
       consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in
       the pattern will not match a / in the pathname. For example,
       "Documentation/*.html" matches "Documentation/git.html" but not
       "Documentation/ppc/ppc.html" or
       "tools/perf/Documentation/perf.html".

So, either specify the full path to the appropriate *.pyc entry, or put it in a .gitignore file in any of the directories leading from the repository root (inclusive).

How can I check if an ip is in a network in Python?

If you do not want to import other modules you could go with:

def ip_matches_network(self, network, ip):
    """
    '{:08b}'.format(254): Converts 254 in a string of its binary representation

    ip_bits[:net_mask] == net_ip_bits[:net_mask]: compare the ip bit streams

    :param network: string like '192.168.33.0/24'
    :param ip: string like '192.168.33.1'
    :return: if ip matches network
    """
    net_ip, net_mask = network.split('/')
    net_mask = int(net_mask)
    ip_bits = ''.join('{:08b}'.format(int(x)) for x in ip.split('.'))
    net_ip_bits = ''.join('{:08b}'.format(int(x)) for x in net_ip.split('.'))
    # example: net_mask=24 -> compare strings at position 0 to 23
    return ip_bits[:net_mask] == net_ip_bits[:net_mask]

How to get last items of a list in Python?

Slicing

Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data.

Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:

num_list[-9:]

When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")

Explanation:

The full notation is

sequence[start:stop:step]

But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists in Python 2 is

list_copy = sequence[:]

And clearing them is with:

del my_list[:]

(Lists get list.copy and list.clear in Python 3.)

Give your slices a descriptive name!

You may find it useful to separate forming the slice from passing it to the list.__getitem__ method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.

However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:

last_nine_slice = slice(-9, None)

The second argument, None, is required, so that the first argument is interpreted as the start argument otherwise it would be the stop argument.

You can then pass the slice object to your sequence:

>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]

islice

islice from the itertools module is another possibly performant way to get this. islice doesn't take negative arguments, so ideally your iterable has a __reversed__ special method - which list does have - so you must first pass your list (or iterable with __reversed__) to reversed.

>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>

islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list):

>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]

Convert from ASCII string encoded in Hex to plain ASCII?

A slightly simpler solution:

>>> "7061756c".decode("hex")
'paul'

Calling a user defined function in jQuery

Try this $('div').myFunction();

This should work

$(document).ready(function() {
 $('#btnSun').click(function(){
  myFunction();
 });

function myFunction()
{
alert('hi');
}

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

CSS getting text in one line rather than two

The best way to use is white-space: nowrap; This will align the text to one line.

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

Did you try setting the style:

input {
    text-align:right;
}

Just tested, this works fine (in FF3 at least):

<html>
    <head>
        <title>Blah</title>
        <style type="text/css">
        input { text-align:right; }
        </style>
    </head>
    <body>
        <input type="text" value="2">
    </body>
</html>

You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.

How to make my font bold using css?

You can use the strong element in html, which is great semantically (also good for screen readers etc.), which typically renders as bold text:

_x000D_
_x000D_
See here, some <strong>emphasized text</strong>.
_x000D_
_x000D_
_x000D_

Or you can use the font-weight css property to style any element's text as bold:

_x000D_
_x000D_
span { font-weight: bold; }
_x000D_
<p>This is a paragraph of <span>bold text</span>.</p>
_x000D_
_x000D_
_x000D_

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

Adding days to a date in Java

Simple, without any other API:

To add 8 days:

Date today=new Date();
long ltime=today.getTime()+8*24*60*60*1000;
Date today8=new Date(ltime);

Android: How do I prevent the soft keyboard from pushing my view up?

Include in your manifest file under activity which you want to display .But make sure not using Full screen Activity

android:windowSoftInputMode="adjustPan"

What is difference between sjlj vs dwarf vs seh?

SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks

DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.

SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.

source: https://wiki.qt.io/MinGW-64-bit

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

Here is the answer.

System.exit(0);// normal termination - Successful - zero
System.exit(-1);//Exit with some Error
System.exit(1);//one or any positive integer // exit with some Information message

jQuery rotate/transform

t = setTimeout(function() { rotate(++degree); },65);

and clearTimeout to stop

clearTimeout(t);

I use this with AJAX

success:function(){ clearTimeout(t); }

how to add background image to activity?

You can set the "background image" to an activity by setting android:background xml attributes as followings:

(Here, for example, Take a LinearLayout for an activity and setting a background image for the layout(i.e. indirectly to an activity))

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01" 
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:background="@drawable/icon">
 </LinearLayout>

How to return a string from a C++ function?

string str1, str2, str3;

cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;

From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:

string str1 = "the dog jumped over the fence", 
       str2 = "the",
       str3 = "that";

cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;

How can I create a text box for a note in markdown?

The simplest solution I've found to the exact same problem is to use a multiple line table with one row and no header (there is an image in the first column and the text in the second):

----------------------- ------------------------------------
![Tip](images/tip.png)\ Table multiline text bla bla bla bla
                        bla bla bla bla bla bla bla ... the
                        blank line below is important 

----------------------------------------------------------------

Another approach that might work (for PDF) is to use Latex default fbox directive :

 \fbox{My text!}

Or FancyBox module for more advanced features (and better looking boxes) : http://www.ctan.org/tex-archive/macros/latex/contrib/fancybox.

Reading numbers from a text file into an array in C

change to

fscanf(myFile, "%1d", &numberArray[i]);

How to keep footer at bottom of screen

use this style

min-height:250px;
height:auto;

find all the name using mysql query which start with the letter 'a'

You can use like 'A%' expression, but if you want this query to run fast for large tables I'd recommend you to put number of first button into separate field with tiny int type.

Turning error reporting off php

Tried this yet?

error_reporting(0);
@ini_set('display_errors', 0);

Showing all session data at once?

print_r($this->session->userdata); 

or

print_r($this->session->all_userdata());

How to determine a user's IP address in node

If using express...

req.ip

I was looking this up then I was like wait, I'm using express. Duh.

C++ equivalent of StringBuffer/StringBuilder?

std::string is the C++ equivalent: It's mutable.

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

Copy Files from Windows to the Ubuntu Subsystem

You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.

Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt) such as /mnt/c/Users/yourusername/files within WSL. These files stay synced between WSL and Windows.

For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

How to use JavaScript to change div backgroundColor

It's very simple just use a function on javaScript and call it onclick

   <script type="text/javascript">
            function change()
            {
            document.getElementById("catestory").style.backgroundColor="#666666";
            }
            </script>

    <a href="#" onclick="change()">Change Bacckground Color</a>

how to write value into cell with vba code without auto type conversion?

This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:

prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _ 
    param_cls_shift.Start_Date (string property of my class) 

Double quotes within php script echo

if you need to access your variables for an echo statement within your quotes put your variable inside curly brackets

echo "i need to open my lock with its: {$array['key']}";

Purpose of returning by const value?

It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.

Though any optimizer would most likely optimize it out anyway...

How can I ping a server port with PHP?

Try this :

echo exec('ping -n 1 -w 1 72.10.169.28');

How to access command line arguments of the caller inside a function?

One can do it like this as well

#!/bin/bash
# script_name function_test.sh
function argument(){
for i in $@;do
    echo $i
done;
}
argument $@

Now call your script like

./function_test.sh argument1 argument2

performSelector may cause a leak because its selector is unknown

To make Scott Thompson's macro more generic:

// String expander
#define MY_STRX(X) #X
#define MY_STR(X) MY_STRX(X)

#define MYSilenceWarning(FLAG, MACRO) \
_Pragma("clang diagnostic push") \
_Pragma(MY_STR(clang diagnostic ignored MY_STR(FLAG))) \
MACRO \
_Pragma("clang diagnostic pop")

Then use it like this:

MYSilenceWarning(-Warc-performSelector-leaks,
[_target performSelector:_action withObject:self];
                )

sorting a List of Map<String, String>

@Test
public void testSortedMaps() {
    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("name", "Josh");

    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("name", "Anna");

    Map<String, String> map3 = new HashMap<String, String>();
    map3.put("name", "Bernie");

    List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
    mapList.add(map1);
    mapList.add(map2);
    mapList.add(map3);

    Collections.sort(mapList, new Comparator<Map<String, String>>() {
        public int compare(final Map<String, String> o1, final Map<String, String> o2) {
            return o1.get("name").compareTo(o2.get("name"));
        }
    });

    Assert.assertEquals("Anna", mapList.get(0).get("name"));
    Assert.assertEquals("Bernie", mapList.get(1).get("name"));
    Assert.assertEquals("Josh", mapList.get(2).get("name"));

}

How to get Last record from Sqlite?

If you have already got the cursor, then this is how you may get the last record from cursor:

cursor.moveToPosition(cursor.getCount() - 1);
//then use cursor to read values

Checkout multiple git repos into same Jenkins workspace

We are using git-repo to manage our multiple GIT repositories. There is also a Jenkins Repo plugin that allows to checkout all or part of the repositories managed by git-repo to the same Jenkins job workspace.

How to add default signature in Outlook

The existing answers had a few problems for me:

  1. I needed to insert text (e.g. 'Good Day John Doe') with html formatting where you would normally type your message.
  2. At least on my machine, Outlook adds 2 blank lines above the signature where you should start typing. These should obviously be removed (replaced with custom HTML).

The code below does the job. Please note the following:

  1. The 'From' parameter allows you to choose the account (since there could be different default signatures for different email accounts)
  2. The 'Recipients' parameter expects an array of emails, and it will 'Resolve' the added email (i.e. find it in contacts, as if you had typed it in the 'To' box)
  3. Late binding is used, so no references are required
'Opens an outlook email with the provided email body and default signature
'Parameters:
'  from: Email address of Account to send from.  Wildcards are supported e.g. *@example.com
'  recipients: Array of recipients.  Recipient can be a Contact name or email address
'  subject: Email subject
'  htmlBody: Html formatted body to insert before signature (just body markup, should not contain html, head or body tags)
Public Sub CreateMail(from As String, recipients, subject As String, htmlBody As String)
    Dim oApp, oAcc As Object
    
    Set oApp = CreateObject("Outlook.application")
    
    With oApp.CreateItem(0) 'olMailItem = 0
        'Ensure we are sending with the correct account (to insert the correct signature)
        'oAcc is of type Outlook.Account, which has other properties that could be filtered with if required
        'SmtpAddress is usually equal to the raw email address
        .SendUsingAccount = Nothing
        For Each oAcc In oApp.Session.Accounts
            If CStr(oAcc.SmtpAddress) = from Or CStr(oAcc.SmtpAddress) Like from Then
                Set .SendUsingAccount = oAcc
            End If
        Next oAcc
        If .SendUsingAccount Is Nothing Then Err.Raise -1, , "Unknown email account " & from
        For Each addr In recipients
            With .recipients.Add(addr)
                'This will resolve the recipient as if you had typed the name/email and pressed Tab/Enter
                .Resolve
            End With
        Next addr
        .subject = subject
        .Display 'HTMLBody is only populated after this line
        'Remove blank lines at the top of the body
        .htmlBody = Replace(.htmlBody, "<o:p>&nbsp;</o:p>", "")
        'Insert the html at the start of the 'body' tag
        Dim bodyTagEnd As Long: bodyTagEnd = InStr(InStr(1, .htmlBody, "<body"), .htmlBody, ">")
        .htmlBody = Left(.htmlBody, bodyTagEnd) & htmlBody & Right(.htmlBody, Len(.htmlBody) - bodyTagEnd)
    End With
    Set oApp = Nothing
End Sub

Use as follows:

CreateMail from:="*@contoso.com", _
    recipients:= Array("[email protected]", "Jane Doe", "[email protected]"), _
    subject:= "Test Email", _
    htmlBody:= "<p>Good Day All</p><p>Hello <b>World!</b></p>"

Result:

Sample Outlook Email

How to find and restore a deleted file in a Git repository

If you know the commit that deleted the file(s), run this command where <SHA1_deletion> is the commit that deleted the file:

git diff --diff-filter=D --name-only <SHA1_deletion>~1 <SHA1_deletion> | xargs git checkout <SHA1_deletion>~1 --

The part before the pipe lists all the files that were deleted in the commit; they are all checkout from the previous commit to restore them.

What is 'PermSize' in Java?

A quick definition of the "permanent generation":

"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]

In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space if an application loads a large number of classes and/or on redeployment).

Note that PermSize is additional to the -Xmx value set by the user on the JVM options. But MaxPermSize allows for the JVM to be able to grow the PermSize to the amount specified. Initially when the VM is loaded, the MaxPermSize will still be the default value (32mb for -client and 64mb for -server) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize and MaxPermSize to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx setting.

MySQL Error #1133 - Can't find any matching row in the user table

In my case I had just renamed the Mysql user which was going to change his password on a gui based db tool (DbVisualizer). The terminal in which I tried to 'SET PASSWORD' did not work(MySQL Error #1133).

However this answer worked for me, even after changing the password the 'SET PASSWORD' command did not work yet.

After closing the terminal and opening new one the command worked very well.

load and execute order of scripts

The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.

To test this fact:

// file: test.php
sleep(10);
die("alert('Done!');");

// HTML file:
<script type="text/javascript" src="test.php"></script>

Dynamically added scripts are executed as soon as they are appended to the document.

To test this fact:

<!DOCTYPE HTML>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <script type="text/javascript">
        var s = document.createElement('script');
        s.type = "text/javascript";
        s.src = "link.js"; // file contains alert("hello!");
        document.body.appendChild(s);
        alert("appended");
    </script>
    <script type="text/javascript">
        alert("final");
    </script>
</body>
</html>

Order of alerts is "appended" -> "hello!" -> "final"

If in a script you attempt to access an element that hasn't been reached yet (example: <script>do something with #blah</script><div id="blah"></div>) then you will get an error.

Overall, yes you can include external scripts and then access their functions and variables, but only if you exit the current <script> tag and start a new one.

PHP - concatenate or directly insert variables in string

From the point of view of making thinks simple, readable, consistent and easy to understand (since performance doesn't matter here):

  • Using embedded vars in double quotes can lead to complex and confusing situations when you want to embed object properties, multidimentional arrays etc. That is, generally when reading embedded vars, you cannot be instantly 100% sure of the final behavior of what you are reading.

  • You frequently need add crutches such as {} and \, which IMO adds confusion and makes concatenation readability nearly equivalent, if not better.

  • As soon as you need to wrap a function call around the var, for example htmlspecialchars($var), you have to switch to concatenation.

  • AFAIK, you cannot embed constants.

In some specific cases, "double quotes with vars embedding" can be useful, but generally speaking, I would go for concatenation (using single or double quotes when convenient)

How to avoid a System.Runtime.InteropServices.COMException?

I came across System.Runtime.InteropServices.COMException while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM Methods. I ran Visual Studio as Administrator and the exception was gone.

Spring Boot - Loading Initial Data

If you want to insert only few rows and u have JPA Setup. You can use below

    @SpringBootApplication
        @Slf4j
        public class HospitalManagementApplication {

            public static void main(String[] args) {
                SpringApplication.run(HospitalManagementApplication.class, args);
            }            

            @Bean
            ApplicationRunner init(PatientRepository repository) {
                return (ApplicationArguments args) ->  dataSetup(repository);
            } 

            public void dataSetup(PatientRepository repository){
            //inserts

     }

How to do INSERT into a table records extracted from another table

No "VALUES", no parenthesis:

INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;

Vector of Vectors to create matrix

Vector needs to be initialized before using it as cin>>v[i][j]. Even if it was 1D vector, it still needs an initialization, see this link

After initialization there will be no errors, see this link

Single line if statement with 2 actions

Sounds like you really want a Dictionary<int, string> or possibly a switch statement...

You can do it with the conditional operator though:

userType = user.Type == 0 ? "Admin"
         : user.Type == 1 ? "User"
         : user.Type == 2 ? "Employee"
         : "The default you didn't specify";

While you could put that in one line, I'd strongly urge you not to.

I would normally only do this for different conditions though - not just several different possible values, which is better handled in a map.

Letsencrypt add domain to existing certificate

this worked for me

 sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
 domain.com -d www.domain.com

Hibernate-sequence doesn't exist

Working with Spring Boot

Solution

Put the string below in .application.properties

spring.jpa.properties.hibernate.id.new_generator_mappings=false

Explanation

On Hibernate 4.X this attribute defaults to true.

How would you count occurrences of a string (actually a char) within a string?

In C#, a nice String SubString counter is this unexpectedly tricky fellow:

public static int CCount(String haystack, String needle)
{
    return haystack.Split(new[] { needle }, StringSplitOptions.None).Length - 1;
}

Access a JavaScript variable from PHP

JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.

Room persistance library. Delete all

As of Room 1.1.0 you can use clearAllTables() which:

Deletes all rows from all the tables that are registered to this database as entities().

Open directory using C

Here is a simple way to implement ls command using c. To run use for example ./xls /tmp

    #include<stdio.h>
    #include <dirent.h>
    void main(int argc,char *argv[])
    {
   DIR *dir;
   struct dirent *dent;
   dir = opendir(argv[1]);   

   if(dir!=NULL)
      {
   while((dent=readdir(dir))!=NULL)
                    {
        if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
            {
            }
       else
              {
        printf(dent->d_name);
        printf("\n");
              }
                    }
       }
       close(dir);
     }

If my interface must return Task what is the best way to have a no-operation implementation?

To add to Reed Copsey's answer about using Task.FromResult, you can improve performance even more if you cache the already completed task since all instances of completed tasks are the same:

public static class TaskExtensions
{
    public static readonly Task CompletedTask = Task.FromResult(false);
}

With TaskExtensions.CompletedTask you can use the same instance throughout the entire app domain.


The latest version of the .Net Framework (v4.6) adds just that with the Task.CompletedTask static property

Task completedTask = Task.CompletedTask;

Styling HTML email for Gmail

The answers here are outdated, as of today Sep 30 2016. Gmail is currently rolling out support for the style tag in the head, as well as media queries. If Gmail is your only concern, you're safe to use classes like a modern developer!

For reference, you can check the official gmail CSS docs.

As a side note, Gmail was the only major client that didn't support style (reference, until they update anyway). That means you can almost safely stop putting styles inline. Some of the more obscure clients may still need them.

align images side by side in html

You mean something like this?

<div class="image123">
    <div class="imgContainer">
        <img src="/images/tv.gif" height="200" width="200"/>
        <p>This is image 1</p>
    </div>
    <div class="imgContainer">
        <img class="middle-img" src="/images/tv.gif"/ height="200" width="200"/>
        <p>This is image 2</p>
    </div>
    <div class="imgContainer">
         <img src="/images/tv.gif"/ height="200" width="200"/>
        <p>This is image 3</p>
    </div>
</div>

with the imgContainer style as

.imgContainer{
    float:left;
}

Also see this jsfiddle.

Deserializing a JSON file with JavaScriptSerializer()

Create a sub-class User with an id field and screen_name field, like this:

public class User
{
    public string id { get; set; }
    public string screen_name { get; set; }
}

public class Response {

    public string id { get; set; }
    public string text { get; set; }
    public string url { get; set; }
    public string width { get; set; }
    public string height { get; set; }
    public string size { get; set; }
    public string type { get; set; }
    public string timestamp { get; set; }
    public User user { get; set; }
}

How can I flush GPU memory using CUDA (physical reset is unavailable)

First type

nvidia-smi

then select the PID that you want to kill

sudo kill -9 PID

TypeError: 'float' object is not callable

The problem is with -3.7(prof[x]), which looks like a function call (note the parens). Just use a * like this -3.7*prof[x].

How to store directory files listing into an array?

Here's a variant that lets you use a regex pattern for initial filtering, change the regex to be get the filtering you desire.

files=($(find -E . -type f -regex "^.*$"))
for item in ${files[*]}
do
  printf "   %s\n" $item
done

Getting data-* attribute for onclick event for an html element

here is an example

 <a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>

    $('.facultySelecter').click(function() {        
    var unhide = $(this).data("faculty");
    });

this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get

How can I pass data from Flask to JavaScript in a template?

You can use {{ variable }} anywhere in your template, not just in the HTML part. So this should work:

<html>
<head>
  <script>
    var someJavaScriptVar = '{{ geocode[1] }}';
  </script>
</head>
<body>
  <p>Hello World</p>
  <button onclick="alert('Geocode: {{ geocode[0] }} ' + someJavaScriptVar)" />
</body>
</html>

Think of it as a two-stage process: First, Jinja (the template engine Flask uses) generates your text output. This gets sent to the user who executes the JavaScript he sees. If you want your Flask variable to be available in JavaScript as an array, you have to generate an array definition in your output:

<html>
  <head>
    <script>
      var myGeocode = ['{{ geocode[0] }}', '{{ geocode[1] }}'];
    </script>
  </head>
  <body>
    <p>Hello World</p>
    <button onclick="alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])" />
  </body>
</html>

Jinja also offers more advanced constructs from Python, so you can shorten it to:

<html>
<head>
  <script>
    var myGeocode = [{{ ', '.join(geocode) }}];
  </script>
</head>
<body>
  <p>Hello World</p>
  <button onclick="alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])" />
</body>
</html>

You can also use for loops, if statements and many more, see the Jinja2 documentation for more.

Also, have a look at Ford's answer who points out the tojson filter which is an addition to Jinja2's standard set of filters.

Edit Nov 2018: tojson is now included in Jinja2's standard set of filters.

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

Lot's of great answer. I just want to add a small note about decoupling the stream.

cin.tie(NULL);

I have faced an issue while decoupling the stream with CodeChef platform. When I submitted my code, the platform response was "Wrong Answer" but after tying the stream and testing the submission. It worked.

So, If anyone wants to untie the stream, the output stream must be flushed.

Edit: I am not familiar with all the platform but this is what I have experienced.

ComboBox: Adding Text and Value to an Item (no Binding Source)

Don't know if this will work for the situation given in the original post (never mind the fact that this is two years later), but this example works for me:

Hashtable htImageTypes = new Hashtable();
htImageTypes.Add("JPEG", "*.jpg");
htImageTypes.Add("GIF", "*.gif");
htImageTypes.Add("BMP", "*.bmp");

foreach (DictionaryEntry ImageType in htImageTypes)
{
    cmbImageType.Items.Add(ImageType);
}
cmbImageType.DisplayMember = "key";
cmbImageType.ValueMember = "value";

To read your value back out, you'll have to cast the SelectedItem property to a DictionaryEntry object, and you can then evaluate the Key and Value properties of that. For instance:

DictionaryEntry deImgType = (DictionaryEntry)cmbImageType.SelectedItem;
MessageBox.Show(deImgType.Key + ": " + deImgType.Value);

What is the best IDE to develop Android apps in?

I think intellij is the best option for android. i have used both eclipse and intellij and found intellij is much easier to use with android as compared to eclipse because of these reasons :-

Intellij provides a built-in support for android and you don't have to configure it as you need to do with eclipse. Intellij gives you auto-lookup feature which is really important for developer like us to increase our productivity. And if we talk about eclipse you have to type each and every method, classname etc on your own. (May be eclipse has this feature too but i never found it and trust me i tried to find it like anything) Its much more user friendly and easy to use than eclipse. I hope it will help you and other members of stack overflow to decide which IDE is best for Android development.

My personal choice is Intellij.

EDIT

But there is one thing i love about eclipse and that is visual layout creator. You can use drag and drop technique to create a layout and eclipse will automatically generate an XML file for you just like XCODE.

EDIT

Good News!! Intellij added a new feature which shows how your app's view is going to look like. It doesn't work exactly like Eclipse but it will give you a good idea about your layout.

My personal choice is still Intellij because it helps me to type faster than eclipse.

EDIT

Ok guys these days i am using eclipse juno and found its kind of buggy and slow. So if you still want to use eclipse better stick to some older version. And finally i am able to found how to enable auto-complete in eclipse. Below is a small tutorial.

Eclipse -> Preference - > Java -> Editor -> Content Assist -> Auto Activation

Now put following in the three given boxes

Auto Activation delay(ms) - 0
Auto activation triggers for java - .(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Auto activation triggers for javadoc - @#

You are now good to go. Happy coding.

EDIT

As now Google has adopted Intellij for their own Android dev tool, there is no question now about which one is better. Intellij is far far better than eclipse. And i switched back to Intellij and it feels like i am back home!! :D

How does the stack work in assembly language?

(I've made a gist of all the code in this answer in case you want to play with it)

I have only ever did most basic things in asm during my CS101 course back in 2003. And I had never really "got it" how asm and stack work until I've realized that it's all basicaly like programming in C or C++ ... but without local variables, parameters and functions. Probably doesn't sound easy yet :) Let me show you (for x86 asm with Intel syntax).


1. What is the stack

Stack is usually a contiguous chunk of memory allocated for every thread before they start. You can store there whatever you want. In C++ terms (code snippet #1):

const int STACK_CAPACITY = 1000;
thread_local int stack[STACK_CAPACITY];

2. Stack's top and bottom

In principle, you could store values in random cells of stack array (snippet #2.1):

stack[333] = 123;
stack[517] = 456;
stack[555] = stack[333] + stack[517];

But imagine how hard would it be to remember which cells of stack are already in use and wich ones are "free". That's why we store new values on the stack next to each other.

One weird thing about (x86) asm's stack is that you add things there starting with the last index and move to lower indexes: stack[999], then stack[998] and so on (snippet #2.2):

stack[999] = 123;
stack[998] = 456;
stack[997] = stack[999] + stack[998];

And still (caution, you're gonna be confused now) the "official" name for stack[999] is bottom of the stack.
The last used cell (stack[997] in the example above) is called top of the stack (see Where the top of the stack is on x86).


3. Stack pointer (SP)

For the purpose of this discussion let's assume CPU registers are represented as global variables (see General-Purpose Registers).

int AX, BX, SP, BP, ...;
int main(){...}

There is special CPU register (SP) that tracks the top of the stack. SP is a pointer (holds a memory address like 0xAAAABBCC). But for the purposes of this post I'll use it as an array index (0, 1, 2, ...).

When a thread starts, SP == STACK_CAPACITY and then the program and OS modify it as needed. The rule is you can't write to stack cells beyond stack's top and any index less then SP is invalid and unsafe (because of system interrupts), so you first decrement SP and then write a value to the newly allocated cell.

When you want to push several values in the stack in a row, you can reserve space for all of them upfront (snippet #3):

SP -= 3;
stack[999] = 12;
stack[998] = 34;
stack[997] = stack[999] + stack[998];

Note. Now you can see why allocation on the stack is so fast - it's just a single register decrement.


4. Local variables

Let's take a look at this simplistic function (snippet #4.1):

int triple(int a) {
    int result = a * 3;
    return result;
}

and rewrite it without using of local variable (snippet #4.2):

int triple_noLocals(int a) {
    SP -= 1; // move pointer to unused cell, where we can store what we need
    stack[SP] = a * 3;
    return stack[SP];
}

and see how it is being called (snippet #4.3):

// SP == 1000
someVar = triple_noLocals(11);
// now SP == 999, but we don't need the value at stack[999] anymore
// and we will move the stack index back, so we can reuse this cell later
SP += 1; // SP == 1000 again

5. Push / pop

Addition of a new element on the top of the stack is such a frequent operation, that CPUs have a special instruction for that, push. We'll implent it like this (snippet 5.1):

void push(int value) {
    --SP;
    stack[SP] = value;
}

Likewise, taking the top element of the stack (snippet 5.2):

void pop(int& result) {
    result = stack[SP];
    ++SP; // note that `pop` decreases stack's size
}

Common usage pattern for push/pop is temporarily saving some value. Say, we have something useful in variable myVar and for some reason we need to do calculations which will overwrite it (snippet 5.3):

int myVar = ...;
push(myVar); // SP == 999
myVar += 10;
... // do something with new value in myVar
pop(myVar); // restore original value, SP == 1000

6. Function parameters

Now let's pass parameters using stack (snippet #6):

int triple_noL_noParams() { // `a` is at index 999, SP == 999
    SP -= 1; // SP == 998, stack[SP + 1] == a
    stack[SP] = stack[SP + 1] * 3;
    return stack[SP];
}

int main(){
    push(11); // SP == 999
    assert(triple(11) == triple_noL_noParams());
    SP += 2; // cleanup 1 local and 1 parameter
}

7. return statement

Let's return value in AX register (snippet #7):

void triple_noL_noP_noReturn() { // `a` at 998, SP == 998
    SP -= 1; // SP == 997

    stack[SP] = stack[SP + 1] * 3;
    AX = stack[SP];

    SP += 1; // finally we can cleanup locals right in the function body, SP == 998
}

void main(){
    ... // some code
    push(AX); // save AX in case there is something useful there, SP == 999
    push(11); // SP == 998
    triple_noL_noP_noReturn();
    assert(triple(11) == AX);
    SP += 1; // cleanup param
             // locals were cleaned up in the function body, so we don't need to do it here
    pop(AX); // restore AX
    ...
}

8. Stack base pointer (BP) (also known as frame pointer) and stack frame

Lets take more "advanced" function and rewrite it in our asm-like C++ (snippet #8.1):

int myAlgo(int a, int b) {
    int t1 = a * 3;
    int t2 = b * 3;
    return t1 - t2;
}

void myAlgo_noLPR() { // `a` at 997, `b` at 998, old AX at 999, SP == 997
    SP -= 2; // SP == 995

    stack[SP + 1] = stack[SP + 2] * 3; 
    stack[SP]     = stack[SP + 3] * 3;
    AX = stack[SP + 1] - stack[SP];

    SP += 2; // cleanup locals, SP == 997
}

int main(){
    push(AX); // SP == 999
    push(22); // SP == 998
    push(11); // SP == 997
    myAlgo_noLPR();
    assert(myAlgo(11, 22) == AX);
    SP += 2;
    pop(AX);
}

Now imagine we decided to introduce new local variable to store result there before returning, as we do in tripple (snippet #4.1). The body of the function will be (snippet #8.2):

SP -= 3; // SP == 994
stack[SP + 2] = stack[SP + 3] * 3; 
stack[SP + 1] = stack[SP + 4] * 3;
stack[SP]     = stack[SP + 2] - stack[SP + 1];
AX = stack[SP];
SP += 3;

You see, we had to update every single reference to function parameters and local variables. To avoid that, we need an anchor index, which doesn't change when the stack grows.

We will create the anchor right upon function entry (before we allocate space for locals) by saving current top (value of SP) into BP register. Snippet #8.3:

void myAlgo_noLPR_withAnchor() { // `a` at 997, `b` at 998, SP == 997
    push(BP);   // save old BP, SP == 996
    BP = SP;    // create anchor, stack[BP] == old value of BP, now BP == 996
    SP -= 2;    // SP == 994

    stack[BP - 1] = stack[BP + 1] * 3;
    stack[BP - 2] = stack[BP + 2] * 3;
    AX = stack[BP - 1] - stack[BP - 2];

    SP = BP;    // cleanup locals, SP == 996
    pop(BP);    // SP == 997
}

The slice of stack, wich belongs to and is in full control of the function is called function's stack frame. E.g. myAlgo_noLPR_withAnchor's stack frame is stack[996 .. 994] (both idexes inclusive).
Frame starts at function's BP (after we've updated it inside function) and lasts until the next stack frame. So the parameters on the stack are part of the caller's stack frame (see note 8a).

Notes:
8a. Wikipedia says otherwise about parameters, but here I adhere to Intel software developer's manual, see vol. 1, section 6.2.4.1 Stack-Frame Base Pointer and Figure 6-2 in section 6.3.2 Far CALL and RET Operation. Function's parameters and stack frame are part of function's activation record (see The gen on function perilogues).
8b. positive offsets from BP point to function parameters and negative offsets point to local variables. That's pretty handy for debugging
8c. stack[BP] stores the address of the previous stack frame, stack[stack[BP]] stores pre-previous stack frame and so on. Following this chain, you can discover frames of all the functions in the programm, which didn't return yet. This is how debuggers show you call stack
8d. the first 3 instructions of myAlgo_noLPR_withAnchor, where we setup the frame (save old BP, update BP, reserve space for locals) are called function prologue


9. Calling conventions

In snippet 8.1 we've pushed parameters for myAlgo from right to left and returned result in AX. We could as well pass params left to right and return in BX. Or pass params in BX and CX and return in AX. Obviously, caller (main()) and called function must agree where and in which order all this stuff is stored.

Calling convention is a set of rules on how parameters are passed and result is returned.

In the code above we've used cdecl calling convention:

  • Parameters are passed on the stack, with the first argument at the lowest address on the stack at the time of the call (pushed last <...>). The caller is responsible for popping parameters back off the stack after the call.
  • the return value is placed in AX
  • EBP and ESP must be preserved by the callee (myAlgo_noLPR_withAnchor function in our case), such that the caller (main function) can rely on those registers not having been changed by a call.
  • All other registers (EAX, <...>) may be freely modified by the callee; if a caller wishes to preserve a value before and after the function call, it must save the value elsewhere (we do this with AX)

(Source: example "32-bit cdecl" from Stack Overflow Documentation; copyright 2016 by icktoofay and Peter Cordes ; licensed under CC BY-SA 3.0. An archive of the full Stack Overflow Documentation content can be found at archive.org, in which this example is indexed by topic ID 3261 and example ID 11196.)


10. Function calls

Now the most interesting part. Just like data, executable code is also stored in memory (completely unrelated to memory for stack) and every instruction has an address.
When not commanded otherwise, CPU executes instructions one after another, in the order they are stored in memory. But we can command CPU to "jump" to another location in memory and execute instructions from there on. In asm it can be any address, and in more high-level languages like C++ you can only jump to addresses marked by labels (there are workarounds but they are not pretty, to say the least).

Let's take this function (snippet #10.1):

int myAlgo_withCalls(int a, int b) {
    int t1 = triple(a);
    int t2 = triple(b);
    return t1 - t2;
}

And instead of calling tripple C++ way, do the following:

  1. copy tripple's code to the beginning of myAlgo body
  2. at myAlgo entry jump over tripple's code with goto
  3. when we need to execute tripple's code, save on the stack address of the code line just after tripple call, so we can return here later and continue execution (PUSH_ADDRESS macro below)
  4. jump to the address of the 1st line (tripple function) and execute it to the end (3. and 4. together are CALL macro)
  5. at the end of the tripple (after we've cleaned up locals), take return address from the top of the stack and jump there (RET macro)

Because there is no easy way to jump to particular code address in C++, we will use labels to mark places of jumps. I won't go into detail how macros below work, just believe me they do what I say they do (snippet #10.2):

// pushes the address of the code at label's location on the stack
// NOTE1: this gonna work only with 32-bit compiler (so that pointer is 32-bit and fits in int)
// NOTE2: __asm block is specific for Visual C++. In GCC use https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
#define PUSH_ADDRESS(labelName) {               \
    void* tmpPointer;                           \
    __asm{ mov [tmpPointer], offset labelName } \
    push(reinterpret_cast<int>(tmpPointer));    \
}

// why we need indirection, read https://stackoverflow.com/a/13301627/264047
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)

// generates token (not a string) we will use as label name. 
// Example: LABEL_NAME(155) will generate token `lbl_155`
#define LABEL_NAME(num) TOKENPASTE2(lbl_, num)

#define CALL_IMPL(funcLabelName, callId)    \
    PUSH_ADDRESS(LABEL_NAME(callId));       \
    goto funcLabelName;                     \
    LABEL_NAME(callId) :

// saves return address on the stack and jumps to label `funcLabelName`
#define CALL(funcLabelName) CALL_IMPL(funcLabelName, __LINE__)

// takes address at the top of stack and jump there
#define RET() {                                         \
    int tmpInt;                                         \
    pop(tmpInt);                                        \
    void* tmpPointer = reinterpret_cast<void*>(tmpInt); \
    __asm{ jmp tmpPointer }                             \
}

void myAlgo_asm() {
    goto my_algo_start;

triple_label:
    push(BP);
    BP = SP;
    SP -= 1;

    // stack[BP] == old BP, stack[BP + 1] == return address
    stack[BP - 1] = stack[BP + 2] * 3;
    AX = stack[BP - 1];

    SP = BP;     
    pop(BP);
    RET();

my_algo_start:
    push(BP);   // SP == 995
    BP = SP;    // BP == 995; stack[BP] == old BP, 
                // stack[BP + 1] == dummy return address, 
                // `a` at [BP + 2], `b` at [BP + 3]
    SP -= 2;    // SP == 993

    push(AX);
    push(stack[BP + 2]);
    CALL(triple_label);
    stack[BP - 1] = AX;
    SP -= 1;
    pop(AX);

    push(AX);
    push(stack[BP + 3]);
    CALL(triple_label);
    stack[BP - 2] = AX;
    SP -= 1;
    pop(AX);

    AX = stack[BP - 1] - stack[BP - 2];

    SP = BP; // cleanup locals, SP == 997
    pop(BP);
}

int main() {
    push(AX);
    push(22);
    push(11);
    push(7777); // dummy value, so that offsets inside function are like we've pushed return address
    myAlgo_asm();
    assert(myAlgo_withCalls(11, 22) == AX);
    SP += 1; // pop dummy "return address"
    SP += 2;
    pop(AX);
}

Notes:
10a. because return address is stored on the stack, in principle we can change it. This is how stack smashing attack works
10b. the last 3 instructions at the "end" of triple_label (cleanup locals, restore old BP, return) are called function's epilogue


11. Assembly

Now let's look at real asm for myAlgo_withCalls. To do that in Visual Studio:

  • set build platform to x86 (not x86_64)
  • build type: Debug
  • set break point somewhere inside myAlgo_withCalls
  • run, and when execution stops at break point press Ctrl + Alt + D

One difference with our asm-like C++ is that asm's stack operate on bytes instead of ints. So to reserve space for one int, SP will be decremented by 4 bytes.
Here we go (snippet #11.1, line numbers in comments are from the gist):

;   114: int myAlgo_withCalls(int a, int b) {
 push        ebp        ; create stack frame 
 mov         ebp,esp  
; return address at (ebp + 4), `a` at (ebp + 8), `b` at (ebp + 12)
 
 sub         esp,0D8h   ; reserve space for locals. Compiler can reserve more bytes then needed. 0D8h is hexadecimal == 216 decimal 
 
 push        ebx        ; cdecl requires to save all these registers
 push        esi  
 push        edi  
 
 ; fill all the space for local variables (from (ebp-0D8h) to (ebp)) with value 0CCCCCCCCh repeated 36h times (36h * 4 == 0D8h)
 ; see https://stackoverflow.com/q/3818856/264047
 ; I guess that's for ease of debugging, so that stack is filled with recognizable values
 ; 0CCCCCCCCh in binary is 110011001100...
 lea         edi,[ebp-0D8h]     
 mov         ecx,36h    
 mov         eax,0CCCCCCCCh  
 rep stos    dword ptr es:[edi]  
 
;   115:    int t1 = triple(a);
 mov         eax,dword ptr [ebp+8]   ; push parameter `a` on the stack
 push        eax  
 
 call        triple (01A13E8h)  
 add         esp,4                   ; clean up param 
 mov         dword ptr [ebp-8],eax   ; copy result from eax to `t1`
 
;   116:    int t2 = triple(b);
 mov         eax,dword ptr [ebp+0Ch] ; push `b` (0Ch == 12)
 push        eax  
 
 call        triple (01A13E8h)  
 add         esp,4  
 mov         dword ptr [ebp-14h],eax ; t2 = eax
 
 mov         eax,dword ptr [ebp-8]   ; calculate and store result in eax
 sub         eax,dword ptr [ebp-14h]  

 pop         edi  ; restore registers
 pop         esi  
 pop         ebx  
 
 add         esp,0D8h  ; check we didn't mess up esp or ebp. this is only for debug builds
 cmp         ebp,esp  
 call        __RTC_CheckEsp (01A116Dh)  
 
 mov         esp,ebp  ; destroy frame
 pop         ebp  
 ret  

And asm for tripple (snippet #11.2):

 push        ebp  
 mov         ebp,esp  
 sub         esp,0CCh  
 push        ebx  
 push        esi  
 push        edi  
 lea         edi,[ebp-0CCh]  
 mov         ecx,33h  
 mov         eax,0CCCCCCCCh  
 rep stos    dword ptr es:[edi]  
 imul        eax,dword ptr [ebp+8],3  
 mov         dword ptr [ebp-8],eax  
 mov         eax,dword ptr [ebp-8]  
 pop         edi  
 pop         esi  
 pop         ebx  
 mov         esp,ebp  
 pop         ebp  
 ret  

Hope, after reading this post, assembly doesn't look as cryptic as before :)


Here are links from the post's body and some further reading:

stdcall and cdecl

Raymond Chen gives a nice overview of what __stdcall and __cdecl does.

(1) The caller "knows" to clean up the stack after calling a function because the compiler knows the calling convention of that function and generates the necessary code.

void __stdcall StdcallFunc() {}

void __cdecl CdeclFunc()
{
    // The compiler knows that StdcallFunc() uses the __stdcall
    // convention at this point, so it generates the proper binary
    // for stack cleanup.
    StdcallFunc();
}

It is possible to mismatch the calling convention, like this:

LRESULT MyWndProc(HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam);
// ...
// Compiler usually complains but there's this cast here...
windowClass.lpfnWndProc = reinterpret_cast<WNDPROC>(&MyWndProc);

So many code samples get this wrong it's not even funny. It's supposed to be like this:

// CALLBACK is #define'd as __stdcall
LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg
    WPARAM wParam, LPARAM lParam);
// ...
windowClass.lpfnWndProc = &MyWndProc;

However, assuming the programmer doesn't ignore compiler errors, the compiler will generate the code needed to clean up the stack properly since it'll know the calling conventions of the functions involved.

(2) Both ways should work. In fact, this happens quite frequently at least in code that interacts with the Windows API, because __cdecl is the default for C and C++ programs according to the Visual C++ compiler and the WinAPI functions use the __stdcall convention.

(3) There should be no real performance difference between the two.

Converting unix timestamp string to readable date

Use datetime module:

from datetime import datetime
ts = int("1284101485")

# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

Using Javascript in CSS

I think what you may be thinking of is expressions or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:

width:expression(document.body.clientWidth > 800? "800px": "auto" );

This code makes IE emulate the max-width property it doesn't support.

All things considered, however, avoid using these. They are a bad, bad thing.

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

I had the same issue just now, and I found it to be one of the simplest of oversights. I was building classes, copying and pasting code from one class file to the others. When I changed the name of the class in, say Class2, for example, there was a dropdown next to the class name asking if I wanted to change all references to Class2, which, when I selected 'yes', it in turn changed Class1's name to Class2.

Like I said, this is a very simple oversight that had me scratching my head for a short while, but double check your other files, especially the source file you copied from to ensure that VS didn't change the name on you, behind the scenes.

Date Comparison using Java

Use java.util.Calendar if you have extensive date related processing.

Date has before(), after() methods. you could use them as well.

HttpWebRequest using Basic authentication

If you can use the WebClient class, using basic authentication becomes simple:

var client = new WebClient {Credentials = new NetworkCredential("user_name", "password")};
var response = client.DownloadString("https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2");

Transparent CSS background color

In this case background-color:rgba(0,0,0,0.5); is the best way. For example: background-color:rgba(0,0,0,opacity option);

How to return multiple objects from a Java method?

Regarding the issue about multiple return values in general I usually use a small helper class that wraps a single return value and is passed as parameter to the method:

public class ReturnParameter<T> {
    private T value;

    public ReturnParameter() { this.value = null; }
    public ReturnParameter(T initialValue) { this.value = initialValue; }

    public void set(T value) { this.value = value; }
    public T get() { return this.value; }
}

(for primitive datatypes I use minor variations to directly store the value)

A method that wants to return multiple values would then be declared as follows:

public void methodThatReturnsTwoValues(ReturnParameter<ClassA> nameForFirstValueToReturn, ReturnParameter<ClassB> nameForSecondValueToReturn) {
    //...
    nameForFirstValueToReturn.set("...");
    nameForSecondValueToReturn.set("...");
    //...
}

Maybe the major drawback is that the caller has to prepare the return objects in advance in case he wants to use them (and the method should check for null pointers)

ReturnParameter<ClassA> nameForFirstValue = new ReturnParameter<ClassA>();
ReturnParameter<ClassB> nameForSecondValue = new ReturnParameter<ClassB>();
methodThatReturnsTwoValues(nameForFirstValue, nameForSecondValue);

Advantages (in comparison to other solutions proposed):

  • You do not have to create a special class declaration for individual methods and its return types
  • The parameters get a name and therefore are easier to differentiate when looking at the method signature
  • Type safety for each parameter

How to return first 5 objects of Array in Swift?

For getting the first 5 elements of an array, all you need to do is slice the array in question. In Swift, you do it like this: array[0..<5].

To make picking the N first elements of an array a bit more functional and generalizable, you could create an extension method for doing it. For instance:

extension Array {
    func takeElements(var elementCount: Int) -> Array {
        if (elementCount > count) {
            elementCount = count
        }
        return Array(self[0..<elementCount])
    }
}

SQL Inner Join On Null Values

You could also use the coalesce function. I tested this in PostgreSQL, but it should also work for MySQL or MS SQL server.

INNER JOIN x ON coalesce(x.qid, -1) = coalesce(y.qid, -1)

This will replace NULL with -1 before evaluating it. Hence there must be no -1 in qid.

Getting RAW Soap Data from a Web Reference Client running in ASP.net

I made following changes in web.config to get the SOAP (Request/Response) Envelope. This will output all of the raw SOAP information to the file trace.log.

<system.diagnostics>
  <trace autoflush="true"/>
  <sources>
    <source name="System.Net" maxdatasize="1024">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
    <source name="System.Net.Sockets" maxdatasize="1024">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener"
      initializeData="trace.log"/>
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose"/>
    <add name="System.Net.Sockets" value="Verbose"/>
  </switches>
</system.diagnostics>

joining two select statements

This will do what you want:

select * 
  from orders_products 
       INNER JOIN orders 
          ON orders_products.orders_id = orders.orders_id
 where products_id in (180, 181);

Visual studio code CSS indentation and formatting

I recommend using Prettier as it's very extensible but still works perfectly out of the box:

1. CMD + Shift + P -> Format Document

or

1. Select the text you want to Prettify
2. CMD + Shift + P -> Format Selection

Iterate through a C++ Vector using a 'for' loop

With STL, programmers use iterators for traversing through containers, since iterator is an abstract concept, implemented in all standard containers. For example, std::list has no operator [] at all.

Ways to insert javascript into URL?

JavaScript injection is not at attack on your web application. JavaScript injection simply adds JavaScript code for the browser to execute. The only way JavaScript could harm your web application is if you have a blog posting or some other area in which user input is stored. This could be a problem because an attacker could inject their code and leave it there for other users to execute. This attack is known as Cross-Site Scripting. The worst scenario would be Cross-Site Forgery, which allows attackers to inject a statement that will steal a user's cookie and therefore give the attacker their session ID.

What is the purpose of XSD files?

Without XML Schema (XSD file) an XML file is a relatively free set of elements and attributes. The XSD file defines which elements and attributes are permitted and in which order.

In general XML is a metalanguage. XSD files define specific languages within that metalanguage. For example, if your XSD file contains the definition of XHTML 1.0, then your XML file is required to fit XHTML 1.0 rather than some other format.

What is the equivalent of bigint in C#?

if you are using bigint in your database table, you can use Long in C#

how to check if input field is empty

As javascript is dynamically typed, rather than using the .length property as above you can simply treat the input value as a boolean:

var input = $.trim($("#spa").val());

if (input) {
    // Do Stuff
}

You can also extract the logic out into functions, then by assigning a class and using the each() method the code is more dynamic if, for example, in the future you wanted to add another input you wouldn't need to change any code.

So rather than hard coding the function call into the input markup, you can give the inputs a class, in this example it's test, and use:

$(".test").each(function () {
    $(this).keyup(function () {
        $("#submit").prop("disabled", CheckInputs());
    });
});

which would then call the following and return a boolean value to assign to the disabled property:

function CheckInputs() {
    var valid = false;
    $(".test").each(function () {
        if (valid) { return valid; }
        valid = !$.trim($(this).val());
    });
    return valid;
}

You can see a working example of everything I've mentioned in this JSFiddle.

Trigger change event of dropdown

For some reason, the other jQuery solutions provided here worked when running the script from console, however, it did not work for me when triggered from Chrome Bookmarklets.

Luckily, this Vanilla JS solution (the triggerChangeEvent function) did work:

_x000D_
_x000D_
/**_x000D_
  * Trigger a `change` event on given drop down option element._x000D_
  * WARNING: only works if not already selected._x000D_
  * @see https://stackoverflow.com/questions/902212/trigger-change-event-of-dropdown/58579258#58579258_x000D_
  */_x000D_
function triggerChangeEvent(option) {_x000D_
  // set selected property_x000D_
  option.selected = true;_x000D_
  _x000D_
  // raise event on parent <select> element_x000D_
  if ("createEvent" in document) {_x000D_
    var evt = document.createEvent("HTMLEvents");_x000D_
    evt.initEvent("change", false, true);_x000D_
    option.parentNode.dispatchEvent(evt);_x000D_
  }_x000D_
  else {_x000D_
    option.parentNode.fireEvent("onchange");_x000D_
  }_x000D_
}_x000D_
_x000D_
// ################################################_x000D_
// Setup our test case_x000D_
// ################################################_x000D_
_x000D_
(function setup() {_x000D_
  const sel = document.querySelector('#fruit');_x000D_
  sel.onchange = () => {_x000D_
    document.querySelector('#result').textContent = sel.value;_x000D_
  };_x000D_
})();_x000D_
_x000D_
function runTest() {_x000D_
  const sel = document.querySelector('#selector').value;_x000D_
  const optionEl = document.querySelector(sel);_x000D_
  triggerChangeEvent(optionEl);_x000D_
}
_x000D_
<select id="fruit">_x000D_
  <option value="">(select a fruit)</option>_x000D_
  <option value="apple">Apple</option>_x000D_
  <option value="banana">Banana</option>_x000D_
  <option value="pineapple">Pineapple</option>_x000D_
</select>_x000D_
_x000D_
<p>_x000D_
  You have selected: <b id="result"></b>_x000D_
</p>_x000D_
<p>_x000D_
  <input id="selector" placeholder="selector" value="option[value='banana']">_x000D_
  <button onclick="runTest()">Trigger select!</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to open a different activity on recyclerView item onclick

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<Android> android;
Context context;
private ImageView img;
public DataAdapter(Context contextN, ArrayList<Android> android) {
    this.android = android;
    this.context=contextN;
}

@Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_list, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {

    viewHolder.tv_name.setText(android.get(i).getOffer());
    viewHolder.tv_version.setText(android.get(i).getOfferType());
    Picasso.with(context).load(android.get(i).getImg()).transform(new CircleTransform()).into(img);

}

@Override
public int getItemCount() {
    return android.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{
    private TextView tv_name,tv_version,tv_api_level;

    public ViewHolder(View view) {
        super(view);

        tv_name = (TextView)view.findViewById(R.id.tv_name);
        tv_version = (TextView)view.findViewById(R.id.tv_version);
        img = (ImageView) view.findViewById(R.id.img);

                context = itemView.getContext();

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        int itemPosition = getLayoutPosition();
                        Toast.makeText(context, "" + itemPosition, Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(context,Show.class);
                        intent.putExtra("name",""+android.get(itemPosition).getOffer());
                        intent.putExtra("img",""+android.get(itemPosition).getImg());
                        context.startActivity(intent);

            }
        });
    }
}
}

bundle install returns "Could not locate Gemfile"

Think more about what you are installing and navigate Gemfile folder, then try using sudo bundle install

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

How do I sort a two-dimensional (rectangular) array in C#?

Load your two-dimensional string array into an actual DataTable (System.Data.DataTable), and then use the DataTable object's Select() method to generate a sorted array of DataRow objects (or use a DataView for a similar effect).

// assumes stringdata[row, col] is your 2D string array
DataTable dt = new DataTable();
// assumes first row contains column names:
for (int col = 0; col < stringdata.GetLength(1); col++)
{
    dt.Columns.Add(stringdata[0, col]);
}
// load data from string array to data table:
for (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)
{
    DataRow row = dt.NewRow();
    for (int col = 0; col < stringdata.GetLength(1); col++)
    {
        row[col] = stringdata[rowindex, col];
    }
    dt.Rows.Add(row);
}
// sort by third column:
DataRow[] sortedrows = dt.Select("", "3");
// sort by column name, descending:
sortedrows = dt.Select("", "COLUMN3 DESC");

You could also write your own method to sort a two-dimensional array. Both approaches would be useful learning experiences, but the DataTable approach would get you started on learning a better way of handling tables of data in a C# application.

How do I enumerate through a JObject?

JObjects can be enumerated via JProperty objects by casting it to a JToken:

foreach (JProperty x in (JToken)obj) { // if 'obj' is a JObject
    string name = x.Name;
    JToken value = x.Value;
}

If you have a nested JObject inside of another JObject, you don't need to cast because the accessor will return a JToken:

foreach (JProperty x in obj["otherObject"]) { // Where 'obj' and 'obj["otherObject"]' are both JObjects
    string name = x.Name;
    JToken value = x.Value;
}

Bash: Syntax error: redirection unexpected

Does your script reference /bin/bash or /bin/sh in its hash bang line? The default system shell in Ubuntu is dash, not bash, so if you have #!/bin/sh then your script will be using a different shell than you expect. Dash does not have the <<< redirection operator.

How to check if a file exists in Go?

basicly


package main

import (
    "fmt"
    "os"
)

func fileExists(path string) bool {
    _, err := os.Stat(path)
    return !os.IsNotExist(err)
}

func main() {

    var file string = "foo.txt"
    exist := fileExists(file)
    
    if exist {
        fmt.Println("file exist")
    } else {

        fmt.Println("file not exists")
    }

}

run example

other way

with os.Open

package main

import (
    "fmt"
    "os"
)

func fileExists(path string) bool {
    _, err := os.Open(path) // For read access.
    return err == nil

}

func main() {

    fmt.Println(fileExists("d4d.txt"))

}


run it

How can I convert a string to boolean in JavaScript?

You can use regular expressions:

/*
 * Converts a string to a bool.
 *
 * This conversion will:
 *
 *  - match 'true', 'on', or '1' as true.
 *  - ignore all white-space padding
 *  - ignore capitalization (case).
 *
 * '  tRue  ','ON', and '1   ' will all evaluate as true.
 *
 */
function strToBool(s)
{
    // will match one and only one of the string 'true','1', or 'on' rerardless
    // of capitalization and regardless off surrounding white-space.
    //
    regex=/^\s*(true|1|on)\s*$/i

    return regex.test(s);
}

If you like extending the String class you can do:

String.prototype.bool = function() {
    return strToBool(this);
};

alert("true".bool());

For those (see the comments) that would like to extend the String object to get this but are worried about enumerability and are worried about clashing with other code that extends the String object:

Object.defineProperty(String.prototype, "com_example_bool", {
    get : function() {
        return (/^(true|1)$/i).test(this);
    }
});
alert("true".com_example_bool);

(Won't work in older browsers of course and Firefox shows false while Opera, Chrome, Safari and IE show true. Bug 720760)

What in the world are Spring beans?

The XML configuration of Spring is composed of Beans and Beans are basically classes. They're just POJOs that we use inside of our ApplicationContext. Defining Beans can be thought of as replacing the keyword new. So wherever you are using the keyword new in your application something like:

MyRepository myRepository =new MyRepository ();

Where you're using that keyword new that's somewhere you can look at removing that configuration and placing it into an XML file. So we will code like this:

<bean name="myRepository " 
      class="com.demo.repository.MyRepository " />

Now we can simply use Setter Injection/ Constructor Injection. I'm using Setter Injection.

public class MyServiceImpl implements MyService {
    private MyRepository myRepository;
    public void setMyRepository(MyRepository myRepository)
        {
    this.myRepository = myRepository ;
        }
public List<Customer> findAll() {
        return myRepository.findAll();
    }
}

How can I do GUI programming in C?

Windows API and Windows SDK if you want to build everything yourself (or) Windows API and Visual C Express. Get the 2008 edition. This is a full blown IDE and a remarkable piece of software by Microsoft for Windows development.

All operating systems are written in C. So, any application, console/GUI you write in C is the standard way of writing for the operating system.

Update ViewPager dynamically?

Using ViewPager2 and FragmentStateAdapter:

Updating data dynamically is supported by ViewPager2.

There is an important note in the docs on how to get this working:

Note: The DiffUtil utility class relies on identifying items by ID. If you are using ViewPager2 to page through a mutable collection, you must also override getItemId() and containsItem(). (emphasis mine)

Based on ViewPager2 documentation and Android's Github sample project there are a few steps we need to take:

  1. Set up FragmentStateAdapter and override the following methods: getItemCount, createFragment, getItemId, and containsItem (note: FragmentStatePagerAdapter is not supported by ViewPager2)

  2. Attach adapter to ViewPager2

  3. Dispatch list updates to ViewPager2 with DiffUtil (don't need to use DiffUtil, as seen in sample project)


Example:

private val items: List<Int>
    get() = viewModel.items
private val viewPager: ViewPager2 = binding.viewPager

private val adapter = object : FragmentStateAdapter(this@Fragment) {
    override fun getItemCount() = items.size
    override fun createFragment(position: Int): Fragment = MyFragment()
    override fun getItemId(position: Int): Long = items[position].id
    override fun containsItem(itemId: Long): Boolean = items.any { it.id == itemId }
}
viewPager.adapter = adapter
    
private fun onDataChanged() {
    DiffUtil
        .calculateDiff(object : DiffUtil.Callback() {
            override fun getOldListSize(): Int = viewPager.adapter.itemCount
            override fun getNewListSize(): Int = viewModel.items.size
            override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
                viewPager.adapter?.getItemId(oldItemPosition) == viewModel.items[newItemPosition].id

            override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
                areItemsTheSame(oldItemPosition, newItemPosition)
        }, false)
        .dispatchUpdatesTo(viewPager.adapter!!)
}

How to install PHP intl extension in Ubuntu 14.04

you could search with aptitude search intl after you can choose the right one, for example sudo aptitude install php-intl and finally sudo service apache2 restart

good Luck!

How to list containers in Docker

To display only running containers

docker ps

To show all containers (includes all states)

docker ps -a

To show the latest created container (includes all states)

docker ps -l

To show n last created containers (includes all states)

docker ps -n=-1

To display total file sizes

docker ps -s

In the new version of Docker, commands are updated, and some management commands are added:

docker container ls

List all the running containers.

docker container ls -a

Use '=' or LIKE to compare strings in SQL?

In my small experience:

"=" for Exact Matches.

"LIKE" for Partial Matches.

What's the best practice to "git clone" into an existing folder?

To clone a git repo into an empty existing directory do the following:

cd myfolder
git clone https://myrepo.com/git.git . 

Notice the . at the end of your git clone command. That will download the repo into the current working directory.

Notepad++ incrementally replace

Not sure about regex, but there is a way for you to do this in Notepad++, although it isn't very flexible.

In the example that you gave, hold Alt and select the column of numbers that you wish to change. Then go to Edit->Column Editor and select the Number to Insert radio button in the window that appears. Then specify your initial number and increment, and hit OK. It should write out the incremented numbers.

Note: this also works with the Multi-editing feature (selecting several locations while maintaining Ctrl key pressed).

This is, however, not anywhere near the flexibility that most people would find useful. Notepad++ is great, but if you want a truly powerful editor that can do things like this with ease, I'd say use Vim.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

When should I use Memcache instead of Memcached?

This is 2013. Forget about the 2009 comments. Likewise, if you are running serious traffic loads, do not even contemplate how to make-do with a windows based memcache. When dealing with a very large scale (500+ front end web servers) and 20+ back end database servers and replicants (mysql & mssql mix), a farm of memcached servers (12 servers in group) supports multiple high volume OLTP applications answering 25K ~ 40K mc->get calls per-second. These calls are those that do NOT have to reach a database.

IMHO, this use of memcached provided SERIOUS $$$,$$$savings on CAPEX for new DB servers & licences as well as on support contracts for large commercial designs.

Replace substring with another substring C++

There is no one built-in function in C++ to do this. If you'd like to replace all instances of one substring with another, you can do so by intermixing calls to string::find and string::replace. For example:

size_t index = 0;
while (true) {
     /* Locate the substring to replace. */
     index = str.find("abc", index);
     if (index == std::string::npos) break;

     /* Make the replacement. */
     str.replace(index, 3, "def");

     /* Advance index forward so the next iteration doesn't pick it up as well. */
     index += 3;
}

In the last line of this code, I've incremented index by the length of the string that's been inserted into the string. In this particular example - replacing "abc" with "def" - this is not actually necessary. However, in a more general setting, it is important to skip over the string that's just been replaced. For example, if you want to replace "abc" with "abcabc", without skipping over the newly-replaced string segment, this code would continuously replace parts of the newly-replaced strings until memory was exhausted. Independently, it might be slightly faster to skip past those new characters anyway, since doing so saves some time and effort by the string::find function.

Hope this helps!

How to make an autocomplete address field with google maps api?

It is easy, but the Google API examples give you detailed explanation with how you can get the map to display the entered location. For only autocomplete feature, you can do something like this.

First, enable Google Places API Web Service. Get the API key. You will have to use it in the script tag in html file.

<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>

Use script file to load the autocomplete class. Your scripts.js file will look something like this.

    // scripts.js custom js file
$(document).ready(function () {
   google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    var input = document.getElementById('location');
    var autocomplete = new google.maps.places.Autocomplete(input);
}

Principal Component Analysis (PCA) in Python

this sample code loads the Japanese yield curve, and creates PCA components. It then estimates a given date's move using the PCA and compares it against the actual move.

%matplotlib inline

import numpy as np
import scipy as sc
from scipy import stats
from IPython.display import display, HTML
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import datetime
from datetime import timedelta

import quandl as ql

start = "2016-10-04"
end = "2019-10-04"

ql_data = ql.get("MOFJ/INTEREST_RATE_JAPAN", start_date = start, end_date = end).sort_index(ascending= False)

eigVal_, eigVec_ = np.linalg.eig(((ql_data[:300]).diff(-1)*100).cov()) # take latest 300 data-rows and normalize to bp
print('number of PCA are', len(eigVal_))

loc_ = 10
plt.plot(eigVec_[:,0], label = 'PCA1')
plt.plot(eigVec_[:,1], label = 'PCA2')
plt.plot(eigVec_[:,2], label = 'PCA3')
plt.xticks(range(len(eigVec_[:,0])), ql_data.columns)
plt.legend()
plt.show()

x = ql_data.diff(-1).iloc[loc_].values * 100 # set the differences
x_ = x[:,np.newaxis]
a1, _, _, _ = np.linalg.lstsq(eigVec_[:,0][:, np.newaxis], x_) # linear regression without intercept
a2, _, _, _ = np.linalg.lstsq(eigVec_[:,1][:, np.newaxis], x_)
a3, _, _, _ = np.linalg.lstsq(eigVec_[:,2][:, np.newaxis], x_)

pca_mv = m1 * eigVec_[:,0] + m2 * eigVec_[:,1] + m3 * eigVec_[:,2] + c1 + c2 + c3
pca_MV = a1[0][0] * eigVec_[:,0] + a2[0][0] * eigVec_[:,1] + a3[0][0] * eigVec_[:,2]
pca_mV = b1 * eigVec_[:,0] + b2 * eigVec_[:,1] + b3 * eigVec_[:,2]

display(pd.DataFrame([eigVec_[:,0], eigVec_[:,1], eigVec_[:,2], x, pca_MV]))
print('PCA1 regression is', a1, a2, a3)


plt.plot(pca_MV)
plt.title('this is with regression and no intercept')
plt.plot(ql_data.diff(-1).iloc[loc_].values * 100, )
plt.title('this is with actual moves')
plt.show()

Make a Bash alias that takes a parameter?

Syntax:

alias shortName="your custom command here"

Example:

alias tlogs='_t_logs() { tail -f ../path/$1/to/project/logs.txt ;}; _t_logs'

Open link in new tab or window

You should add the target="_blank" and rel="noopener noreferrer" in the anchor tag.

For example:

<a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>

Adding rel="noopener noreferrer" is not mandatory, but it's a recommended security measure. More information can be found in the links below.

Source:

go to link on button click - jquery

Why not just change the second line to

document.location.href="www.example.com/index.php?id=" + $(this).attr('id');

How to find the most recent file in a directory using .NET, and without looping?

If you want to search recursively, you can use this beautiful piece of code:

public static FileInfo GetNewestFile(DirectoryInfo directory) {
   return directory.GetFiles()
       .Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
       .OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
       .FirstOrDefault();                        
}

Just call it the following way:

FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"C:\directory\"));

and that's it. Returns a FileInfo instance or null if the directory is empty.

postgresql COUNT(DISTINCT ...) very slow

I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.

Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -

SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;

Query performance is also high.

Code to loop through all records in MS Access

You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm

My own standard loop looks something like this:

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")

'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst 'Unnecessary in this case, but still a good habit
    Do Until rs.EOF = True
        'Perform an edit
        rs.Edit
        rs!VendorYN = True
        rs("VendorYN") = True 'The other way to refer to a field
        rs.Update

        'Save contact name into a variable
        sContactName = rs!FirstName & " " & rs!LastName

        'Move to the next record. Don't ever forget to do this.
        rs.MoveNext
    Loop
Else
    MsgBox "There are no records in the recordset."
End If

MsgBox "Finished looping through records."

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

How Do I Convert an Integer to a String in Excel VBA?

In my case, the function CString was not found. But adding an empty string to the value works, too.

Dim Test As Integer, Test2 As Variant
Test = 10
Test2 = Test & ""
//Test2 is now "10" not 10

How to insert multiple rows from array using CodeIgniter framework?

Although it is too late to answer this question. Here are my answer on the same.

If you are using CodeIgniter then you can use inbuilt methods defined in query_builder class.

$this->db->insert_batch()

Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

$data = array(
    array(
            'title' => 'My title',
            'name' => 'My Name',
            'date' => 'My date'
    ),
    array(
            'title' => 'Another title',
            'name' => 'Another Name',
            'date' => 'Another date'
    )
);

$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')

The first parameter will contain the table name, the second is an associative array of values.

You can find more details about query_builder here

How can I find the dimensions of a matrix in Python?

The number of rows of a list of lists would be: len(A) and the number of columns len(A[0]) given that all rows have the same number of columns, i.e. all lists in each index are of the same size.

How can I strip HTML tags from a string in ASP.NET?

For the second parameter,i.e. keep some tags, you may need some code like this by using HTMLagilityPack:

public string StripTags(HtmlNode documentNode, IList keepTags)
{
    var result = new StringBuilder();
        foreach (var childNode in documentNode.ChildNodes)
        {
            if (childNode.Name.ToLower() == "#text")
            {
                result.Append(childNode.InnerText);
            }
            else
            {
                if (!keepTags.Contains(childNode.Name.ToLower()))
                {
                    result.Append(StripTags(childNode, keepTags));
                }
                else
                {
                    result.Append(childNode.OuterHtml.Replace(childNode.InnerHtml, StripTags(childNode, keepTags)));
                }
            }
        }
        return result.ToString();
    }

More explanation on this page: http://nalgorithm.com/2015/11/20/strip-html-tags-of-an-html-in-c-strip_html-php-equivalent/

Center a column using Twitter Bootstrap 3

Bootstrap 3 now has a built-in class for this .center-block

.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

If you are still using 2.X then just add this to your CSS.

Java: Casting Object to Array type

Your values object is obviously an Object[] containing a String[] containing the values.

String[] stringValues = (String[])values[0];

How can I view all historical changes to a file in SVN

There's no built-in command for it, so I usually just do something like this:

#!/bin/bash

# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs.  The first revision of the file is emitted as
# full text since there's not previous version to compare it to.

function history_of_file() {
    url=$1 # current url of file
    svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {

#       first revision as full text
        echo
        read r
        svn log -r$r $url@HEAD
        svn cat -r$r $url@HEAD
        echo

#       remaining revisions as differences to previous revision
        while read r
        do
            echo
            svn log -r$r $url@HEAD
            svn diff -c$r $url@HEAD
            echo
        done
    }
}

Then, you can call it with:

history_of_file $1

How do I make a text go onto the next line if it overflows?

word-wrap: break-word; 

add this to your container that should do the trick

Why doesn't java.io.File have a close method?

The javadoc of the File class describes the class as:

An abstract representation of file and directory pathnames.

File is only a representation of a pathname, with a few methods concerning the filesystem (like exists()) and directory handling but actual streaming input and output is done elsewhere. Streams can be opened and closed, files cannot.

(My personal opinion is that it's rather unfortunate that Sun then went on to create RandomAccessFile, causing much confusion with its inconsistent naming.)