Programs & Examples On #Mysql error 2002

Can't connect to local MySQL server through socket

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

please check the mysql.ini file in your xampp mysql installation... its found on xampp/mysql/bin directory

check the line 43

> log_error="mysql_error.log"
> #bind-address="127.0.0.1"

uncomment the line 43 if its still commented

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Check the "bind-adress" parameter in my.cnf.

Else try with the command:

mysql -h 127.0.0.1 -P 3306 -u root -p
  • -h for host 127.0.0.1, that is, localhost

  • -P (notice -P as uppercase) for port 3306, that is, the default port for MySQL

Connecting to remote MySQL server using PHP

It is very easy to connect remote MySQL Server Using PHP, what you have to do is:

  1. Create a MySQL User in remote server.

  2. Give Full privilege to the User.

  3. Connect to the Server using PHP Code (Sample Given Below)

$link = mysql_connect('your_my_sql_servername or IP Address', 'new_user_which_u_created', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';

mysql_select_db('sandsbtob',$link) or die ("could not open db".mysql_error());
// we connect to localhost at port 3306

How to get the Development/Staging/production Hosting Environment in ConfigureServices

If you need to test this somewhere in your codebase that doesn't have easy access to the IHostingEnvironment, another easy way to do it is like this:

bool isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";

Collectors.toMap() keyMapper -- more succinct expression?

List<Person> roster = ...;

Map<String, Person> map = 
    roster
        .stream()
        .collect(
            Collectors.toMap(p -> p.getLast(), p -> p)
        );

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)

Hive query output to file

This will put the results in tab delimited file(s) under a directory:

INSERT OVERWRITE LOCAL DIRECTORY '/home/hadoop/YourTableDir'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
STORED AS TEXTFILE
SELECT * FROM table WHERE id > 100;

Print array elements on separate lines in Bash?

I've discovered that you can use eval to avoid using a subshell. Thus:

IFS=$'\n' eval 'echo "${my_array[*]}"'

catch specific HTTP error in python

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

Update query using Subquery in Sql Server

because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:

SELECT *
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Then note that we have two table aliases a and b. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b, the statement will be:

UPDATE  b
SET     b.marks = a.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a only (leaving b intact) for those records that match by name:

DELETE a
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

You can use the SQL Fiddle created by JW as a playground

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

For debugging purposes, you could use print(repr(data)).

To display text, always print Unicode. Don't hardcode the character encoding of your environment such as Cp850 inside your script. To decode the HTTP response, see A good way to get the charset/encoding of an HTTP response in Python.

To print Unicode to Windows console, you could use win-unicode-console package.

What does LINQ return when the results are empty

In Linq-to-SQL if you try to get the first element on a query with no results you will get sequence contains no elements error. I can assure you that the mentioned error is not equal to object reference not set to an instance of an object. in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;)

ImportError: No module named site on Windows

First uninstall python and again install the latest version during installation use custom install and mark all user checkbox and set the installation path C:\Python 3.9 and make PYTHON_HOME value C:\Python 3.9 in the Environmental variable it works for me

How to set up tmux so that it starts up with specified windows opened?

The plugin tmux-continuum will auto save your tmux session and load it the next time tmux starts, should be easier to setup than some of the custom script solutions here.

Features:

  • continuous saving of tmux environment
  • automatic tmux start when computer/server is turned on
  • automatic restore when tmux is started

To save your session on demand you can use the tmux-resurrect plugin. tmux-resurrect is also required to run tmux-continuum

tmux-resurrect saves all the little details from your tmux environment so it can be completely restored after a system restart (or when you feel like it). No configuration is required. You should feel like you never quit tmux.

How do you round UP a number in Python?

For those who doesn't want to use import.

For a given list or any number:

x = [2, 2.1, 2.5, 3, 3.1, 3.5, 2.499,2.4999999999, 3.4999999,3.99999999999]

You must first evaluate if the number is equal to its integer, which always rounds down. If the result is True, you return the number, if is not, return the integer(number) + 1.

w = lambda x: x if x == int(x) else int(x)+1
[w(i) for i in z]
>>> [2, 3, 3, 3, 4, 4, 3, 3, 4, 4]

Math logic:

  • If the number has decimal part: round_up - round_down == 1, always.
  • If the number doens't have decimal part: round_up - round_down == 0.

So:

  • round_up == x + round_down

With:

  • x == 1 if number != round_down
  • x == 0 if number == round_down

You are cutting the number in 2 parts, the integer and decimal. If decimal isn't 0, you add 1.

PS:I explained this in details since some comments above asked for that and I'm still noob here, so I can't comment.

How do I use arrays in C++?

5. Common pitfalls when using arrays.

5.1 Pitfall: Trusting type-unsafe linking.

OK, you’ve been told, or have found out yourself, that globals (namespace scope variables that can be accessed outside the translation unit) are Evil™. But did you know how truly Evil™ they are? Consider the program below, consisting of two files [main.cpp] and [numbers.cpp]:

// [main.cpp]
#include <iostream>

extern int* numbers;

int main()
{
    using namespace std;
    for( int i = 0;  i < 42;  ++i )
    {
        cout << (i > 0? ", " : "") << numbers[i];
    }
    cout << endl;
}

// [numbers.cpp]
int numbers[42] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

In Windows 7 this compiles and links fine with both MinGW g++ 4.4.1 and Visual C++ 10.0.

Since the types don't match, the program crashes when you run it.

The Windows 7 crash dialog

In-the-formal explanation: the program has Undefined Behavior (UB), and instead of crashing it can therefore just hang, or perhaps do nothing, or it can send threating e-mails to the presidents of the USA, Russia, India, China and Switzerland, and make Nasal Daemons fly out of your nose.

In-practice explanation: in main.cpp the array is treated as a pointer, placed at the same address as the array. For 32-bit executable this means that the first int value in the array, is treated as a pointer. I.e., in main.cpp the numbers variable contains, or appears to contain, (int*)1. This causes the program to access memory down at very bottom of the address space, which is conventionally reserved and trap-causing. Result: you get a crash.

The compilers are fully within their rights to not diagnose this error, because C++11 §3.5/10 says, about the requirement of compatible types for the declarations,

[N3290 §3.5/10]
A violation of this rule on type identity does not require a diagnostic.

The same paragraph details the variation that is allowed:

… declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4).

This allowed variation does not include declaring a name as an array in one translation unit, and as a pointer in another translation unit.

5.2 Pitfall: Doing premature optimization (memset & friends).

Not written yet

5.3 Pitfall: Using the C idiom to get number of elements.

With deep C experience it’s natural to write …

#define N_ITEMS( array )   (sizeof( array )/sizeof( array[0] ))

Since an array decays to pointer to first element where needed, the expression sizeof(a)/sizeof(a[0]) can also be written as sizeof(a)/sizeof(*a). It means the same, and no matter how it’s written it is the C idiom for finding the number elements of array.

Main pitfall: the C idiom is not typesafe. For example, the code …

#include <stdio.h>

#define N_ITEMS( array ) (sizeof( array )/sizeof( *array ))

void display( int const a[7] )
{
    int const   n = N_ITEMS( a );          // Oops.
    printf( "%d elements.\n", n );
}

int main()
{
    int const   moohaha[]   = {1, 2, 3, 4, 5, 6, 7};

    printf( "%d elements, calling display...\n", N_ITEMS( moohaha ) );
    display( moohaha );
}

passes a pointer to N_ITEMS, and therefore most likely produces a wrong result. Compiled as a 32-bit executable in Windows 7 it produces …

7 elements, calling display...
1 elements.

  1. The compiler rewrites int const a[7] to just int const a[].
  2. The compiler rewrites int const a[] to int const* a.
  3. N_ITEMS is therefore invoked with a pointer.
  4. For a 32-bit executable sizeof(array) (size of a pointer) is then 4.
  5. sizeof(*array) is equivalent to sizeof(int), which for a 32-bit executable is also 4.

In order to detect this error at run time you can do …

#include <assert.h>
#include <typeinfo>

#define N_ITEMS( array )       (                               \
    assert((                                                    \
        "N_ITEMS requires an actual array as argument",        \
        typeid( array ) != typeid( &*array )                    \
        )),                                                     \
    sizeof( array )/sizeof( *array )                            \
    )

7 elements, calling display...
Assertion failed: ( "N_ITEMS requires an actual array as argument", typeid( a ) != typeid( &*a ) ), file runtime_detect ion.cpp, line 16

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

The runtime error detection is better than no detection, but it wastes a little processor time, and perhaps much more programmer time. Better with detection at compile time! And if you're happy to not support arrays of local types with C++98, then you can do that:

#include <stddef.h>

typedef ptrdiff_t   Size;

template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }

#define N_ITEMS( array )       n_items( array )

Compiling this definition substituted into the first complete program, with g++, I got …

M:\count> g++ compile_time_detection.cpp
compile_time_detection.cpp: In function 'void display(const int*)':
compile_time_detection.cpp:14: error: no matching function for call to 'n_items(const int*&)'

M:\count> _

How it works: the array is passed by reference to n_items, and so it does not decay to pointer to first element, and the function can just return the number of elements specified by the type.

With C++11 you can use this also for arrays of local type, and it's the type safe C++ idiom for finding the number of elements of an array.

5.4 C++11 & C++14 pitfall: Using a constexpr array size function.

With C++11 and later it's natural, but as you'll see dangerous!, to replace the C++03 function

typedef ptrdiff_t   Size;

template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }

with

using Size = ptrdiff_t;

template< class Type, Size n >
constexpr auto n_items( Type (&)[n] ) -> Size { return n; }

where the significant change is the use of constexpr, which allows this function to produce a compile time constant.

For example, in contrast to the C++03 function, such a compile time constant can be used to declare an array of the same size as another:

