Programs & Examples On #Truncated

Truncation is the term for limiting the number of digits right of the decimal point, by discarding the least significant ones.

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

I've seen a couple cases where this error occurs:

1. using the not equals operator != in a where clause with a list of multiple or values

such as:

where columnName !=('A'||'B')

This can be resolved by using

where columnName not in ('A','B')

2. missing a comparison operator in an if() function:

select if(col1,col1,col2);

in order to select the value in col1 if it exists and otherwise show the value in col2...this throws the error; it can be resolved by using:

select if(col1!='',col1,col2);

Converting a character code to char (VB.NET)

you can also use

Dim intValue as integer = 65  ' letter A for instance
Dim strValue As String = Char.ConvertFromUtf32(intValue)

this doesn't requirement Microsoft.VisualBasic reference

Multiple selector chaining in jQuery?

I think you might see slightly better performance by doing it this way:

$("#Create, #Edit").find(".myClass").plugin(){
    // Options
});

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

Seems like a lazy way to always know that your WHERE clause is already defined and allow you to keep adding conditions without having to check if it is the first one.

How do I discover memory usage of my application in Android?

Hackbod's is one of the best answers on Stack Overflow. It throws light on a very obscure subject. It helped me a lot.

Another really helpful resource is this must-see video: Google I/O 2011: Memory management for Android Apps


UPDATE:

Process Stats, a service to discover how your app manages memory explained at the blog post Process Stats: Understanding How Your App Uses RAM by Dianne Hackborn:

How to create a folder with name as current date in batch (.bat) files

This works for me, try:

ECHO %DATE:~7,2%_%DATE:~4,2%_%DATE:~12,2%

Call a url from javascript

You can make an AJAX request if the url is in the same domain, e.g., same host different application. If so, I'd probably use a framework like jQuery, most likely the get method.

$.get('http://someurl.com',function(data,status) {
      ...parse the data...
},'html');

If you run into cross domain issues, then your best bet is to create a server-side action that proxies the request for you. Do your request to your server using AJAX, have the server request and return the response from the external host.

Thanks to@nickf, for pointing out the obvious problem with my original solution if the url is in a different domain.

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Your syntax is pretty screwy.

Change this:

input:not(disabled)not:[type="submit"]:focus{

to:

input:not(:disabled):not([type="submit"]):focus{

Seems that many people don't realize :enabled and :disabled are valid CSS selectors...

How to fix/convert space indentation in Sublime Text?

The easiest thing i did was,

changed my Indentation to Tabs

and it resolved my problem.

You can do the same,

to Spaces

as well as per your need.

Mentioned the snapshot of the same.

enter image description here

Convert pyspark string to date format

In the accepted answer's update you don't see the example for the to_date function, so another solution using it would be:

from pyspark.sql import functions as F

df = df.withColumn(
            'new_date',
                F.to_date(
                    F.unix_timestamp('STRINGCOLUMN', 'MM-dd-yyyy').cast('timestamp')))

Tab key == 4 spaces and auto-indent after curly braces in Vim

As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your .vimrc):

filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab

In your [.vimrc:][1] file:
set smartindent
set tabstop=4
set shiftwidth=4
set expandtab

The help files take a bit of time to get used to, but the more you read, the better Vim gets:

:help smartindent

Even better, you can embed these settings in your source for portability:

:help auto-setting

To see your current settings:

:set all

As graywh points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax:

:help C-indenting

How to raise a ValueError?

>>> def contains(string, char):
...     for i in xrange(len(string) - 1, -1, -1):
...         if string[i] == char:
...             return i
...     raise ValueError("could not find %r in %r" % (char, string))
...
>>> contains('bababa', 'k')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in contains
ValueError: could not find 'k' in 'bababa'
>>> contains('bababa', 'a')
5
>>> contains('bababa', 'b')
4
>>> contains('xbababa', 'x')
0
>>>

How to detect if user select cancel InputBox VBA Excel

If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

EDIT to properly differentiate between empty string and cancel, according to this answer.

Your example

Private Sub test()
    Dim result As String
    result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
    If StrPtr(result) = 0 Then
        MsgBox ("User canceled!")
    ElseIf result = vbNullString Then
        MsgBox ("User didn't enter anything!")
    Else
        MsgBox ("User entered " & result)
    End If
End Sub

Would tell the user they canceled when they delete the default string, or they click cancel.

See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

Install Android App Bundle on device

Short answer:

Not directly.

Longer answer:

Android App Bundles is a publishing format. Android devices require .apk files to install applications.

The PlayStore or any other source that you're installing from needs to extract apks from the bundle, sign each one and then install them specific to the target device.

The conversion from .aab to .apk is done via bundletool.

You can use Internal App Sharing to upload a debuggable build of your app to the Play Store and share it with testers.

Making an array of integers in iOS

C array:

NSInteger array[6] = {1, 2, 3, 4, 5, 6};

Objective-C Array:

NSArray *array = @[@1, @2, @3, @4, @5, @6];
// numeric values must in that case be wrapped into NSNumbers

Swift Array:

var array = [1, 2, 3, 4, 5, 6]

This is correct too:

var array = Array(1...10)

NB: arrays are strongly typed in Swift; in that case, the compiler infers from the content that the array is an array of integers. You could use this explicit-type syntax, too:

var array: [Int] = [1, 2, 3, 4, 5, 6]

If you wanted an array of Doubles, you would use :

var array = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] // implicit type-inference

or:

var array: [Double] = [1, 2, 3, 4, 5, 6] // explicit type

Change IPython/Jupyter notebook working directory

just change to the preferred directory in CMD, so if you are in

C:\Users\USERNAME>

just change the path like this

C:\Users\USERNAME>cd D:\MyProjectFolder

the CMD cursor then will move to this folder

D:\MyProjectFolder>

next you can call jupyter

D:\MyProjectFolder>jupyter notebook

Rotate an image in image source in html

This might be your script-free solution: http://davidwalsh.name/css-transform-rotate

It's supported in all browsers prefixed and, in IE10-11 and all still-used Firefox versions, unprefixed.

That means that if you don't care for old IEs (the bane of web designers) you can skip the -ms- and -moz- prefixes to economize space.

However, the Webkit browsers (Chrome, Safari, most mobile navigators) still need -webkit-, and there's a still-big cult following of pre-Next Opera and using -o- is sensate.

Redirect to Action in another controller

Use this:

return RedirectToAction("LogIn", "Account", new { area = "" });

This will redirect to the LogIn action in the Account controller in the "global" area.

It's using this RedirectToAction overload:

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    Object routeValues
)

MSDN

SQL Server CTE and recursion example

The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.

The semantics of the recursive execution is as follows:

  1. Split the CTE expression into anchor and recursive members.
  2. Run the anchor member(s) creating the first invocation or base result set (T0).
  3. Run the recursive member(s) with Ti as an input and Ti+1 as an output.
  4. Repeat step 3 until an empty set is returned.
  5. Return the result set. This is a UNION ALL of T0 to Tn.

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

JMS Topic vs Queues

Topics are for the publisher-subscriber model, while queues are for point-to-point.

Find a commit on GitHub given the commit hash

View single commit:
https://github.com/<user>/<project>/commit/<hash>

View log:
https://github.com/<user>/<project>/commits/<hash>

View full repo:
https://github.com/<user>/<project>/tree/<hash>

<hash> can be any length as long as it is unique.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

How to access the elements of a 2D array?

Seems to work here:

>>> a=[[1,1],[2,1],[3,1]]
>>> a
[[1, 1], [2, 1], [3, 1]]
>>> a[1]
[2, 1]
>>> a[1][0]
2
>>> a[1][1]
1

Initialization of all elements of an array to one default value in C++?

For the case of an array of single-byte elements, you can use memset to set all elements to the same value.

There's an example here.

Git undo local branch delete

If you know the last SHA1 of the branch, you can try

git branch branchName <SHA1>

You can find the SHA1 using git reflog, described in the solution --defect link--.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

This may not be relevant to your specific issue, but I had a similar problem when the pickle archive had been created using gzip.

For example if a compressed pickle archive is made like this,

import gzip, pickle
with gzip.open('test.pklz', 'wb') as ofp:
    pickle.dump([1,2,3], ofp)

Trying to open it throws the errors

 with open('test.pklz', 'rb') as ifp:
     print(pickle.load(ifp))
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
_pickle.UnpicklingError: invalid load key, ''.

But, if the pickle file is opened using gzip all is harmonious

with gzip.open('test.pklz', 'rb') as ifp:
    print(pickle.load(ifp))

[1, 2, 3]

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

I'd do

for i in `seq 0 2 10`; do echo $i; done

(though of course seq 0 2 10 will produce the same output on its own).

Note that seq allows floating-point numbers (e.g., seq .5 .25 3.5) but bash's brace expansion only allows integers.

Set title background color

Try with the following code

View titleView = getWindow().findViewById(android.R.id.title);
    if (titleView != null) {
      ViewParent parent = titleView.getParent();
      if (parent != null && (parent instanceof View)) {
        View parentView = (View)parent;
        parentView.setBackgroundColor(Color.RED);
      }
    }

also use this link its very useful : http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/

How can I convert string to double in C++?

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << stod("  99.999  ") << endl;
}

Output: 99.999 (which is double, whitespace was automatically stripped)

Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double

I want a function that returns 0 when the string is not numerical.

You can add try catch statement when stod throws an exception.

How to get the current working directory in Java?

Use CodeSource#getLocation().

This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by Class#getProtectionDomain().

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}

no module named zlib

Sounds like you need to install the devel package for zlib, probably want to do something like sudo apt-get install zlib1g-dev (I don't use ubuntu so you'll want to double-check the package). Instead of using python-brew you might want to consider just compiling by hand, it's not very hard. Just download the source, and configure, make, make install. You'll want to at least set --prefix to somewhere, so it'll get installed where you want.

./configure --prefix=/opt/python2.7 + other options
make
make install

You can check what configuration options are available with ./configure --help and see what your system python was compiled with by doing:

python -c "import sysconfig; print sysconfig.get_config_var('CONFIG_ARGS')"

The key is to make sure you have the development packages installed for your system, so that Python will be able to build the zlib, sqlite3, etc modules. The python docs cover the build process in more detail: http://docs.python.org/using/unix.html#building-python.

How to get line count of a large file cheaply in Python?

Here is what I use, seems pretty clean:

import subprocess

def count_file_lines(file_path):
    """
    Counts the number of lines in a file using wc utility.
    :param file_path: path to file
    :return: int, no of lines
    """
    num = subprocess.check_output(['wc', '-l', file_path])
    num = num.split(' ')
    return int(num[0])

UPDATE: This is marginally faster than using pure python but at the cost of memory usage. Subprocess will fork a new process with the same memory footprint as the parent process while it executes your command.

Do we have router.reload in vue-router?

this.$router.go(this.$router.currentRoute)

Vue-Router Docs:

I checked vue-router repo on GitHub and it seems that there isn't reload() method any more. But in the same file, there is: currentRoute object.

Source: vue-router/src/index.js
Docs: docs

get currentRoute (): ?Route {
    return this.history && this.history.current
  }

