Programs & Examples On #Permalinks

A permalink, or permanent link, is a URL that points to a specific blog or forum entry after it has passed from the front page to the archives.

upstream sent too big header while reading response header from upstream

We ended up realising that our one server that was experiencing this had busted fpm config resulting in php errors/warnings/notices that'd normally be logged to disk were being sent over the FCGI socket. It looks like there's a parsing bug when part of the header gets split across the buffer chunks.

So setting php_admin_value[error_log] to something actually writeable and restarting php-fpm was enough to fix the problem.

We could reproduce the problem with a smaller script:

<?php
for ($i = 0; $i<$_GET['iterations']; $i++)
    error_log(str_pad("a", $_GET['size'], "a"));
echo "got here\n";

Raising the buffers made the 502s harder to hit but not impossible, e.g native:

bash-4.1# for it in {30..200..3}; do for size in {100..250..3}; do echo "size=$size iterations=$it $(curl -sv "http://localhost/debug.php?size=$size&iterations=$it" 2>&1 | egrep '^< HTTP')"; done; done | grep 502 | head
size=121 iterations=30 < HTTP/1.1 502 Bad Gateway
size=109 iterations=33 < HTTP/1.1 502 Bad Gateway
size=232 iterations=33 < HTTP/1.1 502 Bad Gateway
size=241 iterations=48 < HTTP/1.1 502 Bad Gateway
size=145 iterations=51 < HTTP/1.1 502 Bad Gateway
size=226 iterations=51 < HTTP/1.1 502 Bad Gateway
size=190 iterations=60 < HTTP/1.1 502 Bad Gateway
size=115 iterations=63 < HTTP/1.1 502 Bad Gateway
size=109 iterations=66 < HTTP/1.1 502 Bad Gateway
size=163 iterations=69 < HTTP/1.1 502 Bad Gateway
[... there would be more here, but I piped through head ...]

fastcgi_buffers 16 16k; fastcgi_buffer_size 32k;:

bash-4.1# for it in {30..200..3}; do for size in {100..250..3}; do echo "size=$size iterations=$it $(curl -sv "http://localhost/debug.php?size=$size&iterations=$it" 2>&1 | egrep '^< HTTP')"; done; done | grep 502 | head
size=223 iterations=69 < HTTP/1.1 502 Bad Gateway
size=184 iterations=165 < HTTP/1.1 502 Bad Gateway
size=151 iterations=198 < HTTP/1.1 502 Bad Gateway

So I believe the correct answer is: fix your fpm config so it logs errors to disk.

WordPress path url in js script file

For users working with the Genesis framework.

Add the following to your child theme functions.php

add_action( 'genesis_before', 'script_urls' );

function script_urls() {
?>
    <script type="text/javascript">
     var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';
    </script>
<?php
}

And use that variable to set the relative url in your script. For example:

Reset.style.background = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";

How to define an optional field in protobuf 3

Another way is that you can use bitmask for each optional field. and set those bits if values are set and reset those bits which values are not set

enum bitsV {
    baz_present = 1; // 0x01
    baz1_present = 2; // 0x02

}
message Foo {
    uint32 bitMask;
    required int32 bar = 1;
    optional int32 baz = 2;
    optional int32 baz1 = 3;
}

On parsing check for value of bitMask.

if (bitMask & baz_present)
    baz is present

if (bitMask & baz1_present)
    baz1 is present

How to go to each directory and execute a command?

If you're using GNU find, you can try -execdir parameter, e.g.:

find . -type d -execdir realpath "{}" ';'

or (as per @gniourf_gniourf comment):

find . -type d -execdir sh -c 'printf "%s/%s\n" "$PWD" "$0"' {} \;

Note: You can use ${0#./} instead of $0 to fix ./ in the front.

or more practical example:

find . -name .git -type d -execdir git pull -v ';'

If you want to include the current directory, it's even simpler by using -exec:

find . -type d -exec sh -c 'cd -P -- "{}" && pwd -P' \;

or using xargs:

find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'

Or similar example suggested by @gniourf_gniourf:

find . -type d -print0 | while IFS= read -r -d '' file; do
# ...
done

The above examples support directories with spaces in their name.


Or by assigning into bash array:

dirs=($(find . -type d))
for dir in "${dirs[@]}"; do
  cd "$dir"
  echo $PWD
done

Change . to your specific folder name. If you don't need to run recursively, you can use: dirs=(*) instead. The above example doesn't support directories with spaces in the name.

So as @gniourf_gniourf suggested, the only proper way to put the output of find in an array without using an explicit loop will be available in Bash 4.4 with:

mapfile -t -d '' dirs < <(find . -type d -print0)

Or not a recommended way (which involves parsing of ls):

ls -d */ | awk '{print $NF}' | xargs -n1 sh -c 'cd $0 && pwd && echo Do stuff'

The above example would ignore the current dir (as requested by OP), but it'll break on names with the spaces.

See also:

html <input type="text" /> onchange event not working

Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.

For static and dynamic inputs:

$(document).on('input', '.my-class', function(){
    alert('Input changed');
});

For static inputs only:

$('.my-class').on('input', function(){
    alert('Input changed');
});

JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Target class controller does not exist - Laravel 8

Happened to me when I passing null to the middleware function

Route::middleware(null)->group(function () {
    Route::get('/some-path', [SomeController::class, 'search']);
});

Passing [] for no middleware works or probably just remove the middleware call if not using middleware :D

How to get value of Radio Buttons?

You need to check one if you have two

if(rbMale.Checked)
{

}
else
{

}

You need to check all the checkboxes if more then two

if(rb1.Checked)
{

}
else if(rb2.Checked)
{

}
else if(rb3.Checked)
{

}

Pycharm: run only part of my Python file

  1. Go to File >> Settings >> Plugins and install the plugin PyCharm cell mode
  2. Go to File >> Settings >> Appearance & Behavior >> Keymap and assign your keyboard shortcuts for Run Cell and Run Cell and go to next

A cell is delimited by ##

Ref https://plugins.jetbrains.com/plugin/7858-pycharm-cell-mode

Append to the end of a file in C

Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

You need to provide a candidate for autowire. That means that an instance of PasswordHint must be known to spring in a way that it can guess that it must reference it.

Please provide the class head of PasswordHint and/or the spring bean definition of that class for further assistance.

Try changing the name of

PasswordHintAction action;

to

PasswordHintAction passwordHintAction;

so that it matches the bean definition.

define a List like List<int,string>?

You could use an immutable struct

public struct Data
{
    public Data(int intValue, string strValue)
    {
        IntegerData = intValue;
        StringData = strValue;
    }

    public int IntegerData { get; private set; }
    public string StringData { get; private set; }
}

var list = new List<Data>();

Or a KeyValuePair<int, string>

using Data = System.Collections.Generic.KeyValuePair<int, string>
...
var list = new List<Data>();
list.Add(new Data(12345, "56789"));

What does the question mark and the colon (?: ternary operator) mean in objective-c?

It's the ternary or conditional operator. It's basic form is:

condition ? valueIfTrue : valueIfFalse

Where the values will only be evaluated if they are chosen.

How to detect the end of loading of UITableView

Swift 2 solution:

// willDisplay function
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    let lastRowIndex = tableView.numberOfRowsInSection(0)
    if indexPath.row == lastRowIndex - 1 {
        fetchNewDataFromServer()
    }
}

// data fetcher function
func fetchNewDataFromServer() {
    if(!loading && !allDataFetched) {
        // call beginUpdates before multiple rows insert operation
        tableView.beginUpdates()
        // for loop
        // insertRowsAtIndexPaths
        tableView.endUpdates()
    }
}

For loop example in MySQL

You can exchange this local variable for a global, it would be easier.

DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      SET @a = 0;
      simple_loop: LOOP
         SET @a=@a+1;
         select @a;
         IF @a=5 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

Returning boolean if set is empty

def myfunc(a,b):
    c = a.intersection(b)
    return bool(c)

bool() will do something similar to not not, but more ideomatic and clear.

String representation of an Enum

Unfortunately reflection to get attributes on enums is quite slow:

See this question: Anyone know a quick way to get to custom attributes on an enum value?

The .ToString() is quite slow on enums too.

You can write extension methods for enums though:

public static string GetName( this MyEnum input ) {
    switch ( input ) {
        case MyEnum.WINDOWSAUTHENTICATION:
            return "Windows";
        //and so on
    }
}

This isn't great, but will be quick and not require the reflection for attributes or field name.


C#6 Update

If you can use C#6 then the new nameof operator works for enums, so nameof(MyEnum.WINDOWSAUTHENTICATION) will be converted to "WINDOWSAUTHENTICATION" at compile time, making it the quickest way to get enum names.

Note that this will convert the explicit enum to an inlined constant, so it doesn't work for enums that you have in a variable. So:

nameof(AuthenticationMethod.FORMS) == "FORMS"

But...

var myMethod = AuthenticationMethod.FORMS;
nameof(myMethod) == "myMethod"

Redirecting exec output to a buffer or file