// Example 1
void foo()
{
    int const x[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
    constexpr Size n = n_items( x );
    int y[n] = {};
    // Using y here.
}

But consider this code using the constexpr version:

// Example 2
template< class Collection >
void foo( Collection const& c )
{
    constexpr int n = n_items( c );     // Not in C++14!
    // Use c here
}

auto main() -> int
{
    int x[42];
    foo( x );
}

The pitfall: as of July 2015 the above compiles with MinGW-64 5.1.0 with -pedantic-errors, and, testing with the online compilers at gcc.godbolt.org/, also with clang 3.0 and clang 3.2, but not with clang 3.3, 3.4.1, 3.5.0, 3.5.1, 3.6 (rc1) or 3.7 (experimental). And important for the Windows platform, it does not compile with Visual C++ 2015. The reason is a C++11/C++14 statement about use of references in constexpr expressions:

C++11 C++14 $5.19/2 nineth dash

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
        ?

  • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
    • it is initialized with a constant expression or
    • it is a non-static data member of an object whose lifetime began within the evaluation of e;

One can always write the more verbose

// Example 3  --  limited

using Size = ptrdiff_t;

template< class Collection >
void foo( Collection const& c )
{
    constexpr Size n = std::extent< decltype( c ) >::value;
    // Use c here
}

… but this fails when Collection is not a raw array.

To deal with collections that can be non-arrays one needs the overloadability of an n_items function, but also, for compile time use one needs a compile time representation of the array size. And the classic C++03 solution, which works fine also in C++11 and C++14, is to let the function report its result not as a value but via its function result type. For example like this:

// Example 4 - OK (not ideal, but portable and safe)

#include <array>
#include <stddef.h>

using Size = ptrdiff_t;

template< Size n >
struct Size_carrier
{
    char sizer[n];
};

template< class Type, Size n >
auto static_n_items( Type (&)[n] )
    -> Size_carrier<n>;
// No implementation, is used only at compile time.

template< class Type, size_t n >        // size_t for g++
auto static_n_items( std::array<Type, n> const& )
    -> Size_carrier<n>;
// No implementation, is used only at compile time.

#define STATIC_N_ITEMS( c ) \
    static_cast<Size>( sizeof( static_n_items( c ).sizer ) )

template< class Collection >
void foo( Collection const& c )
{
    constexpr Size n = STATIC_N_ITEMS( c );
    // Use c here
    (void) c;
}

auto main() -> int
{
    int x[42];
    std::array<int, 43> y;
    foo( x );
    foo( y );
}

About the choice of return type for static_n_items: this code doesn't use std::integral_constant because with std::integral_constant the result is represented directly as a constexpr value, reintroducing the original problem. Instead of a Size_carrier class one can let the function directly return a reference to an array. However, not everybody is familiar with that syntax.

About the naming: part of this solution to the constexpr-invalid-due-to-reference problem is to make the choice of compile time constant explicit.

Hopefully the oops-there-was-a-reference-involved-in-your-constexpr issue will be fixed with C++17, but until then a macro like the STATIC_N_ITEMS above yields portability, e.g. to the clang and Visual C++ compilers, retaining type safety.

Related: macros do not respect scopes, so to avoid name collisions it can be a good idea to use a name prefix, e.g. MYLIB_STATIC_N_ITEMS.

Highlight label if checkbox is checked

This is an example of using the :checked pseudo-class to make forms more accessible. The :checked pseudo-class can be used with hidden inputs and their visible labels to build interactive widgets, such as image galleries. I created the snipped for the people that wanna test.

_x000D_
_x000D_
input[type=checkbox] + label {_x000D_
  color: #ccc;_x000D_
  font-style: italic;_x000D_
} _x000D_
input[type=checkbox]:checked + label {_x000D_
  color: #f00;_x000D_
  font-style: normal;_x000D_
} 
_x000D_
<input type="checkbox" id="cb_name" name="cb_name"> _x000D_
<label for="cb_name">CSS is Awesome</label> 
_x000D_
_x000D_
_x000D_

How to call Base Class's __init__ method from the child class?

If you are using Python 3, it is recommended to simply call super() without any argument:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Do not call super with class as it may lead to infinite recursion exceptions as per this answer.

JSON to TypeScript class instance?

What is actually the most robust and elegant automated solution for deserializing JSON to TypeScript runtime class instances?

Using property decorators with ReflectDecorators to record runtime-accessible type information that can be used during a deserialization process provides a surprisingly clean and widely adaptable approach, that also fits into existing code beautifully. It is also fully automatable, and works for nested objects as well.

An implementation of this idea is TypedJSON, which I created precisely for this task:

@JsonObject
class Foo {
    @JsonMember
    name: string;

    getName(): string { return this.name };
}
var foo = TypedJSON.parse('{"name": "John Doe"}', Foo);

foo instanceof Foo; // true
foo.getName(); // "John Doe"

How to load image (and other assets) in Angular an project?

Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.

Sample example

<img [src]="'assets/img/klogo.png'" alt="image">

How to plot a 2D FFT in Matlab?

Assuming that I is your input image and F is its Fourier Transform (i.e. F = fft2(I))

You can use this code:

F = fftshift(F); % Center FFT

F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1

imshow(F,[]); % Display the result

How to thoroughly purge and reinstall postgresql on ubuntu?

Steps that worked for me on Ubuntu 8.04.2 to remove postgres 8.3

  1. List All Postgres related packages

    dpkg -l | grep postgres
    
    ii  postgresql                            8.3.17-0ubuntu0.8.04.1           object-relational SQL database (latest versi
    ii  postgresql-8.3                        8.3.9-0ubuntu8.04                object-relational SQL database, version 8.3
    ii  postgresql-client                     8.3.9-0ubuntu8.04                front-end programs for PostgreSQL (latest ve
    ii  postgresql-client-8.3                 8.3.9-0ubuntu8.04                front-end programs for PostgreSQL 8.3
    ii  postgresql-client-common              87ubuntu2                        manager for multiple PostgreSQL client versi
    ii  postgresql-common                     87ubuntu2                        PostgreSQL database-cluster manager
    ii  postgresql-contrib                    8.3.9-0ubuntu8.04                additional facilities for PostgreSQL (latest
    ii  postgresql-contrib-8.3                8.3.9-0ubuntu8.04                additional facilities for PostgreSQL
    
  2. Remove all above listed

    sudo apt-get --purge remove postgresql postgresql-8.3  postgresql-client  postgresql-client-8.3 postgresql-client-common postgresql-common  postgresql-contrib postgresql-contrib-8.3
    
  3. Remove the following folders

    sudo rm -rf /var/lib/postgresql/
    sudo rm -rf /var/log/postgresql/
    sudo rm -rf /etc/postgresql/
    

Tomcat request timeout

With Tomcat 7, you can add the StuckThreadDetectionValve which will enable you to identify threads that are "stuck". You can set-up the valve in the Context element of the applications where you want to do detecting:

<Context ...>
  ...
  <Valve 
    className="org.apache.catalina.valves.StuckThreadDetectionValve"
    threshold="60" />
  ...
</Context>

This would write a WARN entry into the tomcat log for any thread that takes longer than 60 seconds, which would enable you to identify the applications and ban them because they are faulty.

Based on the source code you may be able to write your own valve that attempts to stop the thread, however this would have knock on effects on the thread pool and there is no reliable way of stopping a thread in Java without the cooperation of that thread...

How do I find out if the GPS of an Android device is enabled

In your LocationListener, implement onProviderEnabled and onProviderDisabled event handlers. When you call requestLocationUpdates(...), if GPS is disabled on the phone, onProviderDisabled will be called; if user enables GPS, onProviderEnabled will be called.

Why can I not push_back a unique_ptr into a vector?

std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.

error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
 std::unique_ptr<int>]'

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

The following works with the new emplace calls.

std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );

See using unique_ptr with standard library containers for further reading.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

jquery - How to determine if a div changes its height or any css attribute?

Another simple example.

For this sample we can use 100x100 DIV-box:

<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
 // Red box contents here...
</div>

And small jQuery trick:

<script type="text/javascript">
  jQuery("#box").bind("resize", function() {
    alert("Box was resized from 100x100 to 200x200");
  });
  jQuery("#box").width(200).height(200).trigger("resize");
</script>

Steps:

  1. We created DIV block element for resizing operatios
  2. Add simple JavaScript code with:
    • jQuery bind
    • jQuery resizer with trigger action "resize" - trigger is most important thing in my example
  3. After resize you can check the browser alert information

That's all. ;-)

Make first letter of a string upper case (with maximum performance)

I took the fastest method from http://www.dotnetperls.com/uppercase-first-letter and converted to extension method:

    /// <summary>
    /// Returns the input string with the first character converted to uppercase, or mutates any nulls passed into string.Empty
    /// </summary>
    public static string FirstLetterToUpperCaseOrConvertNullToEmptyString(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return string.Empty;

        char[] a = s.ToCharArray();
        a[0] = char.ToUpper(a[0]);
        return new string(a);
    }

NOTE: The reason using ToCharArray is faster than the alternative char.ToUpper(s[0]) + s.Substring(1), is that only one string is allocated, whereas the Substring approach allocates a string for the substring, then a second string to compose the final result.


EDIT: Here is what this approach looks like, combined with the initial test from CarlosMuñoz accepted answer:

    /// <summary>
    /// Returns the input string with the first character converted to uppercase
    /// </summary>
    public static string FirstLetterToUpperCase(this string s)
    {
        if (string.IsNullOrEmpty(s))
            throw new ArgumentException("There is no first letter");

        char[] a = s.ToCharArray();
        a[0] = char.ToUpper(a[0]);
        return new string(a);
    }

Windows Batch Files: if else

You have to do the following:

if "%1" == "" (
    echo The variable is empty
) ELSE (
    echo The variable contains %1
)

Getting each individual digit from a whole integer

#include<stdio.h>

int main() {
int num; //given integer
int reminder;
int rev=0; //To reverse the given integer
int count=1;

printf("Enter the integer:");
scanf("%i",&num);

/*First while loop will reverse the number*/
while(num!=0)
{
    reminder=num%10;
    rev=rev*10+reminder;
    num/=10;
}
/*Second while loop will give the number from left to right*/
while(rev!=0)
{
    reminder=rev%10;
    printf("The %d digit is %d\n",count, reminder);
    rev/=10;
    count++; //to give the number from left to right 
}
return (EXIT_SUCCESS);}

Add a link to an image in a css style sheet

You can not do that...

via css the URL you put on the background-image is just for the image.

Via HTML you have to add the href for your hyperlink in this way:

<a href="http://home.com" id="logo">Your logo</a>

With text-indent and some other css you can adjust your a element to show just the image and clicking on it you will go to your link.


EDIT:

I'm here again to show you and explain why my solution is much better:

<a href="http://home.com" id="logo">Your logo name</a>

This block of HTML is SEO friendly because you have some text inside your link!

How to style it with css:

#logo {
  background-image: url(images/logo.png);
  display: block;
  margin: 0 auto;
  text-indent: -9999px;
  width: 981px;
  height: 180px;
}

Then if you don't care about SEO good to choose the other answer.

How can strings be concatenated?

The easiest way would be

Section = 'Sec_' + Section

But for efficiency, see: https://waymoot.org/home/python_string/

How to sort an STL vector?

this is my approach to solve this generally. It extends the answer from Steve Jessop by removing the requirement to set template arguments explicitly and adding the option to also use functoins and pointers to methods (getters)

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>

using namespace std;

template <typename T, typename U>
struct CompareByGetter {
    U (T::*getter)() const;
    CompareByGetter(U (T::*getter)() const) : getter(getter) {};
    bool operator()(const T &lhs, const T &rhs) {
        (lhs.*getter)() < (rhs.*getter)();
    }
};

template <typename T, typename U>
CompareByGetter<T,U> by(U (T::*getter)() const) {
    return CompareByGetter<T,U>(getter);
}

//// sort_by
template <typename T, typename U>
struct CompareByMember {
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

template <typename T, typename U>
CompareByMember<T,U> by(U T::*f) {
    return CompareByMember<T,U>(f);
}

template <typename T, typename U>
struct CompareByFunction {
    function<U(T)> f;
    CompareByFunction(function<U(T)> f) : f(f) {}
    bool operator()(const T& a, const T& b) const {
        return f(a) < f(b);
    }
};

template <typename T, typename U>
CompareByFunction<T,U> by(function<U(T)> f) {
    CompareByFunction<T,U> cmp{f};
    return cmp;
}

struct mystruct {
    double x,y,z;
    string name;
    double length() const {
        return sqrt( x*x + y*y + z*z );
    }
};

ostream& operator<< (ostream& os, const mystruct& ms) {
    return os << "{ " << ms.x << ", " << ms.y << ", " << ms.z << ", " << ms.name << " len: " << ms.length() << "}";
}

template <class T>
ostream& operator<< (ostream& os, std::vector<T> v) {
    os << "[";
    for (auto it = begin(v); it != end(v); ++it) {
        if ( it != begin(v) ) {
            os << " ";
        }
        os << *it;
    }
    os << "]";
    return os;
}

void sorting() {
    vector<mystruct> vec1 = { {1,1,0,"a"}, {0,1,2,"b"}, {-1,-5,0,"c"}, {0,0,0,"d"} };

    function<string(const mystruct&)> f = [](const mystruct& v){return v.name;};

    cout << "unsorted  " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::x) );
    cout << "sort_by x " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::length));
    cout << "sort_by len " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(f) );
    cout << "sort_by name " << vec1 << endl;
}

console.log showing contents of array object

Json stands for JavaScript Object Notation really all json is are javascript objects so your array is in json form already. To write it out in a div you could do a bunch of things one of the easiest I think would be:

 objectDiv.innerHTML = filter;

where objectDiv is the div you want selected from the DOM using jquery. If you wanted to list parts of the array out you could access them since it is a javascript object like so:

 objectDiv.innerHTML = filter.dvals.valueToDisplay; //brand or count depending.

edit: anything you want to be a string but is not currently (which is rare javascript treats almost everything as a string) just use the toString() function built in. so line above if you needed it would be filter.dvals.valueToDisplay.toString();

second edit to clarify: this answer is in response to the OP's comments and not completely to his original question.

Get day of week using NSDate

Swift 3 : Xcode 8 helper function:

func getDayOfWeek(fromDate date: Date) -> String? {
    let cal = Calendar(identifier: .gregorian)
    let dayOfWeek = cal.component(.weekday, from: date)
    switch dayOfWeek {
     case 1:
        return "Sunday"
    case 2:
        return "Monday"
    case 3:
        return "Tuesday"
    case 4:
        return "Wednesday"
    case 5:
        return "Thursday"
    case 6:
        return "Friday"
    case 7:
        return "Saturday"
    default:
        return nil
    }
}

PHPExcel Make first row bold

You can try

$objPHPExcel->getActiveSheet()->getStyle(1)->getFont()->setBold(true);