Now you can use this.$router.go(this.$router.currentRoute) for reload current route.

Simple example.

Version for this answer:

"vue": "^2.1.0",
"vue-router": "^2.1.1"

On npm install: Unhandled rejection Error: EACCES: permission denied

This happens if the first time you run NPM it's with sudo, for example when trying to do an npm install -g.

The cache folders need to be owned by the current user, not root.

sudo chown -R $USER:$GROUP ~/.npm
sudo chown -R $USER:$GROUP ~/.config

This will give ownership to the above folders when running with normal user permissions (not as sudo).

It's also worth noting that you shouldn't be installing global packages using SUDO. If you do run into issues with permissions, it's worth changing your global directory. The docs recommend:

mkdir ~/.npm-global

npm config set prefix '~/.npm-global'

Then updating your PATH in wherever you define that (~/.profile etc.)

export PATH=~/.npm-global/bin:$PATH

You'll then need to make sure the PATH env variable is set (restarting terminal or using the source command)

https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally

How to make an element width: 100% minus padding?

You can do this:

width: auto;
padding: 20px;

How to clear all data in a listBox?

This should work:

listBox1.Items.Clear();

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014

Just be sure to be using correct instance and connect each other

Just pay attention in Stored procs must be recompiled

How to write and read java serialized objects into a file

I think you have to write each object to an own File or you have to split the one when reading it. You may also try to serialize your list and retrieve that when deserializing.

Use jQuery to hide a DIV when the user clicks outside of it

By using this code you can hide as many items as you want

var boxArray = ["first element's id","second element's id","nth element's id"];
   window.addEventListener('mouseup', function(event){
   for(var i=0; i < boxArray.length; i++){
    var box = document.getElementById(boxArray[i]);
    if(event.target != box && event.target.parentNode != box){
        box.style.display = 'none';
    }
   }
})

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

How do I manually configure a DataSource in Java?

One thing you might want to look at is the Commons DBCP project. It provides a BasicDataSource that is configured fairly similarly to your example. To use that you need the database vendor's JDBC JAR in your classpath and you have to specify the vendor's driver class name and the database URL in the proper format.

Edit:

If you want to configure a BasicDataSource for MySQL, you would do something like this:

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");

Code that needs a DataSource can then use that.

How to Import 1GB .sql file to WAMP/phpmyadmin

The values indicated by Ram Sharma might need to be changed in Wamp alias configuration files instead.

In <wamp_dir>/alias/phpmyadmin.conf, in the <Directory> section:

  php_admin_value upload_max_filesize 1280M
  php_admin_value post_max_size 1280M
  php_admin_value max_execution_time 1800

How to customize the background/border colors of a grouped table view cell?

One thing I ran into with the above CustomCellBackgroundView code from Mike Akers which might be useful to others:

cell.backgroundView doesn't get automatically redrawn when cells are reused, and changes to the backgroundView's position var don't affect reused cells. That means long tables will have incorrectly drawn cell.backgroundViews given their positions.

To fix this without having to create a new backgroundView every time a row is displayed, call [cell.backgroundView setNeedsDisplay] at the end of your -[UITableViewController tableView:cellForRowAtIndexPath:]. Or for a more reusable solution, override CustomCellBackgroundView's position setter to include a [self setNeedsDisplay].

LEFT function in Oracle

I've discovered that LEFT and RIGHT are not supported functions in Oracle. They are used in SQL Server, MySQL, and some other versions of SQL. In Oracle, you need to use the SUBSTR function. Here are simple examples:

LEFT ('Data', 2) = 'Da'

->   SUBSTR('Data',1,2) = 'Da'

RIGHT ('Data', 2) = 'ta'

->   SUBSTR('Data',-2,2) = 'ta'

Notice that a negative number counts back from the end.

Remove last 3 characters of string or number in javascript

Remove last 3 characters of a string

var str = '1437203995000';
str = str.substring(0, str.length-3);
// '1437203995'

Remove last 3 digits of a number

var a = 1437203995000;
a = (a-(a%1000))/1000;
// a = 1437203995

How to use WPF Background Worker

You may want to also look into using Task instead of background workers.

The easiest way to do this is in your example is Task.Run(InitializationThread);.

There are several benefits to using tasks instead of background workers. For example, the new async/await features in .net 4.5 use Task for threading. Here is some documentation about Task https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task

Which port(s) does XMPP use?

According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.

The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.

Force Java timezone as GMT/UTC

The OP answered this question to change the default timezone for a single instance of a running JVM, set the user.timezone system property:

java -Duser.timezone=GMT ... <main-class>

If you need to set specific time zones when retrieving Date/Time/Timestamp objects from a database ResultSet, use the second form of the getXXX methods that takes a Calendar object:

Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
ResultSet rs = ...;
while (rs.next()) {
    Date dateValue = rs.getDate("DateColumn", tzCal);
    // Other fields and calculations
}

Or, setting the date in a PreparedStatement:

Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
PreparedStatement ps = conn.createPreparedStatement("update ...");
ps.setDate("DateColumn", dateValue, tzCal);
// Other assignments
ps.executeUpdate();

These will ensure that the value stored in the database is consistent when the database column does not keep timezone information.

The java.util.Date and java.sql.Date classes store the actual time (milliseconds) in UTC. To format these on output to another timezone, use SimpleDateFormat. You can also associate a timezone with the value using a Calendar object:

TimeZone tz = TimeZone.getTimeZone("<local-time-zone>");
//...
Date dateValue = rs.getDate("DateColumn");
Calendar calValue = Calendar.getInstance(tz);
calValue.setTime(dateValue);

Usefull Reference

https://docs.oracle.com/javase/9/troubleshoot/time-zone-settings-jre.htm#JSTGD377

https://confluence.atlassian.com/kb/setting-the-timezone-for-the-java-environment-841187402.html

Executing Javascript from Python

You can use requests-html which will download and use chromium underneath.

from requests_html import HTML

html = HTML(html="<a href='http://www.example.com/'>")

script = """
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
"""

val = html.render(script=script, reload=False)
print(val)
# +1 425-984-7450

More on this read here

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

I encountered a similar problem when I was trying to connect my Django application to PostgreSQL database.

I wrote my Dockerfile with instructions to setup the Django project followed by instructions to install PostgreSQL and run Django server in my docker-compose.yml.

I defined two services in my docker-compose-yml.

services:
  postgres:
    image: "postgres:latest"
    environment:
      - POSTGRES_DB=abc
      - POSTGRES_USER=abc
      - POSTGRES_PASSWORD=abc
    volumes:
      - pg_data:/var/lib/postgresql/data/
  django:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8004
    volumes:
      - .:/app
    ports:
      - 8004:8004
    depends_on:
      - postgres 

Unfortunately whenever I used to run docker-compose up then same err. used to pop up.

And this is how my database was defined in Django settings.py.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'abc',
        'USER': 'abc',
        'PASSWORD': 'abc',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'OPTIONS': {
            'client_encoding': 'UTF8',
        },
    }
} 

So, In the end I made use of docker-compose networking which means if I change the host of my database to postgres which is defined as a service in docker-compose.yml will do the wonders.

So, Replacing 'HOST': '127.0.0.1' => 'HOST': 'postgres' did wonders for me.

After replacement this is how your Database config in settings.py will look like.

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'abc',
            'USER': 'abc',
            'PASSWORD': 'abc',
            'HOST': 'postgres',
            'PORT': '5432',
            'OPTIONS': {
                'client_encoding': 'UTF8',
            },
        }
    } 

How to set default values in Go structs

type Config struct {
    AWSRegion                               string `default:"us-west-2"`
}

how to use php DateTime() function in Laravel 5

Best way is to use the Carbon dependency.

With Carbon\Carbon::now(); you get the current Datetime.

With Carbon you can do like enything with the DateTime. Event things like this:

$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();

MSBUILD : error MSB1008: Only one project can be specified

For me adding the path to the solution file in double quotes solved the issue. One of the folders in the path had a blank space in the name and this caused it to consider 2 solution files instead of one. I executed in the following was and it worked.

MSBuild.exe "C:\Folder Name With Space\Project\project.sln"

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

UsedRange represents not only nonempty cells, but also formatted cells without any value. And that's why you should be very vigilant.

C++ sorting and keeping track of indexes

I wrote generic version of index sort.

template <class RAIter, class Compare>
void argsort(RAIter iterBegin, RAIter iterEnd, Compare comp, 
    std::vector<size_t>& indexes) {

    std::vector< std::pair<size_t,RAIter> > pv ;
    pv.reserve(iterEnd - iterBegin) ;

    RAIter iter ;
    size_t k ;
    for (iter = iterBegin, k = 0 ; iter != iterEnd ; iter++, k++) {
        pv.push_back( std::pair<int,RAIter>(k,iter) ) ;
    }

    std::sort(pv.begin(), pv.end(), 
        [&comp](const std::pair<size_t,RAIter>& a, const std::pair<size_t,RAIter>& b) -> bool 
        { return comp(*a.second, *b.second) ; }) ;

    indexes.resize(pv.size()) ;
    std::transform(pv.begin(), pv.end(), indexes.begin(), 
        [](const std::pair<size_t,RAIter>& a) -> size_t { return a.first ; }) ;
}

Usage is the same as that of std::sort except for an index container to receive sorted indexes. testing:

int a[] = { 3, 1, 0, 4 } ;
std::vector<size_t> indexes ;
argsort(a, a + sizeof(a) / sizeof(a[0]), std::less<int>(), indexes) ;
for (size_t i : indexes) printf("%d\n", int(i)) ;

you should get 2 1 0 3. for the compilers without c++0x support, replace the lamba expression as a class template:

template <class RAIter, class Compare> 
class PairComp {
public:
  Compare comp ;
  PairComp(Compare comp_) : comp(comp_) {}
  bool operator() (const std::pair<size_t,RAIter>& a, 
    const std::pair<size_t,RAIter>& b) const { return comp(*a.second, *b.second) ; }        
} ;

and rewrite std::sort as

std::sort(pv.begin(), pv.end(), PairComp(comp)()) ;

Python 3 ImportError: No module named 'ConfigParser'

Compatibility of Python 2/3 for configparser can be solved simply by six library

from six.moves import configparser

List all employee's names and their managers by manager name using an inner join

select a.empno,a.ename,a.job,a.mgr,B.empno,B.ename as MGR_name, B.job as MGR_JOB from 
    emp a, emp B where a.mgr=B.empno ;

Java Strings: "String s = new String("silly");"

Java strings are interesting. It looks like the responses have covered some of the interesting points. Here are my two cents.

strings are immutable (you can never change them)

String x = "x";
x = "Y"; 
  • The first line will create a variable x which will contain the string value "x". The JVM will look in its pool of string values and see if "x" exists, if it does, it will point the variable x to it, if it does not exist, it will create it and then do the assignment
  • The second line will remove the reference to "x" and see if "Y" exists in the pool of string values. If it does exist, it will assign it, if it does not, it will create it first then assignment. As the string values are used or not, the memory space in the pool of string values will be reclaimed.

string comparisons are contingent on what you are comparing

String a1 = new String("A");