For sending the output to another file (I'm leaving out error checking to focus on the important details):

if (fork() == 0)
{
    // child
    int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

    dup2(fd, 1);   // make stdout go to file
    dup2(fd, 2);   // make stderr go to file - you may choose to not do this
                   // or perhaps send stderr to another file

    close(fd);     // fd no longer needed - the dup'ed handles are sufficient

    exec(...);
}

For sending the output to a pipe so you can then read the output into a buffer:

int pipefd[2];
pipe(pipefd);

if (fork() == 0)
{
    close(pipefd[0]);    // close reading end in the child

    dup2(pipefd[1], 1);  // send stdout to the pipe
    dup2(pipefd[1], 2);  // send stderr to the pipe

    close(pipefd[1]);    // this descriptor is no longer needed

    exec(...);
}
else
{
    // parent

    char buffer[1024];

    close(pipefd[1]);  // close the write end of the pipe in the parent

    while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
    {
    }
}

jQuery Determine if a matched class has a given id

I would probably use $('.mydiv').is('#foo'); That said if you know the Id why wouldnt you just apply it to the selector in the first place?

Conversion failed when converting the nvarchar value ... to data type int

I use the latest version of SSMS or sql server management studio. I have a SQL script (in query editor) which has about 100 lines of code. This is error I got in the query:

Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the nvarchar value 'abcd' to data type int.

Solution - I had seen this kind of error before when I forgot to enclose a number (in varchar column) in single quotes.

As an aside, the error message is misleading. The actual error on line number 70 in the query editor and not line 2 as the error says!

How to parse a text file with C#

You could open the file up and use StreamReader.ReadLine to read the file in line-by-line. Then you can use String.Split to break each line into pieces (use a \t delimiter) to extract the second number.

As the number of items is different you would need to search the string for the pattern 'item\*.ddj'.

To delete an item you could (for example) keep all of the file's contents in memory and write out a new file when the user clicks 'Save'.

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

PHP Get all subdirectories of a given directory

Proper way

/**
 * Get all of the directories within a given directory.
 *
 * @param  string  $directory
 * @return array
 */
function directories($directory)
{
    $glob = glob($directory . '/*');

    if($glob === false)
    {
        return array();
    }

    return array_filter($glob, function($dir) {
        return is_dir($dir);
    });
}

Inspired by Laravel

Downloading a file from spring controllers

What I can quickly think of is, generate the pdf and store it in webapp/downloads/< RANDOM-FILENAME>.pdf from the code and send a forward to this file using HttpServletRequest

request.getRequestDispatcher("/downloads/<RANDOM-FILENAME>.pdf").forward(request, response);

or if you can configure your view resolver something like,

  <bean id="pdfViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
              value="org.springframework.web.servlet.view.JstlView" />
    <property name="order" value=”2"/>
    <property name="prefix" value="/downloads/" />
    <property name="suffix" value=".pdf" />
  </bean>

then just return

return "RANDOM-FILENAME";

Convert a byte array to integer in Java and vice versa

A basic implementation would be something like this:

public class Test {
    public static void main(String[] args) {
        int[] input = new int[] { 0x1234, 0x5678, 0x9abc };
        byte[] output = new byte[input.length * 2];

        for (int i = 0, j = 0; i < input.length; i++, j+=2) {
            output[j] = (byte)(input[i] & 0xff);
            output[j+1] = (byte)((input[i] >> 8) & 0xff);
        }

        for (int i = 0; i < output.length; i++)
            System.out.format("%02x\n",output[i]);
    }
}

In order to understand things you can read this WP article: http://en.wikipedia.org/wiki/Endianness

The above source code will output 34 12 78 56 bc 9a. The first 2 bytes (34 12) represent the first integer, etc. The above source code encodes integers in little endian format.

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

SELECT employee_number, course_code, MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

My httpd.conf is empty

OK - what you're missing is that its designed to be more industrial and serve many sites, so the config you want is probably:

/etc/apache2/sites-available/default

which on my system is linked to from /etc/apache2/sites-enabled/

if you want to have different sites with different options, copy the file and then change those...

How to: Install Plugin in Android Studio

As far as installing a custom plugin there is a good walkthrough on GitHub for the rest2mobile library that could be used for any plugin.

Basically the steps are as follows:

  1. Run Android Studio.
  2. From the menu bar, select Android Studio > Preferences.
  3. Under IDE Settings, click Plugins and then click Install plugin from disk.
  4. Navigate to the folder where you downloaded the plugin and double-click it.
  5. Restart Android Studio.

select rows in sql with latest date for each ID repeated multiple times

This question has been asked before. Please see this question.

Using the accepted answer and adapting it to your problem you get:

SELECT tt.*
FROM myTable tt
INNER JOIN
    (SELECT ID, MAX(Date) AS MaxDateTime
    FROM myTable
    GROUP BY ID) groupedtt 
ON tt.ID = groupedtt.ID 
AND tt.Date = groupedtt.MaxDateTime

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

I reached the point that I set, up to max_iter=1200000 on my LinearSVC classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False and leaving max_iter to its default.

With LogisticRegression(solver='lbfgs') classifier, you should increase max_iter. Mine have reached max_iter=7600 before the "ConvergenceWarning" disappears when training with large dataset's features.

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

How can I find the link URL by link text with XPath?

Too late for you, but for anyone else with the same question...

//a[contains(text(), 'programming')]/@href

Of course, 'programming' can be any text fragment.

Fastest way to Remove Duplicate Value from a list<> by lambda

If you want to stick with the original List instead of creating a new one, you can something similar to what the Distinct() extension method does internally, i.e. use a HashSet to check for uniqueness:

HashSet<long> set = new HashSet<long>(longs.Count);
longs.RemoveAll(x => !set.Add(x));

The List class provides this convenient RemoveAll(predicate) method that drops all elements not satisfying the condition specified by the predicate. The predicate is a delegate taking a parameter of the list's element type and returning a bool value. The HashSet's Add() method returns true only if the set doesn't contain the item yet. Thus by removing any items from the list that can't be added to the set you effectively remove all duplicates.

How to access global js variable in AngularJS directive

I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window makes testing more difficult.

HTML:

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>

JavaScript:

// global variable outside angular
var variable1 = true;

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

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);

Why can't I center with margin: 0 auto?

I don't know why the first answer is the best one, I tried it and not working in fact, as @kalys.osmonov said, you can give text-align:center to header, but you have to make ul as inline-block rather than inline, and also you have to notice that text-align can be inherited which is not good to some degree, so the better way (not working below IE 9) is using margin and transform. Just remove float right and margin;0 auto from ul, like below:

#header ul {
   /* float: right; */
   /* margin: 0 auto; */
   display: inline-block;
   margin-left: 50%; /* From parent width */
   transform: translateX(-50%); /* use self width which can be unknown */
  -ms-transform: translateX(-50%); /* For IE9 */
}

This way can fix the problem that making dynamic width of ul center if you don't care IE8 etc.

In Django, how do I check if a user is in a certain group?

I did it like this. For group named Editor.

# views.py
def index(request):
    current_user_groups = request.user.groups.values_list("name", flat=True)
    context = {
        "is_editor": "Editor" in current_user_groups,
    }
    return render(request, "index.html", context)

template

# index.html
{% if is_editor %}
  <h1>Editor tools</h1>
{% endif %}

What is the difference between a candidate key and a primary key?

Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table) and the candidate key-> the same as Primary key but the Primary Key chosen by DB administrator's prospective for example(the primary key the least candidate key in size)

How to handle anchor hash linking in AngularJS

None of the solution above works for me, but I just tried this, and it worked,

<a href="#/#faq-1">Question 1</a>

So I realized I need to notify the page to start with the index page and then use the traditional anchor.

How to rename array keys in PHP?

This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.

Also the foreach examples will throw a warning when using strict PHP error handling.

Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.

function multi_rename_key(&$array, $old_keys, $new_keys)
{
    if(!is_array($array)){
        ($array=="") ? $array=array() : false;
        return $array;
    }
    foreach($array as &$arr){
        if (is_array($old_keys))
        {
            foreach($new_keys as $k => $new_key)
            {
                (isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
                $arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
                unset($arr[$old_keys[$k]]);
            }
        }else{
            $arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
            unset($arr[$old_keys]);
        }
    }
    return $array;
}

Usage is simple. You can either change a single key like in your example:

multi_rename_key($tags, "url", "value");

or a more complex multikey

multi_rename_key($tags, array("url","name"), array("value","title"));

It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.

Use this all the time, hope it helps!

Setting background colour of Android layout element

The above answers are nice.You can also go like this programmatically if you want

First, your layout should have an ID. Add it by writing following +id line in res/layout/*.xml

<RelativeLayout ...
...
android:id="@+id/your_layout_id"
...
</RelativeLayout>

Then, in your Java code, make following changes.

RelativeLayout rl = (RelativeLayout)findViewById(R.id.your_layout_id);
rl.setBackgroundColor(Color.RED);

apart from this, if you have the color defined in colors.xml, then also you can do programmatically :

rl.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.red));

How to change an element's title attribute using jQuery

jqueryTitle({
    title: 'New Title'
});

for first title:

jqueryTitle('destroy');

https://github.com/ertaserdi/jQuery-Title

How do I create variable variables?

Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing

$foo = "bar"
$$foo = "baz"

you write

mydict = {}
foo = "bar"
mydict[foo] = "baz"

This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".

Working with UTF-8 encoding in Python source

In the source header you can declare:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
....

It is described in the PEP 0263:

Then you can use UTF-8 in strings:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)

This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).

In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.

"use database_name" command in PostgreSQL

When you get a connection to PostgreSQL it is always to a particular database. To access a different database, you must get a new connection.

Using \c in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.

How to make HTTP Post request with JSON body in Swift

var request = URLRequest(url: URL(string: "http://yogpande.apphb.com/api/my/posttblhouse")!)
        request.httpMethod = "POST"
        let postString = "[email protected]&password=1234567"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print("error=(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {     
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")

            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")
        }
        task.resume()
    }

explode string in jquery

Try This

var data = 'allow~5'; 
var result=data.split('~');

RESULT

alert(result[0]);

Linq Query Group By and Selecting First Items

First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.

Set up your variable like this:

IEnumerable<IEnumerable<string>> data = new[] {
    new[]{"...", "...", "..."},
    ... etc ...
};

Then you'd simply go:

var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null); 

The Where makes sure it prunes any nulls if you have an empty list as an item inside.

Alternatively you can implement it as:

string[][] = new[] {
    new[]{"...","...","..."},
    new[]{"...","...","..."},
    ... etc ...
};

This could be used similarly to a [x,y] array but it's used like this: [x][y]

How to get phpmyadmin username and password

Try changing the following lines with new values

$cfg['Servers'][$i]['user'] = 'NEW_USERNAME';
$cfg['Servers'][$i]['password'] = 'NEW_PASSWORD';

Updated due to the absence of the above lines in the config file

Stop the MySQL server

sudo service mysql stop

Start mysqld

sudo mysqld --skip-grant-tables &

Login to MySQL as root

mysql -u root mysql

Change MYSECRET with your new root password

UPDATE user SET Password=PASSWORD('MYSECRET') WHERE User='root'; FLUSH PRIVILEGES; exit;

Kill mysqld

sudo pkill mysqld

Start mysql

sudo service mysql start

Login to phpmyadmin as root with your new password

How can I merge two commits into one if I already started rebase?

Let me suggest you an easier approach,

Instead of divind into GIT's deep consepts and bothering with the editor's crab, you could do the following;

Lets suppose you created a branch named bug1 from master. Made 2 commits to bug1. You only modified 2 files with these changes.

Copy these two files into a text editor. Checkout master. Paste the files. Commit.

That simple.

Synchronization vs Lock

Many answers here recommend using synchronized.

However, it depends on the usecase.

The synchronized keyword has naturally built in language support. This can mean the JIT can optimise synchronised blocks in ways it cannot with Locks. e.g. it can combine synchronized blocks. Only one thread is allowed to access only one method at any given point of time using a synchronized block. This is a very expensive operation.

Locks avoid this by allowing configuration of various locks for different purpose. One can have couple of methods synchronized under one lock and other methods under a different lock. This allows more concurrency and also increases overall performance.

So, for a smaller system which can do without concurrency and allowing one thread to execute an operation, synchronized can work. Otherwise, lock can be taken on the key.

How to debug Spring Boot application with Eclipse?

The best solution in my opinion is add a plugin in the pom.xml, and you don't need to do anything else all the time:

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <jvmArguments>
                        -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9898
                    </jvmArguments>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

How can I remove a character from a string using JavaScript?

Your first func is almost right. Just remove the 'g' flag which stands for 'global' (edit) and give it some context to spot the second 'r'.

Edit: didn't see it was the second 'r' before so added the '/'. Needs \/ to escape the '/' when using a regEx arg. Thanks for the upvotes but I was wrong so I'll fix and add more detail for people interested in understanding the basics of regEx better but this would work:

mystring.replace(/\/r/, '/')

Now for the excessive explanation:

When reading/writing a regEx pattern think in terms of: <a character or set of charcters> followed by <a character or set of charcters> followed by <...

In regEx <a character or set of charcters> could be one at a time:

/each char in this pattern/

So read as e, followed by a, followed by c, etc...

Or a single <a character or set of charcters> could be characters described by a character class:

/[123!y]/
//any one of these
/[^123!y]/
//anything but one of the chars following '^' (very useful/performance enhancing btw)

Or expanded on to match a quantity of characters (but still best to think of as a single element in terms of the sequential pattern):

/a{2}/
//precisely two 'a' chars - matches identically as /aa/ would

/[aA]{1,3}/
//1-3 matches of 'a' or 'A'

/[a-zA-Z]+/
//one or more matches of any letter in the alphabet upper and lower
//'-' denotes a sequence in a character class

/[0-9]*/
//0 to any number of matches of any decimal character (/\d*/ would also work)

So smoosh a bunch together:

   var rePattern = /[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/g
   var joesStr = 'aaaAAAaaEat at Joes123454321 or maybe aAaAJoes all you can   eat098765';

   joesStr.match(rePattern);

   //returns ["aaaAAAaaEat at Joes123454321", "aAaAJoes all you can eat0"]
   //without the 'g' after the closing '/' it would just stop at the first   match and return:
   //["aaaAAAaaEat at Joes123454321"]

And of course I've over-elaborated but my point was simply that this:

/cat/

is a series of 3 pattern elements (a thing followed by a thing followed by a thing).

And so is this:

/[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/

As wacky as regEx starts to look, it all breaks down to series of things (potentially multi-character things) following each other sequentially. Kind of a basic point but one that took me a while to get past so I've gone overboard explaining it here as I think it's one that would help the OP and others new to regEx understand what's going on. The key to reading/writing regEx is breaking it down into those pieces.

Continue For loop

I sometimes do a double do loop:

Do

    Do

        If I_Don't_Want_to_Finish_This_Loop Then Exit Do

        Exit Do

    Loop

Loop Until Done

This avoids having "goto spaghetti"

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

Load local javascript file in chrome for testing?

You can use a light weight webserver to serve the file.
For example,
1. install Node
2. install the "http-server" (or similar) package
3. Run the http-server package ( "http-server -c-1") from the folder where the script file is located
4. Load the script from chrome console (run the following script on chrome console

var ele = document.createElement("script");
var scriptPath = "http://localhost:8080/{scriptfilename}.js" //verify the script path
ele.setAttribute("src",scriptPath);
document.head.appendChild(ele)
  1. The script is now loaded the browser. You can test it from console.

JavaScriptSerializer - JSON serialization of enum as string

You can actually use a JavaScriptConverter to accomplish this with the built-in JavaScriptSerializer. By converting your enum to a Uri you can encode it as a string.

I've described how to do this for dates but it can be used for enums as well. Custom DateTime JSON Format for .NET JavaScriptSerializer.

Converting integer to digit list

>>>list(map(int, str(number)))  #number is a given integer

It returns a list of all digits of number.

Locating child nodes of WebElements in selenium

According to JavaDocs, you can do this:

WebElement input = divA.findElement(By.xpath(".//input"));

How can I ask in xpath for "the div-tag that contains a span with the text 'hello world'"?

WebElement elem = driver.findElement(By.xpath("//div[span[text()='hello world']]"));

The XPath spec is a suprisingly good read on this.

Uninstall Django completely

The Issue is with pip --version or python --version.

try solving issue with pip2.7 uninstall Django command

If you are not able to uninstall using the above command then for sure your pip2.7 version is not installed so you can follow the below steps:

1)which pip2.7 it should give you an output like this :

/usr/local/bin/pip2.7

2) If you have not got this output please install pip using following commands

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py

3) Now check your pip version : which pip2.7 Now you will get

/usr/local/bin/pip2.7 as output 

4) uninstall Django using pip2.7 uninstall Django command.