How to get highcharts dates in the x axis?

You write like this-:

xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
           day: '%d %b %Y'    //ex- 01 Jan 2016
        }
}

also check for other datetime format

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

Where does MySQL store database files on Windows and what are the names of the files?

I just installed MySQL 5.7 on Windows7. The database files are located in the following directory which is a hidden one: C:\ProgramData\MySQL\MySQL Server 5.7\Data

The my.ini file is located in the same root: C:\ProgramData\MySQL\MySQL Server 5.7

check if variable empty

empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:

if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}

What characters are allowed in an email address?

See RFC 5322: Internet Message Format and, to a lesser extent, RFC 5321: Simple Mail Transfer Protocol.

RFC 822 also covers email addresses, but it deals mostly with its structure:

 addr-spec   =  local-part "@" domain        ; global address     
 local-part  =  word *("." word)             ; uninterpreted
                                             ; case-preserved

 domain      =  sub-domain *("." sub-domain)     
 sub-domain  =  domain-ref / domain-literal     
 domain-ref  =  atom                         ; symbolic reference

And as usual, Wikipedia has a decent article on email addresses:

The local-part of the email address may use any of these ASCII characters:

  • uppercase and lowercase Latin letters A to Z and a to z;
  • digits 0 to 9;
  • special characters !#$%&'*+-/=?^_`{|}~;
  • dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. [email protected] is not allowed but "John..Doe"@example.com is allowed);
  • space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
  • comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)[email protected] are both equivalent to [email protected].

In addition to ASCII characters, as of 2012 you can use international characters above U+007F, encoded as UTF-8 as described in the RFC 6532 spec and explained on Wikipedia. Note that as of 2019, these standards are still marked as Proposed, but are being rolled out slowly. The changes in this spec essentially added international characters as valid alphanumeric characters (atext) without affecting the rules on allowed & restricted special characters like !# and @:.

For validation, see Using a regular expression to validate an email address.

The domain part is defined as follows:

The Internet standards (Request for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters a through z (in a case-insensitive manner), the digits 0 through 9, and the hyphen (-). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or blank spaces are permitted.

NavigationBar bar, tint, and title text color in iOS 8

Swift up through Swift 3.2 (not Swift 4.0)

    self.navigationController?.navigationItem.largeTitleDisplayMode = .always
    self.navigationController?.navigationBar.prefersLargeTitles = true
    self.navigationController?.navigationBar.largeTitleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

    // unconfirmed but I assume this works:
    self.navigationController?.navigationBar.barTintColor = UIColor.white
    self.navigationController?.navigationBar.barStyle = UIBarStyle.black

git pull from master into the development branch

The steps you listed will work, but there's a longer way that gives you more options:

git checkout dmgr2      # gets you "on branch dmgr2"
git fetch origin        # gets you up to date with origin
git merge origin/master

The fetch command can be done at any point before the merge, i.e., you can swap the order of the fetch and the checkout, because fetch just goes over to the named remote (origin) and says to it: "gimme everything you have that I don't", i.e., all commits on all branches. They get copied to your repository, but named origin/branch for any branch named branch on the remote.

At this point you can use any viewer (git log, gitk, etc) to see "what they have" that you don't, and vice versa. Sometimes this is only useful for Warm Fuzzy Feelings ("ah, yes, that is in fact what I want") and sometimes it is useful for changing strategies entirely ("whoa, I don't want THAT stuff yet").

Finally, the merge command takes the given commit, which you can name as origin/master, and does whatever it takes to bring in that commit and its ancestors, to whatever branch you are on when you run the merge. You can insert --no-ff or --ff-only to prevent a fast-forward, or merge only if the result is a fast-forward, if you like.

When you use the sequence:

git checkout dmgr2
git pull origin master

the pull command instructs git to run git fetch, and then the moral equivalent of git merge origin/master. So this is almost the same as doing the two steps by hand, but there are some subtle differences that probably are not too concerning to you. (In particular the fetch step run by pull brings over only origin/master, and it does not update the ref in your repo:1 any new commits winds up referred-to only by the special FETCH_HEAD reference.)

If you use the more-explicit git fetch origin (then optionally look around) and then git merge origin/master sequence, you can also bring your own local master up to date with the remote, with only one fetch run across the network:

git fetch origin
git checkout master
git merge --ff-only origin/master
git checkout dmgr2
git merge --no-ff origin/master

for instance.


1This second part has been changed—I say "fixed"—in git 1.8.4, which now updates "remote branch" references opportunistically. (It was, as the release notes say, a deliberate design decision to skip the update, but it turns out that more people prefer that git update it. If you want the old remote-branch SHA-1, it defaults to being saved in, and thus recoverable from, the reflog. This also enables a new git 1.9/2.0 feature for finding upstream rebases.)

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

I use this way in work life: "Forget common loops" in this case and use this combination of "setInterval" includes "setTimeOut"s:

    function iAsk(lvl){
        var i=0;
        var intr =setInterval(function(){ // start the loop 
            i++; // increment it
            if(i>lvl){ // check if the end round reached.
                clearInterval(intr);
                return;
            }
            setTimeout(function(){
                $(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
            },50);
            setTimeout(function(){
                 // do another bla bla bla after 100 millisecond.
                seq[i-1]=(Math.ceil(Math.random()*4)).toString();
                $("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
                $("#d"+seq[i-1]).prop("src",pGif);
                var d =document.getElementById('aud');
                d.play();                   
            },100);
            setTimeout(function(){
                // keep adding bla bla bla till you done :)
                $("#d"+seq[i-1]).prop("src",pPng);
            },900);
        },1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
    }

PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.

PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..

how to Call super constructor in Lombok

As an option you can use com.fasterxml.jackson.databind.ObjectMapper to initialize a child class from parent

public class A {
    int x;
    int y;
}

public class B extends A {
    int z;
}

ObjectMapper MAPPER = new ObjectMapper(); //it's configurable
MAPPER.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
MAPPER.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );

//Then wherever you need to initialize child from parent:
A parent = new A(x, y);
B child = MAPPER.convertValue( parent, B.class);
child.setZ(z);

You can still use any lombok annotations on A and B if you need.

Where is localhost folder located in Mac or Mac OS X?

Macintosh HD/Library/WebServer/Documents

Macintosh HD is the name of your HD

If you can't find it: Open Finder > click "Go" at the very top > Computer > Your HD should be there. You can drag and drop the HD to favorites on the left.

How to create a checkbox with a clickable label?

<label for="vehicle">Type of Vehicle:</label>
<input type="checkbox" id="vehicle" name="vehicle" value="Bike" />

Override hosts variable of Ansible playbook from the command line

Just came across this googling for a solution. Actually, there is one in Ansible 2.5. You can specify your inventory file with --inventory, like this: ansible --inventory configs/hosts --list-hosts all

How to join components of a path when you are constructing a URL in Python

Rune Kaagaard provided a great and compact solution that worked for me, I expanded on it a little:

def urljoin(*args):
    trailing_slash = '/' if args[-1].endswith('/') else ''
    return "/".join(map(lambda x: str(x).strip('/'), args)) + trailing_slash

This allows all arguments to be joined regardless of trailing and ending slashes while preserving the last slash if present.

Microsoft Excel ActiveX Controls Disabled?

I'm an Excel developer, and I definitely felt the pain when this happened. Fortunately, I was able to find a workaround by renaming the MSForms.exd files in VBA even when Excel is running, which also can fix the issue. Excel developers who need to distribute their spreadsheets can add the following VBA code to their spreadsheets to make them immune to the MS update.

Place this code in any module.

Public Sub RenameMSFormsFiles() 
  Const tempFileName As String = "MSForms - Copy.exd"  
  Const msFormsFileName As String = "MSForms.exd"  
  On Error Resume Next 

  'Try to rename the C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\MSForms.exd file  
  RenameFile Environ("TEMP") & "\Excel8.0\" & msFormsFileName, Environ("TEMP") & "\Excel8.0\" & tempFileName 
  'Try to rename the C:\Users\[user.name]\AppData\Local\Temp\VBE\MSForms.exd file  
  RenameFile Environ("TEMP") & "\VBE\" & msFormsFileName, Environ("TEMP") & "\VBE\" & tempFileName 
End Sub  

Private Sub RenameFile(fromFilePath As String, toFilePath As String) 
  If CheckFileExist(fromFilePath) Then 
      DeleteFile toFilePath  
      Name fromFilePath As toFilePath  
  End If  
End Sub

Private Function CheckFileExist(path As String) As Boolean 
  CheckFileExist = (Dir(path) <> "")  
End Function  

Private Sub DeleteFile(path As String) 
  If CheckFileExist(path) Then 
      SetAttr path, vbNormal  
      Kill path  
  End If  
End Sub    

The RenameMSFormsFiles subroutine tries to rename the MSForms.exd files in the C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\ and C:\Users\[user.name]\AppData\Local\Temp\VBE\ folders to MSForms - Copy.exd.

Then call the RenameMSFormsFiles subroutine at the very beginning of the Workbook_Open event.

Private Sub Workbook_Open() 
  RenameMSFormsFiles  
End Sub

The spreadsheet will try to rename the MSForms.exd files when it opens. Obviously, this is not a perfect fix:

  1. The affected user will still experience the ActiveX control errors when running the VBA code the very first time opening the spreadsheet. Only after executing the VBA code once and restarting Excel, the issue is fixed. Normally when a user encounters a broken spreadsheet, the knee-jerk reaction is to close Excel and try to open the spreadsheet again. :)
  2. The MSForms.exd files are renamed every time the spreadsheet opens, even when there's no issue with the MSForms.exd files. But the spreadsheet will work just fine.

At least for now, Excel developers can continue to distribute their work with this workaround until Microsoft releases a fix.

I've posted this solution here.

How can I generate a tsconfig.json file?

this worked for me:

tsc --init

Can I obtain method parameter name using Java reflection?

see org.springframework.core.DefaultParameterNameDiscoverer class

DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
String[] params = discoverer.getParameterNames(MathUtils.class.getMethod("isPrime", Integer.class));

Spring Boot access static resources missing scr/main/resources

You can use following code to read file in String from resource folder.

final Resource resource = new ClassPathResource("public.key");
String publicKey = null;
try {
     publicKey = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
     e.printStackTrace();
}

Wrapping text inside input type="text" element HTML/CSS

To create a text input in which the value under the hood is a single line string but is presented to the user in a word-wrapped format you can use the contenteditable attribute on a <div> or other element:

_x000D_
_x000D_
const el = document.querySelector('div[contenteditable]');_x000D_
_x000D_
// Get value from element on input events_x000D_
el.addEventListener('input', () => console.log(el.textContent));_x000D_
_x000D_
// Set some value_x000D_
el.textContent = 'Lorem ipsum curae magna venenatis mattis, purus luctus cubilia quisque in et, leo enim aliquam consequat.'
_x000D_
div[contenteditable] {_x000D_
  border: 1px solid black;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div contenteditable></div>
_x000D_
_x000D_
_x000D_

How to safely call an async method in C# without await

I'm late to the party here, but there's an awesome library I've been using which I haven't seen referenced in the other answers

https://github.com/brminnick/AsyncAwaitBestPractices

If you need to "Fire And Forget" you call the extension method on the task.

Passing the action onException to the call ensures that you get the best of both worlds - no need to await execution and slow your users down, whilst retaining the ability to handle the exception in a graceful manner.

In your example you would use it like this:

   public string GetStringData()
    {
        MyAsyncMethod().SafeFireAndForget(onException: (exception) =>
                    {
                      //DO STUFF WITH THE EXCEPTION                    
                    }); 
        return "hello world";
    }

It also gives awaitable AsyncCommands implementing ICommand out the box which is great for my MVVM Xamarin solution

How to install gem from GitHub source?

Try the specific_install gem it allows you you to install a gem from its github repository (like 'edge'), or from an arbitrary URL. Very usefull for forking gems and hacking on them on multiple machines and such.

gem install specific_install
gem specific_install -l <url to a github gem>

e.g.

gem specific_install https://github.com/githubsvnclone/rdoc.git 

How do I make CMake output into a 'bin' dir?

Regardless of whether I define this in the main CMakeLists.txt or in the individual ones, it still assumes I want all the libs and bins off the main path, which is the least useful assumption of all.

Check if two unordered lists are equal

Assuming you already know lists are of equal size, the following will guarantee True if and only if two vectors are exactly the same (including order)

functools.reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, listA, ListB), True)

Example:

>>> from functools import reduce
>>> def compvecs(a,b):
...     return reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, a, b), True)
... 
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compvecs(a=[1,2,3,4], b=[1,2,3,4])
True
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compare_vectors(a=[1,2,3,4], b=[1,2,2,4])
False
>>> 