String a2 = new String("A");
  • a1 does not equal a2
  • a1 and a2 are object references
  • When string is explicitly declared, new instances are created and their references will not be the same.

I think you're on the wrong path with trying to use the caseinsensitive class. Leave the strings alone. What you really care about is how you display or compare the values. Use another class to format the string or to make comparisons.

i.e.

TextUtility.compare(string 1, string 2) 
TextUtility.compareIgnoreCase(string 1, string 2)
TextUtility.camelHump(string 1)

Since you are making up the class, you can make the compares do what you want - compare the text values.

Modify a Column's Type in sqlite3

If you prefer a GUI, DB Browser for SQLite will do this with a few clicks.

  1. "File" - "Open Database"
  2. In the "Database Structure" tab, click on the table content (not table name), then "Edit" menu, "Modify table", and now you can change the data type of any column with a drop down menu. I changed a 'text' field to 'numeric' in order to retrieve data in a number range.

DB Browser for SQLite is open source and free. For Linux it is available from the repository.

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Pass accepts header parameter to jquery ajax

You had already identified the accepts parameter as the one you wanted and keyur is right in showing you the correct way to set it, but if you set DataType to "json" then it will automatically set the default value of accepts to the value you want as per the jQuery reference. So all you need is:

jQuery.ajax({
    url: _this.attr('href'),
    dataType: "json"
});

Initialize value of 'var' in C# to null

The var keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var keyword has a type. For instance, you'll find that the following code outputs "String".

var myString = "";
Console.Write(myString.GetType().Name);

Furthermore, the code above is equivalent to:

String myString = "";
Console.Write(myString.GetType().Name);

The var keyword is simply C#'s way of saying "I can figure out the type for myString from the context, so don't worry about specifying the type."

var myVariable = (MyType)null or MyType myVariable = null should work because you are giving the C# compiler context to figure out what type myVariable should will be.

For more information:

How to use ESLint with Jest

ESLint supports this as of version >= 4:

/*
.eslintrc.js
*/
const ERROR = 2;
const WARN = 1;

module.exports = {
  extends: "eslint:recommended",
  env: {
    es6: true
  },
  overrides: [
    {
      files: [
        "**/*.test.js"
      ],
      env: {
        jest: true // now **/*.test.js files' env has both es6 *and* jest
      },
      // Can't extend in overrides: https://github.com/eslint/eslint/issues/8813
      // "extends": ["plugin:jest/recommended"]
      plugins: ["jest"],
      rules: {
        "jest/no-disabled-tests": "warn",
        "jest/no-focused-tests": "error",
        "jest/no-identical-title": "error",
        "jest/prefer-to-have-length": "warn",
        "jest/valid-expect": "error"
      }
    }
  ],
};

Here is a workaround (from another answer on here, vote it up!) for the "extend in overrides" limitation of eslint config :

overrides: [
  Object.assign(
    {
      files: [ '**/*.test.js' ],
      env: { jest: true },
      plugins: [ 'jest' ],
    },
    require('eslint-plugin-jest').configs.recommended
  )
]

From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724

How do I do logging in C# without using 3rd party libraries?

If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.

How to parse a CSV in a Bash script?

First prototype using plain old grep and cut:

grep "${VALUE}" inputfile.csv | cut -d, -f"${INDEX}"

If that's fast enough and gives the proper output, you're done.

jQuery Array of all selected checkboxes (by class)

You can use the :checkbox and :checked pseudo-selectors and the .class selector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.

Then you can easily use the Traversing/map method to get an array of values:

var values = $('input:checkbox:checked.group1').map(function () {
  return this.value;
}).get(); // ["18", "55", "10"]

Get list of data-* attributes using javascript / jQuery

One way of finding all data attributes is using element.attributes. Using .attributes, you can loop through all of the element attributes, filtering out the items which include the string "data-".

let element = document.getElementById("element");

function getDataAttributes(element){
    let elementAttributes = {},
        i = 0;

    while(i < element.attributes.length){
        if(element.attributes[i].name.includes("data-")){
            elementAttributes[element.attributes[i].name] = element.attributes[i].value
        }
        i++;
    }

    return elementAttributes;

}

Encrypt and decrypt a password in Java

You can use java.security.MessageDigest with SHA as your algorithm choice.

For reference,

Try available example here

How to convert an address to a latitude/longitude?

Google has a geocoding API which seems to work pretty well for most of the locations that they have Google Maps data for.

http://googlemapsapi.blogspot.com/2006/06/geocoding-at-last.html

They provide online geocoding (via JavaScript):

http://code.google.com/apis/maps/documentation/services.html#Geocoding

Or backend geocoding (via an HTTP request):

http://code.google.com/apis/maps/documentation/services.html#Geocoding_Direct

The data is usually the same used by Google Maps itself. (note that there are some exceptions to this, such as the UK or Israel, where the data is from a different source and of slightly reduced quality)

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

How to get the clicked link's href with jquery?

Suppose we have three anchor tags like ,

<a  href="ID=1" class="testClick">Test1.</a>
<br />
<a  href="ID=2" class="testClick">Test2.</a>
<br />
<a  href="ID=3" class="testClick">Test3.</a>

now in script

$(".testClick").click(function () {
        var anchorValue= $(this).attr("href");
        alert(anchorValue);
});

use this keyword instead of className (testClick)

Check if list contains element that contains a string and get that element

You could use Linq's FirstOrDefault extension method:

string element = myList.FirstOrDefault(s => s.Contains(myString));

This will return the fist element that contains the substring myString, or null if no such element is found.

If all you need is the index, use the List<T> class's FindIndex method:

int index = myList.FindIndex(s => s.Contains(myString));

This will return the the index of fist element that contains the substring myString, or -1 if no such element is found.

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Yes. It's like the difference between a tollbooth and a door. The ManualResetEvent is the door, which needs to be closed (reset) manually. The AutoResetEvent is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

YouTube iframe embed - full screen

Noticed mine worked on chrome. Got it to work in Firefox by going to <about:config> and setting full-screen-api.allow-trusted-requests-only to false.

After full screen worked once, I could set that back to true, and full screen still worked which was quite perplexing.

How to make a stable two column layout in HTML/CSS

Here you go:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Cols</title>_x000D_
  <style>_x000D_
    #left {_x000D_
      width: 200px;_x000D_
      float: left;_x000D_
    }_x000D_
    #right {_x000D_
      margin-left: 200px;_x000D_
      /* Change this to whatever the width of your left column is*/_x000D_
    }_x000D_
    .clear {_x000D_
      clear: both;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="container">_x000D_
    <div id="left">_x000D_
      Hello_x000D_
    </div>_x000D_
    <div id="right">_x000D_
      <div style="background-color: red; height: 10px;">Hello</div>_x000D_
    </div>_x000D_
    <div class="clear"></div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

See it in action here: http://jsfiddle.net/FVLMX/

How to search and replace text in a file?

I have done this:

#!/usr/bin/env python3

import fileinput
import os

Dir = input ("Source directory: ")
os.chdir(Dir)

Filelist = os.listdir()
print('File list: ',Filelist)

NomeFile = input ("Insert file name: ")

CarOr = input ("Text to search: ")

CarNew = input ("New text: ")

with fileinput.FileInput(NomeFile, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(CarOr, CarNew), end='')

file.close ()

How to manually update datatables table with new JSON data

Here is solution for legacy datatable 1.9.4

    var myData = [
      {
        "id": 1,
        "first_name": "Andy",
        "last_name": "Anderson"
      }
   ];
    var myData2 = [
      {
        "id": 2,
        "first_name": "Bob",
        "last_name": "Benson"
      }
    ];

  $('#table').dataTable({
  //  data: myData,
       aoColumns: [
         { mData: 'id' },
         { mData: 'first_name' },
         { mData: 'last_name' }
      ]
  });

 $('#table').dataTable().fnClearTable();
 $('#table').dataTable().fnAddData(myData2);

How to embed matplotlib in pyqt - for Dummies

It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg. FigureCanvasQTAgg and NavigationToolbar2QT are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure, Navigation and a single button that draws some random data. I've added comments to explain things.

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

Edit:

Updated to reflect comments and API changes.

  • NavigationToolbar2QTAgg changed with NavigationToolbar2QT
  • Directly import Figure instead of pyplot
  • Replace deprecated ax.hold(False) with ax.clear()

How do I add an "Add to Favorites" button or link on my website?

Credit to @Gert Grenander , @Alaa.Kh , and Ross Shanon

Trying to make some order:

it all works - all but the firefox bookmarking function. for some reason the 'window.sidebar.addPanel' is not a function for the debugger, though it is working fine.

The problem is that it takes its values from the calling <a ..> tag: title as the bookmark name and href as the bookmark address. so this is my code:

javascript:

$("#bookmarkme").click(function () {
  var url = 'http://' + location.host; // i'm in a sub-page and bookmarking the home page
  var name = "Snir's Homepage";

  if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1){ //chrome
    alert("In order to bookmark go to the homepage and press " 
        + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 
            'Command/Cmd' : 'CTRL') + "+D.")
  } 
  else if (window.sidebar) { // Mozilla Firefox Bookmark
    //important for firefox to add bookmarks - remember to check out the checkbox on the popup
    $(this).attr('rel', 'sidebar');
    //set the appropriate attributes
    $(this).attr('href', url);
    $(this).attr('title', name);

    //add bookmark:
    //  window.sidebar.addPanel(name, url, '');
    //  window.sidebar.addPanel(url, name, '');
    window.sidebar.addPanel('', '', '');
  } 
  else if (window.external) { // IE Favorite
        window.external.addFavorite(url, name);
  } 
  return;
});

html:

  <a id="bookmarkme" href="#" title="bookmark this page">Bookmark This Page</a>

In internet explorer there is a different between 'addFavorite': <a href="javascript:window.external.addFavorite('http://tiny.cc/snir','snir-site')">..</a> and 'AddFavorite': <span onclick="window.external.AddFavorite(location.href, document.title);">..</span>.

example here: http://www.yourhtmlsource.com/javascript/addtofavorites.html

Important, in chrome we can't add bookmarks using js (aspnet-i): http://www.codeproject.com/Questions/452899/How-to-add-bookmark-in-Google-Chrome-Opera-and-Saf

C# Parsing JSON array of objects

string jsonData1=@"[{""name"":""0"",""price"":""40"",""count"":""1"",""productId"":""4"",""catid"":""4"",""productTotal"":""40"",""orderstatus"":""0"",""orderkey"":""123456789""}]";

                  string jsonData = jsonData1.Replace("\"", "");


                  DataSet ds = new DataSet();
                  DataTable dt = new DataTable();
       JArray array= JArray.Parse(jsonData);

couldnot parse , if the vaule is a string..

look at name : meals , if name : 1 then it will parse

Open Jquery modal dialog on click event

$(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();

    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").hide();
                }
            });
    }); //close click
});

Better to use .hide() instead of .remove(). With .remove() it returns undefined if you have pressed the link once, then close the modal and if you press the modal link again, it returns undefined with .remove.

With .hide() it doesnt and it works like a breeze. Ty for the snippet in the first hand!

How do I run all Python unit tests in a directory?