Problem can also be related to Python version. I had a similar problem, this is how I uninstalled Django.

Issue occurred because I had multiple python installed in my virtual environment.

$ ls

activate       activate_this.py  easy_install-3.4  pip2.7  python     python3        wheel
activate.csh   easy_install      pip               pip3    python2    python3.4
activate.fish  easy_install-2.7  pip2              pip3.4  python2.7  python-config

Now when I tried to un-install using pip uninstall Django Django got uninstalled from python 2.7 but not from python 3.4 so I followed the following steps to resolve the issue :

1)alias python=/usr/bin/python3

2) Now check your python version using python -V command

3) If you have switched to your required python version now you can simply uninstall Django using pip3 uninstall Django command

Hope this answer helps.

How do I make an image smaller with CSS?

CSS 3 introduces the background-size property, but support is not universal.

Having the browser resize the image is inefficient though, the large image still has to be downloaded. You should resize it server side (caching the result) and use that instead. It will use less bandwidth and work in more browsers.

SQL JOIN and different types of JOINs

I'm going to push my pet peeve: the USING keyword.

If both tables on both sides of the JOIN have their foreign keys properly named (ie, same name, not just "id) then this can be used:

SELECT ...
FROM customers JOIN orders USING (customer_id)

I find this very practical, readable, and not used often enough.

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

Of course there is a best way.Objects in javascript have enumerable and nonenumerable properties.

var empty = {};
console.log(empty.toString);
// . function toString(){...}
console.log(empty.toString());
// . [object Object]

In the example above you can see that an empty object actually has properties.

Ok first let's see which is the best way:

var new_object = Object.create(null)

new_object.name = 'Roland'
new_object.last_name = 'Doda'
//etc

console.log("toString" in new_object) //=> false

In the example above the log will output false.

Now let's see why the other object creation ways are incorrect.

//Object constructor
var object = new Object();

console.log("toString" in object); //=> true

//Literal constructor
var person = { 
  name : "Anand",
  getName : function (){
   return this.name
  } 
} 

console.log("toString" in person); //=> true

//function Constructor
function Person(name){
  this.name = name
  this.getName = function(){
    return this.name
  } 
}

var person = new Person ('landi')

console.log("toString" in person); //=> true

//Prototype
function Person(){};

Person.prototype.name = "Anand";

console.log("toString" in person); //=> true

//Function/Prototype combination
function Person2(name){
  this.name = name;
} 

Person2.prototype.getName = function(){
  return this.name
}

var person2 = new Person2('Roland')

console.log("toString" in person2) //=> true

As you can see above,all examples log true.Which means if you have a case that you have a for in loop to see if the object has a property will lead you to wrong results probably.

Note that the best way it is not easy.You have to define all properties of object line by line.The other ways are more easier and will have less code to create an object but you have to be aware in some cases. I always use the "other ways" by the way and one solution to above warning if you don't use the best way is:

 for (var property in new_object) {
  if (new_object.hasOwnProperty(property)) {
    // ... this is an own property
  }
 }

Change border color on <select> HTML form

You can set the border color in IE however there are some issues.

Argh... I could have sworn you could do this... just tested and realized I wasn't correct. The notes below still apply though.

  1. in IE8 (Beta1 -> RC1) changing the border color or the background color/image causes a de-theming of the control in WindowsXP (the drop arrow and box look like Windows 95)

  2. you still can't style the options within the select control very well because IE doesn't support it. (see bug #291)

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

It means your table is not mapped to the JPA. Either Name of the table is wrong (Maybe case sensitive), or you need to put an entry in the XML file.

Happy Coding :)

How to get current class name including package name in Java?

There is a class, Class, that can do this:

Class c = Class.forName("MyClass"); // if you want to specify a class
Class c = this.getClass();          // if you want to use the current class

System.out.println("Package: "+c.getPackage()+"\nClass: "+c.getSimpleName()+"\nFull Identifier: "+c.getName());

If c represented the class MyClass in the package mypackage, the above code would print:

Package: mypackage
Class: MyClass
Full Identifier: mypackage.MyClass

You can take this information and modify it for whatever you need, or go check the API for more information.

Copy a file from one folder to another using vbscripting

Try this. It will check to see if the file already exists in the destination folder, and if it does will check if the file is read-only. If the file is read-only it will change it to read-write, replace the file, and make it read-only again.

Const DestinationFile = "c:\destfolder\anyfile.txt"
Const SourceFile = "c:\sourcefolder\anyfile.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
    'Check to see if the file already exists in the destination folder
    If fso.FileExists(DestinationFile) Then
        'Check to see if the file is read-only
        If Not fso.GetFile(DestinationFile).Attributes And 1 Then 
            'The file exists and is not read-only.  Safe to replace the file.
            fso.CopyFile SourceFile, "C:\destfolder\", True
        Else 
            'The file exists and is read-only.
            'Remove the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
            'Replace the file
            fso.CopyFile SourceFile, "C:\destfolder\", True
            'Reapply the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
        End If
    Else
        'The file does not exist in the destination folder.  Safe to copy file to this folder.
        fso.CopyFile SourceFile, "C:\destfolder\", True
    End If
Set fso = Nothing

jQuery Ajax POST example with PHP

HTML:

    <form name="foo" action="form.php" method="POST" id="foo">
        <label for="bar">A bar</label>
        <input id="bar" class="inputs" name="bar" type="text" value="" />
        <input type="submit" value="Send" onclick="submitform(); return false;" />
    </form>

JavaScript:

   function submitform()
   {
       var inputs = document.getElementsByClassName("inputs");
       var formdata = new FormData();
       for(var i=0; i<inputs.length; i++)
       {
           formdata.append(inputs[i].name, inputs[i].value);
       }
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
           xmlhttp = new XMLHttpRequest;
       }
       else
       {
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function()
       {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
          {

          }
       }
       xmlhttp.open("POST", "insert.php");
       xmlhttp.send(formdata);
   }

What are intent-filters in Android?

There can be no two Lancher AFAIK. Logcat is a usefull tool to debug and check application/machine status in the behind. it will be automatic while switching from one activity to another activity.

Apache Cordova - uninstall globally

This can happen when the cordova was installed globally on a different version of the node.

Being necessary to manually delete yourself as suggested in the previous comment:

which cordova

it will output something like this

/usr/local/bin/

then removing by

rm -rf /usr/local/bin/cordova

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'> attribute for the inner html.

For example, for the inner html, use the this html parameter (yes - this is defined and it refers to the parent window of the inner body element):

<body onload='changeForm(this)'>

In the inner html :

    function changeForm(window) {
        console.log('inner window loaded: do whatever you want with the inner html');
        window.document.getElementById('mturk_form').style.display = 'none';
    </script>

How do I retrieve an HTML element's actual width and height?

NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.

As of jQuery 1.2.6 you can use one of the core CSS functions, height and width (or outerHeight and outerWidth, as appropriate).

var height = $("#myDiv").height();
var width = $("#myDiv").width();

var docHeight = $(document).height();
var docWidth = $(document).width();

What does __FILE__ mean in Ruby?

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.chdir anywhere else in your application, this path will expand incorrectly.

puts __FILE__
Dir.chdir '../../'
puts __FILE__

One workaround to this problem is to store the expanded value of __FILE__ outside of any application code. As long as your require statements are at the top of your definitions (or at least before any calls to Dir.chdir), this value will continue to be useful after changing directories.

$MY_FILE_PATH = File.expand_path(File.dirname(__FILE__))

# open class and do some stuff that changes directory

puts $MY_FILE_PATH

How to get value in the session in jQuery

Assuming you are using this plugin, you are misusing the .set method. .set must be passed the name of the key as a string as well as the value. I suppose you meant to write:

$.session.set("userName", $("#uname").val());

This sets the userName key in session storage to the value of the input, and allows you to retrieve it using:

$.session.get('userName');

Add padding to HTML text input field

you can solve this, taking the input tag inside a div, then put the padding property on div tag. This work's for me...

Like this:

<div class="paded">
    <input type="text" />
</div>

and css:

.paded{
    padding-right: 20px;
}

Content Type application/soap+xml; charset=utf-8 was not supported by service

In my case one of the classes didn't have a default constructor - and class without default constructor can't be serialized.

How to change visibility of layout programmatically

You can change layout visibility just in the same way as for regular view. Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.

WPF Timer Like C# Timer

The timer has special functions.

  1. Call an asynchronous timer or synchronous timer.
  2. Change the time interval
  3. Ability to cancel and resume  

if you use StartAsync () or Start (), the thread does not block the user interface element

     namespace UITimer


     {
        using thread = System.Threading;
        public class Timer
        {

        public event Action<thread::SynchronizationContext> TaskAsyncTick;
        public event Action Tick;
        public event Action AsyncTick;
        public int Interval { get; set; } = 1;
        private bool canceled = false;
        private bool canceling = false;
        public async void Start()
        {
            while(true)
            {

                if (!canceled)
                {
                    if (!canceling)
                    {
                        await Task.Delay(Interval);
                        Tick.Invoke();
                    }
                }
                else
                {
                    canceled = false;
                    break;
                }
            }


        }
        public void Resume()
        {
            canceling = false;
        }
        public void Cancel()
        {
            canceling = true;
        }
        public async void StartAsyncTask(thread::SynchronizationContext 
        context)
        {

                while (true)
                {
                    if (!canceled)
                    {
                    if (!canceling)
                    {
                        await Task.Delay(Interval).ConfigureAwait(false);

                        TaskAsyncTick.Invoke(context);
                    }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }

        }
        public void StartAsync()
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while (true)
                {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);

                    Application.Current.Dispatcher.Invoke(AsyncTick);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }

        public void StartAsync(thread::SynchronizationContext context)
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while(true)
                 {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);
                            context.Post((xfail) => { AsyncTick.Invoke(); }, null);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }
        public void Abort()
        {
            canceled = true;
        }
    }


     }

Getting a union of two arrays in JavaScript

Simple way to deal with merging single array values.

var values[0] = {"id":1235,"name":"value 1"}
values[1] = {"id":4323,"name":"value 2"}

var object=null;
var first=values[0];
for (var i in values) 
 if(i>0)    
 object= $.merge(values[i],first)

what is the difference between XSD and WSDL

XSD defines a schema which is a definition of how an XML document can be structured. You can use it to check that a given XML document is valid and follows the rules you've laid out in the schema.

WSDL is a XML document that describes a web service. It shows which operations are available and how data should be structured to send to those operations.

WSDL documents have an associated XSD that show what is valid to put in a WSDL document.

How to get option text value using AngularJS?

Instead of ng-options="product as product.label for product in products"> in the select element, you can even use this:

<option ng-repeat="product in products" value="{{product.label}}">{{product.label}}

which works just fine as well.

Parameter in like clause JPQL

There is nice like() method in JPA criteria API. Try to use that, hope it will help.

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery criteriaQuery = cb.createQuery(Employees.class);
Root<Employees> rootOfQuery = criteriaQuery.from(Employees.class);
criteriaQuery.select(rootOfQuery).where(cb.like(rootOfQuery.get("firstName"), "H%"));

int to unsigned int conversion

You can convert an int to an unsigned int. The conversion is valid and well-defined.

Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)