Get form data in ReactJS

Adding on to Michael Schock's answer:

class MyForm extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);

    console.log(data.get('email')); // reference by form input's `name` tag

    fetch('/api/form-submit-url', {
      method: 'POST',
      body: data,
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />

        <label htmlFor="email">Enter your email</label>
        <input id="email" name="email" type="email" />

        <label htmlFor="birthdate">Enter your birth date</label>
        <input id="birthdate" name="birthdate" type="text" />

        <button>Send data!</button>
      </form>
    );
  }
}

See this Medium article: How to Handle Forms with Just React

This method gets form data only when Submit button is pressed. Much cleaner IMO!

Copy mysql database from remote server to local computer

This can have different reasons like:

  • You are using an incorrect password
  • The MySQL server got an error when trying to resolve the IP address of the client host to a name
  • No privileges are granted to the user

You can try one of the following steps:

To reset the password for the remote user by:

SET PASSWORD FOR some_user@ip_addr_of_remote_client=PASSWORD('some_password');

To grant access to the user by:

GRANT SELECT, INSERT, UPDATE, DELETE, LOCK TABLES ON YourDB.* TO user@Host IDENTIFIED by 'password';

Hope this helps you, if not then you will have to go through the documentation

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

How do I put my website's logo to be the icon image in browser tabs?

<link rel="apple-touch-icon" sizes="114x114" href="${resource(dir: 'images', file: 
'apple-touch-icon-retina.png')}">

or you can use this one

<link rel="shortcut icon" sizes="114x114" href="${resource(dir: 'images', file: 'favicon.ico')}"
type="image/x-icon">

jQuery Form Validation before Ajax submit

You could use the submitHandler option. Basically put the $.ajax call inside this handler, i.e. invert it with the validation setup logic.

$('#form').validate({

    ... your validation rules come here,

    submitHandler: function(form) {
        $.ajax({
            url: form.action,
            type: form.method,
            data: $(form).serialize(),
            success: function(response) {
                $('#answers').html(response);
            }            
        });
    }
});

The jQuery.validate plugin will invoke the submit handler if the validation has passed.

matching query does not exist Error in Django

I also had this problem. It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion. (Meaning the id of a non-existent database record was still present in the session the next time the development server started)

To resolve this during development, I used

request.session.flush()

pandas read_csv and filter columns with usecols

import csv first and use csv.DictReader its easy to process...

How to make a movie out of images in python

You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here.

I'm attaching below a code snipped I used to combine all png files from a folder called "images" into a video.

import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()

How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain

Use this manual http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/ This guide really helped me. It is important to observe a sequence of certificates in the store. For example: import the lowermost Intermediate CA certificate first and then all the way up to the Root CA certificate.

MySQLDump one INSERT statement for each data row

In newer versions change was made to the flags: from the documentation:

--extended-insert, -e

Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.

--opt

This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.

Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.

--skip-extended-insert

Turn off extended-insert

Changing :hover to touch/click for mobile devices

On most devices, the other answers work. For me, to ensure it worked on every device (in react) I had to wrap it in an anchor tag <a> and add the following: :hover, :focus, :active (in that order), as well as role="button" and tabIndex="0".

error: cast from 'void*' to 'int' loses precision

Instead of:

int x = (int)arg;

use:

int x = (long)arg;

On most platforms pointers and longs are the same size, but ints and pointers often are not the same size on 64bit platforms. If you convert (void*) to (long) no precision is lost, then by assigning the (long) to an (int), it properly truncates the number to fit.

Storyboard - refer to ViewController in AppDelegate

For iOS 13+

in SceneDelegate:

var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options 
connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    let storyboard = UIStoryboard(name: "Main", bundle: nil) // Where "Main" is the storyboard file name
    let vc = storyboard.instantiateViewController(withIdentifier: "ViewController") // Where "ViewController" is the ID of your viewController
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
}

comparing two strings in ruby

Here are some:

"Ali".eql? "Ali"
=> true

The spaceship (<=>) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:

"Apples" <=> "Apples"
=> 0

"Apples" <=> "Pears"
=> -1

"Pears" <=> "Apples"
=> 1

A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:

"Apples".casecmp "apples"
=> 0

How do I center text vertically and horizontally in Flutter?

Overview: I used the Flex widget to center text on my page using the MainAxisAlignment.center along the horizontal axis. I use the container padding to create a margin space around my text.

  Flex(
            direction: Axis.horizontal,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
                Container(
                    padding: EdgeInsets.all(20),
                    child:
                        Text("No Records found", style: NoRecordFoundStyle))
  ])

How can I get the assembly file version

UPDATE: As mentioned by Richard Grimes in my cited post, @Iain and @Dmitry Lobanov, my answer is right in theory but wrong in practice.

As I should have remembered from countless books, etc., while one sets these properties using the [assembly: XXXAttribute], they get highjacked by the compiler and placed into the VERSIONINFO resource.

For the above reason, you need to use the approach in @Xiaofu's answer as the attributes are stripped after the signal has been extracted from them.


public static string GetProductVersion()
{
  var attribute = (AssemblyVersionAttribute)Assembly
    .GetExecutingAssembly()
    .GetCustomAttributes( typeof(AssemblyVersionAttribute), true )
    .Single();
   return attribute.InformationalVersion;
}

(From http://bytes.com/groups/net/420417-assemblyversionattribute - as noted there, if you're looking for a different attribute, substitute that into the above)

Unzip All Files In A Directory

This works in bash, according to this link:

unzip \*.zip

Android setOnClickListener method - How does it work?

This is the best way to implement Onclicklistener for many buttons in a row implement View.onclicklistener.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

This is a button in the MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bt_submit = (Button) findViewById(R.id.submit);

    bt_submit.setOnClickListener(this);
}

This is an override method

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.submit:
                //action

                break;

            case R.id.secondbutton:
                //action
                break;
        }
    }

How can I check the extension of a file?

import os
source = ['test_sound.flac','ts.mp3']

for files in source:
   fileName,fileExtension = os.path.splitext(files)
   print fileExtension   # Print File Extensions
   print fileName   # It print file name

Build fails with "Command failed with a nonzero exit code"

For me this was to do with a constraint that I was removing at build time. Unticking Remove at build time fixed the issue, and I suspect the compiler had an issue determining the layout without it.

The error code will mention which Storyboard is causing the issue.

How to add header data in XMLHttpRequest when using formdata?

Your error

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):

xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);

DataTables: Cannot read property style of undefined

The solution is pretty simple.

_x000D_
_x000D_
  <table id="TASK_LIST_GRID" class="table table-striped table-bordered table-hover dataTable no-footer" width="100%" role="grid" aria-describedby="TASK_LIST_GRID_info">_x000D_
  <thead>_x000D_
    <tr role="row">_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Solution</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Status</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Category</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Type</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Due Date</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Create Date</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Owner</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Comments</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Mnemonic</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Domain</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Approve</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Dismiss</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody></tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
                TASKLISTGRID = $("#TASK_LIST_GRID").DataTable({_x000D_
                    data : response,_x000D_
                    columns : columns.AdoptionTaskInfo.columns,_x000D_
                    paging: true_x000D_
                });_x000D_
                _x000D_
                //Note: columns : columns.AdoptionTaskInfo.columns has at least a column not definded in the <thead>
_x000D_
_x000D_
_x000D_

Note: columns : columns.AdoptionTaskInfo.columns has at least a column not defined in the table head

Mockito: Mock private field initialization

In case you use Spring Test try org.springframework.test.util.ReflectionTestUtils

 ReflectionTestUtils.setField(testObject, "person", mockedPerson);

How to delete the top 1000 rows from a table using Sql Server 2008?

It is fast. Try it:

DELETE FROM YourTABLE
FROM (SELECT TOP XX PK FROM YourTABLE) tbl
WHERE YourTABLE.PK = tbl.PK

Replace YourTABLE by table name, XX by a number, for example 1000, pk is the name of the primary key field of your table.

How to check if function exists in JavaScript?

For me the easiest way :

function func_exists(fname)
{
  return (typeof window[fname] === 'function');
}

How to convert Json array to list of objects in c#

As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.

To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:

  1. I added a Wrapper class corresponding to the outer object in your JSON.
  2. I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.
  3. I added some additional [JsonProperty] attributes to match the property names in your JSON objects.

Class definitions:

class Wrapper
{
    [JsonProperty("JsonValues")]
    public ValueSet ValueSet { get; set; }
}

class ValueSet
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("values")]
    public Dictionary<string, Value> Values { get; set; }
}

class Value
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("diaplayName")]
    public string DisplayName { get; set; }
}

You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.

var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

Here is a working program to demonstrate:

class Program
{
    static void Main(string[] args)
    {
        string jsonString = @"
        {
            ""JsonValues"": {
                ""id"": ""MyID"",
                ""values"": {
                    ""value1"": {
                        ""id"": ""100"",
                        ""diaplayName"": ""MyValue1""
                    },
                    ""value2"": {
                        ""id"": ""200"",
                        ""diaplayName"": ""MyValue2""
                    }
                }
            }
        }";

        var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

        Console.WriteLine("id: " + valueSet.Id);
        foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
        {
            Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
            Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
        }
    }
}

And here is the output:

id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2

python dict to numpy structured array

Even more simple if you accept using pandas :

import pandas
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
df = pandas.DataFrame(result, index=[0])
print df

gives :

          0         1         2         3  4         5         6
0  1.118175  0.556608  0.471827  0.487167  1  0.139508  0.209416

How do I read the source code of shell commands?

ls is part of coreutils. You can get it with git :

git clone git://git.sv.gnu.org/coreutils

You'll find coreutils listed with other packages (scroll to bottom) on this page.

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

import an array in python

Have a look at SciPy cookbook. It should give you an idea of some basic methods to import /export data.

If you save/load the files from your own Python programs, you may also want to consider the Pickle module, or cPickle.

How to get the focused element with jQuery?

// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

Which one should you use? quoting the jQuery docs:

As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':focus') is equivalent to $('*:focus'). If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

The answer is:

document.activeElement

And if you want a jQuery object wrapping the element:

$(document.activeElement)

C compiler for Windows?

I'm late to this party, but for any future C folks on Windows, Visual Studio targets C90 instead of C99, which is what you'd get on *nix. I am currently targeting C99 on Windows by using Sublime Text 2 in tandem with Cygwin.

Bootstrap footer at the bottom of the page

Use this stylesheet:

_x000D_
_x000D_
/* Sticky footer styles_x000D_
-------------------------------------------------- */_x000D_
html {_x000D_
  position: relative;_x000D_
  min-height: 100%;_x000D_
}_x000D_
body {_x000D_
  /* Margin bottom by footer height */_x000D_
  margin-bottom: 60px;_x000D_
}_x000D_
.footer {_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 100%;_x000D_
  /* Set the fixed height of the footer here */_x000D_
  height: 60px;_x000D_
  line-height: 60px; /* Vertically center the text there */_x000D_
  background-color: #f5f5f5;_x000D_
}_x000D_
_x000D_
_x000D_
/* Custom page CSS_x000D_
-------------------------------------------------- */_x000D_
/* Not required for template or sticky footer method. */_x000D_
_x000D_
body > .container {_x000D_
  padding: 60px 15px 0;_x000D_
}_x000D_
_x000D_
.footer > .container {_x000D_
  padding-right: 15px;_x000D_
  padding-left: 15px;_x000D_
}_x000D_
_x000D_
code {_x000D_
  font-size: 80%;_x000D_
}
_x000D_
_x000D_
_x000D_

Creating a triangle with for loops

This lets you have a little more control and an easier time making it:

public static int biggestoddnum = 31;

public static void main(String[] args) {
    for (int i=1; i<biggestoddnum; i += 2)
    {
        for (int k=0; k < ((biggestoddnum / 2) - i / 2); k++)
        {
            System.out.print(" ");
        }
        for (int j=0; j<i; j++)
        {
            System.out.print("*");
        }
        System.out.println("");
    }
}