Here is my approach by creating a wrapper to run tests from the command line:

#!/usr/bin/env python3
import os, sys, unittest, argparse, inspect, logging

if __name__ == '__main__':
    # Parse arguments.
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-?", "--help",     action="help",                        help="show this help message and exit" )
    parser.add_argument("-v", "--verbose",  action="store_true", dest="verbose",  help="increase output verbosity" )
    parser.add_argument("-d", "--debug",    action="store_true", dest="debug",    help="show debug messages" )
    parser.add_argument("-h", "--host",     action="store",      dest="host",     help="Destination host" )
    parser.add_argument("-b", "--browser",  action="store",      dest="browser",  help="Browser driver.", choices=["Firefox", "Chrome", "IE", "Opera", "PhantomJS"] )
    parser.add_argument("-r", "--reports-dir", action="store",   dest="dir",      help="Directory to save screenshots.", default="reports")
    parser.add_argument('files', nargs='*')
    args = parser.parse_args()

    # Load files from the arguments.
    for filename in args.files:
        exec(open(filename).read())

    # See: http://codereview.stackexchange.com/q/88655/15346
    def make_suite(tc_class):
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(tc_class)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(tc_class(name, cargs=args))
        return suite

    # Add all tests.
    alltests = unittest.TestSuite()
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(obj) and name.startswith("FooTest"):
            alltests.addTest(make_suite(obj))

    # Set-up logger
    verbose = bool(os.environ.get('VERBOSE', args.verbose))
    debug   = bool(os.environ.get('DEBUG', args.debug))
    if verbose or debug:
        logging.basicConfig( stream=sys.stdout )
        root = logging.getLogger()
        root.setLevel(logging.INFO if verbose else logging.DEBUG)
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.INFO if verbose else logging.DEBUG)
        ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s'))
        root.addHandler(ch)
    else:
        logging.basicConfig(stream=sys.stderr)

    # Run tests.
    result = unittest.TextTestRunner(verbosity=2).run(alltests)
    sys.exit(not result.wasSuccessful())

For sake of simplicity, please excuse my non-PEP8 coding standards.

Then you can create BaseTest class for common components for all your tests, so each of your test would simply look like:

from BaseTest import BaseTest
class FooTestPagesBasic(BaseTest):
    def test_foo(self):
        driver = self.driver
        driver.get(self.base_url + "/")

To run, you simply specifying tests as part of the command line arguments, e.g.:

./run_tests.py -h http://example.com/ tests/**/*.py

Line Break in XML?

At the end of your lines, simply add the following special character: &#xD;

That special character defines the carriage-return character.

Difference between onStart() and onResume()

Reference to http://developer.android.com/training/basics/activity-lifecycle/starting.html

onResume() Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it. Always followed by onPause().

onPause() Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns. Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.

PHP to search within txt file and echo the whole line

$searchfor = $_GET['keyword'];
$file = 'users.txt';

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";

if (preg_match_all($pattern, $contents, $matches)) {
    echo "Found matches:<br />";
    echo implode("<br />", $matches[0]);
} else {
    echo "No matches found";
    fclose ($file); 
}

How can I consume a WSDL (SOAP) web service in Python?

There is a relatively new library which is very promising and albeit still poorly documented, seems very clean and pythonic: python zeep.

See also this answer for an example.

How to detect if a stored procedure already exists

If you DROP and CREATE the procedure, you will loose the security settings. This might annoy your DBA or break your application altogether.

What I do is create a trivial stored procedure if it doesn't exist yet. After that, you can ALTER the stored procedure to your liking.

IF object_id('YourSp') IS NULL
    EXEC ('create procedure dbo.YourSp as select 1')
GO
ALTER PROCEDURE dbo.YourSp
AS
...

This way, security settings, comments and other meta deta will survive the deployment.

What is the difference between MySQL, MySQLi and PDO?

Those are different APIs to access a MySQL backend

  • The mysql is the historical API
  • The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
  • PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don't use specific RDBM function in your queries), also object-oriented.

So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...

My advice would be

  1. PDO
  2. MySQLi
  3. mysql

Also my feeling, the mysql API would probably being deleted in future releases of PHP.

how to insert value into DataGridView Cell?

This is perfect code but it cannot add a new row:

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But this code can insert a new row:

var index = this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[1].Value = "1";
this.dataGridView1.Rows[index].Cells[2].Value = "Baqar";

Palindrome check in Javascript

At least three things:

  • You are trying to test for equality with =, which is used for setting. You need to test with == or ===. (Probably the latter, if you don't have a reason for the former.)

  • You are reporting results after checking each character. But you don't know the results until you've checked enough characters.

  • You double-check each character-pair, as you really only need to check if, say first === last and not also if last === first.

Notepad++ Multi editing

Notepad++ has a powerful regex engine, capable to search and replace patterns at will.

In your scenario:

  1. Click the menu item Search\Replace...

  2. Fill the 'Find what' field with the search pattern:

    ^(\d{4})\s+(\w{3})\s+(\w{3})$
    
  3. Fill the replace pattern:

    Insert into tbl (\1, \2) where clm = \3
    
  4. Click the Replace All button.

And that's it.

NotePad++ replace window screenshot

How to check if cursor exists (open status)

You can use the CURSOR_STATUS function to determine its state.

IF CURSOR_STATUS('global','myCursor')>=-1
BEGIN
 DEALLOCATE myCursor
END

anaconda - graphviz - can't import after installation

Remeber! If you are using jupyter notebook, please restart it after the installing. That's work for me.

Because the condition before is a static variate as below:

enter image description here

enter image description here

enter image description here

SQL Server : How to test if a string has only digit characters

DECLARE @x int=1
declare @exit bit=1
WHILE @x<=len('123c') AND @exit=1
BEGIN
IF ascii(SUBSTRING('123c',@x,1)) BETWEEN 48 AND 57
BEGIN
set @x=@x+1
END
ELSE
BEGIN
SET @exit=0
PRINT 'string is not all numeric  -:('
END
END

What's the best way to get the last element of an array without deleting it?

If you don't care about modifying the internal pointer (the following lines support both indexed and associative arrays):

// false if empty array
$last = end($array);

// null if empty array
$last = !empty($array) ? end($array) : null;


If you want an utility function that doesn't modify the internal pointer (because the array is passed by value to the function, so the function operates on a copy of it):

function array_last($array) {
    if (empty($array)) {
        return null;
    }
    return end($array);
}


Though, PHP produces copies "on-the-fly", i.e. only when actually needed. As the end() function modifies the array, internally a copy of the whole array (minus one item) is generated.


Therefore, I would recommend the following alternative that is actually faster, as internally it doesn't copy the array, it just makes a slice:

function array_last($array) {
    if (empty($array)) {
        return null;
    }
    foreach (array_slice($array, -1) as $value) {
        return $value;
    }
}

Additionally, the "foreach / return" is a tweak for efficiently getting the first (and here single) item.


Finally, the fastest alternative but for indexed arrays (and without gaps) only:

$last = !empty($array) ? $array[count($array)-1] : null;


For the record, here is another answer of mine, for the array's first element.

How do I declare and use variables in PL/SQL like I do in T-SQL?

In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:

declare
  myname varchar2(20) := 'tom';
begin
  for result_cursor in (select * from mytable where first_name = myname) loop
    dbms_output.put_line(result_cursor.first_name);
    dbms_output.put_line(result_cursor.other_field);
  end loop;
end;

If you have a query that returns exactly one row, then you can use the select...into... syntax, e.g.:

declare 
  myname varchar2(20);
begin
  select first_name into myname 
    from mytable 
    where person_id = 123;
end;

Tomcat view catalina.out log file

Just be aware also that catalina.out can be renamed - it can be set in /bin/catalina.sh with the CATALINA_OUT environment variable.

What does [object Object] mean? (JavaScript)

That is because there are different types of objects in Javascript!

For example

  • Function objects:

stringify(function (){}) -> [object Function]

  • Array objects:

stringify([]) -> [object Array]

  • RegExp objects

stringify(/x/) -> [object RegExp]

  • Date objects

stringify(new Date) -> [object Date]

...
  • Object objects!

stringify({}) -> [object Object]

the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.

When you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.

If you want to see value inside "[Object objects]" use:

console.log(JSON.stringify(result))

How to access local files of the filesystem in the Android emulator?

Update! You can access the Android filesystem via Android Device Monitor. In Android Studio go to Tools >> Android >> Android Device Monitor.

Note that you can run your app in the simulator while using the Android Device Monitor. But you cannot debug you app while using the Android Device Monitor.

What is the difference between #include <filename> and #include "filename"?

Many of the answers here focus on the paths the compiler will search in order to find the file. While this is what most compilers do, a conforming compiler is allowed to be preprogrammed with the effects of the standard headers, and to treat, say, #include <list> as a switch, and it need not exist as a file at all.

This is not purely hypothetical. There is at least one compiler that work that way. Using #include <xxx> only with standard headers is recommended.

C# guid and SQL uniqueidentifier

You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.

Your method may look like this (provided that your only parameter is the Guid):

public static void StoreGuid(Guid guid)
{
    using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
    using (var cmd = new SqlCommand {
        Connection = cnx,
        CommandType = CommandType.StoredProcedure,
        CommandText = "StoreGuid",
        Parameters = {
            new SqlParameter {
                ParameterName = "@guid",
                SqlDbType = SqlDbType.UniqueIdentifier, // right here
                Value = guid
            }
        }
    })
    {
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

See also: SQL Server's uniqueidentifier

How to retrieve current workspace using Jenkins Pipeline Groovy script?

A quick note for anyone who is using bat in the job and needs to access Workspace:

It won't work.

$WORKSPACE https://issues.jenkins-ci.org/browse/JENKINS-33511 as mentioned here only works with PowerShell. So your code should have powershell for execution

 stage('Verifying Workspace') {
  powershell label: '', script: 'dir $WORKSPACE'
}

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

I would say echo() ing them directly into the Javascript source code is the most reliable and downward compatible way. Stay with that unless you have a good reason not to.

Get HTML5 localStorage keys

You can use the localStorage.key(index) function to return the string representation, where index is the nth object you want to retrieve.

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

Loop through all nested dictionary values?

Alternative iterative solution:

def myprint(d):
    stack = d.items()
    while stack:
        k, v = stack.pop()
        if isinstance(v, dict):
            stack.extend(v.iteritems())
        else:
            print("%s: %s" % (k, v))

How do I center a Bootstrap div with a 'spanX' class?

Twitter's bootstrap .span classes are floated to the left so they won't center by usual means. So, if you want it to center your span simply add float:none to your #main rule.

CSS

#main {
 margin:0 auto;
 float:none;
}

Show/hide div if checkbox selected

change the input boxes like

<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox

and js code as

function showMe (box) {

    var chboxs = document.getElementsByName("c1");
    var vis = "none";
    for(var i=0;i<chboxs.length;i++) { 
        if(chboxs[i].checked){
         vis = "block";
            break;
        }
    }
    document.getElementById(box).style.display = vis;


}

here is a demo fiddle

Exclude property from type

If you prefer to use a library, use ts-essentials.

import { Omit } from "ts-essentials";

type ComplexObject = {
  simple: number;
  nested: {
    a: string;
    array: [{ bar: number }];
  };
};

type SimplifiedComplexObject = Omit<ComplexObject, "nested">;

// Result:
// {
//  simple: number
// }

// if you want to Omit multiple properties just use union type:
type SimplifiedComplexObject = Omit<ComplexObject, "nested" | "simple">;

// Result:
// { } (empty type)

PS: You will find lots of other useful stuff there ;)

Invalid date in safari

Though you might hope that browsers would support ISO 8601 (or date-only subsets thereof), this is not the case. All browsers that I know of (at least in the US/English locales I use) are able to parse the horrible US MM/DD/YYYY format.

If you already have the parts of the date, you might instead want to try using Date.UTC(). If you don't, but you must use the YYYY-MM-DD format, I suggest using a regular expression to parse the pieces you know and then pass them to Date.UTC().

Running a cron every 30 seconds

write one shell script create .sh file

nano every30second.sh

and write script

#!/bin/bash
For  (( i=1; i <= 2; i++ ))
do
    write Command here
    sleep 30
done

then set cron for this script crontab -e

(* * * * * /home/username/every30second.sh)

this cron call .sh file in every 1 min & in the .sh file command is run 2 times in 1 min

if you want run script for 5 seconds then replace 30 by 5 and change for loop like this: For (( i=1; i <= 12; i++ ))

when you select for any second then calculate 60/your second and write in For loop

How to use breakpoints in Eclipse

To put breakpoints in your code, double click in the left margin on the line you want execution to stop on. You may alternatively put your cursor in this line and then press Shift+Ctrl+B.

To control execution use the Step Into, Step Over and Step Return buttons. They have the shortcuts F5, F6 and F7 respectively.

To allow execution to continue normally or until it hits the next breakpoint, hit the Resume button or F8.

I have created a table in hive, I would like to know which directory my table is created in?

You can use below commands for the same.

show create table <table>;
desc formatted <table>;
describe formatted <table>;

How do I install Python packages in Google's Colab?

A better, more modern, answer to this question is to use the %pip magic, like:

%pip install scipy

That will automatically use the correct Python version. Using !pip might be tied to a different version of Python, and then you might not find the package after installing it.

And in colab, the magic gives a nice message and button if it detects that you need to restart the runtime if pip updated a packaging you have already imported.

BTW, there is also a %conda magic for doing the same with conda.

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

How do I iterate over a range of numbers defined by variables in Bash?

discussion

Using seq is fine, as Jiaaro suggested. Pax Diablo suggested a Bash loop to avoid calling a subprocess, with the additional advantage of being more memory friendly if $END is too large. Zathrus spotted a typical bug in the loop implementation, and also hinted that since i is a text variable, continuous conversions to-and-fro numbers are performed with an associated slow-down.

integer arithmetic

This is an improved version of the Bash loop:

typeset -i i END
let END=5 i=1
while ((i<=END)); do
    echo $i
    …
    let i++
done

If the only thing that we want is the echo, then we could write echo $((i++)).

ephemient taught me something: Bash allows for ((expr;expr;expr)) constructs. Since I've never read the whole man page for Bash (like I've done with the Korn shell (ksh) man page, and that was a long time ago), I missed that.