In this case, since int on your platform has a width of 32 bits, 62 is subtracted from 232, yielding 4,294,967,234.

How to write string literals in python without having to escape them?

(Assuming you are not required to input the string from directly within Python code)

to get around the Issue Andrew Dalke pointed out, simply type the literal string into a text file and then use this;

input_ = '/directory_of_text_file/your_text_file.txt' 
input_open   = open(input_,'r+')
input_string = input_open.read()

print input_string

This will print the literal text of whatever is in the text file, even if it is;

 '   ''' """  “ \

Not fun or optimal, but can be useful, especially if you have 3 pages of code that would’ve needed character escaping.

How to combine GROUP BY and ROW_NUMBER?

Undoubtly this can be simplified but the results match your expectations.

The gist of this is to

  • Calculate the maximum price in a seperate CTE for each t2ID
  • Calculate the total price in a seperate CTE for each t2ID
  • Combine the results of both CTE's

SQL Statement

;WITH MaxPrice AS ( 
    SELECT  t2ID
            , t1ID
    FROM    (       
                SELECT  t2.ID AS t2ID
                        , t1.ID AS t1ID
                        , rn = ROW_NUMBER() OVER (PARTITION BY t2.ID ORDER BY t1.Price DESC)
                FROM    @t1 t1
                        INNER JOIN @relation r ON r.t1ID = t1.ID        
                        INNER JOIN @t2 t2 ON t2.ID = r.t2ID
            ) maxt1
    WHERE   maxt1.rn = 1                            
)
, SumPrice AS (
    SELECT  t2ID = t2.ID
            , Price = SUM(Price)
    FROM    @t1 t1
            INNER JOIN @relation r ON r.t1ID = t1.ID
            INNER JOIN @t2 t2 ON t2.ID = r.t2ID
    GROUP BY
            t2.ID           
)           
SELECT  t2.ID
        , t2.Name
        , t2.Orders
        , mp.t1ID
        , t1.ID
        , t1.Name
        , sp.Price
FROM    @t2 t2
        INNER JOIN MaxPrice mp ON mp.t2ID = t2.ID
        INNER JOIN SumPrice sp ON sp.t2ID = t2.ID
        INNER JOIN @t1 t1 ON t1.ID = mp.t1ID

What is the difference between UTF-8 and ISO-8859-1?

UTF-8 is a multibyte encoding that can represent any Unicode character. ISO 8859-1 is a single-byte encoding that can represent the first 256 Unicode characters. Both encode ASCII exactly the same way.

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Here are some supplemental examples to see the raw text that Postman passes in the request. You can see this by opening the Postman console:

enter image description here

form-data

Header

content-type: multipart/form-data; boundary=--------------------------590299136414163472038474

Body

key1=value1key2=value2

x-www-form-urlencoded

Header

Content-Type: application/x-www-form-urlencoded

Body

key1=value1&key2=value2

Raw text/plain

Header

Content-Type: text/plain

Body

This is some text.

Raw json

Header

Content-Type: application/json

Body

{"key1":"value1","key2":"value2"}

Select all child elements recursively in CSS

The rule is as following :

A B 

B as a descendant of A

A > B 

B as a child of A

So

div.dropdown *

and not

div.dropdown > *

np.mean() vs np.average() in Python NumPy?

np.mean always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result).

np.average can compute a weighted average if the weights parameter is supplied.

Mysql - delete from multiple tables with one query

usually, i would expect this as a 'cascading delete' enforced in a trigger, you would only need to delete the main record, then all the depepndent records would be deleted by the trigger logic.

this logic would be similar to what you have written.

How to use order by with union all in sql?

select CONCAT(Name, '(',substr(occupation, 1, 1), ')') AS f1
from OCCUPATIONS
union
select temp.str AS f1 from 
(select count(occupation) AS counts, occupation, concat('There are a total of ' ,count(occupation) ,' ', lower(occupation),'s.') As str  from OCCUPATIONS group by occupation order by counts ASC, occupation ASC
 ) As temp
 order by f1

Import pandas dataframe column as string not int

This probably isn't the most elegant way to do it, but it gets the job done.

In[1]: import numpy as np

In[2]: import pandas as pd

In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])

In[4]: df
Out[4]: 
                       ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

Just replace '/Users/spencerlyon2/Desktop/test.csv' with the path to your file

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

Quick summary, you can do either:

  1. Include the JavaFX modules via --module-path and --add-modules like in José's answer.

    OR

  2. Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java file).


This answer is a supplement to Jose's answer.

The situation is this:

  1. You are using a recent Java version, e.g. 13.
  2. You have a JavaFX application as a Maven project.
  3. In your Maven project you have the JavaFX plugin configured and JavaFX dependencies setup as per Jose's answer.
  4. You go to the source code of your main class which extends Application, you right-click on it and try to run it.
  5. You get an IllegalAccessError involving an "unnamed module" when trying to launch the app.

Excerpt for a stack trace generating an IllegalAccessError when trying to run a JavaFX app from Intellij Idea:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
    at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
    at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
    at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main

OK, now you are kind of stuck and have no clue what is going on.

What has actually happened is this:

  1. Maven has successfully downloaded the JavaFX dependencies for your application, so you don't need to separately download the dependencies or install a JavaFX SDK or module distribution or anything like that.
  2. Idea has successfully imported the modules as dependencies to your project, so everything compiles OK and all of the code completion and everything works fine.

So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).

This is where some of the other answers to this question, which reference module-info.java, come into the picture.

So let's take a crash course in Java modules:

The key part is this:

4.9. Opens

If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.

But remember, this will open the package up to the entire world, so make sure that is what you want:

module my.module { opens com.my.package; }

So, perhaps you don't want to open your package to the entire world, then you can do:

4.10. Opens … To

Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:

module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }

So, you end up creating a src/main/java/module-info.java class which looks like this:

module org.jewelsea.demo.javafx.springboot {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}

Where, org.jewelsea.demo.javafx.springboot is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics and javafx.fxml to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError generated by JavaFX's use of reflection will no longer occur.

But what if you don't want to create a module-info.java file

If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:

  1. Went to the Maven window in the side of the IDE.
  2. Chose the javafx maven plugin target javafx.run.
  3. Right-clicked on that and chose either Run Maven Build or Debug....

Then the app will run without the module-info.java file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java file, though I don't know how this is accomplished.

To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run Maven target and choose the option to Create Run/Debug Configuration for the target. Then you can just choose Run from the top toolbar to execute the Maven target.

Excel how to find values in 1 column exist in the range of values in another

This is what you need:

 =NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0)))  ## pseudo code

For the first cell of A, this would be:

 =NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))

Enter formula (and drag down) as follows:

enter image description here

You will get:

enter image description here

Excel 2010: how to use autocomplete in validation list

As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.

As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.

pip3: command not found but python3-pip is already installed

For Kali, you must use this code after the update.

$sudo python3 get-pip.py

or if you write this, it also works but not supported anymore. So don't use:

$sudo python get-pip.py

Java - Best way to print 2D array?

That's the best I guess:

   for (int[] row : matrix){
    System.out.println(Arrays.toString(row));
   }

jquery append external html file into my page

i'm not sure what you're expecting this to refer to in your example.. here's an alternative method:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                $.get("banner.html", function (data) {
                    $("#appendToThis").append(data);
                });
            });
        </script>
    </head>
    <body>
        <div id="appendToThis"></div>
    </body>
</html>

Rewrite left outer join involving multiple tables from Informix to Oracle

I'm guessing that you want something like

SELECT tab1.a, tab2.b, tab3.c, tab4.d
  FROM table1 tab1 
       JOIN table2 tab2 ON (tab1.fg = tab2.fg)
       LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
       LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
       LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
                                       tab3.dd = tab5.dd)

Entity Framework rollback and remove bad migration

You have 2 options:

  • You can take the Down from the bad migration and put it in a new migration (you will also need to make the subsequent changes to the model). This is effectively rolling up to a better version.

    I use this option on things that have gone to multiple environments.

  • The other option is to actually run Update-Database –TargetMigration: TheLastGoodMigration against your deployed database and then delete the migration from your solution. This is kinda the hulk smash alternative and requires this to be performed against any database deployed with the bad version.

    Note: to rescaffold the migration you can use Add-Migration [existingname] -Force. This will however overwrite your existing migration, so be sure to do this only if you have removed the existing migration from the database. This does the same thing as deleting the existing migration file and running add-migration

    I use this option while developing.

How to handle floats and decimal separators with html5 input type number

When you call $("#my_input").val(); it returns as string variable. So use parseFloat and parseIntfor converting. When you use parseFloat your desktop or phone ITSELF understands the meaning of variable.

And plus you can convert a float to string by using toFixed which has an argument the count of digits as below:

var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01

Formatting Numbers by padding with leading zeros in SQL Server

Another way, just for completeness.

DECLARE @empNumber INT = 7123
SELECT STUFF('000000', 6-LEN(@empNumber)+1, LEN(@empNumber), @empNumber)

Or, as per your query

SELECT STUFF('000000', 6-LEN(EmployeeID)+1, LEN(EmployeeID), EmployeeID) 
         AS EmployeeCode
FROM dbo.RequestItems
WHERE ID=0

How to access SVG elements with Javascript

If you are using an <img> tag for the SVG, then you cannot manipulate its contents (as far as I know).

As the accepted answer shows, using <object> is an option.

I needed this recently and used gulp-inject during my gulp build to inject the contents of an SVG file directly into the HTML document as an <svg> element, which is then very easy to work with using CSS selectors and querySelector/getElementBy*.

break statement in "if else" - java

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

How to get the ActionBar height?

I found a more generic way to discover it:

  int[] location = new int[2];
  mainView.getLocationOnScreen(location);
  int toolbarHeight = location[1];

where 'mainView' is the root view of your layout.

The idea is basically get the Y position of the mainView as it is set right below the ActionBar (or Toolbar).

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

This is a problem with your web server sending out an HTTP header that does not match the one you define. For instructions on how to make the server send the correct headers, see this page.

Otherwise, you can also use PHP to modify the headers, but this has to be done before outputting any text using this code:

header('Content-Type: text/html; charset=utf-8');

More information on how to send out headers using PHP can be found in the documentation for the header function.

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

The issue arises when the image is not present on the cluster and k8s engine is going to pull the respective registry. k8s Engine enables 3 types of ImagePullPolicy mentioned :

  1. Always : It always pull the image in container irrespective of changes in the image
  2. Never : It will never pull the new image on the container
  3. IfNotPresent : It will pull the new image in cluster if the image is not present.

Best Practices : It is always recommended to tag the new image in both docker file as well as k8s deployment file. So That it can pull the new image in container.

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

Adding value to input field with jQuery

$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});

Why does the C++ STL not provide any "tree" containers?

IMO, an omission. But I think there is good reason not to include a Tree structure in the STL. There is a lot of logic in maintaining a tree, which is best written as member functions into the base TreeNode object. When TreeNode is wrapped up in an STL header, it just gets messier.

For example:

template <typename T>
struct TreeNode
{
  T* DATA ; // data of type T to be stored at this TreeNode

  vector< TreeNode<T>* > children ;

  // insertion logic for if an insert is asked of me.
  // may append to children, or may pass off to one of the child nodes
  void insert( T* newData ) ;

} ;

template <typename T>
struct Tree
{
  TreeNode<T>* root;

  // TREE LEVEL functions
  void clear() { delete root ; root=0; }

  void insert( T* data ) { if(root)root->insert(data); } 
} ;

Omitting the first line from any Linux command output

ls -lart | tail -n +2 #argument means starting with line 2

How to convert java.lang.Object to ArrayList?

    Object object = new Object();

    // First way
    List objects1 = new ArrayList<Object>();
    objects1.add(object);

    // second way
    List<Object> objects2 = Arrays.asList(object);

    // Third way
    List<Object> objects3 = Collections.singletonList(object);

How can I count the rows with data in an Excel sheet?

Try this scenario:

Array = A1:C7. A1-A3 have values, B2-B6 have value and C1, C3 and C6 have values.

To get a count of the number of rows add a column D (you can hide it after formulas are set up) and in D1 put formula =If(Sum(A1:C1)>0,1,0). Copy the formula from D1 through D7 (for others searching who are not excel literate, the numbers in the sum formula will change to the row you are on and this is fine).

Now in C8 make a sum formula that adds up the D column and the answer should be 6. For visually pleasing purposes hide column D.

CASE statement in SQLite query

Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END

Push Notifications in Android Platform

You can use Xtify (http://developer.xtify.com) - they have a push notifications webservice that works with their SDK. it's free and so far, it's worked really well for me.

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

How to echo print statements while executing a sql script

For mysql you can add \p to the commands to have them print out while they run in the script:

SELECT COUNT(*) FROM `mysql`.`user`
\p;

Run it in the MySQL client:

mysql> source example.sql
--------------
SELECT COUNT(*) FROM `mysql`.`user`
--------------

+----------+
| COUNT(*) |
+----------+
|       24 |
+----------+
1 row in set (0.00 sec)

High-precision clock in Python

On the same win10 OS system using "two distinct method approaches" there appears to be an approximate "500 ns" time difference. If you care about nanosecond precision check my code below.

The modifications of the code is based on code from user cod3monk3y and Kevin S.

OS: python 3.7.3 (default, date, time) [MSC v.1915 64 bit (AMD64)]

def measure1(mean):
    for i in range(1, my_range+1):
        x = time.time()
        
        td = x- samples1[i-1][2]
        if i-1 == 0:
            td = 0
        td = f'{td:.6f}'
        samples1.append((i, td, x))
        mean += float(td)
        print (mean)
        sys.stdout.flush()
        time.sleep(0.001)
    
    mean = mean/my_range
    
    return mean

def measure2(nr):
    t0 = time.time()
    t1 = t0
    while t1 == t0:
        t1 = time.time()
    td = t1-t0
    td = f'{td:.6f}'
    return (nr, td, t1, t0)

samples1 = [(0, 0, 0)]
my_range = 10
mean1    = 0.0
mean2    = 0.0

mean1 = measure1(mean1)

for i in samples1: print (i)

print ('...\n\n')

samples2 = [measure2(i) for i in range(11)]

for s in samples2:
    #print(f'time delta: {s:.4f} seconds')
    mean2 += float(s[1])
    print (s)
    
mean2 = mean2/my_range

print ('\nMean1 : ' f'{mean1:.6f}')
print ('Mean2 : ' f'{mean2:.6f}')

The measure1 results:

nr, td, t0
(0, 0, 0)
(1, '0.000000', 1562929696.617988)
(2, '0.002000', 1562929696.6199884)
(3, '0.001001', 1562929696.620989)
(4, '0.001001', 1562929696.62199)
(5, '0.001001', 1562929696.6229906)
(6, '0.001001', 1562929696.6239917)
(7, '0.001001', 1562929696.6249924)
(8, '0.001000', 1562929696.6259928)
(9, '0.001001', 1562929696.6269937)
(10, '0.001001', 1562929696.6279945)
...

The measure2 results:

nr, td , t1, t0
(0, '0.000500', 1562929696.6294951, 1562929696.6289947)
(1, '0.000501', 1562929696.6299958, 1562929696.6294951)
(2, '0.000500', 1562929696.6304958, 1562929696.6299958)
(3, '0.000500', 1562929696.6309962, 1562929696.6304958)
(4, '0.000500', 1562929696.6314962, 1562929696.6309962)
(5, '0.000500', 1562929696.6319966, 1562929696.6314962)
(6, '0.000500', 1562929696.632497, 1562929696.6319966)
(7, '0.000500', 1562929696.6329975, 1562929696.632497)
(8, '0.000500', 1562929696.633498, 1562929696.6329975)
(9, '0.000500', 1562929696.6339984, 1562929696.633498)
(10, '0.000500', 1562929696.6344984, 1562929696.6339984)

End result:

Mean1 : 0.001001 # (measure1 function)

Mean2 : 0.000550 # (measure2 function)

Change line width of lines in matplotlib pyplot legend

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

Method 1

import numpy as np
import matplotlib.pyplot as plt

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

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

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

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

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

Method 2

import numpy as np
import matplotlib.pyplot as plt

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

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

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

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

The above two methods produce the same output image:

output image

How to check if an NSDictionary or NSMutableDictionary contains a key?

Yes. This kind of errors are very common and lead to app crash. So I use to add NSDictionary in each project as below:

//.h file code :

@interface NSDictionary (AppDictionary)

- (id)objectForKeyNotNull : (id)key;

@end

//.m file code is as below

#import "NSDictionary+WKDictionary.h"

@implementation NSDictionary (WKDictionary)

 - (id)objectForKeyNotNull:(id)key {

    id object = [self objectForKey:key];
    if (object == [NSNull null])
     return nil;

    return object;
 }

@end

In code you can use as below:

NSStrting *testString = [dict objectForKeyNotNull:@"blah"];

How to add a string to a string[] array? There's no .Add function

string[] coleccion = Directory.GetFiles(inputPath)
    .Select(x => new FileInfo(x).Name)
    .ToArray();

How to make all controls resize accordingly proportionally when window is maximized?

Just thought i'd share this with anyone who needs more clarity on how to achieve this:

myCanvas is a Canvas control and Parent to all other controllers. This code works to neatly resize to any resolution from 1366 x 768 upward. Tested up to 4k resolution 4096 x 2160

Take note of all the MainWindow property settings (WindowStartupLocation, SizeToContent and WindowState) - important for this to work correctly - WindowState for my user case requirement was Maximized

xaml

<Window x:Name="mainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyApp" 
    xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    x:Class="MyApp.MainWindow" 
     Title="MainWindow"  SizeChanged="MainWindow_SizeChanged"
    Width="1366" Height="768" WindowState="Maximized" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
  
    <Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1356">
        <Image x:Name="maxresdefault_1_1__jpg" Source="maxresdefault-1[1].jpg" Stretch="Fill" Opacity="0.6" Height="767" Canvas.Left="-6" Width="1366"/>

        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" Height="0" Canvas.Left="-811" Canvas.Top="148" Width="766"/>
        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" HorizontalAlignment="Right" Width="210" Height="0" Canvas.Left="1653" Canvas.Top="102"/>
        <Image x:Name="imgscroll" Source="BcaKKb47i[1].png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" Height="523" Canvas.Left="-3" Canvas.Top="122" Width="580">
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="89.093"/>
                    <TranslateTransform/>
                </TransformGroup>
            </Image.RenderTransform>
        </Image>

.cs

 private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        myCanvas.Width = e.NewSize.Width;
        myCanvas.Height = e.NewSize.Height;

        double xChange = 1, yChange = 1;

        if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width / e.PreviousSize.Width);

        if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

        ScaleTransform scale = new ScaleTransform(myCanvas.LayoutTransform.Value.M11 * xChange, myCanvas.LayoutTransform.Value.M22 * yChange);
        myCanvas.LayoutTransform = scale;
        myCanvas.UpdateLayout();
    }

How to do HTTP authentication in android?

This works for me

 URL imageUrl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) imageUrl
                            .openConnection();
                    conn.setRequestProperty("Authorization", "basic " +
                            Base64.encode("username:password".getBytes()));
                    conn.setConnectTimeout(30000);
                    conn.setReadTimeout(30000);
                    conn.setInstanceFollowRedirects(true);
                    InputStream is = conn.getInputStream();

GIT: Checkout to a specific folder

I defined an git alias to achieve just this (before I found this question).

It's a short bash function which saves the current path, switch to the git repo, does a checkout and return where it started.

git checkto develop ~/my_project_git

This e.g. would checkout the develop branch into "~/my_project_git" directory.

This is the alias code inside ~/.gitconfig:

[alias]
    checkTo = "!f(){ [ -z \"$1\" ] && echo \"Need to specify branch.\" && \
               exit 1; [ -z \"$2\" ] && echo \"Need to specify target\
               dir\" && exit 2; cDir=\"$(pwd)\"; cd \"$2\"; \
               git checkout \"$1\"; cd \"$cDir\"; };f"

How to detect the device orientation using CSS media queries?

CSS to detect screen orientation:

 @media screen and (orientation:portrait) { … }
 @media screen and (orientation:landscape) { … }

The CSS definition of a media query is at http://www.w3.org/TR/css3-mediaqueries/#orientation

What is the difference between signed and unsigned int

In practice, there are two differences:

  1. printing (eg with cout in C++ or printf in C): unsigned integer bit representation is interpreted as a nonnegative integer by print functions.
  2. ordering: the ordering depends on signed or unsigned specifications.

this code can identify the integer using ordering criterion:

char a = 0;
a--;
if (0 < a)
    printf("unsigned");
else
    printf("signed");

char is considered signed in some compilers and unsigned in other compilers. The code above determines which one is considered in a compiler, using the ordering criterion. If a is unsigned, after a--, it will be greater than 0, but if it is signed it will be less than zero. But in both cases, the bit representation of a is the same. That is, in both cases a-- does the same change to the bit representation.

Only local connections are allowed Chrome and Selenium webdriver

C#:

    ChromeOptions options = new ChromeOptions();

    options.AddArgument("C:/Users/username/Documents/Visual Studio 2012/Projects/Interaris.Test/Interaris.Tes/bin/Debug/chromedriver.exe");

    ChromeDriver chrome = new ChromeDriver(options);

Worked for me.

Does VBA contain a comment block syntax?

There is no syntax for block quote in VBA. The work around is to use the button to quickly block or unblock multiple lines of code.

How to use sbt from behind proxy?

In windows environment simply add following line in the sbt/sbtconfig.txt

-Dhttp.proxyHost=PROXYHOST 
-Dhttp.proxyPort=PROXYPORT 
-Dhttp.proxyUser=USERNAME 
-Dhttp.proxyPassword=XXXX

or the Https equivalent (thanks to comments)

-Dhttps.proxyHost=PROXYHOST 
-Dhttps.proxyPort=PROXYPORT 
-Dhttps.proxyUser=USERNAME 
-Dhttps.proxyPassword=XXXX

Converting Hexadecimal String to Decimal Integer

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

It can convert from and to hexadecimals. It supports:

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

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

Example:

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

Is it possible to sort a ES6 map object?

The idea is to extract the keys of your map into an array. Sort this array. Then iterate over this sorted array, get its value pair from the unsorted map and put them into a new map. The new map will be in sorted order. The code below is it's implementation:

var unsortedMap = new Map();
unsortedMap.set('2-1', 'foo');
unsortedMap.set('0-1', 'bar');

// Initialize your keys array
var keys = [];
// Initialize your sorted maps object
var sortedMap = new Map();

// Put keys in Array
unsortedMap.forEach(function callback(value, key, map) {
    keys.push(key);
});

// Sort keys array and go through them to put in and put them in sorted map
keys.sort().map(function(key) {
    sortedMap.set(key, unsortedMap.get(key));
});

// View your sorted map
console.log(sortedMap);

Why doesn't Java support unsigned ints?

Because unsigned type is pure evil.

The fact that in C unsigned - int produces unsigned is even more evil.

Here is a snapshot of the problem that burned me more than once:

// We have odd positive number of rays, 
// consecutive ones at angle delta from each other.
assert( rays.size() > 0 && rays.size() % 2 == 1 );

// Get a set of ray at delta angle between them.
for( size_t n = 0; n < rays.size(); ++n )
{
    // Compute the angle between nth ray and the middle one.
    // The index of the middle one is (rays.size() - 1) / 2,
    // the rays are evenly spaced at angle delta, therefore
    // the magnitude of the angle between nth ray and the 
    // middle one is: 
    double angle = delta * fabs( n - (rays.size() - 1) / 2 ); 

    // Do something else ...
}

Have you noticed the bug yet? I confess I only saw it after stepping in with the debugger.

Because n is of unsigned type size_t the entire expression n - (rays.size() - 1) / 2 evaluates as unsigned. That expression is intended to be a signed position of the nth ray from the middle one: the 1st ray from the middle one on the left side would have position -1, the 1st one on the right would have position +1, etc. After taking abs value and multiplying by the delta angle I would get the angle between nth ray and the middle one.

Unfortunately for me the above expression contained the evil unsigned and instead of evaluating to, say, -1, it evaluated to 2^32-1. The subsequent conversion to double sealed the bug.

After a bug or two caused by misuse of unsigned arithmetic one has to start wondering whether the extra bit one gets is worth the extra trouble. I am trying, as much as feasible, to avoid any use of unsigned types in arithmetic, although still use it for non-arithmetic operations such as binary masks.

Propagate all arguments in a bash shell script

Sometimes you want to pass all your arguments, but preceded by a flag (e.g. --flag)

$ bar --flag "$1" --flag "$2" --flag "$3"

You can do this in the following way:

$ bar $(printf -- ' --flag "%s"' "$@")

note: to avoid extra field splitting, you must quote %s and $@, and to avoid having a single string, you cannot quote the subshell of printf.

How to change background and text colors in Sublime Text 3

I had the same issue. Sublime3 no longer shows all of the installed packages when you choose Show Packages from the Preferences Menu.

To customise a colour scheme do the following (UNIX):

  • Locate your SublimeText packages directory under the directory which SublimeText is installed in (in my setup this was /opt/sublime/Packages)
  • Open "Color Scheme - Default.sublime-package"
  • Choose the colour scheme which is closest to your requirements and copy it
  • From Sublime Text choose Preferences - Browse Packages - User
  • Paste the colour scheme you copied earlier here and rename it. It should now show up on your "Preferences - Color Scheme" menu under "User"
  • Follow the instructions at the link you previously mentioned to make the changes you require (Sublime 2 -changing background color based on file type?)

--- EDIT ---

For Mac OS X the themes are stored in zipped files so although the preferences file shows them as being in Packages/Color Scheme - Default/ they don't appear in that directory unless you extract them.

  • They can be extracted using the Package Resource Viewer (See this answer for how to install and use the Package Resource Viewer).
  • Search for Color Scheme in the Package Extractor (should give options for Color Scheme Default and Color Scheme legacy)
  • Extract the one you want. It will now be available at users/UserName/Library/Application Support/Sublime Text 3/Packages/Color Scheme - Default (or Legacy)
  • Make a copy of the scheme you want to modify, edit as needed and save it
  • Add or change the line in user preferences which points to the color scheme

for example

"color_scheme": "Packages/Color Scheme - Legacy/myTheme.tmTheme"

How to squash commits in git after they have been pushed?

git rebase -i master

you will get the editor vm open and msgs something like this

Pick 2994283490 commit msg1
f 7994283490 commit msg2
f 4654283490 commit msg3
f 5694283490 commit msg4
#Some message 
#
#some more

Here I have changed pick for all the other commits to "f" (Stands for fixup).

git push -f origin feature/feature-branch-name-xyz

this will fixup all the commits to one commit and will remove all the other commits . I did this and it helped me.

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

Few steps to add Access-Control-Allow-Origin header to localhost or *.

Step 1: Create Cors middleware :

php artisan make:middleware Cors

Step 2: Set header in Cors middleware like this

public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->headers->set('Access-Control-Allow-Origin' , '*');
        $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');

        return $response;
    }

Step 3: We need to add Cors class in app/Http/Kernel.php

 protected $middleware = [
        ....
        \App\Http\Middleware\Cors::class,
    ];

Here no needed to check any middleware because we add Cors class in $middleware in app/Http/Kernel.php

Checking if a variable is an integer in PHP

Using is_numeric() for checking if a variable is an integer is a bad idea. This function will return TRUE for 3.14 for example. It's not the expected behavior.

To do this correctly, you can use one of these options:

Considering this variables array :

$variables = [
    "TEST 0" => 0,
    "TEST 1" => 42,
    "TEST 2" => 4.2,
    "TEST 3" => .42,
    "TEST 4" => 42.,
    "TEST 5" => "42",
    "TEST 6" => "a42",
    "TEST 7" => "42a",
    "TEST 8" => 0x24,
    "TEST 9" => 1337e0
];

The first option (FILTER_VALIDATE_INT way) :

# Check if your variable is an integer
if ( filter_var($variable, FILTER_VALIDATE_INT) === false ) {
  echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ?
TEST 1 : 42 (type:integer) is an integer ?
TEST 2 : 4.2 (type:double) is not an integer ?
TEST 3 : 0.42 (type:double) is not an integer ?
TEST 4 : 42 (type:double) is an integer ?
TEST 5 : 42 (type:string) is an integer ?
TEST 6 : a42 (type:string) is not an integer ?
TEST 7 : 42a (type:string) is not an integer ?
TEST 8 : 36 (type:integer) is an integer ?
TEST 9 : 1337 (type:double) is an integer ?

The second option (CASTING COMPARISON way) :

# Check if your variable is an integer
if ( strval($variable) !== strval(intval($variable)) ) {
  echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ?
TEST 1 : 42 (type:integer) is an integer ?
TEST 2 : 4.2 (type:double) is not an integer ?
TEST 3 : 0.42 (type:double) is not an integer ?
TEST 4 : 42 (type:double) is an integer ?
TEST 5 : 42 (type:string) is an integer ?
TEST 6 : a42 (type:string) is not an integer ?
TEST 7 : 42a (type:string) is not an integer ?
TEST 8 : 36 (type:integer) is an integer ?
TEST 9 : 1337 (type:double) is an integer ?

The third option (CTYPE_DIGIT way) :

# Check if your variable is an integer
if ( ! ctype_digit(strval($variable)) ) {
  echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ?
TEST 1 : 42 (type:integer) is an integer ?
TEST 2 : 4.2 (type:double) is not an integer ?
TEST 3 : 0.42 (type:double) is not an integer ?
TEST 4 : 42 (type:double) is an integer ?
TEST 5 : 42 (type:string) is an integer ?
TEST 6 : a42 (type:string) is not an integer ?
TEST 7 : 42a (type:string) is not an integer ?
TEST 8 : 36 (type:integer) is an integer ?
TEST 9 : 1337 (type:double) is an integer ?

The fourth option (REGEX way) :

# Check if your variable is an integer
if ( ! preg_match('/^\d+$/', $variable) ) {
  echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ?
TEST 1 : 42 (type:integer) is an integer ?
TEST 2 : 4.2 (type:double) is not an integer ?
TEST 3 : 0.42 (type:double) is not an integer ?
TEST 4 : 42 (type:double) is an integer ?
TEST 5 : 42 (type:string) is an integer ?
TEST 6 : a42 (type:string) is not an integer ?
TEST 7 : 42a (type:string) is not an integer ?
TEST 8 : 36 (type:integer) is an integer ?
TEST 9 : 1337 (type:double) is an integer ?

What does $(function() {} ); do?

I think you may be confusing Javascript with jQuery methods. Vanilla or plain Javascript is something like:

function example() {
}

A function of that nature can be called at any time, anywhere.

jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is:

$(document).ready(function() {
});

So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method.

$(document).ready(function() {        
    // Assign all list items on the page to be the  color red.  
    //      This does not work until AFTER the entire DOM is "ready", hence the $(document).ready()
    $('li').css('color', 'red');   
});

The pseudo-code for that block is:

When the document object model $(document) is ready .ready(), call the following function function() { }. In that function, check for all <li>'s on the page $('li') and using the jQuery method .CSS() to set the CSS property "color" to the value "red" .css('color', 'red');

Import Excel Spreadsheet Data to an EXISTING sql table?

If you would like a software tool to do this, you might like to check out this step-by-step guide:

"How to Validate and Import Excel spreadsheet to SQL Server database"

http://leansoftware.net/forum/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

How to add a scrollbar to an HTML5 table?

You can use a division class with the overflow attribute using the value scroll. Or you can enclose the table inside an iframe. The iframe works well with old and new IE browsers, but it may not work with other browsers and probably not with the latest IE.

 #myid { overflow-x: scroll; overflow-y: hide; width:200px; /* Or whatever the amount of pixels */ }
.myid { overflow-x: scroll; overflow-y: hide; width:200px; /* Or whatever the amount of pixels */ }

<div class="myid">
     <div class="row">Content1</div>
     <div class="row2">Content2</div>
</div>

<table id="myid"><tr><td>Content</td></tr></table>

Failed to allocate memory: 8

Have a look at the official issue 33930. There is pointed out, that it may have to do with the start up of OpenGL during the start of the emulator. Others wrote it only crashes when they use WXGA800-skin and suggest to manually set the resolution to 800x1280.

Further there are ZIP-files provided to manually downgrade your android SDK to version 19 and plattform-tools to version 11. This may help as well to temporally fix the issue.

Where does gcc look for C and C++ header files?

g++ -print-search-dirs
gcc -print-search-dirs

Difference between .keystore file and .jks file

Ultimately, .keystore and .jks are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).

In Java, the word keystore can have either of the following meanings, depending on the context:

When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.

Java uses its KeyStore class and related API to make use of a keystore (whether it's file based or not). JKS is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:

  • .jks for type "JKS",
  • .p12 or .pfx for type "PKCS12" (the specification name is PKCS#12, but the # is not used in the Java keystore type name).

In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks extension), which is frequently used for Android applications.

How do you decompile a swf file

Usually 'lost' is a euphemism for "We stopped paying the developer and now he wont give us the source code."

That being said, I own a copy of Burak's ActionScript Viewer, and it works pretty well. A simple google search will find you many other SWF decompilers.

What's the easiest way to call a function every 5 seconds in jQuery?

Both setInterval and setTimeout can work for you (as @Doug Neiner and @John Boker wrote both now point to setInterval).
See here for some more explanation about both to see which suites you most and how to stop each of them.

Using NotNull Annotation in method argument

@Nullable and @NotNull do nothing on their own. They are supposed to act as Documentation tools.

The @Nullable Annotation reminds you about the necessity to introduce an NPE check when:

  1. Calling methods that can return null.
  2. Dereferencing variables (fields, local variables, parameters) that can be null.

The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot should not hold null value.

For example, instead of writing:

/**
 * @param aX should not be null
 */
public void setX(final Object aX ) {
    // some code
}

You can use:

public void setX(@NotNull final Object aX ) {
    // some code
}

Additionally, @NotNull is often checked by ConstraintValidators (eg. in spring and hibernate).

The @NotNull annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator type reference.

For more info see:

  1. Bean validation
  2. NotNull.java
  3. Constraint.java
  4. ConstraintValidator.java

What are "named tuples" in Python?

named tuples allow backward compatibility with code that checks for the version like this

>>> sys.version_info[0:2]
(3, 1)

while allowing future code to be more explicit by using this syntax

>>> sys.version_info.major
3
>>> sys.version_info.minor
1

Merging two CSV files using Python

You need to store all of the extra rows in the files in your dictionary, not just one of them:

dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}

Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:

w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])

How to make type="number" to positive numbers only

Try

<input type="number" pattern="^[0-9]" title='Only Number' min="1" step="1">

What are NR and FNR and what does "NR==FNR" imply?

Assuming you have Files a.txt and b.txt with

cat a.txt
a
b
c
d
1
3
5
cat b.txt
a
1
2
6
7

Keep in mind NR and FNR are awk built-in variables. NR - Gives the total number of records processed. (in this case both in a.txt and b.txt) FNR - Gives the total number of records for each input file (records in either a.txt or b.txt)

awk 'NR==FNR{a[$0];}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
a.txt 1 1 a
a.txt 2 2 b
a.txt 3 3 c
a.txt 4 4 d
a.txt 5 5 1
a.txt 6 6 3
a.txt 7 7 5
b.txt 8 1 a
b.txt 9 2 1

lets Add "next" to skip the first matched with NR==FNR

in b.txt and in a.txt

awk 'NR==FNR{a[$0];next}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 8 1 a
b.txt 9 2 1

in b.txt but not in a.txt

 awk 'NR==FNR{a[$0];next}{if(!($0 in a))print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 10 3 2
b.txt 11 4 6
b.txt 12 5 7

awk 'NR==FNR{a[$0];next}!($0 in a)' a.txt b.txt
2
6
7

What is the easiest way to encrypt a password when I save it to the registry?

You don't decrypt authentication passwords!

Hash them using something like the SHA256 provider and when you have to challenge, hash the input from the user and see if the two hashes match.

byte[] data = System.Text.Encoding.ASCII.GetBytes(inputString);
data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
String hash = System.Text.Encoding.ASCII.GetString(data);

Leaving passwords reversible is a really horrible model.

Edit2: I thought we were just talking about front-line authentication. Sure there are cases where you want to encrypt passwords for other things that need to be reversible but there should be a 1-way lock on top of it all (with a very few exceptions).

I've upgraded the hashing algorithm but for the best possible strength you want to keep a private salt and add that to your input before hashing it. You would do this again when you compare. This adds another layer making it even harder for somebody to reverse.

How to generate random float number in C

This generates a random float between two floats.

float RandomFloat(float min, float max){
   return ((max - min) * ((float)rand() / RAND_MAX)) + min;
}

Is there a way to return a list of all the image file names from a folder using only Javascript?

This will list all jpg files in the folder you define under url: and append them to a div as a paragraph. Can do it with ul li as well.

$.ajax({
  url: "YOUR FOLDER",
  success: function(data){
     $(data).find("a:contains(.jpg)").each(function(){
        // will loop through 
        var images = $(this).attr("href");

        $('<p></p>').html(images).appendTo('a div of your choice')

     });
  }
});

How to print (using cout) a number in binary form?

Similar to what is already posted, just using bit-shift and mask to get the bit; usable for any type, being a template (only not sure if there is a standard way to get number of bits in 1 byte, I used 8 here).

#include<iostream>
#include <climits>

template<typename T>
void printBin(const T& t){
    size_t nBytes=sizeof(T);
    char* rawPtr((char*)(&t));
    for(size_t byte=0; byte<nBytes; byte++){
        for(size_t bit=0; bit<CHAR_BIT; bit++){
            std::cout<<(((rawPtr[byte])>>bit)&1);
        }
    }
    std::cout<<std::endl;
};

int main(void){
    for(int i=0; i<50; i++){
        std::cout<<i<<": ";
        printBin(i);
    }
}

php convert datetime to UTC

try

echo date('F d Y', strtotime('2010-01-19 00:00:00'));

will output:

January 19 2010

you should change format time to see other output

How do I pass named parameters with Invoke-Command?

-ArgumentList is based on use with scriptblock commands, like:

Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True

When you call it with a -File it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).

So, you have two options:

If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug is implied because when I use the Parameter attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):

param(
   [Parameter(Position=0)]
   $one
,
   [Parameter(Position=1)]
   $two
,
   [Parameter()]
   [Switch]$Clear
)

"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."

Without getting hung up on the meaning of $Clear ... if you wanted to invoke that you could use either of the following Invoke-Command syntaxes:

icm -cn (gc Servers.txt) { 
    param($one,$two,$Debug=$False,$Clear=$False)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true

In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:

icm -cn $Env:ComputerName { 
    param([bool]$Clear)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)

The other option

If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:

$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )

Invoke-Command -Script $script -Args "uno", "dos", $false, $true

PostScript:

If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script or an environment variable $Env:Script with the name of a script, you can execute it with the call operator (&): &$Script or &$Env:Script

If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:

Invoke-Command -cn $Env:ComputerName { 
    param([String]$Script, [bool]$Clear)
    & $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)

How can I make a list of installed packages in a certain virtualenv?

If you're still a bit confused about virtualenv you might not pick up how to combine the great tips from the answers by Ioannis and Sascha. I.e. this is the basic command you need:

/YOUR_ENV/bin/pip freeze --local

That can be easily used elsewhere. E.g. here is a convenient and complete answer, suited for getting all the local packages installed in all the environments you set up via virtualenvwrapper:

cd ${WORKON_HOME:-~/.virtualenvs}
for dir in *; do [ -d $dir ] && $dir/bin/pip freeze --local >  /tmp/$dir.fl; done
more /tmp/*.fl

Excel how to fill all selected blank cells with text

To put the same text in a certain number of cells do the following:

  1. Highlight the cells you want to put text into
  2. Type into the cell you're currently in the data you want to be repeated
  3. Hold Crtl and press 'return'

You will find that all the highlighted cells now have the same data in them. Have a nice day.

Best timing method in C?

If you don't want CPU time then I think what you're looking for is the timeval struct.

I use the below for calculating execution time:

int timeval_subtract(struct timeval *result,                                                                                                                                        
                     struct timeval end,                                                                                                                                                 
                     struct timeval start)                                                                                                                                               
{                                                                                                                                                                                   
        if (start.tv_usec < end.tv_usec) {                                                                                                                                          
                int nsec = (end.tv_usec - start.tv_usec) / 1000000 + 1;                                                                                                             
                end.tv_usec -= 1000000 * nsec;                                                                                                                                      
                end.tv_sec += nsec;                                                                                                                                                 
        }                                                                                                                                                                           
        if (start.tv_usec - end.tv_usec > 1000000) {                                                                                                                                
                int nsec = (end.tv_usec - start.tv_usec) / 1000000;                                                                                                                 
                end.tv_usec += 1000000 * nsec;                                                                                                                                      
                end.tv_sec -= nsec;                                                                                                                                                 
        }                                                                                                                                                                           

        result->tv_sec = end.tv_sec - start.tv_sec;                                                                                                                                 
        result->tv_usec = end.tv_usec - start.tv_usec;                                                                                                                              

        return end.tv_sec < start.tv_sec;                                                                                                                                           
}                                                                                                                                                                                   

void set_exec_time(int end)                                                                                                                                                         
{                                                                                                                                                                                   
        static struct timeval time_start;                                                                                                                                           
        struct timeval time_end;                                                                                                                                                    
        struct timeval time_diff;                                                                                                                                                   

        if (end) {                                                                                                                                                                  
                gettimeofday(&time_end, NULL);                                                                                                                                      
                if (timeval_subtract(&time_diff, time_end, time_start) == 0) {                                                                                                      
                        if (end == 1)                                                                                                                                               
                                printf("\nexec time: %1.2fs\n",                                                                                                                     
                                        time_diff.tv_sec + (time_diff.tv_usec / 1000000.0f));                                                                                       
                        else if (end == 2)                                                                                                                                          
                                printf("%1.2fs",                                                                                                                                    
                                        time_diff.tv_sec + (time_diff.tv_usec / 1000000.0f));                                                                                       
                }                                                                                                                                                                   
                return;                                                                                                                                                             
        }                                                                                                                                                                           
        gettimeofday(&time_start, NULL);                                                                                                                                            
}                                                                                                                                                                                   

void start_exec_timer()                                                                                                                                                             
{                                                                                                                                                                                   
        set_exec_time(0);                                                                                                                                                           
}                                                                                                                                                                                   

void print_exec_timer()                                                                                                                                                             
{                                                                                                                                                                                   
        set_exec_time(1);                                                                                                                                                           
}

pandas get rows which are NOT in other dataframe

How about this:

df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 
                               'col2' : [10, 11, 12, 13, 14]}) 
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 
                               'col2' : [10, 11, 12]})
records_df2 = set([tuple(row) for row in df2.values])
in_df2_mask = np.array([tuple(row) in records_df2 for row in df1.values])
result = df1[~in_df2_mask]

How to write the code for the back button?

<a href="javascript:history.back(1)">Back</a>

this one (by Eiko) is perfect, use css to make a button of <a>... eg you can use this css class in <a> as `

<a class=".back_button" href="javascript:history.back(1)">Back</a>`

.back_button {
display:block;
width:100px;
height:30px;
text-align:center;
background-color:yellow;
border:1px solid #000000;
}

How to change the height of a div dynamically based on another div using css?

Flex answer

.div1 {
   width:300px;
   background-color: grey;  
   border:1px solid;
   overflow:auto;
   display: flex;
}
.div2 {
   width:150px;
   background-color: #F4A460;
 }
.div3 {
    width:150px;
    background-color: #FFFFE0;  
 }

Check the fiddle at http://jsfiddle.net/germangonzo/E4Zgj/575/

Force flushing of output to a file while bash script is still running

Buffering of output depends on how your program /homedir/MyScript is implemented. If you find that output is getting buffered, you have to force it in your implementation. For example, use sys.stdout.flush() if it's a python program or use fflush(stdout) if it's a C program.

Error CS2001: Source file '.cs' could not be found

In my case, I add file as Link from another project and then rename file in source project that cause problem in destination project. I delete linked file in destination and add again with new name.

Get index of current item in a PowerShell loop

I am not sure it's possible with an "automatic" variable. You can always declare one for yourself and increment it:

$letters = { 'A', 'B', 'C' }
$letters | % {$counter = 0}{...;$counter++}

Or use a for loop instead...

for ($counter=0; $counter -lt $letters.Length; $counter++){...}

Xcode 10 Error: Multiple commands produce

While checking the build log, I noticed a warning:

note: Using new build system
note: Planning build
note: Constructing build description
Build system information
warning: The Copy Bundle Resources build phase contains this target's Info.plist file '/Users/<redacted>/Repositories/Whitesmith/optimize-ios/Carthage/Checkouts/WSStatusBarNotification/Miscellaneous/Info.plist'. (in target 'JDStatusBarNotification')

So, if that's your case then just go to your target:

  1. Build Phases
  2. Copy Bundle Resource
  3. Remove info.plist.

How to convert answer into two decimal point

Call me lazy but:

 lblTellBMI.Text = "Your BMI is: " & Math.Round(sngBMI, 2)

I.e.: Label lblTellBMI will display Your BMI is: and then append the value from a Single type variable (sngBMI) as 2 decimal points, simply by using the Math.Round method.

The Math.Round method rounds a value to the nearest integer or to the specified number of fractional digits.

Source: https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

I had the same issue because of an incorrect product sku.

I was using android.test.purchase instead of android.test.purchased.

How can I export tables to Excel from a webpage

mozilla still support base 64 URIs. This allows you to compose dynamically the binary content using javascript:

<a href="data:application/vnd.ms-excel<base64 encoded binary excel content here>"> download xls</a>

if your excel file is not very fancy (no diagrams, formulas, macroses) you can dig into the format and compose bytes for your file, then encode them with base64 and put in to the href

refer to https://developer.mozilla.org/en/data_URIs

jQuery datepicker years shown

Perfect for date of birth fields (and what I use) is similar to what Shog9 said, although I'm going to give a more specific DOB example:

$(".datePickerDOB").datepicker({ 
    yearRange: "-122:-18", //18 years or older up to 122yo (oldest person ever, can be sensibly set to something much smaller in most cases)
    maxDate: "-18Y", //Will only allow the selection of dates more than 18 years ago, useful if you need to restrict this
    minDate: "-122Y"
});

Hope future googlers find this useful :).

Can I run a 64-bit VMware image on a 32-bit machine?

VMware? No. However, QEMU has an x86_64 system target that you can use. You likely won't be able to use a VMware image directly (IIRC, there's no conversion tool), but you can install the OS and such yourself and work inside it. QEMU can be a bit of a PITA to get up and running, but it tends to work quite nicely.

When does Git refresh the list of remote branches?

The OP did not ask for cleanup for all remotes, rather for all branches of default remote.

So git fetch --prune is what should be used.

Setting git config remote.origin.prune true makes --prune automatic. In that case just git fetch will also prune stale remote branches from the local copy. See also Automatic prune with Git fetch or pull.

Note that this does not clean local branches that are no longer tracking a remote branch. See How to prune local tracking branches that do not exist on remote anymore for that.

Insert image after each list item

For IE8 support, the "content" property cannot be empty.

To get around this I've done the following :

.ul li:after {
    content:"icon";
    text-indent:-999em;
    display:block;
    width:32px;
    height:32px;
    background:url(../img/icons/spritesheet.png) 0 -620px no-repeat;
    margin:5% 0 0 45%;
}

Note : This works with image sprites too

Can a shell script set environment variables of the calling shell?

I created a solution using pipes, eval and signal.

parent() {
    if [ -z "$G_EVAL_FD" ]; then
            die 1 "Rode primeiro parent_setup no processo pai"
    fi
    if [ $(ppid) = "$$" ]; then
            "$@"
    else
            kill -SIGUSR1 $$
            echo "$@">&$G_EVAL_FD
    fi
}
parent_setup() {
    G_EVAL_FD=99
    tempfile=$(mktemp -u)
    mkfifo "$tempfile"
    eval "exec $G_EVAL_FD<>'$tempfile'"
    rm -f "$tempfile"
    trap "read CMD <&$G_EVAL_FD; eval \"\$CMD\"" USR1
}
parent_setup #on parent shell context
( A=1 ); echo $A # prints nothing
( parent A=1 ); echo $A # prints 1

It might work with any command.

'uint32_t' does not name a type

just navigate to /usr/include/x86_64-linux-gnu/bits open stdint-uintn.h and add these lines

typedef __uint8_t uint8_t;
typedef __uint16_t uint16_t;
typedef __uint32_t uint32_t;
typedef __uint64_t uint64_t;

again open stdint-intn.h and add

typedef __int8_t int8_t;
typedef __int16_t int16_t;
typedef __int32_t int32_t;
typedef __int64_t int64_t;

note these lines are already present just copy and add the missing lines cheerss..

Python 2.6: Class inside a Class?

class Second:
    def __init__(self, data):
        self.data = data

class First:
    def SecondClass(self, data):
        return Second(data)

FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data

Is it possible to use Visual Studio on macOS?

Yes! You can use the new Visual Studio for Mac, which Microsoft launched in November.

Read about it here: https://msdn.microsoft.com/magazine/mt790182

Download a preview version here: https://www.visualstudio.com/vs/visual-studio-mac/

Python setup.py develop vs install

From the documentation. The develop will not install the package but it will create a .egg-link in the deployment directory back to the project source code directory.

So it's like installing but instead of copying to the site-packages it adds a symbolic link (the .egg-link acts as a multiplatform symbolic link).

That way you can edit the source code and see the changes directly without having to reinstall every time that you make a little change. This is useful when you are the developer of that project hence the name develop. If you are just installing someone else's package you should use install

Undo git update-index --assume-unchanged <file>

If this is a command that you use often - you may want to consider having an alias for it as well. Add to your global .gitconfig:

[alias]
    hide = update-index --assume-unchanged
    unhide = update-index --no-assume-unchanged

How to set an alias (if you don't know already):

git config --configLocation alias.aliasName 'command --options'

Example:

git config --global alias.hide 'update-index --assume-unchanged'
git config... etc

After saving this to your .gitconfig, you can run a cleaner command.

git hide myfile.ext

or

git unhide myfile.ext

This git documentation was very helpful.

As per the comments, this is also a helpful alias to find out what files are currently being hidden:

[alias]
    hidden = ! git ls-files -v | grep '^h' | cut -c3-

Moment JS start and end of given month

your startDate is first-day-of-month, In this case we can use

var endDate = moment(startDate).add(1, 'months').subtract(1, 'days');

Hope this helps!!

Insert array into MySQL database with PHP

<?php
 function mysqli_insert_array($table, $data, $exclude = array()) {
    $con=  mysqli_connect("localhost", "root","","test");
     $fields = $values = array();
    if( !is_array($exclude) ) $exclude = array($exclude);
    foreach( array_keys($data) as $key ) {
        if( !in_array($key, $exclude) ) {
            $fields[] = "`$key`";
            $values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
        }
    }
    $fields = implode(",", $fields);
    $values = implode(",", $values);
    if( mysqli_query($con,"INSERT INTO `$table` ($fields) VALUES ($values)") ) {
        return array( "mysql_error" => false,
                      "mysql_insert_id" => mysqli_insert_id($con),
                      "mysql_affected_rows" => mysqli_affected_rows($con),
                      "mysql_info" => mysqli_info($con)
                    );
    } else {
        return array( "mysql_error" => mysqli_error($con) );
    }
}

 $a['firstname']="abc";
 $a['last name']="xyz";
 $a['birthdate']="1993-09-12";
 $a['profilepic']="img.jpg";
 $a['gender']="male";
 $a['email']="[email protected]";
 $a['likechoclate']="Dm";
 $a['status']="1";
$result=mysqli_insert_array('registration',$a,'abc');
if( $result['mysql_error'] ) {
    echo "Query Failed: " . $result['mysql_error'];
} else {
    echo "Query Succeeded! <br />";
    echo "<pre>";
    print_r($result);
    echo "</pre>";
}
?>

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

PDANet driver was the only solution for me to successfully connect to Google Galaxy Nexus 4.2.1 on Windows 7 x64 which was rejecting/ignoring official USB drivers from the latest 4.2 ADK (revision 7) - http://junefabrics.com/android/index.php

SELECT inside a COUNT

SELECT a AS current_a, COUNT(*) AS b,
   (SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
   from t group by a order by b desc

List comprehension on a nested list?

Here is how you would do this with a nested list comprehension:

[[float(y) for y in x] for x in l]

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].

MySQL: How to reset or change the MySQL root password?

I faced problems with ubuntu 18.04 and mysql 5.7, this is the solution

Try restart mysql-server before execution the comands

sudo service mysql restart

MYSQL-SERVER >= 5.7

sudo mysql -uroot -p
USE mysql;
UPDATE user SET authentication_string=PASSWORD('YOUR_PASSWORD') WHERE User='root';
UPDATE user SET plugin="mysql_native_password";
FLUSH PRIVILEGES;
quit;

MYSQL-SERVER < 5.7

sudo mysql -uroot -p
USE mysql;
UPDATE user SET password=PASSWORD('YOUR_PASSWORD') WHERE User='root';
UPDATE user SET plugin="mysql_native_password";
FLUSH PRIVILEGES;
quit;

How to simulate a button click using code?

Just to clarify what moonlightcheese stated: To trigger a button click event through code in Android provide the following:

buttonName.performClick();

jQuery: outer html()

If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:

var myID = "xxx";

var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";

What is mapDispatchToProps?

Now suppose there is an action for redux as:

export function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

When you do import it,

import {addTodo} from './actions';

class Greeting extends React.Component {

    handleOnClick = () => {
        this.props.onTodoClick(); // This prop acts as key to callback prop for mapDispatchToProps
    }

    render() {
        return <button onClick={this.handleOnClick}>Hello Redux</button>;
    }
}

const mapDispatchToProps = dispatch => {
    return {
      onTodoClick: () => { // handles onTodoClick prop's call here
        dispatch(addTodo())
      }
    }
}

export default connect(
    null,
    mapDispatchToProps
)(Greeting);

As function name says mapDispatchToProps(), map dispatch action to props(our component's props)

So prop onTodoClick is a key to mapDispatchToProps function which delegates furthere to dispatch action addTodo.

Also if you want to trim the code and bypass manual implementation, then you can do this,

import {addTodo} from './actions';
class Greeting extends React.Component {

    handleOnClick = () => {
        this.props.addTodo();
    }

    render() {
        return <button onClick={this.handleOnClick}>Hello Redux</button>;
    }
}

export default connect(
    null,
    {addTodo}
)(Greeting);

Which exactly means

const mapDispatchToProps = dispatch => {
    return {
      addTodo: () => { 
        dispatch(addTodo())
      }
    }
}

How to change the size of the font of a JLabel to take the maximum size

Not the most pretty code, but the following will pick an appropriate font size for a JLabel called label such that the text inside will fit the interior as much as possible without overflowing the label:

Font labelFont = label.getFont();
String labelText = label.getText();

int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();

// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;

int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();

// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);

// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));

Basically, the code looks at how much space the text in the JLabel takes up by using the FontMetrics object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel.

The above code can be inserted into perhaps the paint method of the JFrame which holds the JLabel, or some method which will be invoked when the font size needs to be changed.

The following is an screenshot of the above code in action:

alt text
(source: coobird.net)

Difference between abstract class and interface in Python

In general, interfaces are used only in languages that use the single-inheritance class model. In these single-inheritance languages, interfaces are typically used if any class could use a particular method or set of methods. Also in these single-inheritance languages, abstract classes are used to either have defined class variables in addition to none or more methods, or to exploit the single-inheritance model to limit the range of classes that could use a set of methods.

Languages that support the multiple-inheritance model tend to use only classes or abstract base classes and not interfaces. Since Python supports multiple inheritance, it does not use interfaces and you would want to use base classes or abstract base classes.

http://docs.python.org/library/abc.html

Android read text raw resource file

1.First create a Directory folder and name it raw inside the res folder 2.create a .txt file inside the raw directory folder you created earlier and give it any name eg.articles.txt.... 3.copy and paste the text you want inside the .txt file you created"articles.txt" 4.dont forget to include a textview in your main.xml MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gettingtoknowthe_os);

    TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos);
    helloTxt.setText(readTxt());

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();//to exclude the ActionBar
}

private String readTxt() {

    //getting the .txt file
    InputStream inputStream = getResources().openRawResource(R.raw.articles);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    try {
        int i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return byteArrayOutputStream.toString();
}

Hope it worked!

Check if Nullable Guid is empty in c#

If you want be sure you need to check both

SomeProperty == null || SomeProperty == Guid.Empty

Because it can be null 'Nullable' and it can be an empty GUID something like this {00000000-0000-0000-0000-000000000000}

Adding a library/JAR to an Eclipse Android project

If you are using the ADT version 22, you need to check the android dependencies and android private libraries in the order&Export tab in the project build path

Modulo operator in Python

Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3, 7.3 % 4.0 = 3.3

Beware of floating point accuracy issues.

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

Forcing anti-aliasing using css: Is this a myth?

Using an opacity setting of 99% (through the DXTransform filters) actually forces Internet Explorer to turn off ClearType, at least in Version 7. Source

Using ORDER BY and GROUP BY together

SQL>

SELECT interview.qtrcode QTR, interview.companyname "Company Name", interview.division Division 
FROM interview 
JOIN jobsdev.employer 
    ON (interview.companyname = employer.companyname AND employer.zipcode like '100%')
GROUP BY interview.qtrcode, interview.companyname, interview.division
ORDER BY interview.qtrcode;

How to get POSTed JSON in Flask?

The following codes can be used:

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
  content = request.json['text']
  print content
  return uuid

Here is a screenshot of me getting the json data:

enter image description here

You can see that what is returned is a dictionary type of data.

How to Position a table HTML?

You would want to use CSS to achieve that.

say you have a table with the attribute id="my_table"

You would want to write the following in your css file

#my_table{
    margin-top:10px //moves your table 10pixels down
    margin-left:10px //moves your table 10pixels right
}

if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px to the style attribute in your table element like so

<table style="margin-top:10px; margin-left:10px;">
    ....
</table>

There are a lot of resources on the net describing CSS and HTML in detail