Just change public static int biggestoddnum's value to whatever odd number you want it to be, and the for(int k...) has been tested to work.

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

HashMap - getting First Key value

You may also try the following in order to get the entire first entry,

Map.Entry<String, String> entry = map.entrySet().stream().findFirst().get();
String key = entry.getKey();
String value = entry.getValue();

The following shows how you may get the key of the first entry,

String key = map.entrySet().stream().map(Map.Entry::getKey).findFirst().get();
// or better
String key = map.keySet().stream().findFirst().get();

The following shows how you may get the value of the first entry,

String value = map.entrySet().stream().map(Map.Entry::getValue).findFirst().get();
// or better
String value = map.values().stream().findFirst().get();

Moreover, in case wish to get the second (same for third etc) item of a map and you have validated that this map contains at least 2 entries, you may use the following.

Map.Entry<String, String> entry = map.entrySet().stream().skip(1).findFirst().get();
String key = map.keySet().stream().skip(1).findFirst().get();
String value = map.values().stream().skip(1).findFirst().get();

Bootstrap 3 grid with no gap

Use "clearfix" instead of "row". It does the exact same except it doesn't have a negative margin. Step through the "row" usage and you'll see that's the only difference.

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017 and may leave the author guessing (which I am a victim of myself).

Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:

"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"


So, not supported are:

  • Start of String ancor \A, alternatively use the ^ caret to match postion before 1st char in string
  • End of String ancor \Z, alternatively use the $ dollar sign to match postion after last char in string
  • Positive LookBehind, e.g.: (?<=a)b (whilst postive LookAhead is supported)
  • Negative LookBehind, e.g.: (?<!a)b (whilst negative LookAhead is supported)
  • Atomic Grouping
  • Possessive Quantifiers
  • Unicode e.g.: \{uFFFF}
  • Named Capturing Groups. Alternatively use Numbered Capturing Groups
  • Inline modifiers, e.g.: /i (case sensitivity) or /g (global) etc. Set these through the RegExp object properties > RegExp.Global = True and RegExp.IgnoreCase = True if available.
  • Conditionals
  • Regular Expression Comments. Add these with regular ' comments in script

I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.

P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

In HTML5, should the main navigation be inside or outside the <header> element?

I do not like putting the nav in the header. My reasoning is:

Logic

The header contains introductory information about the document. The nav is a menu that links to other documents. To my mind this means that the content of the nav belongs to the site rather than the document. An exception would be if the NAV held forward links.

Accessibility

I like to put menus at the end of the source code rather than the start. I use CSS to send it to the top of a computer screen or leave it at the end for text-speech browsers and small screens. This avoids the need for skip-links.

How to start working with GTest and CMake

Just as an update to @Patricia's comment in the accepted answer and @Fraser's comment for the original question, if you have access to CMake 3.11+ you can make use of CMake's FetchContent function.

CMake's FetchContent page uses googletest as an example!

I've provided a small modification of the accepted answer:

cmake_minimum_required(VERSION 3.11)
project(basic_test)

set(GTEST_VERSION 1.6.0 CACHE STRING "Google test version")

################################
# GTest
################################
FetchContent_Declare(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-${GTEST_VERSION})

FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
  FetchContent_Populate(googletest)
  add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
endif()

enable_testing()

################################
# Unit Tests
################################
# Add test cpp file
add_executable(runUnitTests testgtest.cpp)

# Include directories
target_include_directories(runUnitTests 
                      $<TARGET_PROPERTY:gtest,INTERFACE_SYSTEM_INCLUDE_DIRECTORIES>
                      $<TARGET_PROPERTY:gtest_main,INTERFACE_SYSTEM_INCLUDE_DIRECTORIES>)

# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests gtest
                                   gtest_main)

add_test(runUnitTests runUnitTests)

You can use the INTERFACE_SYSTEM_INCLUDE_DIRECTORIES target property of the gtest and gtest_main targets as they are set in the google test CMakeLists.txt script.

Keras input explanation: input_shape, units, batch_size, dim, etc

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

In Keras LSTM, it refers to the total Time Steps

The term has been very confusing, is correct and we live in a very confusing world!!

I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

print arraylist element?

First make sure that Dog class implements the method public String toString() then use

System.out.println(list.get(index))

where index is the position inside the list. Of course since you provide your implementation you can decide how dog prints itself.

How to call a php script/function on a html button click

Modify the_script.php like this.

<script>
the_function() {
    alert("You win");
}
</script>

What is a Python egg?

Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code.

The easiest way to install and use Python eggs is to use the "Easy Install" Python package manager, which will find, download, build, and install eggs for you; all you do is tell it the name (and optionally, version) of the Python project(s) you want to use.

Python eggs can be used with Python 2.3 and up, and can be built using the setuptools package (see the Python Subversion sandbox for source code, or the EasyInstall page for current installation instructions).

The primary benefits of Python Eggs are:

  • They enable tools like the "Easy Install" Python package manager

  • .egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used)

  • They can include package metadata, such as the other eggs they depend on

  • They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope., twisted., peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.)

  • They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet.

  • They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept).

There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format.

How to convert const char* to char* in C?

To convert a const char* to char* you could create a function like this :

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

char* unconstchar(const char* s) {
    if(!s)
      return NULL;
    int i;
    char* res = NULL;
    res = (char*) malloc(strlen(s)+1);
    if(!res){
        fprintf(stderr, "Memory Allocation Failed! Exiting...\n");
        exit(EXIT_FAILURE);
    } else{
        for (i = 0; s[i] != '\0'; i++) {
            res[i] = s[i];
        }
        res[i] = '\0';
        return res;
    }
}

int main() {
    const char* s = "this is bikash";
    char* p = unconstchar(s);
    printf("%s",p);
    free(p);
}

How can I create a border around an Android LinearLayout?

Don't want to create a drawable resource?

  <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/black"
    android:minHeight="128dp">

    <FrameLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_margin="1dp"
      android:background="@android:color/white">

      <TextView ... />
    </FrameLayout>
  </FrameLayout>

Accessing Redux state in an action creator?

I agree with @Bloomca. Passing the value needed from the store into the dispatch function as an argument seems simpler than exporting the store. I made an example here:

import React from "react";
import {connect} from "react-redux";
import * as actions from '../actions';

class App extends React.Component {

  handleClick(){
    const data = this.props.someStateObject.data;
    this.props.someDispatchFunction(data);
  }

  render(){
    return (
      <div>       
      <div onClick={ this.handleClick.bind(this)}>Click Me!</div>      
      </div>
    );
  }
}


const mapStateToProps = (state) => {
  return { someStateObject: state.someStateObject };
};

const mapDispatchToProps = (dispatch) => {
  return {
    someDispatchFunction:(data) => { dispatch(actions.someDispatchFunction(data))},

  };
}


export default connect(mapStateToProps, mapDispatchToProps)(App);

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID

Query based on multiple where clauses in Firebase

Frank's answer is good but Firestore introduced array-contains recently that makes it easier to do AND queries.

You can create a filters field to add you filters. You can add as many values as you need. For example to filter by comedy and Jack Nicholson you can add the value comedy_Jack Nicholson but if you also you want to by comedy and 2014 you can add the value comedy_2014 without creating more fields.

{
  "movies": {
    "movie1": {
      "genre": "comedy",
      "name": "As good as it gets",
      "lead": "Jack Nicholson",
      "year": 2014,
      "filters": [
        "comedy_Jack Nicholson",
        "comedy_2014"
      ]
    }
  }
}

How can I run a function from a script in command line?

Well, while the other answers are right - you can certainly do something else: if you have access to the bash script, you can modify it, and simply place at the end the special parameter "$@" - which will expand to the arguments of the command line you specify, and since it's "alone" the shell will try to call them verbatim; and here you could specify the function name as the first argument. Example:

$ cat test.sh
testA() {
  echo "TEST A $1";
}

testB() {
  echo "TEST B $2";
}

"$@"


$ bash test.sh
$ bash test.sh testA
TEST A 
$ bash test.sh testA arg1 arg2
TEST A arg1
$ bash test.sh testB arg1 arg2
TEST B arg2

For polish, you can first verify that the command exists and is a function:

# Check if the function exists (bash specific)
if declare -f "$1" > /dev/null
then
  # call arguments verbatim
  "$@"
else
  # Show a helpful error
  echo "'$1' is not a known function name" >&2
  exit 1
fi

Get event listeners attached to node using addEventListener

You can obtain all jQuery events using $._data($('[selector]')[0],'events'); change [selector] to what you need.

There is a plugin that gather all events attached by jQuery called eventsReport.

Also i write my own plugin that do this with better formatting.

But anyway it seems we can't gather events added by addEventListener method. May be we can wrap addEventListener call to store events added after our wrap call.

It seems the best way to see events added to an element with dev tools.

But you will not see delegated events there. So there we need jQuery eventsReport.

UPDATE: NOW We CAN see events added by addEventListener method SEE RIGHT ANSWER TO THIS QUESTION.

What is PHPSESSID?

Check php.ini for auto session id.

If you enable it, you will have PHPSESSID in your cookies.

How to get the parent dir location

Here is another relatively simple solution that:

  • does not use dirname() (which does not work as expected on one level arguments like "file.txt" or relative parents like "..")
  • does not use abspath() (avoiding any assumptions about the current working directory) but instead preserves the relative character of paths

it just uses normpath and join:

def parent(p):
    return os.path.normpath(os.path.join(p, os.path.pardir))

# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
        'dir/file.txt', '../up/', '/abs/path']:
    print parent(p)

Result:

.
foo/bar
with/trailing
dir
..
/abs

NuGet behind a proxy

To anyone using VS2015: I was encountering a "407 Proxy Authentication required" error, which broke my build. After a few hours investigating, it turns out MSBuild wasn't sending credentials when trying to download Nuget as part of the 'DownloadNuGet' target. The solution was to add the following XML to C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe.config inside the <configuration> element:

<system.net>
            <defaultProxy useDefaultCredentials="true">
            </defaultProxy>
</system.net>

Copying files into the application folder at compile time

You can use the PostBuild event of the project. After the build is completed, you can run a DOS batch file and copy the desired files to your desired folder.

Having both a Created and Last Updated timestamp columns in MySQL 4.0

create table test_table( 
id integer not null auto_increment primary key, 
stamp_created timestamp default '0000-00-00 00:00:00', 
stamp_updated timestamp default now() on update now() 
); 

source: http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/

Stop UIWebView from "bouncing" vertically?

One of the subviews of UIWebView should be a UIScrollView. Set its scrollEnabled property to NO and the web view will have scrolling disabled entirely.

Note: this is technically using a private API and thus your app could be rejected or crash in future OS releases. Use @try and respondsToSelector

How do I reference a cell within excel named range?

To read a particular date from range EJ_PAYDATES_2021 (index is next to the last "1")

=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,1,1)  // Jan
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,2,1)  // Feb
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,3,1)  // Mar

This allows reading a particular element of a range [0] etc from another spreadsheet file. Target file need not be open. Range in the above example is named EJ_PAYDATES_2021, with one element for each month contained within that range.

Took me a while to parse this out, but it works, and is the answer to the question asked above.