So,

typeset -i i END # Let's be explicit
for ((i=1;i<=END;++i)); do echo $i; done

seems to be the most memory-efficient way (it won't be necessary to allocate memory to consume seq's output, which could be a problem if END is very large), although probably not the “fastest”.

the initial question

eschercycle noted that the {a..b} Bash notation works only with literals; true, accordingly to the Bash manual. One can overcome this obstacle with a single (internal) fork() without an exec() (as is the case with calling seq, which being another image requires a fork+exec):

for i in $(eval echo "{1..$END}"); do

Both eval and echo are Bash builtins, but a fork() is required for the command substitution (the $(…) construct).

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

using if else with eval in aspx page

You can try c#

public string ProcessMyDataItem(object myValue)
 {
  if (myValue == null)
   {
   return "0 %"";
  }
   else
  {
     if(Convert.ToInt32(myValue) < 50)
       return "0";
     else
      return myValue.ToString() + "%";
  }

 }

asp

 <div class="tooltip" style="display: none">                                                                  
      <div style="text-align: center; font-weight: normal">
   Value =<%# ProcessMyDataItem(Eval("Percentage")) %> </div>
 </div>

How to add an onchange event to a select box via javascript?

If you are using prototype.js then you can do this:

transport_select.observe('change', function(){
  toggleSelect(transport_select_id)
})

This eliminate (as hope) the problem in cross-browsers

Rotate a div using javascript

I recently had to build something similar. You can check it out in the snippet below.

The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin

Basically, my code looks like this...

Run Code Snippet

_x000D_
_x000D_
var rocket = document.querySelector('.rocket');_x000D_
var btn = document.querySelector('.toggle');_x000D_
var rotate = false;_x000D_
var runner;_x000D_
var degrees = 0;_x000D_
_x000D_
function start(){_x000D_
    runner = setInterval(function(){_x000D_
        degrees++;_x000D_
        rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
    },50)_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
    clearInterval(runner);_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', function(){_x000D_
    if (!rotate){_x000D_
        rotate = true;_x000D_
        start();_x000D_
    } else {_x000D_
        rotate = false;_x000D_
        stop();_x000D_
    }_x000D_
})
_x000D_
body {_x000D_
  background: #1e1e1e;_x000D_
}    _x000D_
_x000D_
.rocket {_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
    margin: 1em;_x000D_
    border: 3px dashed teal;_x000D_
    border-radius: 50%;_x000D_
    background-color: rgba(128,128,128,0.5);_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
  }_x000D_
  _x000D_
  .rocket h1 {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    font-size: .8em;_x000D_
    color: skyblue;_x000D_
    letter-spacing: 1em;_x000D_
    text-shadow: 0 0 10px black;_x000D_
  }_x000D_
  _x000D_
  .toggle {_x000D_
    margin: 10px;_x000D_
    background: #000;_x000D_
    color: white;_x000D_
    font-size: 1em;_x000D_
    padding: .3em;_x000D_
    border: 2px solid red;_x000D_
    outline: none;_x000D_
    letter-spacing: 3px;_x000D_
  }
_x000D_
<div class="rocket"><h1>SPIN ME</h1></div>_x000D_
<button class="toggle">I/0</button>
_x000D_
_x000D_
_x000D_

"Fade" borders in CSS

You could also use box-shadow property with higher value of blur and rgba() color to set opacity level. Sounds like a better choice in your case.

box-shadow: 0 30px 40px rgba(0,0,0,.1);

Move column by name to front of table in pandas

The most simplist thing you can try is:

df=df[[ 'Mid',   'Upper',   'Lower', 'Net'  , 'Zsore']]

How to iterate over a column vector in Matlab?

If you just want to apply a function to each element and put the results in an output array, you can use arrayfun.

As others have pointed out, for most operations, it's best to avoid loops in MATLAB and vectorise your code instead.

How to filter rows in pandas by regex

Using str slice

foo[foo.b.str[0]=='f']
Out[18]: 
   a    b
1  2  foo
2  3  fat

MySQL SELECT AS combine two columns into one

You don't need to list ContactPhoneAreaCode1 and ContactPhoneNumber1

SELECT FirstName AS First_Name, 
LastName AS Last_Name, 
COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
FROM TABLE1

how to re-format datetime string in php?

If you want to use substr(), you can easily add the dashes or slashes like this..

$datetime = "20130409163705"; 
$yyyy = substr($datetime,0,4);
$mm = substr($datetime,4,6);
$dd = substr($datetime,6,8);
$hh = substr($datetime,8,10);
$MM = substr($datetime,10,12);
$ss = substr($datetime,12,14);
$dt_formatted = $mm."/".$dd."/".$yyyy." ".$hh.":".$MM.":".$ss;

You can figure out any further formatting from that point.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

Java :Add scroll into text area

Try adding these two lines to your code. I hope it will work. It worked for me :)

display.setLineWrap(true);
display.setWrapStyleWord(true);

Picture of output is shown below

enter image description here

How to close Android application?

public class CloseAppActivity extends AppCompatActivity
{
    public static final void closeApp(Activity activity)
    {
        Intent intent = new Intent(activity, CloseAppActivity.class);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        finish();
    }
}

and in manifest:

<activity
     android:name=".presenter.activity.CloseAppActivity"
     android:noHistory="true"
     android:clearTaskOnLaunch="true"/>

Then you can call CloseAppActivity.closeApp(fromActivity) and application will be closed.

Using Gulp to Concatenate and Uglify files

My gulp file produces a final compiled-bundle-min.js, hope this helps someone.

enter image description here

//Gulpfile.js

var gulp = require("gulp");
var watch = require("gulp-watch");

var concat = require("gulp-concat");
var rename = require("gulp-rename");
var uglify = require("gulp-uglify");
var del = require("del");
var minifyCSS = require("gulp-minify-css");
var copy = require("gulp-copy");
var bower = require("gulp-bower");
var sourcemaps = require("gulp-sourcemaps");

var path = {
    src: "bower_components/",
    lib: "lib/"
}

var config = {
    jquerysrc: [
        path.src + "jquery/dist/jquery.js",
        path.src + "jquery-validation/dist/jquery.validate.js",
        path.src + "jquery-validation/dist/jquery.validate.unobtrusive.js"
    ],
    jquerybundle: path.lib + "jquery-bundle.js",
    ngsrc: [
        path.src + "angular/angular.js",
         path.src + "angular-route/angular-route.js",
         path.src + "angular-resource/angular-resource.js"
    ],
    ngbundle: path.lib + "ng-bundle.js",

    //JavaScript files that will be combined into a Bootstrap bundle
    bootstrapsrc: [
        path.src + "bootstrap/dist/js/bootstrap.js"
    ],
    bootstrapbundle: path.lib + "bootstrap-bundle.js"
}

// Synchronously delete the output script file(s)
gulp.task("clean-scripts", function (cb) {
    del(["lib","dist"], cb);
});

//Create a jquery bundled file
gulp.task("jquery-bundle", ["clean-scripts", "bower-restore"], function () {
    return gulp.src(config.jquerysrc)
     .pipe(concat("jquery-bundle.js"))
     .pipe(gulp.dest("lib"));
});

//Create a angular bundled file
gulp.task("ng-bundle", ["clean-scripts", "bower-restore"], function () {
    return gulp.src(config.ngsrc)
     .pipe(concat("ng-bundle.js"))
     .pipe(gulp.dest("lib"));
});

//Create a bootstrap bundled file
gulp.task("bootstrap-bundle", ["clean-scripts", "bower-restore"], function     () {
    return gulp.src(config.bootstrapsrc)
     .pipe(concat("bootstrap-bundle.js"))
     .pipe(gulp.dest("lib"));
});


// Combine and the vendor files from bower into bundles (output to the Scripts folder)
gulp.task("bundle-scripts", ["jquery-bundle", "ng-bundle", "bootstrap-bundle"], function () {

});

//Restore all bower packages
gulp.task("bower-restore", function () {
    return bower();
});

//build lib scripts
gulp.task("compile-lib", ["bundle-scripts"], function () {
    return gulp.src("lib/*.js")
        .pipe(sourcemaps.init())
        .pipe(concat("compiled-bundle.js"))
        .pipe(gulp.dest("dist"))
        .pipe(rename("compiled-bundle.min.js"))
        .pipe(uglify())
        .pipe(sourcemaps.write("./"))
        .pipe(gulp.dest("dist"));
});

C++ style cast from unsigned char * to const char *

Try reinterpret_cast

unsigned char *foo();
std::string str;
str.append(reinterpret_cast<const char*>(foo()));

Print a list of space-separated elements in Python 3

list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
    print(i, end=', ')
print(list[-1])

do for loops really take that much longer to run?

was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:

spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
    print(i, end=', ')
print('and ' + spam[-1])

Opening Chrome From Command Line

open command prompt and type

cd\ (enter)

then type

start chrome "www.google.com"(any website you require)

Gradients on UIView and UILabels On iPhone

You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).

How To limit the number of characters in JTextField?

If you wanna have everything into one only piece of code, then you can mix tim's answer with the example's approach found on the API for JTextField, and you'll get something like this:

public class JTextFieldLimit extends JTextField {
    private int limit;

    public JTextFieldLimit(int limit) {
        super();
        this.limit = limit;
    }

    @Override
    protected Document createDefaultModel() {
        return new LimitDocument();
    }

    private class LimitDocument extends PlainDocument {

        @Override
        public void insertString( int offset, String  str, AttributeSet attr ) throws BadLocationException {
            if (str == null) return;

            if ((getLength() + str.length()) <= limit) {
                super.insertString(offset, str, attr);
            }
        }       

    }

}

Then there is no need to add a Document to the JTextFieldLimit due to JTextFieldLimit already have the functionality inside.

Make a link open a new window (not tab)

I know that its bit old Q but if u get here by searching a solution so i got a nice one via jquery

  jQuery('a[target^="_new"]').click(function() {
    var width = window.innerWidth * 0.66 ;
    // define the height in
    var height = width * window.innerHeight / window.innerWidth ;
    // Ratio the hight to the width as the user screen ratio
    window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));

});

it will open all the <a target="_new"> in a new window

EDIT:

1st, I did some little changes in the original code now it open the new window perfectly followed the user screen ratio (for landscape desktops)

but, I would like to recommend you to use the following code that open the link in new tab if you in mobile (thanks to zvona answer in other question):

jQuery('a[target^="_new"]').click(function() {
    return openWindow(this.href);
}


function openWindow(url) {

    if (window.innerWidth <= 640) {
        // if width is smaller then 640px, create a temporary a elm that will open the link in new tab
        var a = document.createElement('a');
        a.setAttribute("href", url);
        a.setAttribute("target", "_blank");

        var dispatch = document.createEvent("HTMLEvents");
        dispatch.initEvent("click", true, true);

        a.dispatchEvent(dispatch);
    }
    else {
        var width = window.innerWidth * 0.66 ;
        // define the height in
        var height = width * window.innerHeight / window.innerWidth ;
        // Ratio the hight to the width as the user screen ratio
        window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
    }
    return false;
}

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

You can use RawGit:
https://rawgit.com/necolas/css3-social-signin-buttons/master/index.html

It works better (at the time of this writing) than http://htmlpreview.github.com/, serving files with proper Content-Type headers. Additionally, it also provides CDN URL for use in production.

Accessing Object Memory Address

I know this is an old question but if you're still programming, in python 3 these days... I have actually found that if it is a string, then there is a really easy way to do this:

>>> spam.upper
<built-in method upper of str object at 0x1042e4830>
>>> spam.upper()
'YO I NEED HELP!'
>>> id(spam)
4365109296

string conversion does not affect location in memory either:

>>> spam = {437 : 'passphrase'}
>>> object.__repr__(spam)
'<dict object at 0x1043313f0>'
>>> str(spam)
"{437: 'passphrase'}"
>>> object.__repr__(spam)
'<dict object at 0x1043313f0>'

Removing ul indentation with CSS

-webkit-padding-start: 0;

will remove padding added by webkit engine

How to easily initialize a list of Tuples?

Why do like tuples? It's like anonymous types: no names. Can not understand structure of data.

I like classic classes

class FoodItem
{
     public int Position { get; set; }
     public string Name { get; set; }
}

List<FoodItem> list = new List<FoodItem>
{
     new FoodItem { Position = 1, Name = "apple" },
     new FoodItem { Position = 2, Name = "kiwi" }
};

The 'Access-Control-Allow-Origin' header contains multiple values

Add to Register WebApiConfig

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Or web.config

<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>  
</httpProtocol>

BUT NOT BOTH

How to take MySQL database backup using MySQL Workbench?

The Data Export function in MySQL Workbench allows 2 of the 3 ways. There's a checkbox Skip Table Data (no-data) on the export page which allows to either dump with or without data. Just dumping the data without meta data is not supported.

How to check if anonymous object has a method?

What do you mean by an "anonymous object?" myObj is not anonymous since you've assigned an object literal to a variable. You can just test this:

if (typeof myObj.prop2 === 'function')
{
    // do whatever
}

Check if a varchar is a number (TSQL)

I ran into the need to allow decimal values, so I used not Value like '%[^0-9.]%'

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

You can use tee to write to the file without the need for flushing.

/homedir/MyScript 2>&1 | tee some_log.log > /dev/null

How do I download a file using VBA (without Internet Explorer)

A modified version of above to make it more dynamic.

Public Function DownloadFileB(ByVal URL As String, ByVal DownloadPath As String, ByRef Username As String, ByRef Password, Optional Overwrite As Boolean = True) As Boolean
    On Error GoTo Failed

    Dim WinHttpReq          As Object: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")

    WinHttpReq.Open "GET", URL, False, Username, Password
    WinHttpReq.send

    If WinHttpReq.Status = 200 Then
        Dim oStream         As Object: Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.responseBody
        oStream.SaveToFile DownloadPath, Abs(CInt(Overwrite)) + 1
        oStream.Close
        DownloadFileB = Len(Dir(DownloadPath)) > 0
        Exit Function
    End If

Failed:
    DownloadFileB = False
End Function

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

How to define custom exception class in Java, the easiest way?

Exception class has two constructors

  • public Exception() -- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.
  • public Exception(String s) -- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

You can try:

Open sql file by text editor find and replace all

utf8mb4 to utf8

Import again.

Twitter API returns error 215, Bad Authentication Data

Here first every one need to use oauth2/token api then use followers/list api.
Other wise you will get this error. Because followers/list api requires Authentication.

In swift (for mobile app) me also got the same problem.

If you want to know the api's and it's parameters follow this link , Get twitter friends list in swift?

Add and Remove Views in Android Dynamically?

//MainActivity :





 package com.edittext.demo;
    import android.app.Activity;
    import android.os.Bundle;
    import android.text.TextUtils;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.Toast;

    public class MainActivity extends Activity {

        private EditText edtText;
        private LinearLayout LinearMain;
        private Button btnAdd, btnClear;
        private int no;

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

            edtText = (EditText)findViewById(R.id.edtMain);
            btnAdd = (Button)findViewById(R.id.btnAdd);
            btnClear = (Button)findViewById(R.id.btnClear);
            LinearMain = (LinearLayout)findViewById(R.id.LinearMain);

            btnAdd.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(edtText.getText().toString().trim())) {
                        no = Integer.parseInt(edtText.getText().toString());
                        CreateEdittext();
                    }else {
                        Toast.makeText(MainActivity.this, "Please entere value", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            btnClear.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    LinearMain.removeAllViews();
                    edtText.setText("");
                }
            });

            /*edtText.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,int after) {
                }
                @Override
                public void afterTextChanged(Editable s) {
                }
            });*/

        }

        protected void CreateEdittext() {
            final EditText[] text = new EditText[no];
            final Button[] add = new Button[no];
            final LinearLayout[] LinearChild = new LinearLayout[no];
            LinearMain.removeAllViews();

            for (int i = 0; i < no; i++){

                View view = getLayoutInflater().inflate(R.layout.edit_text, LinearMain,false);
                text[i] = (EditText)view.findViewById(R.id.edtText);
                text[i].setId(i);
                text[i].setTag(""+i);

                add[i] = (Button)view.findViewById(R.id.btnAdd);
                add[i].setId(i);
                add[i].setTag(""+i);

                LinearChild[i] = (LinearLayout)view.findViewById(R.id.child_linear);
                LinearChild[i].setId(i);
                LinearChild[i].setTag(""+i);

                LinearMain.addView(view);

                add[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //Toast.makeText(MainActivity.this, "add text "+v.getTag(), Toast.LENGTH_SHORT).show();
                        int a = Integer.parseInt(text[v.getId()].getText().toString());
                        LinearChild[v.getId()].removeAllViews();
                        for (int k = 0; k < a; k++){

                            EditText text = (EditText) new EditText(MainActivity.this);
                            text.setId(k);
                            text.setTag(""+k);

                            LinearChild[v.getId()].addView(text);
                        }
                    }
                });
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

    }

// Now add xml main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/edtMain"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_weight="1"
        android:ems="10"
        android:hint="Enter value" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="Add" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:text="Clear" />
</LinearLayout>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp" >

    <LinearLayout
        android:id="@+id/LinearMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>
</ScrollView>

// now add view xml file..

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/edtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:ems="10" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="Add" />
</LinearLayout>

<LinearLayout
    android:id="@+id/child_linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="5dp"
    android:orientation="vertical" >
</LinearLayout>

Can I change the color of Font Awesome's icon color?

Try this:

<i class="icon-cog text-red">
<i class="icon-cog text-blue">
<i class="icon-cog text-yellow">

force css grid container to fill full screen of device

Two important CSS properties to set for full height pages are these:

  1. Allow the body to grow as high as the content in it requires.

    html { height: 100%; }
    
  2. Force the body not to get any smaller than then window height.

    body { min-height: 100%; }
    

What you do with your gird is irrelevant as long as you use fractions or percentages you should be safe in all cases.

Have a look at this common dashboard layout.

How can I debug a HTTP POST in Chrome?

It has a tricky situation: If you submit a post form, then Chrome will open a new tab to send the request. It's right until now, but if it triggers an event to download file(s), this tab will close immediately so that you cannot capture this request in the Dev Tool.

Solution: Before submitting the post form, you need to cut off your network, which makes the request cannot send successfully so that the tab will not be closed. And then you can capture the request message in the Chrome Devtool(Refreshing the new tab if necessary)

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I have worked alot with msaccess vba. I think you are looking for MID function

example

    dim myReturn as string
    myreturn = mid("bonjour tout le monde",9,4)

will give you back the value "tout"

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution

  1. Right click on installer(.exe)
  2. Select properties option.
  3. Click on checkbox to check Unblock at the bottom of Properties.

This solution work for Heroku CLI (heroku-x64) installer(.exe)

How can I upload fresh code at github?