MySQL - How to parse a string value to DATETIME format inside an INSERT statement?

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
  (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Find number of decimal places in decimal value regardless of culture

string number = "123.456789"; // Convert to string
int length = number.Substring(number.IndexOf(".") + 1).Length;  // 6

How to change an element's title attribute using jQuery

As an addition to @C??? answer, make sure the title of the tooltip has not already been set manually in the HTML element. In my case, the span class for the tooltip already had a fixed tittle text, because of this my JQuery function $('[data-toggle="tooltip"]').prop('title', 'your new title'); did not work.

When I removed the title attribute in the HTML span class, the jQuery was working.

So:

<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
      <span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top" title="this is my pre-set title text"></span>
</span>

Should becode:

<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
      <span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top"></span>
</span>

"Exception has been thrown by the target of an invocation" error (mscorlib)

Encounter the same error when tried to connect to SQLServer2017 through Management Studio 2014

enter image description here

The reason was backward compatibility

So I just downloaded the Management Studio 2017 and tried to connect to SQLServer2017.

Problem Solve!!

WPF - add static items to a combo box

Here is the code from MSDN and the link - Article Link, which you should check out for more detail.

<ComboBox Text="Is not open">
    <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
    <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
    <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

How to add new column to MYSQL table?

Something like:

$db = mysqli_connect("localhost", "user", "password", "database");
$name = $db->mysqli_real_escape_string($name);
$query = 'ALTER TABLE assesment ADD ' . $name . ' TINYINT NOT NULL DEFAULT \'0\'';
if($db->query($query)) {
    echo "It worked";
}

Haven't tested it but should work.

How to reset all checkboxes using jQuery or pure JS?

I have used this before:

$('input[type=checkbox]').prop('checked', false);

seems that .attr and .removeAttr doesn't work for some situations.

edit: Note that in jQuery v1.6 and higher, you should be using .prop('checked', false) instead for greater cross-browser compatibility - see https://api.jquery.com/prop

Comment here: How to reset all checkboxes using jQuery or pure JS?

Is it a bad practice to use an if-statement without curly braces?

Having the braces right from the first moment should help to prevent you from ever having to debug this:

if (statement)
     do this;
else
     do this;
     do that;

where is gacutil.exe?

On Windows 2012 R2, you can't install Visual Studio or SDK. You can use powershell to register assemblies into GAC. It didn't need any special installation for me.

Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")

If you need to get the name and PublicKeyToken see this question.

When to use AtomicReference in Java?

You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.

  1. You can create a copy of the shared object
  2. Modify the shared object
  3. You need to check that the shared object is still the same as before - if yes, then update with the reference of the modified copy.

As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help

How to make an installer for my C# application?

There are several methods, two of which are as follows. Provide a custom installer or a setup project.

Here is how to create a custom installer

[RunInstaller(true)]
public class MyInstaller : Installer
{
    public HelloInstaller()
        : base()
    {
    }

    public override void Commit(IDictionary mySavedState)
    {
        base.Commit(mySavedState);
        System.IO.File.CreateText("Commit.txt");
    }

    public override void Install(IDictionary stateSaver)
    {
        base.Install(stateSaver);
        System.IO.File.CreateText("Install.txt");
    }

    public override void Uninstall(IDictionary savedState)
    {
        base.Uninstall(savedState);
        File.Delete("Commit.txt");
        File.Delete("Install.txt");
    }

    public override void Rollback(IDictionary savedState)
    {
        base.Rollback(savedState);
        File.Delete("Install.txt");
    }
}

To add a setup project

  • Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment

  • Set properties of the project, using the properties window

The article How to create a Setup package by using Visual Studio .NET provides the details.

Detect when input has a 'readonly' attribute

fastest way is to use the .is() jQuery function.

if ( $('input').is('[readonly]') ) { }

using [readonly] as a selector simply checks if the attribute is defined on your element. if you want to check for a value, you can use something like this instead:

if ( $('input').is('[readonly="somevalue"]') ) { }

IntelliJ IDEA "The selected directory is not a valid home for JDK"

for me ,with JDK11 and IntelliJ 2016.3 , I kept getting the same message so I decided to uninstall JDK11 and installed JDK8 instead and it immediately worked!

SVN Error - Not a working copy

I also meet this problem in svn diff operation, it was caused by incorrect file path, you should add './' to indicate the current file directory.

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

How to add months to a date in JavaScript?

I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc):

Date.isLeapYear = function (year) { 
    return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 
};

Date.getDaysInMonth = function (year, month) {
    return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};

Date.prototype.isLeapYear = function () { 
    return Date.isLeapYear(this.getFullYear()); 
};

Date.prototype.getDaysInMonth = function () { 
    return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};

Date.prototype.addMonths = function (value) {
    var n = this.getDate();
    this.setDate(1);
    this.setMonth(this.getMonth() + value);
    this.setDate(Math.min(n, this.getDaysInMonth()));
    return this;
};

This will add "addMonths()" function to any javascript date object that should handle edge cases. Thanks to Coolite Inc!

Use:

var myDate = new Date("01/31/2012");
var result1 = myDate.addMonths(1);

var myDate2 = new Date("01/31/2011");
var result2 = myDate2.addMonths(1);

->> newDate.addMonths -> mydate.addMonths

result1 = "Feb 29 2012"

result2 = "Feb 28 2011"

How to randomize two ArrayLists in the same fashion?

Not totally sure what you mean by "automatically" - you can create a container object that holds both objects:

public class FileImageHolder { String fileName; String imageName; //TODO: insert stuff here }

And then put that in an array list and randomize that array list.

Otherwise, you would need to keep track of where each element moved in one list, and move it in the other one as well.

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

How to click an element in Selenium WebDriver using JavaScript

You can't use WebDriver to do it in JavaScript, as WebDriver is a Java tool. However, you can execute JavaScript from Java using WebDriver, and you could call some JavaScript code that clicks a particular button.

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('gbqfb').click()");

How to install Guest addition in Mac OS as guest and Windows machine as host

I've the same problem, and by the "trial and error" method I have the steps to install the guest additions on a MacOS guest:

  1. insert the guest additions cd
  2. open the cd on file manager
  3. double click on VBoxDarwinAdditions.pkg
  4. the installer opens, then click contine
  5. next screen to set location of installed files, only press install
  6. your password can be asked a couple of time while installing, write it and continue
  7. this is the tricky part, on my installation, macos show an message about the driver created by oracle won't be installed because a security issue, it has the option to enable it, so click on the button to open security screen and click on the allow button next to the oracle software listed at bottom of the security settings window, it will ask your password again. Meanwhile the pkg installer continued as if it has permissions and will say "install finished", but I don't believe it so, once I unlocked the oracle drivers installations I repeat the whole process from step 3, and in the second round all installs without asking more than the first password to install.

And it is done!

What is the main difference between Inheritance and Polymorphism?

Inheritance is when class A inherits all nonstatic protected/public methods/fields from all its parents till Object.

SQL SERVER DATETIME FORMAT

case when isdate(inputdate) = 1 
then convert(datetime, cast(inputdate,datetime2), 103)
else
case when isdate(inputdate) = 0 
then convert(datetime, cast(inputdate,datetime2), 103)

creating batch script to unzip a file without additional zip tools

Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

To unzip file you can use this script :

zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no

jQuery getTime function

Annoyingly Javascript's date.getSeconds() et al will not pad the result with zeros 11:0:0 instead of 11:00:00.

So I like to use

date.toLocaleTimestring()

Which renders 11:00:00 AM. Just beware when using the extra options, some browsers don't support them (Safari)

Documentation

Convert NSDate to String in iOS Swift

Your updated code.update it.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)

How to generate a HTML page dynamically using PHP?

As per your requirement you dont have to generate a html page dynamicaly. It can be done by .htaccess file .

Still this is sample code to generate HTML Page

<?php

 $filename = 'test.html';
 header("Cache-Control: public");
 header("Content-Description: File Transfer");
 header("Content-Disposition: attachment; filename=$filename");
 header("Content-Type: application/octet-stream; ");
 header("Content-Transfer-Encoding: binary");
?>

you can create any .html , .php file just change extention in file name

How to generate entire DDL of an Oracle schema (scriptable)?

First export the schema metadata:

expdp dumpfile=filename logfile=logname directory=dir_name schemas=schema_name

and then import by using the sqlfile option (it will not import data it will just write the schema DDL to that file)

impdp dumpfile=filename logfile=logname directory=dir_name sqlfile=ddl.sql

Should a function have only one return statement?

I'm probably going to be hated for this, but ideally there should be no return statement at all I think, a function should just return its last expression, and should in the completely ideal case contain only one.

So not

function name(arg) {
    if (arg.failure?)
        return;

    //code for non failure
}

But rather