You can create GitHub repositories via the command line using their Repositories API (http://develop.github.com/p/repo.html)

Check Creating github repositories with command line | Do it yourself Android for example usage.

A simple algorithm for polygon intersection

I have no very simple solution, but here are the main steps for the real algorithm:

  1. Do a custom double linked list for the polygon vertices and edges. Using std::list won't do because you must swap next and previous pointers/offsets yourself for a special operation on the nodes. This is the only way to have simple code, and this will give good performance.
  2. Find the intersection points by comparing each pair of edges. Note that comparing each pair of edge will give O(N²) time, but improving the algorithm to O(N·logN) will be easy afterwards. For some pair of edges (say a?b and c?d), the intersection point is found by using the parameter (from 0 to 1) on edge a?b, which is given by t?=d0/(d0-d1), where d0 is (c-a)×(b-a) and d1 is (d-a)×(b-a). × is the 2D cross product such as p×q=p?·q?-p?·q?. After having found t?, finding the intersection point is using it as a linear interpolation parameter on segment a?b: P=a+t?(b-a)
  3. Split each edge adding vertices (and nodes in your linked list) where the segments intersect.
  4. Then you must cross the nodes at the intersection points. This is the operation for which you needed to do a custom double linked list. You must swap some pair of next pointers (and update the previous pointers accordingly).

Then you have the raw result of the polygon intersection resolving algorithm. Normally, you will want to select some region according to the winding number of each region. Search for polygon winding number for an explanation on this.

If you want to make a O(N·logN) algorithm out of this O(N²) one, you must do exactly the same thing except that you do it inside of a line sweep algorithm. Look for Bentley Ottman algorithm. The inner algorithm will be the same, with the only difference that you will have a reduced number of edges to compare, inside of the loop.

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

Import .bak file to a database in SQL server

On Microsoft SQL Server Management Studio 2019:

enter image description here

On Restore Database window:

  1. Choose Device

  2. Choose Add and pick target file

  3. OK to confirm

  4. OK to confirm restore

enter image description here

JAVA_HOME and PATH are set but java -version still shows the old one

In Linux Mint 18 Cinnamon be sure to check /etc/profile.d/jdk_home.sh I renamed this file to jdk_home.sh.old and now my path does not keep getting overridden and I can call java -version and see Java 9 as expected. Even though I correctly selected Java 9 in update-aternatives --config java this jdk_home.sh file kept overriding the $PATH on boot-up.

Spring Boot application as a Service

I just got around to doing this myself, so the following is where I am so far in terms of a CentOS init.d service controller script. It's working quite nicely so far, but I'm no leet Bash hacker, so I'm sure there's room for improvement, so thoughts on improving it are welcome.

First of all, I have a short config script /data/svcmgmt/conf/my-spring-boot-api.sh for each service, which sets up environment variables.

#!/bin/bash
export JAVA_HOME=/opt/jdk1.8.0_05/jre
export APP_HOME=/data/apps/my-spring-boot-api
export APP_NAME=my-spring-boot-api
export APP_PORT=40001

I'm using CentOS, so to ensure that my services are started after a server restart, I have a service control script in /etc/init.d/my-spring-boot-api:

#!/bin/bash
# description: my-spring-boot-api start stop restart
# processname: my-spring-boot-api
# chkconfig: 234 20 80

. /data/svcmgmt/conf/my-spring-boot-api.sh

/data/svcmgmt/bin/spring-boot-service.sh $1

exit 0

As you can see, that calls the initial config script to set up environment variables and then calls a shared script which I use for restarting all of my Spring Boot services. That shared script is where the meat of it all can be found:

#!/bin/bash

echo "Service [$APP_NAME] - [$1]"

echo "    JAVA_HOME=$JAVA_HOME"
echo "    APP_HOME=$APP_HOME"
echo "    APP_NAME=$APP_NAME"
echo "    APP_PORT=$APP_PORT"

function start {
    if pkill -0 -f $APP_NAME.jar > /dev/null 2>&1
    then
        echo "Service [$APP_NAME] is already running. Ignoring startup request."
        exit 1
    fi
    echo "Starting application..."
    nohup $JAVA_HOME/bin/java -jar $APP_HOME/$APP_NAME.jar \
        --spring.config.location=file:$APP_HOME/config/   \
        < /dev/null > $APP_HOME/logs/app.log 2>&1 &
}

function stop {
    if ! pkill -0 -f $APP_NAME.jar > /dev/null 2>&1
    then
        echo "Service [$APP_NAME] is not running. Ignoring shutdown request."
        exit 1
    fi

    # First, we will try to trigger a controlled shutdown using 
    # spring-boot-actuator
    curl -X POST http://localhost:$APP_PORT/shutdown < /dev/null > /dev/null 2>&1

    # Wait until the server process has shut down
    attempts=0
    while pkill -0 -f $APP_NAME.jar > /dev/null 2>&1
    do
        attempts=$[$attempts + 1]
        if [ $attempts -gt 5 ]
        then
            # We have waited too long. Kill it.
            pkill -f $APP_NAME.jar > /dev/null 2>&1
        fi
        sleep 1s
    done
}

case $1 in
start)
    start
;;
stop)
    stop
;;
restart)
    stop
    start
;;
esac
exit 0

When stopping, it will attempt to use Spring Boot Actuator to perform a controlled shutdown. However, in case Actuator is not configured or fails to shut down within a reasonable time frame (I give it 5 seconds, which is a bit short really), the process will be killed.

Also, the script makes the assumption that the java process running the appllication will be the only one with "my-spring-boot-api.jar" in the text of the process details. This is a safe assumption in my environment and means that I don't need to keep track of PIDs.

ng-mouseover and leave to toggle item using mouse in angularjs

Here is example with only CSS for that. In example I'm using SASS and SLIM.

https://codepen.io/Darex1991/pen/zBxPxe

Slim:

a.btn.btn--joined-state
  span joined
  span leave

SASS:

=animate($property...)
  @each $vendor in ('-webkit-', '')
    #{$vendor}transition-property: $property
    #{$vendor}transition-duration: .3s
    #{$vendor}transition-timing-function: ease-in

=visible
  +animate(opacity, max-height, visibility)
  max-height: 150px
  opacity: 1
  visibility: visible

=invisible
  +animate(opacity, max-height, visibility)
  max-height: 0
  opacity: 0
  visibility: hidden

=transform($var)
  @each $vendor in ('-webkit-', '-ms-', '')
    #{$vendor}transform: $var

.btn
  border: 1px solid blue

  &--joined-state
    position: relative
    span
      +animate(opacity)

    span:last-of-type
      +invisible
      +transform(translateX(-50%))
      position: absolute
      left: 50%

    &:hover
      span:first-of-type
        +invisible
      span:last-of-type
        +visible
        border-color: blue

Add custom headers to WebView resource requests - android

Use this:

webView.getSettings().setUserAgentString("User-Agent");

Is there a better jQuery solution to this.form.submit();?

I think what you are looking for is something like this:

$(field).closest("form").submit();

For example, to handle the onchange event, you would have this:

$(select your fields here).change(function() {
    $(this).closest("form").submit();
});

If, for some reason you aren't using jQuery 1.3 or above, you can call parents instead of closest.

What operator is <> in VBA

It means not equal to, as the others said..

I just wanted to say that I read that as "greater than or lesser than".

e.g.

let x = 12

if x <> 0 then
    //code

In this case 'x' is greater than (that's the '>' symbol) 0.

Hope this helps. :D

Round up value to nearest whole number in SQL UPDATE

If you want to round off then use the round function. Use ceiling function when you want to get the smallest integer just greater than your argument.

For ex: select round(843.4923423423,0) from dual gives you 843 and

select round(843.6923423423,0) from dual gives you 844

What is the difference between utf8mb4 and utf8 charsets in MySQL?

Taken from the MySQL 8.0 Reference Manual:

  • utf8mb4: A UTF-8 encoding of the Unicode character set using one to four bytes per character.

  • utf8mb3: A UTF-8 encoding of the Unicode character set using one to three bytes per character.

In MySQL utf8 is currently an alias for utf8mb3 which is deprecated and will be removed in a future MySQL release. At that point utf8 will become a reference to utf8mb4.

So regardless of this alias, you can consciously set yourself an utf8mb4 encoding.

To complete the answer, I'd like to add the @WilliamEntriken's comment below (also taken from the manual):

To avoid ambiguity about the meaning of utf8, consider specifying utf8mb4 explicitly for character set references instead of utf8.

Execution failed app:processDebugResources Android Studio

If it is not your build tools, check your strings, styles, attrs, ... XML files and ensure they are correct. For example a string with an empty name-attribute

<string name="">Test"</string>

or a previously undefined attr without a format specified (attrs.xml):

<declare-styleable name="MediaGridView">
    <attr name="allowVideo"/>
</declare-styleable>

How to outline text in HTML / CSS

from: Outline effect to text

.strokeme
{
    color: white;
    text-shadow:
    -1px -1px 0 #000,
    1px -1px 0 #000,
    -1px 1px 0 #000,
    1px 1px 0 #000;  
}

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

Table-level backup

You probably have two options, as SQL Server doesn't support table backups. Both would start with scripting the table creation. Then you can either use the Script Table - INSERT option which will generate a lot of insert statements, or you can use Integration services (DTS with 2000) or similar to export the data as CSV or similar.

Make error: missing separator

In my case, I was actually missing a tab in between ifeq and the command on the next line. No spaces were there to begin with.

ifeq ($(wildcard $DIR_FILE), )
cd $FOLDER; cp -f $DIR_FILE.tpl $DIR_FILE.xs;
endif

Should have been:

ifeq ($(wildcard $DIR_FILE), )
<tab>cd $FOLDER; cp -f $DIR_FILE.tpl $DIR_FILE.xs;
endif

Note the <tab> is an actual tab character

Pass a datetime from javascript to c# (Controller)

The following format should work:

$.ajax({
    type: "POST",
    url: "@Url.Action("refresh", "group")",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ 
        myDate: '2011-04-02 17:15:45'
    }),
    success: function (result) {
        //do something
    },
    error: function (req, status, error) {
        //error                        
    }
});

What is Inversion of Control?

It seems that the most confusing thing about "IoC" the acronym and the name for which it stands is that it's too glamorous of a name - almost a noise name.

Do we really need a name by which to describe the difference between procedural and event driven programming? OK, if we need to, but do we need to pick a brand new "bigger than life" name that confuses more than it solves?

apache and httpd running but I can't see my website

There are several possibilities.

  • firewall, iptables configuration
  • apache listen address / port

More information is needed about your configuration. What distro are you using? Can you connect via 127.0.0.1?

If the issue is with the firewall/iptables, you can add the following lines to /etc/sysconfig/iptables:

-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

(Second line is only needed for https)

Make sure this is above any lines that would globally restrict access, like the following:

-A INPUT -j REJECT --reject-with icmp-host-prohibited

Tested on CentOS 6.3

And finally

service iptables restart

CSS horizontal centering of a fixed div?

Here's another two-div solution. Tried to keep it concise and not hardcoded. First, the expectable html:

<div id="outer">
  <div id="inner">
    content
  </div>
</div>

The principle behind the following css is to position some side of "outer", then use the fact that it assumes the size of "inner" to relatively shift the latter.

#outer {
  position: fixed;
  left: 50%;          // % of window
}
#inner {
  position: relative;
  left: -50%;         // % of outer (which auto-matches inner width)
}

This approach is similar to Quentin's, but inner can be of variable size.

Body set to overflow-y:hidden but page is still scrollable in Chrome

What works for me on /FF and /Chrome:

body {

    position: fixed;
    width: 100%;
    height: 100%;

}

overflow: hidden just disables display of the scrollbars. (But you can put it in there if you like to).

There is one drawback I found: If you use this method on a page which you want only temporarily to stop scrolling, setting position: fixed will scroll it to the top. This is because position: fixed uses absolute positions which are currently set to 0/0.

This can be repaired e.g. with jQuery:

var lastTop;

function stopScrolling() {
    lastTop = $(window).scrollTop();      
    $('body').addClass( 'noscroll' )          
         .css( { top: -lastTop } )        
         ;            
}

function continueScrolling() {                    

    $('body').removeClass( 'noscroll' );      
    $(window).scrollTop( lastTop );       
}                                         

Is there a way to reset IIS 7.5 to factory settings?

There is one way that I have used my self. Go to Control Panel\Programs\Turn Windows features on or off then uninstall IIS and all of its components completely. I restart windows but I'm not sure if it's required or not. Then install it again from the same path.

Angular2, what is the correct way to disable an anchor element?

You can try this

<a [attr.disabled]="someCondition ? true: null"></a>

Fastest way to serialize and deserialize .NET objects

Having an interest in this, I decided to test the suggested methods with the closest "apples to apples" test I could. I wrote a Console app, with the following code:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace SerializationTests
{
    class Program
    {
        static void Main(string[] args)
        {
            var count = 100000;
            var rnd = new Random(DateTime.UtcNow.GetHashCode());
            Console.WriteLine("Generating {0} arrays of data...", count);
            var arrays = new List<int[]>();
            for (int i = 0; i < count; i++)
            {
                var elements = rnd.Next(1, 100);
                var array = new int[elements];
                for (int j = 0; j < elements; j++)
                {
                    array[j] = rnd.Next();
                }   
                arrays.Add(array);
            }
            Console.WriteLine("Test data generated.");
            var stopWatch = new Stopwatch();

            Console.WriteLine("Testing BinarySerializer...");
            var binarySerializer = new BinarySerializer();
            var binarySerialized = new List<byte[]>();
            var binaryDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                binarySerialized.Add(binarySerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("BinaryFormatter: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in binarySerialized)
            {
                binaryDeserialized.Add(binarySerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("BinaryFormatter: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);


            Console.WriteLine();
            Console.WriteLine("Testing ProtoBuf serializer...");
            var protobufSerializer = new ProtoBufSerializer();
            var protobufSerialized = new List<byte[]>();
            var protobufDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                protobufSerialized.Add(protobufSerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("ProtoBuf: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in protobufSerialized)
            {
                protobufDeserialized.Add(protobufSerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("ProtoBuf: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            Console.WriteLine();
            Console.WriteLine("Testing NetSerializer serializer...");
            var netSerializerSerializer = new ProtoBufSerializer();
            var netSerializerSerialized = new List<byte[]>();
            var netSerializerDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                netSerializerSerialized.Add(netSerializerSerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("NetSerializer: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in netSerializerSerialized)
            {
                netSerializerDeserialized.Add(netSerializerSerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("NetSerializer: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            Console.WriteLine("Press any key to end.");
            Console.ReadKey();
        }

        public class BinarySerializer
        {
            private static readonly BinaryFormatter Formatter = new BinaryFormatter();

            public byte[] Serialize(object toSerialize)
            {
                using (var stream = new MemoryStream())
                {
                    Formatter.Serialize(stream, toSerialize);
                    return stream.ToArray();
                }
            }

            public T Deserialize<T>(byte[] serialized)
            {
                using (var stream = new MemoryStream(serialized))
                {
                    var result = (T)Formatter.Deserialize(stream);
                    return result;
                }
            }
        }

        public class ProtoBufSerializer
        {
            public byte[] Serialize(object toSerialize)
            {
                using (var stream = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize(stream, toSerialize);
                    return stream.ToArray();
                }
            }

            public T Deserialize<T>(byte[] serialized)
            {
                using (var stream = new MemoryStream(serialized))
                {
                    var result = ProtoBuf.Serializer.Deserialize<T>(stream);
                    return result;
                }
            }
        }

        public class NetSerializer
        {
            private static readonly NetSerializer Serializer = new NetSerializer();
            public byte[] Serialize(object toSerialize)
            {
                return Serializer.Serialize(toSerialize);
            }

            public T Deserialize<T>(byte[] serialized)
            {
                return Serializer.Deserialize<T>(serialized);
            }
        }
    }
}

The results surprised me; they were consistent when run multiple times:

Generating 100000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 336.8392ms.
BinaryFormatter: Deserializing took 208.7527ms.

Testing ProtoBuf serializer...
ProtoBuf: Serializing took 2284.3827ms.
ProtoBuf: Deserializing took 2201.8072ms.

Testing NetSerializer serializer...
NetSerializer: Serializing took 2139.5424ms.
NetSerializer: Deserializing took 2113.7296ms.
Press any key to end.

Collecting these results, I decided to see if ProtoBuf or NetSerializer performed better with larger objects. I changed the collection count to 10,000 objects, but increased the size of the arrays to 1-10,000 instead of 1-100. The results seemed even more definitive:

Generating 10000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 285.8356ms.
BinaryFormatter: Deserializing took 206.0906ms.

Testing ProtoBuf serializer...
ProtoBuf: Serializing took 10693.3848ms.
ProtoBuf: Deserializing took 5988.5993ms.

Testing NetSerializer serializer...
NetSerializer: Serializing took 9017.5785ms.
NetSerializer: Deserializing took 5978.7203ms.
Press any key to end.

My conclusion, therefore, is: there may be cases where ProtoBuf and NetSerializer are well-suited to, but in terms of raw performance for at least relatively simple objects... BinaryFormatter is significantly more performant, by at least an order of magnitude.

YMMV.

SQL Insert into table only if record doesn't exist

Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id and date.

ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);

Then when inserting a record add the condition when a conflict is encountered:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value

This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.

Types in MySQL: BigInt(20) vs Int(20)

The number in parentheses in a type declaration is display width, which is unrelated to the range of values that can be stored in a data type. Just because you can declare Int(20) does not mean you can store values up to 10^20 in it:

[...] This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. ...

The display width does not constrain the range of values that can be stored in the column, nor the number of digits that are displayed for values having a width exceeding that specified for the column. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range allowed by three characters are displayed using more than three characters.

For a list of the maximum and minimum values that can be stored in each MySQL datatype, see here.

Webdriver Screenshot

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\NewFolder\\screenshot1.jpg"));

How to deal with http status codes other than 200 in Angular 2

Include required imports and you can make ur decision in handleError method Error status will give the error code

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model'; 

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side or network error occurred. Handle it accordingly.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend returned an unsuccessful response code.
  // The response body may contain clues as to what went wrong,
  console.error(
    `Backend returned code ${error.status}, ` +
    `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
  'Something bad happened; please try again later.');
  };

  getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
  catchError(this.handleError)
);
  }

How to check if a text field is empty or not in swift

Better and more beautiful use

 @IBAction func Button(sender: AnyObject) {
    if textField1.text.isEmpty || textField2.text.isEmpty {

    }
}

Java Minimum and Maximum values in Array

your maximum, minimum method is right

but you don't print int to console!

and... maybe better location change (maximum, minimum) methods

now (maximum, minimum) methods in the roop. it is need not.. just need one call

i suggest change this code

    for (int i = 0 ; i < array.length; i++ ) {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
       break;
       array[i] = next;
}
System.out.println("max Value : " + getMaxValue(array));
System.out.println("min Value : " + getMinValue(array));
System.out.println("These are the numbers you have entered.");
printArray(array);

WCF timeout exception detailed investigation

Looks like this exception message is quite generic and can be received due to a variety of reasons. We ran into this while deploying the client on Windows 8.1 machines. Our WCF client runs inside of a windows service and continuously polls the WCF service. The windows service runs under a non-admin user. The issue was fixed by setting the clientCredentialType to "Windows" in the WCF configuration to allow the authentication to pass-through, as in the following:

      <security mode="None">
        <transport clientCredentialType="Windows" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

The Microsoft way is this:

MSDN: How to determine Which .NET Framework Versions Are Installed (which directs you to the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\...)

If you want foolproof that's another thing. I wouldn't worry about an xcopy of the framework folder. If someone did that I would consider the computer broken.

The most foolproof way would be to write a small program that uses each version of .NET and the libraries that you care about and run them.

For a no install method, PowerBasic is an excellent tool. It creates small no runtime required exe's. It could automate the checks described in the MS KB article above.

HTML5 form required attribute. Set custom validation message?

Can be easily handled by just putting 'title' with the field:

<input type="text" id="username" required title="This field can not be empty"  />

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

You don't need to configure anything. Just make sure that the requests map to your PHP file and use requests with path info. For example, if you have in the root a file named handler.php with this content:

<?php

var_dump($_SERVER['REQUEST_METHOD']);
var_dump($_SERVER['REQUEST_URI']);
var_dump($_SERVER['PATH_INFO']);

if (($stream = fopen('php://input', "r")) !== FALSE)
    var_dump(stream_get_contents($stream));

The following HTTP request would work:

Established connection with 127.0.0.1 on port 81
PUT /handler.php/bla/foo HTTP/1.1
Host: localhost:81
Content-length: 5
 
boo
HTTP/1.1 200 OK
Date: Sat, 29 May 2010 16:00:20 GMT
Server: Apache/2.2.13 (Win32) PHP/5.3.0
X-Powered-By: PHP/5.3.0
Content-Length: 89
Content-Type: text/html
 
string(3) "PUT"
string(20) "/handler.php/bla/foo"
string(8) "/bla/foo"
string(5) "boo
"
Connection closed remotely.

You can hide the "php" extension with MultiViews or you can make URLs completely logical with mod_rewrite.

See also the documentation for the AcceptPathInfo directive and this question on how to make PHP not parse POST data when enctype is multipart/form-data.

How to take off line numbers in Vi?

set number set nonumber

DO work inside .vimrc and make sure you DO NOT precede commands in .vimrc with :

vue.js 'document.getElementById' shorthand

Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.

This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.

Can you set a border opacity in CSS?

Other answers deal with the technical aspect of the border-opacity issue, while I'd like to present a hack(pure CSS and HTML only). Basically create a container div, having a border div and then the content div.

<div class="container">
  <div class="border-box"></div>
  <div class="content-box"></div>
</div>

And then the CSS:(set content border to none, take care of positioning such that border thickness is accounted for)

.container {
  width: 20vw;
  height: 20vw;
  position: relative;
}
.border-box {
  width: 100%;
  height: 100%;
  border: 5px solid black;
  position: absolute;
  opacity: 0.5;
}
.content-box {
  width: 100%;
  height: 100%;
  border: none;
  background: green;
  top: 5px;
  left: 5px;
  position: absolute;
}