function name(arg) {
    if (arg.failure?)
        voidConstant
    else {
        //code for non failure


}

If-statements that aren't expressions and return statements are a very dubious practise to me.

How can I connect to Android with ADB over TCP?

These are the steps I followed and it worked for me,

  1. adb shell ifconfig (get the ip address of the device from here)

  2. adb tcpip 7777 (connect adb to some port)

  3. adb connect "ipaddress":7777

Is there any way to delete local commits in Mercurial?

[Hg Tortoise 4.6.1] If it's recent action, you can use "Rollback/Undo" action (Ctrl+U).

HG Tortoise Image

Converting XDocument to XmlDocument and vice versa

For me this single line solution works very well

XDocument y = XDocument.Parse(pXmldoc.OuterXml); // where pXmldoc is of type XMLDocument

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

Use PHP to convert PNG to JPG with compression?

<?php
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth) {
    $explode = explode(".", $imageName);
    $filetype = $explode[1];

    if ($filetype == 'jpg') {
        $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
    } else
    if ($filetype == 'jpeg') {
        $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
    } else
    if ($filetype == 'png') {
        $srcImg = imagecreatefrompng("$imageDirectory/$imageName");
    } else
    if ($filetype == 'gif') {
        $srcImg = imagecreatefromgif("$imageDirectory/$imageName");
    }

    $origWidth = imagesx($srcImg);
    $origHeight = imagesy($srcImg);

    $ratio = $origWidth / $thumbWidth;
    $thumbHeight = $origHeight / $ratio;

    $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
    imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $origWidth, $origHeight);

    if ($filetype == 'jpg') {
        imagejpeg($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'jpeg') {
        imagejpeg($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'png') {
        imagepng($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'gif') {
        imagegif($thumbImg, "$thumbDirectory/$imageName");
    }
}
    ?>

This is a very good thumbnail script =) Here's an example:

$path = The path to the folder where the original picture is. $name = The filename of the file you want to make a thumbnail of. $thumbpath = The path to the directory where you want the thumbnail to be saved into. $maxwidth = the maximum width of the thumbnail in PX eg. 100 (wich will be 100px).

createThumbnail($path, $name, $thumbpath, $maxwidth);

When to use 'npm start' and when to use 'ng serve'?

For a project that's using the CLI, you will usually use ng serve. In other cases you may want to use npm start. Here the detailed explanation:

ng serve

Will serve a project that is 'Angular CLI aware', i.e. a project that has been created using the Angular CLI, particularly using:

ng new app-name

So, if you've scaffolded a project using the CLI, you'll probably want to use ng serve

npm start

This can be used in the case of a project that is not Angular CLI aware (or it can simply be used to run 'ng serve' for a project that's Angular CLI aware)

As the other answers state, this is an npm command that will run the npm command(s) from the package.json that have the identifier 'start', and it doesn't just have to run 'ng serve'. It's possible to have something like the following in the package.json:

   "scripts": {
     "build:watch": "tsc -p src/ -w",
     "serve": "lite-server -c=bs-config.json",
     "start": "concurrently \"npm run build:watch\" \"npm run serve\""
     ...
   },
   "devDependencies": {
     "concurrently": "^3.2.0",
     "lite-server": "^2.2.2",

In this case, 'npm start' will result in the following commands to be run:

concurrently "npm run build:watch" "npm run serve"

This will concurrently run the TypeScript compiler (watching for code changes), and run the Node lite-server (which users BrowserSync)

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

With Visual Studio 2019, running a .net core 3.1 project, you will need to install the latest test framework to resolve the error.

Easiest way to accomplish this is by hovering the browser over a [Test] annotation (underlined in red) and select suggested fixes. The one needed is to "search for and install the latest test framework."

Change arrow colors in Bootstraps carousel

If you are using bootstrap.min.css for carousel-

<a class="left carousel-control" href="#carouselExample" data-slide="prev">
  <span class="glyphicon glyphicon-chevron-left"></span>
  <span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carouselExample" data-slide="next">
  <span class="glyphicon glyphicon-chevron-right"></span>
  <span class="sr-only">Next</span>
</a>

Open the bootstrap.min.css file and find the property "glyphicon-chevron-right" and add the property "color:red"

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

Not class selector in jQuery

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

Java Calendar, getting current month value, clarification needed

import java.util.*;

class GetCurrentmonth
{
    public static void main(String args[])
    {
        int month;
        GregorianCalendar date = new GregorianCalendar();      
        month = date.get(Calendar.MONTH);
        month = month+1;
        System.out.println("Current month is  " + month);
    }
}

Which comment style should I use in batch files?

Comments with REM

A REM can remark a complete line, also a multiline caret at the line end, if it's not the end of the first token.

REM This is a comment, the caret is ignored^
echo This line is printed

REM This_is_a_comment_the_caret_appends_the_next_line^
echo This line is part of the remark

REM followed by some characters .:\/= works a bit different, it doesn't comment an ampersand, so you can use it as inline comment.

echo First & REM. This is a comment & echo second

But to avoid problems with existing files like REM, REM.bat or REM;.bat only a modified variant should be used.

REM^;<space>Comment

And for the character ; is also allowed one of ;,:\/=

REM is about 6 times slower than :: (tested on Win7SP1 with 100000 comment lines).
For a normal usage it's not important (58µs versus 360µs per comment line)

Comments with ::

A :: always executes a line end caret.

:: This is also a comment^
echo This line is also a comment

Labels and also the comment label :: have a special logic in parenthesis blocks.
They span always two lines SO: goto command not working.
So they are not recommended for parenthesis blocks, as they are often the cause for syntax errors.

With ECHO ON a REM line is shown, but not a line commented with ::

Both can't really comment out the rest of the line, so a simple %~ will cause a syntax error.

REM This comment will result in an error %~ ...

But REM is able to stop the batch parser at an early phase, even before the special character phase is done.

@echo ON
REM This caret ^ is visible

You can use &REM or &:: to add a comment to the end of command line. This approach works because '&' introduces a new command on the same line.

Comments with percent signs %= comment =%

There exists a comment style with percent signs.

In reality these are variables but they are expanded to nothing.
But the advantage is that they can be placed in the same line, even without &.
The equal sign ensures, that such a variable can't exists.

echo Mytest
set "var=3"     %= This is a comment in the same line=%

The percent style is recommended for batch macros, as it doesn't change the runtime behaviour, as the comment will be removed when the macro is defined.

set $test=(%\n%
%=Start of code=% ^
echo myMacro%\n%
)

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

I had same problem in my Windows10,
Isolved my problem by following the steps below.
open Android Studio
- Tools
- SDK Manager
- copy Android SDK Location
Android SDK Location
set system environment variable
ANDROID_HOME and ANDROID_SDK_ROOT
system environment variable

Why is @font-face throwing a 404 error on woff files?

Run IIS Server Manager (run command : inetmgr) Open Mime Types and add following

File name extension: .woff

MIME type: application/octet-stream

Convert string to buffer Node

You can use Buffer.from() to convert a string to buffer. More information on this can be found here

var buf = Buffer.from('some string', 'encoding');

for example

var buf = Buffer.from(bStr, 'utf-8');

How to redirect all HTTP requests to HTTPS

The Apache docs recommend against using a rewrite:

To redirect http URLs to https, do the following:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost>

This snippet should go into main server configuration file, not into .htaccess as asked in the question.

This article might have come up only after the question was asked and answered, but seems to be the current way to go.

How to store printStackTrace into a string

You can use the ExceptionUtils.getStackTrace(Throwable t); from Apache Commons 3 class org.apache.commons.lang3.exception.ExceptionUtils.

http://commons.apache.org/proper/commons-lang/

ExceptionUtils.getStackTrace(Throwable t)

Code example:

try {

  // your code here

} catch(Exception e) {
  String s = ExceptionUtils.getStackTrace(e);
}

Compute row average in pandas

You can specify a new column. You also need to compute the mean along the rows, so use axis=1.

df['mean'] = df.mean(axis=1)
>>> df
       Y1961      Y1962      Y1963      Y1964      Y1965 Region       mean
0  82.567307  83.104757  83.183700  83.030338  82.831958     US  82.943612
1   2.699372   2.610110   2.587919   2.696451   2.846247     US   2.688020
2  14.131355  13.690028  13.599516  13.649176  13.649046     US  13.743824
3   0.048589   0.046982   0.046583   0.046225   0.051750     US   0.048026
4   0.553377   0.548123   0.582282   0.577811   0.620999     US   0.576518

How can I check out a GitHub pull request with git?

Suppose your origin and upstream info is like below

   $ git remote -v
   origin  [email protected]:<yourname>/<repo_name>.git (fetch)
   origin  [email protected]:<yourname>/<repo_name>.git (push)
   upstream   [email protected]:<repo_owner>/<repo_name>.git (fetch)
   upstream   [email protected]:<repo_owner>/<repo_name>.git (push)

and your branch name is like

   <repo_owner>:<BranchName>

then

   git pull origin <BranchName>

shall do the job

Accessing the last entry in a Map

In such scenario last used key is usually known so it can be used for accessing last value (inserted with the one):

class PostIndexData {
    String _office_name;
    Boolean _isGov;
    public PostIndexData(String name, Boolean gov) {
        _office_name = name;
        _isGov = gov;
    }
}
//-----------------------
class KgpData {
    String _postIndex;
    PostIndexData _postIndexData;
    public KgpData(String postIndex, PostIndexData postIndexData) {
        _postIndex = postIndex;
        _postIndexData = postIndexData;;
    }
}

public class Office2ASMPro {
    private HashMap<String,PostIndexData> _postIndexMap = new HashMap<>();
    private HashMap<String,KgpData> _kgpMap = new HashMap<>();
...
private void addOffice(String kgp, String postIndex, String officeName, Boolean gov) {
            if (_postIndexMap.get(postIndex) == null) {
                _postIndexMap.put(postIndex, new PostIndexData(officeName, gov));
            }
            _kgpMap.put( kgp, new KgpData(postIndex, _postIndexMap.get(postIndex)) );
        }

Set up Python 3 build system with Sublime Text 3

first you need to find your python.exe location, to find location run this python script:

import sys
print(sys.executable)

Then you can create your custom python build:

{
"cmd": ["C:\\Users\\Sashi\\AppData\\Local\\Programs\\Python\\Python39\\python.exe", "-u", "$file"],
"file_regex": "^[ ]File \"(...?)\", line ([0-9]*)",
"selector": "source.python"}

You can change the location, In my case it is C:\Users\Sashi\AppData\Local\Programs\Python\Python39\python.exe

Then save your new build. Don't change the file extension while saving.

What does iterator->second mean?

I'm sure you know that a std::vector<X> stores a whole bunch of X objects, right? But if you have a std::map<X, Y>, what it actually stores is a whole bunch of std::pair<const X, Y>s. That's exactly what a map is - it pairs together the keys and the associated values.

When you iterate over a std::map, you're iterating over all of these std::pairs. When you dereference one of these iterators, you get a std::pair containing the key and its associated value.

std::map<std::string, int> m = /* fill it */;
auto it = m.begin();

Here, if you now do *it, you will get the the std::pair for the first element in the map.

Now the type std::pair gives you access to its elements through two members: first and second. So if you have a std::pair<X, Y> called p, p.first is an X object and p.second is a Y object.

So now you know that dereferencing a std::map iterator gives you a std::pair, you can then access its elements with first and second. For example, (*it).first will give you the key and (*it).second will give you the value. These are equivalent to it->first and it->second.

How do I work with dynamic multi-dimensional arrays in C?

malloc will do.

 int rows = 20;
 int cols = 20;
 int *array;

  array = malloc(rows * cols * sizeof(int));

Refer the below article for help:-

http://courses.cs.vt.edu/~cs2704/spring00/mcquain/Notes/4up/Managing2DArrays.pdf

Extract specific columns from delimited file using Awk

Tabulator is a set of unix command line tools to work with csv files that have header lines. Here is an example to extract columns by name from a file test.csv:

name,sex,house_nr,height,shoe_size
arthur,m,42,181,11.5
berta,f,101,163,8.5
chris,m,1333,175,10
don,m,77,185,12.5
elisa,f,204,166,7

Then tblmap -k name,height test.csv produces

name,height
arthur,181
berta,163
chris,175
don,185
elisa,166

release Selenium chromedriver.exe from memory

I am using Protractor with directConnect. Disabling the "--no-sandbox" option fixed the issue for me.

// Capabilities to be passed to the webdriver instance.
capabilities: {
  'directConnect': true,
  'browserName': 'chrome',
  chromeOptions: {
      args: [
        //"--headless",
        //"--hide-scrollbars",
        "--disable-software-rasterizer",
        '--disable-dev-shm-usage',
        //"--no-sandbox",
        "incognito",
        "--disable-gpu",
        "--window-size=1920x1080"]
  }
},

Hashing a string with Sha256

The shortest and fastest way ever. Only 1 line!

public static string StringSha256Hash(string text) =>
    string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

Ubuntu, how do you remove all Python 3 but not 2

Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!

If that happens to you, here is the fix:

https://askubuntu.com/q/384033/402539

https://askubuntu.com/q/810854/402539

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I also faced this issue with Visual Studio(VS) 2010. More interestingly, I had several projects in my solution (Console application, WPF application, Windows Forms application) but it was failing only when, I was setting the "Console Application" type of project as start up project of the solution(Even for those which had literally no code or any additional assemblies referred apart from the default ones which come with project template itself).

Following change finally helped me nail down the issue: Go to project properties of the console application project (Alternatively, select project file in solution explorer and press Alt + Enter key combination) -> Go to Debug tab -> Scroll to Enable Debuggers section in right pane -> Check the Enable unmanaged code debugging check box as shown in the snapshot below -> Click Floppy button in the toolbar to save project properties. Root cause of why it happened is still not known to me. Only thing I observed was that there were lot of windows updates which had got installed on my machine the previous night which mostly constituted of office updates and OS updates (More than a dozen KB articles).

enter image description here

Update: VS 2017 onward the setting name has changed as shown in the screenshot below:

enter image description here

Environment variable substitution in sed

Dealing with VARIABLES within sed

[root@gislab00207 ldom]# echo domainname: None > /tmp/1.txt

[root@gislab00207 ldom]# cat /tmp/1.txt

domainname: None

[root@gislab00207 ldom]# echo ${DOMAIN_NAME}

dcsw-79-98vm.us.oracle.com

[root@gislab00207 ldom]# cat /tmp/1.txt | sed -e 's/domainname: None/domainname: ${DOMAIN_NAME}/g'

 --- Below is the result -- very funny.

domainname: ${DOMAIN_NAME}

 --- You need to single quote your variable like this ... 

[root@gislab00207 ldom]# cat /tmp/1.txt | sed -e 's/domainname: None/domainname: '${DOMAIN_NAME}'/g'


--- The right result is below 

domainname: dcsw-79-98vm.us.oracle.com

NVIDIA NVML Driver/library version mismatch

If you've recently updated, a reboot might solve this problem.

Display text from .txt file in batch file

type log.txt

But that will give you the whole file. You could change it to:

echo %date%, %time% >> log.txt
echo %date%, %time% > log_last.txt
...
type log_last.txt

to get only the last one.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I ran into this a couple times a quarter. This time I had a minimal change summary in my git diff and tracked the problem to a reset classpath (missing my WEB-INF/lib dependency) in eclipse. This seems to occur any time I pull in or pull out parent/sibling maven projects.

There are mentions of adding your spring jars to the tomcat web container lib - this is ok and is the way most EE servers run. However be aware that by placing spring higher in the classloader tree on tomcat you will be running higher than the classloader level of your war context. I recommend you leave the libs in a per/war lower level classloader.

We see the following after a truncated .classpath after a structural project change in eclipse.

Dec 18, 2016 11:13:39 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener
java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener

My classpath was reset and the WEB-INF/lib dependency was removed.

<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
    <attributes>
        <attribute name="maven.pomderived" value="true"/>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>

put back

<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>

and you will be OK.

thank you /michael

Counting the number of files in a directory using Java

Since you don't really need the total number, and in fact want to perform an action after a certain number (in your case 5000), you can use java.nio.file.Files.newDirectoryStream. The benefit is that you can exit early instead having to go through the entire directory just to get a count.

public boolean isOverMax(){
    Path dir = Paths.get("C:/foo/bar");
    int i = 1;

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path p : stream) {
            //larger than max files, exit
            if (++i > MAX_FILES) {
                return true;
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return false;
}

The interface doc for DirectoryStream also has some good examples.

What's the difference between eval, exec, and compile?

The short answer, or TL;DR

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.

eval and exec have these two differences:

  1. eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on.

    An expression in Python is whatever you can have as the value in a variable assignment:

    a_variable = (anything you can put within these parentheses is an expression)
    
  2. eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).

In versions 1.0 - 2.7, exec was a statement, because CPython needed to produce a different kind of code object for functions that used exec for its side effects inside the function.

In Python 3, exec is a function; its use has no effect on the compiled bytecode of the function where it is used.


Thus basically:

>>> a = 5
>>> eval('37 + a')   # it is an expression
42
>>> exec('37 + a')   # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47')   # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47')  # you cannot evaluate a statement
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a = 47
      ^
SyntaxError: invalid syntax

The compile in 'exec' mode compiles any number of statements into a bytecode that implicitly always returns None, whereas in 'eval' mode it compiles a single expression into bytecode that returns the value of that expression.

>>> eval(compile('42', '<string>', 'exec'))  # code returns None
>>> eval(compile('42', '<string>', 'eval'))  # code returns 42
42
>>> exec(compile('42', '<string>', 'eval'))  # code returns 42,
>>>                                          # but ignored by exec

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval') This is where the difference really comes from.

If a code object (which contains Python bytecode) is passed to exec or eval, they behave identically, excepting for the fact that exec ignores the return value, still returning None always. So it is possible use eval to execute something that has statements, if you just compiled it into bytecode before instead of passing it as a string:

>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>

works without problems, even though the compiled code contains statements. It still returns None, because that is the return value of the code object returned from compile.

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

The longer answer, a.k.a the gory details

exec and eval

The exec function (which was a statement in Python 2) is used for executing a dynamically created statement or program:

>>> program = '''
for i in range(3):
    print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>> 

The eval function does the same for a single expression, and returns the value of the expression:

>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84

exec and eval both accept the program/expression to be run either as a str, unicode or bytes object containing source code, or as a code object which contains Python bytecode.

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '<string>', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '<string>', 'eval'))

Since all expressions can be used as statements in Python (these are called the Expr nodes in the Python abstract grammar; the opposite is not true), you can always use exec if you do not need the return value. That is to say, you can use either eval('my_func(42)') or exec('my_func(42)'), the difference being that eval returns the value returned by my_func, and exec discards it:

>>> def my_func(arg):
...     print("Called with %d" % arg)
...     return arg * 2
... 
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>> 

Of the 2, only exec accepts source code that contains statements, like def, for, while, import, or class, the assignment statement (a.k.a a = 42), or entire programs:

>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Both exec and eval accept 2 additional positional arguments - globals and locals - which are the global and local variable scopes that the code sees. These default to the globals() and locals() within the scope that called exec or eval, but any dictionary can be used for globals and any mapping for locals (including dict of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the executed code creates:

>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}

(If you display the value of the entire g, it would be much longer, because exec and eval add the built-ins module as __builtins__ to the globals automatically if it is missing).

In Python 2, the official syntax for the exec statement is actually exec code in globals, locals, as in

>>> exec 'global a; a, b = 123, 42' in g, l

However the alternate syntax exec(code, globals, locals) has always been accepted too (see below).

compile

The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) built-in can be used to speed up repeated invocations of the same code with exec or eval by compiling the source into a code object beforehand. The mode parameter controls the kind of code fragment the compile function accepts and the kind of bytecode it produces. The choices are 'eval', 'exec' and 'single':

  • 'eval' mode expects a single expression, and will produce bytecode that when run will return the value of that expression:

    >>> dis.dis(compile('a + b', '<string>', 'eval'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 RETURN_VALUE
    
  • 'exec' accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None:

    >>> dis.dis(compile('a + b', '<string>', 'exec'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 POP_TOP                             <- discard result
                  8 LOAD_CONST               0 (None)   <- load None on stack
                 11 RETURN_VALUE                        <- return top of stack
    
  • 'single' is a limited form of 'exec' which accepts a source code containing a single statement (or multiple statements separated by ;) if the last statement is an expression statement, the resulting bytecode also prints the repr of the value of that expression to the standard output(!).

    An if-elif-else chain, a loop with else, and try with its except, else and finally blocks is considered a single statement.

    A source fragment containing 2 top-level statements is an error for the 'single', except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:

    In Python 2.7.8:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    >>> a
    5
    

    And in Python 3.4.2:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1
        a = 5
            ^
    SyntaxError: multiple statements found while compiling a single statement
    

    This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval the resulting code.

Thus greatest distinction of exec and eval actually comes from the compile function and its modes.


In addition to compiling source code to bytecode, compile supports compiling abstract syntax trees (parse trees of Python code) into code objects; and source code into abstract syntax trees (the ast.parse is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.


While eval only allows you to evaluate a string that contains a single expression, you can eval a whole statement, or even a whole module that has been compiled into bytecode; that is, with Python 2, print is a statement, and cannot be evalled directly:

>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print("Python is cool")
      ^
SyntaxError: invalid syntax

compile it with 'exec' mode into a code object and you can eval it; the eval function will return None.

>>> code = compile('for i in range(3): print("Python is cool")',
                   'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool

If one looks into eval and exec source code in CPython 3, this is very evident; they both call PyEval_EvalCode with same arguments, the only difference being that exec explicitly returns None.

Syntax differences of exec between Python 2 and Python 3

One of the major differences in Python 2 is that exec is a statement and eval is a built-in function (both are built-in functions in Python 3). It is a well-known fact that the official syntax of exec in Python 2 is exec code [in globals[, locals]].

Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec statement in CPython 2 can be also used with syntax that looks exactly like the exec function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals) built-in function! And that built-in function was replaced with exec statement somewhere before Python 1.0 release.

Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code was a tuple of length 2 or 3, and globals and locals were not passed into the exec statement otherwise, the code would be interpreted as if the 2nd and 3rd element of the tuple were the globals and locals respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:

The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form exec(expr, globals) is equivalent to exec expr in globals, while the form exec(expr, globals, locals) is equivalent to exec expr in globals, locals. The tuple form of exec provides compatibility with Python 3, where exec is a function rather than a statement.

Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.

Thus while exec is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,

>>> exec("print(a)", globals(), {'a': 42})
42

has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).

What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec into a variable:

Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
  File "<stdin>", line 1
    a = exec('print(42)')
           ^
SyntaxError: invalid syntax

(which wouldn't be useful in Python 3 either, as exec always returns None), or pass a reference to exec:

>>> call_later(exec, 'print(42)', delay=1000)
  File "<stdin>", line 1
    call_later(exec, 'print(42)', delay=1000)
                  ^
SyntaxError: invalid syntax

Which a pattern that someone might actually have used, though unlikely;

Or use it in a list comprehension:

>>> [exec(i) for i in ['print(42)', 'print(foo)']
  File "<stdin>", line 1
    [exec(i) for i in ['print(42)', 'print(foo)']
        ^
SyntaxError: invalid syntax

which is abuse of list comprehensions (use a for loop instead!).

What is meant by immutable?

String s1="Hi";
String s2=s1;
s1="Bye";

System.out.println(s2); //Hi  (if String was mutable output would be: Bye)
System.out.println(s1); //Bye

s1="Hi" : an object s1 was created with "Hi" value in it.

s2=s1 : an object s2 is created with reference to s1 object.

s1="Bye" : the previous s1 object's value doesn't change because s1 has String type and String type is an immutable type, instead compiler create a new String object with "Bye" value and s1 referenced to it. here when we print s2 value, the result will be "Hi" not "Bye" because s2 referenced to previous s1 object which had "Hi" value.

How to abort makefile if variable not set?

You can use an IF to test:

check:
        @[ "${var}" ] || ( echo ">> var is not set"; exit 1 )

Result:

$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1

Why do Twitter Bootstrap tables always have 100% width?

<table style="width: auto;" ... works fine. Tested in Chrome 38 , IE 11 and Firefox 34.

jsfiddle : http://jsfiddle.net/rpaul/taqodr8o/

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Really killing a process in Windows

"End Process" on the Processes-Tab calls TerminateProcess which is the most ultimate way Windows knows to kill a process.

If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away.

Have a look at this blog-entry from wayback when: http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx

Unix based systems like Linux also have that problem where processes could survive a kill -9 if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state D) at which point the processes sleep so well that they can't process incoming signals (which is what kill does - sending signals).

Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs (vfork without exec) can end up sleeping in D forever.

php: how to get associative array key from numeric index?

You don't. Your array doesn't have a key [1]. You could:

  • Make a new array, which contains the keys:

    $newArray = array_keys($array);
    echo $newArray[0];
    

    But the value "one" is at $newArray[0], not [1].
    A shortcut would be:

    echo current(array_keys($array));
    
  • Get the first key of the array:

     reset($array);
     echo key($array);
    
  • Get the key corresponding to the value "value":

    echo array_search('value', $array);
    

This all depends on what it is exactly you want to do. The fact is, [1] doesn't correspond to "one" any which way you turn it.

How to do Base64 encoding in node.js?

The accepted answer previously contained new Buffer(), which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).

The Buffer constructor is deprecated according to the documentation.

Here is an example of a vulnerability that can result from using it in the ws library.

The code snippets should read:

console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));

After this answer was written, it has been updated and now matches this.

Efficient way to remove ALL whitespace from String?

I have an alternative way without regexp, and it seems to perform pretty good. It is a continuation on Brandon Moretz answer:

 public static string RemoveWhitespace(this string input)
 {
    return new string(input.ToCharArray()
        .Where(c => !Char.IsWhiteSpace(c))
        .ToArray());
 }

I tested it in a simple unit test:

[Test]
[TestCase("123 123 1adc \n 222", "1231231adc222")]
public void RemoveWhiteSpace1(string input, string expected)
{
    string s = null;
    for (int i = 0; i < 1000000; i++)
    {
        s = input.RemoveWhitespace();
    }
    Assert.AreEqual(expected, s);
}

[Test]
[TestCase("123 123 1adc \n 222", "1231231adc222")]
public void RemoveWhiteSpace2(string input, string expected)
{
    string s = null;
    for (int i = 0; i < 1000000; i++)
    {
        s = Regex.Replace(input, @"\s+", "");
    }
    Assert.AreEqual(expected, s);
}

For 1,000,000 attempts the first option (without regexp) runs in less then a second (700 ms on my machine), and the second takes 3.5 seconds.

In Java what is the syntax for commenting out multiple lines?

You could use /* begin comment and end it with */

Or you can simply use // across each line (not recommended)

/*
Here is an article you could of read that tells you all about how to comment
on multiple lines too!:

[http://java.sun.com/docs/codeconv/html/CodeConventions.doc4.html][1]
*/

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

How to delete columns in pyspark dataframe

Reading the Spark documentation I found an easier solution.

Since version 1.4 of spark there is a function drop(col) which can be used in pyspark on a dataframe.

You can use it in two ways

  1. df.drop('age').collect()
  2. df.drop(df.age).collect()

Pyspark Documentation - Drop

mySQL :: insert into table, data from another table?

for whole row

insert into xyz select * from xyz2 where id="1";

for selected column

insert into xyz(t_id,v_id,f_name) select t_id,v_id,f_name from xyz2 where id="1";

Angular ng-class if else

You can use the ternary operator notation:

<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

Difference between <span> and <div> with text-align:center;?

the difference is not between <span> and <div> specifically, but between inline and block elements. <span> defaults to being display:inline; whereas <div> defaults to being display:block;. But these can be overridden in CSS.

The difference in the way text-align:center works between the two is down to the width.

A block element defaults to being the width of its container. It can have its width set using CSS, but either way it is a fixed width.

An inline element takes its width from the size of its content text.

text-align:center tells the text to position itself centrally in the element. But in an inline element, this is clearly not going to have any effect because the element is the same width as the text; aligning it one way or the other is meaningless.

In a block element, because the element's width is independent of the content, the content can be positioned within the element using the text-align style.

Finally, a solution for you:

There is an additional value for the display property which provides a half-way house between block and inline. Conveniently enough, it's called inline-block. If you specify a <span> to be display:inline-block; in the CSS, it will continue to work as an inline element but will take on some of the properties of a block as well, such as the ability to specify a width. Once you specify a width for it, you will be able to center the text within that width using text-align:center;

Hope that helps.

SQL Server: the maximum number of rows in table

We overflowed an integer primary key once (which is ~2.4 billion rows) on a table. If there's a row limit, you're not likely to ever hit it at a mere 36 million rows per year.

How to multiply individual elements of a list with a number?

In NumPy it is quite simple

import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)

I recommend taking a look at the NumPy tutorial for an explanation of the full capabilities of NumPy's arrays:

https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

I was getting this error by saving an object to the shared preferences as a gson converted string. The gson String was no good, so retrieving and deserializing the object was not actually working correctly. This meant any subsequent accesses to the object resulted in this error. Scary :)