Programs & Examples On #States

onSaveInstanceState () and onRestoreInstanceState ()

The main thing is that if you don't store in onSaveInstanceState() then onRestoreInstanceState() will not be called. This is the main difference between restoreInstanceState() and onCreate(). Make sure you really store something. Most likely this is your problem.

Linux Process States

Yes, tasks waiting for IO are blocked, and other tasks get executed. Selecting the next task is done by the Linux scheduler.

How to convert an ArrayList containing Integers to primitive int array?

It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.

Just go with Apache Commons

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

While working with MVC and having lots of if statements where i only care about either true or false, and printing null, or string.Empty in the other case, I came up with:

public static TResult WhenTrue<TResult>(this Boolean value, Func<TResult> expression)
{
    return value ? expression() : default(TResult);
}

public static TResult WhenTrue<TResult>(this Boolean value, TResult content)
{
    return value ? content : default(TResult);
}

public static TResult WhenFalse<TResult>(this Boolean value, Func<TResult> expression)
{
    return !value ? expression() : default(TResult);
}

public static TResult WhenFalse<TResult>(this Boolean value, TResult content)
{
    return !value ? content : default(TResult);
}

It allows me to change <%= (someBool) ? "print y" : string.Empty %> into <%= someBool.WhenTrue("print y") %> .

I only use it in my Views where I mix code and HTML, in code files writing the "longer" version is more clear IMHO.

BLOB to String, SQL Server

CREATE OR REPLACE FUNCTION HASTANE.getXXXXX(p_rowid in rowid) return VARCHAR2
  as
          l_data long;
  begin
         select XXXXXX into l_data from XXXXX where rowid = p_rowid;
         return substr( l_data, 1, 4000);
  end getlabrapor1;

What is the difference between re.search and re.match?

Much shorter:

  • search scans through the whole string.

  • match scans only the beginning of the string.

Following Ex says it:

>>> a = "123abc"
>>> re.match("[a-z]+",a)
None
>>> re.search("[a-z]+",a)
abc

Disabling browser caching for all browsers from ASP.NET

There are two approaches that I know of. The first is to tell the browser not to cache the page. Setting the Response to no cache takes care of that, however as you suspect the browser will often ignore this directive. The other approach is to set the date time of your response to a point in the future. I believe all browsers will correct this to the current time when they add the page to the cache, but it will show the page as newer when the comparison is made. I believe there may be some cases where a comparison is not made. I am not sure of the details and they change with each new browser release. Final note I have had better luck with pages that "refresh" themselves (another response directive). The refresh seems less likely to come from the cache.

Hope that helps.

PHP cURL GET request and request's body

  <?php
  $post = ['batch_id'=> "2"];
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
  $response = curl_exec($ch);
  $result = json_decode($response);
  curl_close($ch); // Close the connection
  $new=   $result->status;
  if( $new =="1")
  {
    echo "<script>alert('Student list')</script>";
  }
  else 
  {
    echo "<script>alert('Not Removed')</script>";
  }

  ?>

MySql : Grant read only options?

Note for MySQL 8 it's different

You need to do it in two steps:

CREATE USER 'readonly_user'@'localhost' IDENTIFIED BY 'some_strong_password';
GRANT SELECT, SHOW VIEW ON *.* TO 'readonly_user'@'localhost';
flush privileges;

Writing unit tests in Python: How do I start?

unittest comes with the standard library, but I would recomend you nosetests.

"nose extends unittest to make testing easier."

I would also recomend you pylint

"analyzes Python source code looking for bugs and signs of poor quality."

Is it possible to install another version of Python to Virtualenv?

I have not found suitable answer, so here goes my take, which builds upon @toszter answer, but does not use system Python (and you may know, it is not always good idea to install setuptools and virtualenv at system level when dealing with many Python configurations):

#!/bin/sh

mkdir python_ve
cd python_ve

MYROOT=`pwd`
mkdir env pyenv dep

cd ${MYROOT}/dep
wget https://pypi.python.org/packages/source/s/setuptools/setuptools-15.2.tar.gz#md5=a9028a9794fc7ae02320d32e2d7e12ee
wget https://raw.github.com/pypa/virtualenv/master/virtualenv.py
wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz
xz -d Python-2.7.9.tar.xz

cd ${MYROOT}/pyenv
tar xf ../dep/Python-2.7.9.tar
cd Python-2.7.9
./configure --prefix=${MYROOT}/pyenv && make -j 4 && make install

cd ${MYROOT}/pyenv

tar xzf ../dep/setuptools-15.2.tar.gz

cd ${MYROOT}

pyenv/bin/python dep/virtualenv.py --no-setuptools --python=${MYROOT}/pyenv/bin/python --verbose env
env/bin/python pyenv/setuptools-15.2/setup.py install
env/bin/easy_install pip

echo "virtualenv in ${MYROOT}/env"

The trick of breaking chicken-egg problem here is to make virtualenv without setuptools first, because it otherwise fails (pip can not be found). It may be possible to install pip / wheel directly, but somehow easy_install was the first thing which came to my mind. Also, the script can be improved by factoring out concrete versions.

NB. Using xz in the script.

How to convert a string to character array in c (or) how to extract a single char form string?

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

notifyDataSetChanged example

For an ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.

When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.

Your choices are:

  1. Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
  2. Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
  3. Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
  4. Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.

Serving static web resources in Spring Boot & Spring Security application

If you are using webjars. You need to add this in your configure method: http.authorizeRequests().antMatchers("/webjars/**").permitAll();

Make sure this is the first statement. For example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
         http.formLogin()
         .loginPage("/login")
         .failureUrl("/login?error")
         .usernameParameter("email")
         .permitAll()
         .and()
         .logout()
         .logoutUrl("/logout")
         .deleteCookies("remember-me")
         .logoutSuccessUrl("/")
         .permitAll()
         .and()
         .rememberMe();
    }

You will also need to have this in order to have webjars enabled:

@Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        ...
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        ...
    }

"git rm --cached x" vs "git reset head --? x"?

git rm --cached file will remove the file from the stage. That is, when you commit the file will be removed. git reset HEAD -- file will simply reset file in the staging area to the state where it was on the HEAD commit, i.e. will undo any changes you did to it since last commiting. If that change happens to be newly adding the file, then they will be equivalent.

How to use `subprocess` command with pipes

To use a pipe with the subprocess module, you have to pass shell=True.

However, this isn't really advisable for various reasons, not least of which is security. Instead, create the ps and grep processes separately, and pipe the output from one into the other, like so:

ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()

In your particular case, however, the simple solution is to call subprocess.check_output(('ps', '-A')) and then str.find on the output.

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

For files encoding...

public class FRomUtf8ToIso {
        static File input = new File("C:/Users/admin/Desktop/pippo.txt");
        static File output = new File("C:/Users/admin/Desktop/ciccio.txt");


    public static void main(String[] args) throws IOException {

        BufferedReader br = null;

        FileWriter fileWriter = new FileWriter(output);
        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader( input ));

            int i= 0;
            while ((sCurrentLine = br.readLine()) != null) {
                byte[] isoB =  encode( sCurrentLine.getBytes() );
                fileWriter.write(new String(isoB, Charset.forName("ISO-8859-15") ) );
                fileWriter.write("\n");
                System.out.println( i++ );
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }


    static byte[] encode(byte[] arr){
        Charset utf8charset = Charset.forName("UTF-8");
        Charset iso88591charset = Charset.forName("ISO-8859-15");

        ByteBuffer inputBuffer = ByteBuffer.wrap( arr );

        // decode UTF-8
        CharBuffer data = utf8charset.decode(inputBuffer);

        // encode ISO-8559-1
        ByteBuffer outputBuffer = iso88591charset.encode(data);
        byte[] outputData = outputBuffer.array();

        return outputData;
    }

}

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

Force the origin to start at 0

Simply add these to your ggplot:

+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

Example

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for


p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

enter image description here

Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge' could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

PHP page redirect

You can use this code to redirect in php

<?php
/* Redirect browser */
header("Location: http://example.com/");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>

phpMyAdmin on MySQL 8.0

Create another user with mysql_native_password option:

In terminal:

mysql> CREATE USER 'su'@'localhost' IDENTIFIED WITH mysql_native_password BY '123';
mysql> GRANT ALL PRIVILEGES ON * . * TO 'su'@'localhost';
mysql> FLUSH PRIVILEGES;

How to decompile a whole Jar file?

2009: JavaDecompiler can do a good job with a jar: since 0.2.5, All files, in JAR files, are displayed.

http://java.decompiler.free.fr/sites/default/screenshots/screenshot1.png

See also the question "How do I “decompile” Java class files?".

The JD-Eclipse doesn't seem to have changed since late 2009 though (see Changes).
So its integration with latest Eclipse (3.8, 4.2+) might be problematic.

JD-Core is actively maintained.

Both are the result of the fantastic work of (SO user) Emmanuel Dupuy.


2018: A more modern option, mentioned in the comments by David Kennedy Araujo:

JetBrains/intellij-community/plugins/java-decompiler/engine

Fernflower is the first actually working analytical decompiler for Java and probably for a high-level programming language in general.

java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination>

java -jar fernflower.jar -hes=0 -hdc=0 c:\Temp\binary\ -e=c:\Java\rt.jar c:\Temp\source\

See also How to decompile to java files intellij idea for a command working with recent IntelliJ IDEA.

"You have mail" message in terminal, os X

Probably it is some message from your system.

Type in terminal:

man mail

, and see how can you get this message from your system.

SQL Server - Convert date field to UTC

We can convert ServerZone DateTime to UTC and UTC to ServerZone DateTime

Simply run the following scripts to understand the conversion then modify as what you need

--Get Server's TimeZone
DECLARE @ServerTimeZone VARCHAR(50)
EXEC MASTER.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
'SYSTEM\CurrentControlSet\Control\TimeZoneInformation',
'TimeZoneKeyName',@ServerTimeZone OUT

-- ServerZone to UTC DATETIME
DECLARE @CurrentServerZoneDateTime DATETIME = GETDATE()
DECLARE @UTCDateTime  DATETIME =  @CurrentServerZoneDateTime AT TIME ZONE @ServerTimeZone AT TIME ZONE 'UTC' 
--(OR)
--DECLARE @UTCDateTime  DATETIME = GETUTCDATE()
SELECT @CurrentServerZoneDateTime AS CURRENTZONEDATE,@UTCDateTime AS UTCDATE

-- UTC to ServerZone DATETIME
SET @CurrentServerZoneDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE @ServerTimeZone
SELECT @UTCDateTime AS UTCDATE,@CurrentServerZoneDateTime AS CURRENTZONEDATE

Note: This(AT TIME ZONE) working on only SQL Server 2016+ and this advantage is automatically considering Daylight while converting to particular Time zone

How to get the background color code of an element in hex?

My beautiful non-standard solution

HTML

<div style="background-color:#f5b405"></div>

jQuery

$(this).attr("style").replace("background-color:", "");

Result

#f5b405

ToggleButton in C# WinForms

You can just use a CheckBox and set its appearance to Button:

CheckBox checkBox = new System.Windows.Forms.CheckBox(); 
checkBox.Appearance = System.Windows.Forms.Appearance.Button; 

How to use graphics.h in codeblocks?

  1. First download WinBGIm from http://winbgim.codecutter.org/ Extract it.
  2. Copy graphics.h and winbgim.h files in include folder of your compiler directory
  3. Copy libbgi.a to lib folder of your compiler directory
  4. In code::blocks open Settings >> Compiler and debugger >>linker settings click Add button in link libraries part and browse and select libbgi.a file
  5. In right part (i.e. other linker options) paste commands -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32
  6. Click OK

For detail information follow this link.

What is the difference between parseInt() and Number()?

If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0. Also multiply ("10" * 1) or not not (~~"10"). All of them are much faster of Number and parseInt. They even have "feature" returning 0 for not number argument. Here are Performance tests.

ValidateRequest="false" doesn't work in Asp.Net 4

Note that another approach is to keep with the 4.0 validation behaviour, but to define your own class that derives from RequestValidator and set:

<httpRuntime requestValidationType="YourNamespace.YourValidator" />

(where YourNamespace.YourValidator is well, you should be able to guess...)

This way you keep the advantages of 4.0s behaviour (specifically, that the validation happens earlier in the processing), while also allowing the requests you need to let through, through.

error C4996: 'scanf': This function or variable may be unsafe in c programming

You can add "_CRT_SECURE_NO_WARNINGS" in Preprocessor Definitions.

Right-click your project->Properties->Configuration Properties->C/C++ ->Preprocessor->Preprocessor Definitions.

enter image description here

Deleting array elements in JavaScript - delete vs splice

I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice and delete for removing every 'c' from the items Array.

var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  items.splice(items.indexOf('c'), 1);
}

console.log(items); // ["a", "b", "d", "a", "b", "d"]

items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  delete items[items.indexOf('c')];
}

console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
?

How do I install a module globally using npm?

If you want to install a npm module globally, make sure to use the new -g flag, for example:

npm install forever -g

The general recommendations concerning npm module installation since 1.0rc (taken from blog.nodejs.org):

  • If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.
  • If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.

I just recently used this recommendations and it went down pretty smoothly. I installed forever globally (since it is a command line tool) and all my application modules locally.

However, if you want to use some modules globally (i.e. express or mongodb), take this advice (also taken from blog.nodejs.org):

Of course, there are some cases where you want to do both. Coffee-script and Express both are good examples of apps that have a command line interface, as well as a library. In those cases, you can do one of the following:

  • Install it in both places. Seriously, are you that short on disk space? It’s fine, really. They’re tiny JavaScript programs.
  • Install it globally, and then npm link coffee-script or npm link express (if you’re on a platform that supports symbolic links.) Then you only need to update the global copy to update all the symlinks as well.

The first option is the best in my opinion. Simple, clear, explicit. The second is really handy if you are going to re-use the same library in a bunch of different projects. (More on npm link in a future installment.)

I did not test one of those variations, but they seem to be pretty straightforward.

Git blame -- prior commits?

Build on stangls's answer, I put this script in my PATH (even on Windows) as git-bh:

That allows me to look for all commits where a word was involved:

git bh path/to/myfile myWord

Script:

#!/bin/bash
f=$1
shift
csha=""
{ git log --pretty=format:%H -- "$f"; echo; } | {
  while read hash; do
    res=$(git blame -L"/$1/",+1 $hash -- "$f" 2>/dev/null | sed 's/^/  /')
    sha=${res%% (*}
    if [[ "${res}" != "" && "${csha}" != "${sha}" ]]; then
      echo "--- ${hash}"
      echo "${res}"
      csha="${sha}"
    fi
  done
}

How to take the first N items from a generator or list?

With itertools you will obtain another generator object so in most of the cases you will need another step the take the first N elements (N). There are at least two simpler solutions (a little bit less efficient in terms of performance but very handy) to get the elements ready to use from a generator:

Using list comprehension:

first_N_element=[generator.next() for i in range(N)]

Otherwise:

first_N_element=list(generator)[:N]

Where N is the number of elements you want to take (e.g. N=5 for the first five elements).

Change date format in a Java string

Please refer "Date and Time Patterns" here. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;

public class DateConversionExample{

  public static void main(String arg[]){

    try{

    SimpleDateFormat sourceDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

    Date date = sourceDateFormat.parse("2011-01-18 00:00:00.0");


    SimpleDateFormat targetDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(targetDateFormat.format(date));

    }catch(ParseException e){
        e.printStackTrace();
    }
  } 

}

How to center buttons in Twitter Bootstrap 3?

or you can give specific offsets to make button position where you want simply with bootstrap grid system,

<div class="col-md-offset-4 col-md-2 col-md-offset-5">
<input type="submit" class="btn btn-block" value="submit"/>

this way, also let you specify button size if you set btn-block. sure, this will only work md size range, if you want to set other sizes too, use xs,sm,lg.

Getting the first index of an object

they're not really ordered, but you can do:

var first;
for (var i in obj) {
    if (obj.hasOwnProperty(i) && typeof(i) !== 'function') {
        first = obj[i];
        break;
    }
}

the .hasOwnProperty() is important to ignore prototyped objects.

Extract Google Drive zip from Google colab notebook

You can simply use this

!unzip file_location

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

Pandas: Creating DataFrame from Series

Here is how to create a DataFrame where each series is a row.

For a single Series (resulting in a single-row DataFrame):

series = pd.Series([1,2], index=['a','b'])
df = pd.DataFrame([series])

For multiple series with identical indices:

cols = ['a','b']
list_of_series = [pd.Series([1,2],index=cols), pd.Series([3,4],index=cols)]
df = pd.DataFrame(list_of_series, columns=cols)

For multiple series with possibly different indices:

list_of_series = [pd.Series([1,2],index=['a','b']), pd.Series([3,4],index=['a','c'])]
df = pd.concat(list_of_series, axis=1).transpose()

To create a DataFrame where each series is a column, see the answers by others. Alternatively, one can create a DataFrame where each series is a row, as above, and then use df.transpose(). However, the latter approach is inefficient if the columns have different data types.

XAMPP Object not found error

I was getting this error

https://docs.google.com/file/d/0B-dUcqacTOLPcmI3SENMZFBLWG8/edit?usp=drivesdk

but I have done some coding into htdocs/index.php and made this like wamp homepage some thing like this

https://docs.google.com/file/d/0B-dUcqacTOLPVC1ORS1saGdOclU/edit?usp=drivesdk

Add image in title bar

You'll have to use a favicon for your page. put this in the head-tag: <link rel="shortcut icon" href="/favicon.png" type="image/png">

where favicon.png is preferably a 16x16 png image.

source: Adding a favicon to a static HTML page

Does Python SciPy need BLAS?

I guess you are talking about installation in Ubuntu. Just use:

apt-get install python-numpy python-scipy

That should take care of the BLAS libraries compiling as well. Else, compiling the BLAS libraries is very difficult.

How to check if a file exists in Ansible?

If you just want to make sure a certain file exists (f.ex. because it shoud be created in a different way than via ansible) and fail if it doesn't, then you can do this:

- name: sanity check that /some/path/file exists
  command: stat /some/path/file
  check_mode: no # always run
  changed_when: false # doesn't change anything

Calling pylab.savefig without display in ipython

This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('/tmp/test.png')

EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are ready to display the plots:

import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')

# Display all "open" (non-closed) figures
plt.show()

How to ping a server only once from within a batch file?

Just write the command "ping your server IP" without the double quote. save file name as filename.bat and then run the batch file as administrator

Show constraints on tables command

afaik to make a request to information_schema you need privileges. If you need simple list of keys you can use this command:

SHOW INDEXES IN <tablename>

How to generate .angular-cli.json file in Angular Cli?

As far as I know Angular-cli file can't be created via a command like Package-lock file, If you want to create it, you have to do it manually.

  1. You can type ng new to create a new angular project

  2. Locate its .angular-cli.json file

  3. Copy all its content

  4. Create a folder in your original project, and name it .angular-cli.json

  5. Paste what copied from new project in newly created angular cli file of original project.

  6. Locate this line in angular cli file you created, and change the name field to original project's name. You can find the project name in package.json file

project": {
  "name": "<name of the project>"
},

However, in newer angular version now it uses angular.json instead of angular-cli.json.

I want to show all tables that have specified column name

You can use the information schema views:

SELECT DISTINCT TABLE_SCHEMA, TABLE_NAME
FROM Information_Schema.Columns
WHERE COLUMN_NAME = 'ID'

Here's the MSDN reference for the "Columns" view: http://msdn.microsoft.com/en-us/library/ms188348.aspx

How do I set up CLion to compile and run?

I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.

The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.

SHORT ANSWER (should be similar for MinGW too but I haven't tried it):

  1. Install Cygwin with GCC, G++, GDB and CMake (the required versions)
  2. Add full path to Cygwin 'bin' directory to Windows Environment variables
  3. Restart CLion and check 'Settings' -> 'Build, Execution, Deployment' to make sure CLion has picked up the right versions of Cygwin, make and gdb
  4. Check the project configuration ('Run' -> 'Edit configuration') to make sure your project name appears there and you can select options in 'Target', 'Configuration' and 'Executable' fields.
  5. Build and then Run
  6. Enjoy

LONG ANSWER:

Below are the detailed steps that solved this issue for me:

  1. Uninstall/delete the previous version of Cygwin (MinGW in your case)

  2. Make sure that CLion is up-to-date

  3. Run Cygwin setup (x64 for my 64-bit OS)

  4. Install at least the following packages for Cygwin: gcc g++ make Cmake gdb Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).

  5. Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows

[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']

  1. Add the 'bin' folder to the Path variable. For Cygwin, I added: D:\cygwin64\bin

  2. Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings

  3. Select 'Build, Execution, Deployment' and then click on 'Toolchains'

  4. Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)

  5. For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)

  6. 'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]

  7. Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'

See screenshot: Check all paths to the compiler, make and gdb

  1. Now go to 'Run' -> 'Edit configuration'. You should see your project name in the left-side panel and the configurations on the right side

See screenshot: Check the configuration to run the project

  1. There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active

  2. Build your project and then run the project. You should see the output in the terminal window

Hope this helps! Good luck and enjoy CLion.

Is there a wikipedia API just for retrieve content summary?

There's a way to get the entire "intro section" without any html parsing! Similar to AnthonyS's answer with an additional explaintext param, you can get the intro section text in plain text.

Query

Getting Stack Overflow's intro in plain text:

Using page title:

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Stack%20Overflow

or use pageids

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&pageids=21721040

JSON Response

(warnings stripped)

{
    "query": {
        "pages": {
            "21721040": {
                "pageid": 21721040,
                "ns": 0,
                "title": "Stack Overflow",
                "extract": "Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky, as a more open alternative to earlier Q&A sites such as Experts Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.\nIt features questions and answers on a wide range of topics in computer programming. The website serves as a platform for users to ask and answer questions, and, through membership and active participation, to vote questions and answers up or down and edit questions and answers in a fashion similar to a wiki or Digg. Users of Stack Overflow can earn reputation points and \"badges\"; for example, a person is awarded 10 reputation points for receiving an \"up\" vote on an answer given to a question, and can receive badges for their valued contributions, which represents a kind of gamification of the traditional Q&A site or forum. All user-generated content is licensed under a Creative Commons Attribute-ShareAlike license. Questions are closed in order to allow low quality questions to improve. Jeff Atwood stated in 2010 that duplicate questions are not seen as a problem but rather they constitute an advantage if such additional questions drive extra traffic to the site by multiplying relevant keyword hits in search engines.\nAs of April 2014, Stack Overflow has over 2,700,000 registered users and more than 7,100,000 questions. Based on the type of tags assigned to questions, the top eight most discussed topics on the site are: Java, JavaScript, C#, PHP, Android, jQuery, Python and HTML."
            }
        }
    }
}

Documentation: API: query/prop=extracts


Edit: Added &redirects=1 as recommended in comments. Edit: Added pageids example

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ). Let's replace it in its context:

  • x is an array equal to [x0 * n], so its length is 1
  • you're iterating from 0 to n-2 (n doesn't matter here), and i is the index. In the beginning, everything is ok (here there's no beginning apparently... :( ), but as soon as i + 1 >= len(x) <=> i >= 0, the element x[i+1] doesn't exist. Here, this element doesn't exist since the beginning of the for loop.

To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ) by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )).

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

This for sure is an old topic but I want to add up to the voices to crop maybe new ideas. To address the WARNING issue under discussions, all you need to do is to set one of your table columns to a PRIMARY KEY constraint.

How to create standard Borderless buttons (like in the design guideline mentioned)?

For anybody who's still searching:

inherit your own style for Holo buttonbars:

<style name="yourStyle" parent="@android:style/Holo.ButtonBar">
  ...
</style>

or Holo Light:

<style name="yourStyle" parent="@android:style/Holo.Light.ButtonBar">
  ...
</style>

and for borderless Holo buttons:

<style name="yourStyle" parent="@android:style/Widget.Holo.Button.Borderless.Small">
  ...
</style>

or Holo Light:

<style name="yourStyle" parent="@android:style/Widget.Holo.Light.Button.Borderless.Small">
  ...
</style>

How to convert an entire MySQL database characterset and collation to UTF-8?

  1. Make a backup!

  2. Then you need to set the default char sets on the database. This does not convert existing tables, it only sets the default for newly created tables.

    ALTER DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;
    
  3. Then, you will need to convert the char set on all existing tables and their columns. This assumes that your current data is actually in the current char set. If your columns are set to one char set but your data is really stored in another then you will need to check the MySQL manual on how to handle this.

    ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
    

Styling an input type="file" button

As JGuo and CorySimmons mentioned, you can use the clickable behaviour of a stylable label, hiding the less flexible file input element.

<!DOCTYPE html>
<html>
<head>
<title>Custom file input</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>

<body>

<label for="upload-file" class="btn btn-info"> Choose file... </label>
<input id="upload-file" type="file" style="display: none"
onchange="this.nextElementSibling.textContent = this.previousElementSibling.title = this.files[0].name">
<div></div>

</body>
</html>

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

When i try create another package under the Java folder this error will happen

But When i moved this special package under the main package of my project , everything will be ok .

I'm testing on real android device .(Sumsung J2)

Redirecting from cshtml page

You can go to method of same controller..using this line , and if you want to pass some parameters to that action it can be done by writing inside ( new { } ).. Note:- you can add as many parameter as required.

@Html.ActionLink("MethodName", new { parameter = Model.parameter })

Why use multiple columns as primary keys (composite primary key)

Your understanding is correct.

You would do this in many cases. One example is in a relationship like OrderHeader and OrderDetail. The PK in OrderHeader might be OrderNumber. The PK in OrderDetail might be OrderNumber AND LineNumber. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.

The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.

Allowing Untrusted SSL Certificates with HttpClient

For Xamarin Android this was the only solution that worked for me: another stack overflow post

If you are using AndroidClientHandler, you need to supply a SSLSocketFactory and a custom implementation of HostnameVerifier with all checks disabled. To do this, you’ll need to subclass AndroidClientHandler and override the appropriate methods.

internal class BypassHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{
    public bool Verify(string hostname, ISSLSession session)
    {
        return true;
    }
}
 
internal class InsecureAndroidClientHandler : AndroidClientHandler
{
    protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
    {
        return SSLCertificateSocketFactory.GetInsecure(1000, null);
    }
 
    protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
    {
        return new BypassHostnameVerifier();
    }
}

And then

var httpClient = new System.Net.Http.HttpClient(new InsecureAndroidClientHandler());

json_encode is returning NULL?

ntd's anwser didn't solve my problem. For those in same situation, here is how I finally handled this error: Just utf8_encode each of your results.

while($row = mysql_fetch_assoc($result)){
    $rows[] = array_map('utf8_encode', $row);
}

Hope it helps!

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

How To Pass GET Parameters To Laravel From With GET Method ?

So you're trying to get the search term and category into the URL?

I would advise against this as you'll have to deal with multi-word search terms etc, and could end up with all manner of unpleasantness with disallowed characters.

I would suggest POSTing the data, sanitising it and then returning a results page.

Laravel routing is not designed to accept GET requests from forms, it is designed to use URL segments as get parameters, and built around that idea.

Angular directives - when and how to use compile, controller, pre-link and post-link

In which order the directive functions are executed?

For a single directive

Based on the following plunk, consider the following HTML markup:

<body>
    <div log='some-div'></div>
</body>

With the following directive declaration:

myApp.directive('log', function() {
  
    return {
        controller: function( $scope, $element, $attrs, $transclude ) {
            console.log( $attrs.log + ' (controller)' );
        },
        compile: function compile( tElement, tAttributes ) {
            console.log( tAttributes.log + ' (compile)'  );
            return {
                pre: function preLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (pre-link)'  );
                },
                post: function postLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (post-link)'  );
                }
            };
         }
     };  
     
});

The console output will be:

some-div (compile)
some-div (controller)
some-div (pre-link)
some-div (post-link)

We can see that compile is executed first, then controller, then pre-link and last is post-link.

For nested directives

Note: The following does not apply to directives that render their children in their link function. Quite a few Angular directives do so (like ngIf, ngRepeat, or any directive with transclude). These directives will natively have their link function called before their child directives compile is called.

The original HTML markup is often made of nested elements, each with its own directive. Like in the following markup (see plunk):

<body>
    <div log='parent'>
        <div log='..first-child'></div>
        <div log='..second-child'></div>
    </div>
</body>

The console output will look like this:

// The compile phase
parent (compile)
..first-child (compile)
..second-child (compile)

// The link phase   
parent (controller)
parent (pre-link)
..first-child (controller)
..first-child (pre-link)
..first-child (post-link)
..second-child (controller)
..second-child (pre-link)
..second-child (post-link)
parent (post-link)

We can distinguish two phases here - the compile phase and the link phase.

The compile phase

When the DOM is loaded Angular starts the compile phase, where it traverses the markup top-down, and calls compile on all directives. Graphically, we could express it like so:

An image illustrating the compilation loop for children

It is perhaps important to mention that at this stage, the templates the compile function gets are the source templates (not instance template).

The link phase

DOM instances are often simply the result of a source template being rendered to the DOM, but they may be created by ng-repeat, or introduced on the fly.

Whenever a new instance of an element with a directive is rendered to the DOM, the link phase starts.

In this phase, Angular calls controller, pre-link, iterates children, and call post-link on all directives, like so:

An illustration demonstrating the link phase steps

How do I measure request and response times at once using cURL?

Another way is configuring ~/.curlrc like this

-w "\n\n==== cURL measurements stats ====\ntotal: %{time_total} seconds \nsize: %{size_download} bytes \ndnslookup: %{time_namelookup} seconds \nconnect: %{time_connect} seconds \nappconnect: %{time_appconnect} seconds \nredirect: %{time_redirect} seconds \npretransfer: %{time_pretransfer} seconds \nstarttransfer: %{time_starttransfer} seconds \ndownloadspeed: %{speed_download} byte/sec \nuploadspeed: %{speed_upload} byte/sec \n\n"

So the output of curl is

?? curl -I https://google.com
HTTP/2 301
location: https://www.google.com/
content-type: text/html; charset=UTF-8
date: Mon, 04 Mar 2019 08:02:43 GMT
expires: Wed, 03 Apr 2019 08:02:43 GMT
cache-control: public, max-age=2592000
server: gws
content-length: 220
x-xss-protection: 1; mode=block
x-frame-options: SAMEORIGIN
alt-svc: quic=":443"; ma=2592000; v="44,43,39"



==== cURL measurements stats ====
total: 0.211117 seconds
size: 0 bytes
dnslookup: 0.067179 seconds
connect: 0.098817 seconds
appconnect: 0.176232 seconds
redirect: 0.000000 seconds
pretransfer: 0.176438 seconds
starttransfer: 0.209634 seconds
downloadspeed: 0.000 byte/sec
uploadspeed: 0.000 byte/sec

Java time-based map/cache with expiring keys

Typically, a cache should keep objects around some time and shall expose of them some time later. What is a good time to hold an object depends on the use case. I wanted this thing to be simple, no threads or schedulers. This approach works for me. Unlike SoftReferences, objects are guaranteed to be available some minimum amount of time. However, the do not stay around in memory until the sun turns into a red giant.

As useage example think of a slowly responding system that shall be able to check if a request has been done quite recently, and in that case not to perform the requested action twice, even if a hectic user hits the button several times. But, if the same action is requested some time later, it shall be performed again.

class Cache<T> {
    long avg, count, created, max, min;
    Map<T, Long> map = new HashMap<T, Long>();

    /**
     * @param min   minimal time [ns] to hold an object
     * @param max   maximal time [ns] to hold an object
     */
    Cache(long min, long max) {
        created = System.nanoTime();
        this.min = min;
        this.max = max;
        avg = (min + max) / 2;
    }

    boolean add(T e) {
        boolean result = map.put(e, Long.valueOf(System.nanoTime())) != null;
        onAccess();
        return result;
    }

    boolean contains(Object o) {
        boolean result = map.containsKey(o);
        onAccess();
        return result;
    }

    private void onAccess() {
        count++;
        long now = System.nanoTime();
        for (Iterator<Entry<T, Long>> it = map.entrySet().iterator(); it.hasNext();) {
            long t = it.next().getValue();
            if (now > t + min && (now > t + max || now + (now - created) / count > t + avg)) {
                it.remove();
            }
        }
    }
}

Counting array elements in Perl

It sounds like you want a sparse array. A normal array would have 24 items in it, but a sparse array would have 3. In Perl we emulate sparse arrays with hashes:

#!/usr/bin/perl

use strict;
use warnings;

my %sparse;

@sparse{0, 5, 23} = (1 .. 3);

print "there are ", scalar keys %sparse, " items in the sparse array\n",
    map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;

The keys function in scalar context will return the number of items in the sparse array. The only downside to using a hash to emulate a sparse array is that you must sort the keys before iterating over them if their order is important.

You must also remember to use the delete function to remove items from the sparse array (just setting their value to undef is not enough).

Close Bootstrap Modal

Another way of doing this is that first you remove the class modal-open, which closes the modal. Then you remove the class modal-backdrop that removes the grayish cover of the modal.

Following code can be used:

$('body').removeClass('modal-open')
$('.modal-backdrop').remove()  

jQuery CSS Opacity

Try this:

jQuery('#main').css('opacity', '0.6');

or

jQuery('#main').css({'filter':'alpha(opacity=60)', 'zoom':'1', 'opacity':'0.6'});

if you want to support IE7, IE8 and so on.

SFTP in Python? (platform independent)

Paramiko supports SFTP. I've used it, and I've used Twisted. Both have their place, but you might find it easier to start with Paramiko.

convert UIImage to NSData

Use if-let block with Data to prevent app crash & safe execution of code, as function UIImagePNGRepresentation returns an optional value.

if let img = UIImage(named: "TestImage.png") {
    if let data:Data = UIImagePNGRepresentation(img) {
       // Handle operations with data here...         
    }
}

Note: Data is Swift 3 class. Use Data instead of NSData with Swift 3

Generic image operations (like png & jpg both):

if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
        if let data:Data = UIImagePNGRepresentation(img) {
               handleOperationWithData(data: data)     
        } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
               handleOperationWithData(data: data)     
        }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

By using extension:

extension UIImage {

    var pngRepresentationData: Data? {
        return UIImagePNGRepresentation(img)
    }

    var jpegRepresentationData: Data? {
        return UIImageJPEGRepresentation(self, 1.0)
    }
}

*******
if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
      if let data = img.pngRepresentationData {
              handleOperationWithData(data: data)     
      } else if let data = img.jpegRepresentationData {
              handleOperationWithData(data: data)     
     }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Text files in Windows don't have a format. There's an unofficial convention that if the file starts with the BOM codepoint in UTF-8 format that it's UTF-8, but that convention isn't universally supported. That would be the 3 byte sequence "\xef\xbf\xbe", i.e. ￾ in the Latin-1 character set.

Simple regular expression for a decimal with a precision of 2

To include an optional minus sign and to disallow numbers like 015 (which can be mistaken for octal numbers) write:

-?(0|([1-9]\d*))(\.\d+)?

Difference between java HH:mm and hh:mm on SimpleDateFormat

Actually the last one is not weird. Code is setting the timezone for working instead of working2.

SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).

Fixing this error gives:

24:00:00
00:00:00
01:00:00

What's the main difference between int.Parse() and Convert.ToInt32

No difference as such.
Convert.ToInt32() calls int.Parse() internally

Except for one thing Convert.ToInt32() returns 0 when argument is null

Otherwise both work the same way

SQL Server IF EXISTS THEN 1 ELSE 2

Its best practice to have TOP 1 1 always.

What if I use SELECT 1 -> If condition matches more than one record then your query will fetch all the columns records and returns 1.

What if I use SELECT TOP 1 1 -> If condition matches more than one record also, it will just fetch the existence of any row (with a self 1-valued column) and returns 1.

IF EXISTS (SELECT TOP 1 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
BEGIN
   SELECT 1 
END
ELSE
BEGIN
    SELECT 2
END

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

A note of personal experience in addition to both Stefan Gehrig's answer and Dave None's answer (and mmmshuddup's reply):

I was having validation problems using both \n and PHP_EOL when I used the ICS validator at http://severinghaus.org/projects/icv/

I learned I had to use \r\n in order to get it to validate properly, so this was my solution:

function dateToCal($timestamp) {
  return date('Ymd\Tgis\Z', $timestamp);
}

function escapeString($string) {
  return preg_replace('/([\,;])/','\\\$1', $string);
}    

    $eol = "\r\n";
    $load = "BEGIN:VCALENDAR" . $eol .
    "VERSION:2.0" . $eol .
    "PRODID:-//project/author//NONSGML v1.0//EN" . $eol .
    "CALSCALE:GREGORIAN" . $eol .
    "BEGIN:VEVENT" . $eol .
    "DTEND:" . dateToCal($end) . $eol .
    "UID:" . $id . $eol .
    "DTSTAMP:" . dateToCal(time()) . $eol .
    "DESCRIPTION:" . htmlspecialchars($title) . $eol .
    "URL;VALUE=URI:" . htmlspecialchars($url) . $eol .
    "SUMMARY:" . htmlspecialchars($description) . $eol .
    "DTSTART:" . dateToCal($start) . $eol .
    "END:VEVENT" . $eol .
    "END:VCALENDAR";

    $filename="Event-".$id;

    // Set the headers
    header('Content-type: text/calendar; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $filename);

    // Dump load
    echo $load;

That stopped my parse errors and made my ICS files validate properly.

Hidden Features of C#?

Collection Initializer inside Object Initializer:

MailMessage mail = new MailMessage {
   To = { new MailAddress("[email protected]"), new MailAddress("[email protected]") },
   Subject = "Password Recovery"
};

You can initialize a whole tree in a single expression.

How to execute an Oracle stored procedure via a database link

The syntax is

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

I found that if the value passed is a string type, it must be followed by 'px' (i.e. 90px), where if the value is an integer, it will append the px automatically. the width and height properties are more forgiving (either type works).

var x = "90";
var y = "120"
$(selector).css( { left: x, top: y } )        //doesn't work
$(selector).css( { left: x + "px", top: y + "px" } )        //does work

x = 90;
y = 120;
$(selector).css( { left: x, top: y } )        //does work

Copy Notepad++ text with formatting?

Horrible to look for this failure:

Copy .dll to here:

\Program Files\Notepad++\plugins --> put it here

Restart the notepad++

and now you are able to use the copy commands!!!

Age from birthdate in python

The classic gotcha in this scenario is what to do with people born on the 29th day of February. Example: you need to be aged 18 to vote, drive a car, buy alcohol, etc ... if you are born on 2004-02-29, what is the first day that you are permitted to do such things: 2022-02-28, or 2022-03-01? AFAICT, mostly the first, but a few killjoys might say the latter.

Here's code that caters for the 0.068% (approx) of the population born on that day:

def age_in_years(from_date, to_date, leap_day_anniversary_Feb28=True):
    age = to_date.year - from_date.year
    try:
        anniversary = from_date.replace(year=to_date.year)
    except ValueError:
        assert from_date.day == 29 and from_date.month == 2
        if leap_day_anniversary_Feb28:
            anniversary = datetime.date(to_date.year, 2, 28)
        else:
            anniversary = datetime.date(to_date.year, 3, 1)
    if to_date < anniversary:
        age -= 1
    return age

if __name__ == "__main__":
    import datetime

    tests = """

    2004  2 28 2010  2 27  5 1
    2004  2 28 2010  2 28  6 1
    2004  2 28 2010  3  1  6 1

    2004  2 29 2010  2 27  5 1
    2004  2 29 2010  2 28  6 1
    2004  2 29 2010  3  1  6 1

    2004  2 29 2012  2 27  7 1
    2004  2 29 2012  2 28  7 1
    2004  2 29 2012  2 29  8 1
    2004  2 29 2012  3  1  8 1

    2004  2 28 2010  2 27  5 0
    2004  2 28 2010  2 28  6 0
    2004  2 28 2010  3  1  6 0

    2004  2 29 2010  2 27  5 0
    2004  2 29 2010  2 28  5 0
    2004  2 29 2010  3  1  6 0

    2004  2 29 2012  2 27  7 0
    2004  2 29 2012  2 28  7 0
    2004  2 29 2012  2 29  8 0
    2004  2 29 2012  3  1  8 0

    """

    for line in tests.splitlines():
        nums = [int(x) for x in line.split()]
        if not nums:
            print
            continue
        datea = datetime.date(*nums[0:3])
        dateb = datetime.date(*nums[3:6])
        expected, anniv = nums[6:8]
        age = age_in_years(datea, dateb, anniv)
        print datea, dateb, anniv, age, expected, age == expected

Here's the output:

2004-02-28 2010-02-27 1 5 5 True
2004-02-28 2010-02-28 1 6 6 True
2004-02-28 2010-03-01 1 6 6 True

2004-02-29 2010-02-27 1 5 5 True
2004-02-29 2010-02-28 1 6 6 True
2004-02-29 2010-03-01 1 6 6 True

2004-02-29 2012-02-27 1 7 7 True
2004-02-29 2012-02-28 1 7 7 True
2004-02-29 2012-02-29 1 8 8 True
2004-02-29 2012-03-01 1 8 8 True

2004-02-28 2010-02-27 0 5 5 True
2004-02-28 2010-02-28 0 6 6 True
2004-02-28 2010-03-01 0 6 6 True

2004-02-29 2010-02-27 0 5 5 True
2004-02-29 2010-02-28 0 5 5 True
2004-02-29 2010-03-01 0 6 6 True

2004-02-29 2012-02-27 0 7 7 True
2004-02-29 2012-02-28 0 7 7 True
2004-02-29 2012-02-29 0 8 8 True
2004-02-29 2012-03-01 0 8 8 True

program cant start because php5.dll is missing

I needed to change environment variable PATH and PHPRC. Also open new cmd.

I already had PHP installed and added EasyPHP when the problem came up. After I changed both variables to C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\binaries\php\php_runningversion it worked fine.

How to configure welcome file list in web.xml

This is my way to setup Servlet as welcome page.

I share for whom concern.

web.xml

  <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Demo</servlet-name>
        <servlet-class>servlet.Demo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Demo</servlet-name>
        <url-pattern></url-pattern>
    </servlet-mapping>

Servlet class

@WebServlet(name = "/demo")
public class Demo extends HttpServlet {
   public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException  {
       RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
   }
}

Attach Authorization header for all axios requests

There are multiple ways to achieve this. Here, I have explained the two most common approaches.

1. You can use axios interceptors to intercept any requests and add authorization headers.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    const token = store.getState().session.token;
    config.headers.Authorization =  token;

    return config;
});

2. From the documentation of axios you can see there is a mechanism available which allows you to set default header which will be sent with every request you make.

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

So in your case:

axios.defaults.headers.common['Authorization'] = store.getState().session.token;

If you want, you can create a self-executable function which will set authorization header itself when the token is present in the store.

(function() {
     String token = store.getState().session.token;
     if (token) {
         axios.defaults.headers.common['Authorization'] = token;
     } else {
         axios.defaults.headers.common['Authorization'] = null;
         /*if setting null does not remove `Authorization` header then try     
           delete axios.defaults.headers.common['Authorization'];
         */
     }
})();

Now you no longer need to attach token manually to every request. You can place the above function in the file which is guaranteed to be executed every time (e.g: File which contains the routes).

Hope it helps :)

MySQL timestamp select date range

SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'

How to change btn color in Bootstrap

You can add custom colors using bootstrap theming in your config file for example variables.scss and make sure you import that file before bootstrap when compiling.

$theme-colors: (
    "whatever": #900
);

Now you can do .btn-whatever

HTML Submit-button: Different value / button-text?

There are plenty of answers here explaining what you could do (I use the different field name one) but the simple (and as-yet unstated) answer to your question is 'no' - you can't have a different text and value using just HTML.

Can I have H2 autocreate a schema in an in-memory database?

"By default, when an application calls DriverManager.getConnection(url, ...) and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.

Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {

    public static void main(String[] args) throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
        Statement st = conn.createStatement();
        st.execute("create table customer(id integer, name varchar(10))");
        st.execute("insert into customer values (1, 'Thomas')");
        Statement stmt = conn.createStatement();
        ResultSet rset = stmt.executeQuery("select name from customer");
        while (rset.next()) {
            String name = rset.getString(1);
            System.out.println(name);
        }
    }
}

Guzzle 6: no more json() method for responses

If you guys still interested, here is my workaround based on Guzzle middleware feature:

  1. Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:

    <?php
    
    namespace GuzzleHttp\Psr7;
    
    
    class JsonAwareResponse extends Response
    {
        /**
         * Cache for performance
         * @var array
         */
        private $json;
    
        public function getBody()
        {
            if ($this->json) {
                return $this->json;
            }
            // get parent Body stream
            $body = parent::getBody();
    
            // if JSON HTTP header detected - then decode
            if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
                return $this->json = \json_decode($body, true);
            }
            return $body;
        }
    }
    
  2. Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:

    <?php
    
    $client = new \GuzzleHttp\Client();
    
    /** @var HandlerStack $handler */
    $handler = $client->getConfig('handler');
    $handler->push(\GuzzleHttp\Middleware::mapResponse(function (\Psr\Http\Message\ResponseInterface $response) {
        return new \GuzzleHttp\Psr7\JsonAwareResponse(
            $response->getStatusCode(),
            $response->getHeaders(),
            $response->getBody(),
            $response->getProtocolVersion(),
            $response->getReasonPhrase()
        );
    }), 'json_decode_middleware');
    

After this to retrieve JSON as PHP native array use Guzzle as always:

$jsonArray = $client->get('http://httpbin.org/headers')->getBody();

Tested with guzzlehttp/guzzle 6.3.3

Best way to script remote SSH commands in Batch (Windows)

The -m switch of PuTTY takes a path to a script file as an argument, not a command.

Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m

So you have to save your command (command_run) to a plain text file (e.g. c:\path\command.txt) and pass that to PuTTY:

putty.exe -ssh user@host -pw password -m c:\path\command.txt

Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).

A command-line syntax is identical, an output redirection added:

plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt

See Using the command-line connection tool Plink.

And with Plink, you can actually provide the command directly on its command-line:

plink.exe -ssh user@host -pw password command > output.txt

Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file

How to use null in switch

You can also use String.valueOf((Object) nullableString) like

switch (String.valueOf((Object) nullableString)) {
case "someCase"
    //...
    break;
...
case "null": // or default:
    //...
        break;
}

See interesting SO Q/A: Why does String.valueOf(null) throw a NullPointerException

Labeling file upload button

It is normally provided by the browser and hard to change, so the only way around it will be a CSS/JavaScript hack,

See the following links for some approaches:

Variable name as a string in Javascript

This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:

_x000D_
_x000D_
   _x000D_
var myFirstName = "Danilo";_x000D_
var varName = Object.keys({myFirstName:0})[0];_x000D_
console.log(varName);
_x000D_
_x000D_
_x000D_

Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Separation of business logic and data access in django

Django employs a slightly modified kind of MVC. There's no concept of a "controller" in Django. The closest proxy is a "view", which tends to cause confusion with MVC converts because in MVC a view is more like Django's "template".

In Django, a "model" is not merely a database abstraction. In some respects, it shares duty with the Django's "view" as the controller of MVC. It holds the entirety of behavior associated with an instance. If that instance needs to interact with an external API as part of it's behavior, then that's still model code. In fact, models aren't required to interact with the database at all, so you could conceivable have models that entirely exist as an interactive layer to an external API. It's a much more free concept of a "model".

How to SELECT a dropdown list item by value programmatically

This is a simple way to select an option from a dropdownlist based on a string val

private void SetDDLs(DropDownList d,string val)
    {
        ListItem li;
        for (int i = 0; i < d.Items.Count; i++)
        {
            li = d.Items[i];
            if (li.Value == val)
            {
                d.SelectedIndex = i;
                break;
            }
        }
    }

What is token-based authentication?

Token Based (Security / Authentication)

means that In order for us to prove that we’ve access we first have to receive the token. In a real life scenario, the token could be an access card to building, it could be the key to the lock to your house. In order for you to retrieve a key card for your office or the key to your home, you first need to prove who you are, and that you in fact do have access to that token. It could be something as simple as showing someone your ID or giving them a secret password. So imagine I need to get access to my office. I go down to the security office, I show them my ID, and they give me this token, which lets me into the building. Now I have unrestricted access to do whatever I want inside the building, as long as I have my token with me.

What’s the benefit of token based security?

If we think back on the insecure API, what we had to do in that case was that we had to provide our password for everything that we wanted to do.

Imagine that every time we enter a door in our office, we have to give everyone sitting next to the door our password. Now that would be pretty bad, because that means that anyone inside our office could take our password and impersonate us, and that’s pretty bad. Instead, what we do is that we retrieve the token, of course together with password, but we retrieve that from one person. And then we can use this token wherever we want inside the building. Of course if we lose the token, we have the same problem as if someone else knew our password, but that leads us into things like how do we make sure that if we lose the token, we can revoke the access, and maybe the token shouldn’t live for longer than 24hours, so the next day that we come to the office, we need to show our ID again. But still, there’s just one person that we show the ID to, and that’s the security guard sitting where we retrieve the tokens.

ImportError: numpy.core.multiarray failed to import

I was getting the same error and the problem was solved by updating my numpy installation from 1.7.1 to 1.12.1

pip install -U numpy

The followings were my cmd sequence when the error was occurred, slightly different from the above:

$ python

Python 2.7.12 |Anaconda 4.2.0 (x86_64)| (default, Jul  2 2016, 17:43:17) 

[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

Anaconda is brought to you by Continuum Analytics.

Please check out: http://continuum.io/thanks and https://anaconda.org

>>> import cv2

>>> import numpy as np

>>> from matplotlib import pyplot as plt

How to print GETDATE() in SQL Server with milliseconds in time?

these 2 are the same:

Print CAST(GETDATE() as Datetime2 (3) )
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))

enter image description here

Fixed width buttons with Bootstrap

Here I found a solution by comparing buttons in a button-group element. The simple solution is to get the one with the largest width and set the width to the other buttons. So they can have a equal width.

    function EqualizeButtons(parentElementId) {

    var longest = 0; 
    var element = $(parentElementId);

    element.find(".btn:not(.button-controlled)").each(function () {
        $(this).addClass('button-controlled');
        var width = $(this).width();
        if (longest < width) longest = width;

    }).promise().done(function () {
        $('.button-controlled').width(longest);
    });
}

It worked like a charm.

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

Create a date from day month and year with T-SQL

Sql Server 2012 has a function that will create the date based on the parts (DATEFROMPARTS). For the rest of us, here is a db function I created that will determine the date from the parts (thanks @Charles)...

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[func_DateFromParts]'))
    DROP FUNCTION [dbo].[func_DateFromParts]
GO

CREATE FUNCTION [dbo].[func_DateFromParts]
(
    @Year INT,
    @Month INT,
    @DayOfMonth INT,
    @Hour INT = 0,  -- based on 24 hour clock (add 12 for PM :)
    @Min INT = 0,
    @Sec INT = 0
)
RETURNS DATETIME
AS
BEGIN

    RETURN DATEADD(second, @Sec, 
            DATEADD(minute, @Min, 
            DATEADD(hour, @Hour,
            DATEADD(day, @DayOfMonth - 1, 
            DATEADD(month, @Month - 1, 
            DATEADD(Year, @Year-1900, 0))))))

END

GO

You can call it like this...

SELECT dbo.func_DateFromParts(2013, 10, 4, 15, 50, DEFAULT)

Returns...

2013-10-04 15:50:00.000

Open S3 object as a string with Boto3

I had a problem to read/parse the object from S3 because of .get() using Python 2.7 inside an AWS Lambda.

I added json to the example to show it became parsable :)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

NOTE (for python 2.7): My object is all ascii, so I don't need .decode('utf-8')

NOTE (for python 3.6+): We moved to python 3.6 and discovered that read() now returns bytes so if you want to get a string out of it, you must use:

j = json.loads(obj['Body'].read().decode('utf-8'))

How to run regasm.exe from command line other than Visual Studio command prompt?

In command prompt:

SET PATH = "%PATH%;%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"

What is the difference between substr and substring?

As hinted at in yatima2975's answer, there is an additional difference:

substr() accepts a negative starting position as an offset from the end of the string. substring() does not.

From MDN:

If start is negative, substr() uses it as a character index from the end of the string.

So to sum up the functional differences:

substring(begin-offset, end-offset-exclusive) where begin-offset is 0 or greater

substr(begin-offset, length) where begin-offset may also be negative

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

Here you go

col-lg-2 : if the screen is large (lg) then this component will take space of 2 elements considering entire row can fit 12 elements ( so you will see that on large screen this component takes 16% space of a row)

col-lg-6 : if the screen is large (lg) then this component will take space of 6 elements considering entire row can fit 12 elements -- when applied you will see that the component has taken half the available space in the row.

Above rule is only applied when the screen is large. when the screen is small this rule is discarded and only one component per row is shown.

Below image shows various screen size widths :

screen size definitions

How can I disable a button on a jQuery UI dialog?

This worked for me --

$("#dialog-confirm").html('Do you want to permanently delete this?');
$( "#dialog-confirm" ).dialog({
    resizable: false,
    title:'Confirm',
    modal: true,
    buttons: {
        Cancel: function() {
            $( this ).dialog( "close" );
        },
        OK:function(){
            $('#loading').show();
            $.ajax({
                    type:'post',
                    url:'ajax.php',
                    cache:false,
                    data:{action:'do_something'},
                    async:true,
                    success:function(data){
                        var resp = JSON.parse(data);
                        $("#loading").hide();
                        $("#dialog-confirm").html(resp.msg);
                        $( "#dialog-confirm" ).dialog({
                                resizable: false,
                                title:'Confirm',
                                modal: true,
                                buttons: {
                                    Close: function() {
                                        $( this ).dialog( "close" );
                                    }
                                }
                        });
                    }
                });
        }
    }
}); 

How to align flexbox columns left and right?

Another option is to add another tag with flex: auto style in between your tags that you want to fill in the remaining space.

https://jsfiddle.net/tsey5qu4/

The HTML:

<div class="parent">
  <div class="left">Left</div>
  <div class="fill-remaining-space"></div>
  <div class="right">Right</div>
</div>

The CSS:

.fill-remaining-space {
  flex: auto;
}

This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.

RuntimeError: module compiled against API version a but this version of numpy is 9

Check the path

import numpy
print numpy.__path__

For me this was /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy So I moved it to a temporary place

sudo mv /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy \
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy_old

and then the next time I imported numpy the path was /Library/Python/2.7/site-packages/numpy/init.pyc and all was well.

Kotlin's List missing "add", "remove", Map missing "put", etc?

In Kotlin you must use MutableList or ArrayList.

Let's see how the methods of MutableList work:

var listNumbers: MutableList<Int> = mutableListOf(10, 15, 20)
// Result: 10, 15, 20

listNumbers.add(1000)
// Result: 10, 15, 20, 1000

listNumbers.add(1, 250)
// Result: 10, 250, 15, 20, 1000

listNumbers.removeAt(0)
// Result: 250, 15, 20, 1000

listNumbers.remove(20)
// Result: 250, 15, 1000

for (i in listNumbers) { 
    println(i) 
}

Let's see how the methods of ArrayList work:

var arrayNumbers: ArrayList<Int> = arrayListOf(1, 2, 3, 4, 5)
// Result: 1, 2, 3, 4, 5

arrayNumbers.add(20)
// Result: 1, 2, 3, 4, 5, 20

arrayNumbers.remove(1)
// Result: 2, 3, 4, 5, 20

arrayNumbers.clear()
// Result: Empty

for (j in arrayNumbers) { 
    println(j) 
}

JavaScript DOM: Find Element Index In Container

2017 update

The original answer below assumes that the OP wants to include non-empty text node and other node types as well as elements. It doesn't seem clear to me now from the question whether this is a valid assumption.

Assuming instead you just want the element index, previousElementSibling is now well-supported (which was not the case in 2012) and is the obvious choice now. The following (which is the same as some other answers here) will work in everything major except IE <= 8.

function getElementIndex(node) {
    var index = 0;
    while ( (node = node.previousElementSibling) ) {
        index++;
    }
    return index;
}

Original answer

Just use previousSibling until you hit null. I'm assuming you want to ignore white space-only text nodes; if you want to filter other nodes then adjust accordingly.

function getNodeIndex(node) {
    var index = 0;
    while ( (node = node.previousSibling) ) {
        if (node.nodeType != 3 || !/^\s*$/.test(node.data)) {
            index++;
        }
    }
    return index;
}

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

What linux shell command returns a part of a string?

expr(1) has a substr subcommand:

expr substr <string> <start-index> <length>

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

For me it was a permission problem.

enter:

mysqld --verbose --help | grep -A 1 "Default options"

[Warning] World-writable config file '/etc/mysql/my.cnf' is ignored.

So try to execute the following, and then restart the server

chmod 644 '/etc/mysql/my.cnf'

It will give mysql access to read and write to the file.

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

For more information about .scrollHeight property refer to the docs:

The Element.scrollHeight read-only attribute is a measurement of the height of an element's content, including content not visible on the screen due to overflow. The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar. It includes the element padding but not its margin.

Scheduling recurring task in Android

I realize this is an old question and has been answered but this could help someone. In your activity

private ScheduledExecutorService scheduleTaskExecutor;

In onCreate

  scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

    //Schedule a task to run every 5 seconds (or however long you want)
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            // Do stuff here!

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Do stuff to update UI here!
                    Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.

Convert a tensor to numpy array in Tensorflow?

TensorFlow 2.x

Eager Execution is enabled by default, so just call .numpy() on the Tensor object.

import tensorflow as tf

a = tf.constant([[1, 2], [3, 4]])                 
b = tf.add(a, 1)

a.numpy()
# array([[1, 2],
#        [3, 4]], dtype=int32)

b.numpy()
# array([[2, 3],
#        [4, 5]], dtype=int32)

tf.multiply(a, b).numpy()
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

See NumPy Compatibility for more. It is worth noting (from the docs),

Numpy array may share memory with the Tensor object. Any changes to one may be reflected in the other.

Bold emphasis mine. A copy may or may not be returned, and this is an implementation detail based on whether the data is in CPU or GPU (in the latter case, a copy has to be made from GPU to host memory).

But why am I getting AttributeError: 'Tensor' object has no attribute 'numpy'?.
A lot of folks have commented about this issue, there are a couple of possible reasons:

  • TF 2.0 is not correctly installed (in which case, try re-installing), or
  • TF 2.0 is installed, but eager execution is disabled for some reason. In such cases, call tf.compat.v1.enable_eager_execution() to enable it, or see below.

If Eager Execution is disabled, you can build a graph and then run it through tf.compat.v1.Session:

a = tf.constant([[1, 2], [3, 4]])                 
b = tf.add(a, 1)
out = tf.multiply(a, b)

out.eval(session=tf.compat.v1.Session())    
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

See also TF 2.0 Symbols Map for a mapping of the old API to the new one.

Reduce left and right margins in matplotlib plot

Sometimes, the plt.tight_layout() doesn't give me the best view or the view I want. Then why don't plot with arbitrary margin first and do fixing the margin after plot? Since we got nice WYSIWYG from there.

import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(8,8))

plt.plot([2,5,7,8,5,3,5,7,])
plt.show()

Change border and spacing GUI here

Then paste settings into margin function to make it permanent:

fig,ax = plt.subplots(figsize=(8,8))

plt.plot([2,5,7,8,5,3,5,7,])
fig.subplots_adjust(
    top=0.981,
    bottom=0.049,
    left=0.042,
    right=0.981,
    hspace=0.2,
    wspace=0.2
)
plt.show()

Disable form auto submit on button click

another one:

if(this.checkValidity() == false) {

                $(this).addClass('was-validated');
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();

                return false;
}

How to search for string in an array

Completing remark to Jimmy Pena's accepted answer

As SeanC points out, this must be a 1-D array.

The following example call demonstrates that the IsInArray() function cannot be called only for 1-dim arrays, but also for "flat" 2-dim arrays:

Sub TestIsInArray()
    Const SearchItem As String = "ghi"
    Debug.Print "SearchItem = '" & SearchItem & "'"
    '----
    'a) Test 1-dim array
    Dim Arr As Variant
    Arr = Split("abc,def,ghi,jkl", ",")
    Debug.Print "a) 1-dim array " & vbNewLine & "   " & Join(Arr, "|") & " ~~> " & IsInArray(SearchItem, Arr)
    '----
    
        '//quick tool to create a 2-dim 1-based array
        Dim v As Variant, vals As Variant                                       
        v = Array(Array("abc", "def", "dummy", "jkl", 5), _
                  Array("mno", "pqr", "stu", "ghi", "vwx"))
        v = Application.Index(v, 0, 0)  ' create 2-dim array (2 rows, 5 cols)
    
    'b) Test "flat" 2-dim arrays
    Debug.Print "b) ""flat"" 2-dim arrays "
    Dim i As Long
    For i = LBound(v) To UBound(v)
        'slice "flat" 2-dim arrays of one row each
        vals = Application.Index(v, i, 0)
        'check for findings
        Debug.Print Format(i, "   0"), Join(vals, "|") & " ~~> " & IsInArray(SearchItem, vals)
    Next i
End Sub
Function IsInArray(stringToBeFound As String, Arr As Variant) As Boolean
'Site: https://stackoverflow.com/questions/10951687/how-to-search-for-string-in-an-array/10952705
'Note: needs a "flat" array, not necessarily a 1-dimensioned array
  IsInArray = (UBound(Filter(Arr, stringToBeFound)) > -1)
End Function

Results in VB Editor's immediate window

SearchItem = 'ghi'
a) 1-dim array 
   abc|def|ghi|jkl ~~> Wahr
b) "flat" 2-dim arrays 
   1          abc|def|dummy|jkl|5         False
   2          mno|pqr|stu|ghi|vwx         True

Remove columns from DataTable in C#

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

Automatically running a batch file as an administrator

You can use PowerShell to run b.bat as administrator from a.bat:

set mydir=%~dp0

Powershell -Command "& { Start-Process \"%mydir%b.bat\" -verb RunAs}"

It will prompt the user with a confirmation dialog. The user chooses YES, and then b.bat will be run as administrator.

How to implement authenticated routes in React Router 4?

install react-router-dom

then create two components one for valid users and other for invalid users.

try this on app.js

import React from 'react';

import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';

import ValidUser from "./pages/validUser/validUser";
import InValidUser from "./pages/invalidUser/invalidUser";
const loggedin = false;

class App extends React.Component {
 render() {
    return ( 
      <Router>
      <div>
        <Route exact path="/" render={() =>(
          loggedin ? ( <Route  component={ValidUser} />)
          : (<Route component={InValidUser} />)
        )} />

        </div>
      </Router>
    )
  }
}
export default App;

Quantile-Quantile Plot using SciPy

You can use bokeh

from bokeh.plotting import figure, show
from scipy.stats import probplot
# pd_series is the series you want to plot
series1 = probplot(pd_series, dist="norm")
p1 = figure(title="Normal QQ-Plot", background_fill_color="#E8DDCB")
p1.scatter(series1[0][0],series1[0][1], fill_color="red")
show(p1)

Write variable to file, including name

Is something like this what you're looking for?

def write_vars_to_file(f, **vars):
    for name, val in vars.items():
        f.write("%s = %s\n" % (name, repr(val)))

Usage:

>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}

Change values of select box of "show 10 entries" of jquery datatable

If you want to use 'lengthMenu' together with buttons(copy, export), you have to use this option dom: 'lBfrtip'. Here https://datatables.net/reference/option/dom you can find meaning of each symbol. For example, if you will use like this 'Bfrtip', lengthMenu will not appears.

Get exit code of a background process

This is how I solved it when I had a similar need:

# Some function that takes a long time to process
longprocess() {
        # Sleep up to 14 seconds
        sleep $((RANDOM % 15))
        # Randomly exit with 0 or 1
        exit $((RANDOM % 2))
}

pids=""
# Run five concurrent processes
for i in {1..5}; do
        ( longprocess ) &
        # store PID of process
        pids+=" $!"
done

# Wait for all processes to finish, will take max 14s
# as it waits in order of launch, not order of finishing
for p in $pids; do
        if wait $p; then
                echo "Process $p success"
        else
                echo "Process $p fail"
        fi
done

How to submit an HTML form on loading the page?

Do this :

$(document).ready(function(){
     $("#frm1").submit();
});

How to add a ScrollBar to a Stackpanel

It works like this:

<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
        <StackPanel Name="stackPanel1" Width="311">

        </StackPanel>
</ScrollViewer>

TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);

"for" vs "each" in Ruby

(1..4).each { |i| 


  a = 9 if i==3

  puts a 


}
#nil
#nil
#9
#nil

for i in 1..4

  a = 9 if i==3

  puts a

end
#nil
#nil
#9
#9

In 'for' loop, local variable is still lives after each loop. In 'each' loop, local variable refreshes after each loop.

Convert boolean result into number/integer

You can also add 0, use shift operators or xor:

val + 0;
val ^ 0;
val >> 0;
val >>> 0;
val << 0;

These have similar speeds as those from the others answers.

How can I start PostgreSQL server on Mac OS X?

There are two primary components to PostgreSQL: the database server and a client.

There is an included client via the CLI, or like me, you might be used to tools like phpMyAdmin, so it requires a separate GUI client.

For example, on macOS: install Postgres.app which is ~65 MB from: https://postgresapp.com/

Then follow these instructions:

  • install and initialise the server with the button on the right.
  • update your $PATH using terminal: sudo mkdir -p /etc/paths.d && echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp
  • and finally, install the pgAdmin GUI which is about ~100 MB from: https://www.pgadmin.org/download/pgadmin-4-macos/

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

You have to add this permission in Info.plist for iOS 10.

Photo :

Key       :  Privacy - Photo Library Usage Description    
Value   :  $(PRODUCT_NAME) photo use

Microphone :

Key        :  Privacy - Microphone Usage Description    
Value    :  $(PRODUCT_NAME) microphone use

Camera :

Key       :  Privacy - Camera Usage Description   
Value   :  $(PRODUCT_NAME) camera use

Reverse a string without using reversed() or [::-1]?

m = input("Enter string::")
def rev(s):
    z = -1
    x = len(s)
    while x != 0:
        print(s[z], end='')
        z = z-1
        x = x-1
rev(m)

Detect & Record Audio in Python

Thanks to cryo for improved version that I based my tested code below:

#Instead of adding silence at start and end of recording (values=0) I add the original audio . This makes audio sound more natural as volume is >0. See trim()
#I also fixed issue with the previous code - accumulated silence counter needs to be cleared once recording is resumed.

from array import array
from struct import pack
from sys import byteorder
import copy
import pyaudio
import wave

THRESHOLD = 500  # audio levels not normalised.
CHUNK_SIZE = 1024
SILENT_CHUNKS = 3 * 44100 / 1024  # about 3sec
FORMAT = pyaudio.paInt16
FRAME_MAX_VALUE = 2 ** 15 - 1
NORMALIZE_MINUS_ONE_dB = 10 ** (-1.0 / 20)
RATE = 44100
CHANNELS = 1
TRIM_APPEND = RATE / 4

def is_silent(data_chunk):
    """Returns 'True' if below the 'silent' threshold"""
    return max(data_chunk) < THRESHOLD

def normalize(data_all):
    """Amplify the volume out to max -1dB"""
    # MAXIMUM = 16384
    normalize_factor = (float(NORMALIZE_MINUS_ONE_dB * FRAME_MAX_VALUE)
                        / max(abs(i) for i in data_all))

    r = array('h')
    for i in data_all:
        r.append(int(i * normalize_factor))
    return r

def trim(data_all):
    _from = 0
    _to = len(data_all) - 1
    for i, b in enumerate(data_all):
        if abs(b) > THRESHOLD:
            _from = max(0, i - TRIM_APPEND)
            break

    for i, b in enumerate(reversed(data_all)):
        if abs(b) > THRESHOLD:
            _to = min(len(data_all) - 1, len(data_all) - 1 - i + TRIM_APPEND)
            break

    return copy.deepcopy(data_all[_from:(_to + 1)])

def record():
    """Record a word or words from the microphone and 
    return the data as an array of signed shorts."""

    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE)

    silent_chunks = 0
    audio_started = False
    data_all = array('h')

    while True:
        # little endian, signed short
        data_chunk = array('h', stream.read(CHUNK_SIZE))
        if byteorder == 'big':
            data_chunk.byteswap()
        data_all.extend(data_chunk)

        silent = is_silent(data_chunk)

        if audio_started:
            if silent:
                silent_chunks += 1
                if silent_chunks > SILENT_CHUNKS:
                    break
            else: 
                silent_chunks = 0
        elif not silent:
            audio_started = True              

    sample_width = p.get_sample_size(FORMAT)
    stream.stop_stream()
    stream.close()
    p.terminate()

    data_all = trim(data_all)  # we trim before normalize as threshhold applies to un-normalized wave (as well as is_silent() function)
    data_all = normalize(data_all)
    return sample_width, data_all

def record_to_file(path):
    "Records from the microphone and outputs the resulting data to 'path'"
    sample_width, data = record()
    data = pack('<' + ('h' * len(data)), *data)

    wave_file = wave.open(path, 'wb')
    wave_file.setnchannels(CHANNELS)
    wave_file.setsampwidth(sample_width)
    wave_file.setframerate(RATE)
    wave_file.writeframes(data)
    wave_file.close()

if __name__ == '__main__':
    print("Wait in silence to begin recording; wait in silence to terminate")
    record_to_file('demo.wav')
    print("done - result written to demo.wav")

Eclipse interface icons very small on high resolution screen in Windows 8.1

The below change works seamlessly.

Quoting from CrazyPenguin's reply

"For those, like me, who found that even on the new Eclipse it wasn't scaled, see here: swt-autoscale-tweaks Basically I added -Dswt.autoScale=quarter to my eclipse.ini file."

How to debug Google Apps Script (aka where does Logger.log log to?)

2017 Update: Stackdriver Logging is now available for Google Apps Script. From the menu bar in the script editor, goto: View > Stackdriver Logging to view or stream the logs.

console.log() will write DEBUG level messages

Example onEdit() logging:

function onEdit (e) {
  var debug_e = {
    authMode:  e.authMode,  
    range:  e.range.getA1Notation(),    
    source:  e.source.getId(),
    user:  e.user,   
    value:  e.value,
    oldValue: e. oldValue
  }

  console.log({message: 'onEdit() Event Object', eventObject: debug_e});
}

Then check the logs in the Stackdriver UI labeled onEdit() Event Object to see the output

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

Is there an easy way to return a string repeated X number of times?

You can create an ExtensionMethod to do that!

public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    string ret = "";

    for (var x = 0; x < count; x++)
    {
      ret += str;
    }

    return ret;
  }
}

Or using @Dan Tao solution:

public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    if (count == 0)
      return "";

    return string.Concat(Enumerable.Repeat(indent, N))
  }
}

Convert JSON string to dict using Python

If you trust the data source, you can use eval to convert your string into a dictionary:

eval(your_json_format_string)

Example:

>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>

Array versus linked-list

I'll add another - lists can act as purely functional data structures.

For instance, you can have completely different lists sharing the same end section

a = (1 2 3 4, ....)
b = (4 3 2 1 1 2 3 4 ...)
c = (3 4 ...)

i.e.:

b = 4 -> 3 -> 2 -> 1 -> a
c = a.next.next  

without having to copy the data being pointed to by a into b and c.

This is why they are so popular in functional languages, which use immutable variables - prepend and tail operations can occur freely without having to copy the original data - very important features when you're treating data as immutable.

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

It is up to the browser but they behave in similar ways.

I have tested FF, IE7, Opera and Chrome.

F5 usually updates the page only if it is modified. The browser usually tries to use all types of cache as much as possible and adds an "If-modified-since" header to the request. Opera differs by sending a "Cache-Control: no-cache".

CTRL-F5 is used to force an update, disregarding any cache. IE7 adds an "Cache-Control: no-cache", as does FF, which also adds "Pragma: no-cache". Chrome does a normal "If-modified-since" and Opera ignores the key.

If I remember correctly it was Netscape which was the first browser to add support for cache-control by adding "Pragma: No-cache" when you pressed CTRL-F5.

Edit: Updated table

The table below is updated with information on what will happen when the browser's refresh-button is clicked (after a request by Joel Coehoorn), and the "max-age=0" Cache-control-header.

Updated table, 27 September 2010

+------------------------------------------------------------+
¦  UPDATED   ¦                Firefox 3.x                    ¦
¦27 SEP 2010 ¦  +--------------------------------------------¦
¦            ¦  ¦             MSIE 8, 7                      ¦
¦ Version 3  ¦  ¦  +-----------------------------------------¦
¦            ¦  ¦  ¦          Chrome 6.0                     ¦
¦            ¦  ¦  ¦  +--------------------------------------¦
¦            ¦  ¦  ¦  ¦       Chrome 1.0                     ¦
¦            ¦  ¦  ¦  ¦  +-----------------------------------¦
¦            ¦  ¦  ¦  ¦  ¦    Opera 10, 9                    ¦
¦            ¦  ¦  ¦  ¦  ¦  +--------------------------------¦
¦            ¦  ¦  ¦  ¦  ¦  ¦                                ¦
+------------+--+--+--+--+--+--------------------------------¦
¦          F5¦IM¦I ¦IM¦IM¦C ¦                                ¦
¦    SHIFT-F5¦- ¦- ¦CP¦IM¦- ¦ Legend:                        ¦
¦     CTRL-F5¦CP¦C ¦CP¦IM¦- ¦ I = "If-Modified-Since"        ¦
¦      ALT-F5¦- ¦- ¦- ¦- ¦*2¦ P = "Pragma: No-cache"         ¦
¦    ALTGR-F5¦- ¦I ¦- ¦- ¦- ¦ C = "Cache-Control: no-cache"  ¦
+------------+--+--+--+--+--¦ M = "Cache-Control: max-age=0" ¦
¦      CTRL-R¦IM¦I ¦IM¦IM¦C ¦ - = ignored                    ¦
¦CTRL-SHIFT-R¦CP¦- ¦CP¦- ¦- ¦                                ¦
+------------+--+--+--+--+--¦                                ¦
¦       Click¦IM¦I ¦IM¦IM¦C ¦ With 'click' I refer to a      ¦
¦ Shift-Click¦CP¦I ¦CP¦IM¦C ¦ mouse click on the browsers    ¦
¦  Ctrl-Click¦*1¦C ¦CP¦IM¦C ¦ refresh-icon.                  ¦
¦   Alt-Click¦IM¦I ¦IM¦IM¦C ¦                                ¦
¦ AltGr-Click¦IM¦I ¦- ¦IM¦- ¦                                ¦
+------------------------------------------------------------+

Versions tested:

  • Firefox 3.1.6 and 3.0.6 (WINXP)
  • MSIE 8.0.6001 and 7.0.5730.11 (WINXP)
  • Chrome 6.0.472.63 and 1.0.151.48 (WINXP)
  • Opera 10.62 and 9.61 (WINXP)

Notes:

  1. Version 3.0.6 sends I and C, but 3.1.6 opens the page in a new tab, making a normal request with only "I".

  2. Version 10.62 does nothing. 9.61 might do C unless it was a typo in my old table.

Note about Chrome 6.0.472: If you do a forced reload (like CTRL-F5) it behaves like the url is internally marked to always do a forced reload. The flag is cleared if you go to the address bar and press enter.

Better way to shuffle two numpy arrays in unison

This seems like a very simple solution:

import numpy as np
def shuffle_in_unison(a,b):

    assert len(a)==len(b)
    c = np.arange(len(a))
    np.random.shuffle(c)

    return a[c],b[c]

a =  np.asarray([[1, 1], [2, 2], [3, 3]])
b =  np.asarray([11, 22, 33])

shuffle_in_unison(a,b)
Out[94]: 
(array([[3, 3],
        [2, 2],
        [1, 1]]),
 array([33, 22, 11]))

How do I uninstall a package installed using npm link?

The package can be uninstalled using the same uninstall or rm command that can be used for removing installed packages. The only thing to keep in mind is that the link needs to be uninstalled globally - the --global flag needs to be provided.

In order to uninstall the globally linked foo package, the following command can be used (using sudo if necessary, depending on your setup and permissions)

sudo npm rm --global foo

This will uninstall the package.

To check whether a package is installed, the npm ls command can be used:

npm ls --global foo

Get source jar files attached to Eclipse for Maven-managed dependencies

overthink suggested using the setup in the pom:

<project>
...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <configuration>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
                ... other stuff ...
            </configuration>
        </plugin>
    </plgins>
</build>
...

First i thought this still won't attach the javadoc and sources (as i tried unsuccessfully with that -DdownloadSources option before).

But surprise - the .classpath file IS getting its sources and javadoc attached when using the POM variant!

C# Equivalent of SQL Server DataTypes

public static string FromSqlType(string sqlTypeString)
{
    if (! Enum.TryParse(sqlTypeString, out Enums.SQLType typeCode))
    {
        throw new Exception("sql type not found");
    }
    switch (typeCode)
    {
        case Enums.SQLType.varbinary:
        case Enums.SQLType.binary:
        case Enums.SQLType.filestream:
        case Enums.SQLType.image:
        case Enums.SQLType.rowversion:
        case Enums.SQLType.timestamp://?
            return "byte[]";
        case Enums.SQLType.tinyint:
            return "byte";
        case Enums.SQLType.varchar:
        case Enums.SQLType.nvarchar:
        case Enums.SQLType.nchar:
        case Enums.SQLType.text:
        case Enums.SQLType.ntext:
        case Enums.SQLType.xml:
            return "string";
        case Enums.SQLType.@char:
            return "char";
        case Enums.SQLType.bigint:
            return "long";
        case Enums.SQLType.bit:
            return "bool";
        case Enums.SQLType.smalldatetime:
        case Enums.SQLType.datetime:
        case Enums.SQLType.date:
        case Enums.SQLType.datetime2:
            return "DateTime";
        case Enums.SQLType.datetimeoffset:
            return "DateTimeOffset";
        case Enums.SQLType.@decimal:
        case Enums.SQLType.money:
        case Enums.SQLType.numeric:
        case Enums.SQLType.smallmoney:
            return "decimal";
        case Enums.SQLType.@float:
            return "double";
        case Enums.SQLType.@int:
            return "int";
        case Enums.SQLType.real:
            return "Single";
        case Enums.SQLType.smallint:
            return "short";
        case Enums.SQLType.uniqueidentifier:
            return "Guid";
        case Enums.SQLType.sql_variant:
            return "object";
        case Enums.SQLType.time:
            return "TimeSpan";
        default:
            throw new Exception("none equal type");
    }
}

public enum SQLType
{
    varbinary,//(1)
    binary,//(1)
    image,
    varchar,
    @char,
    nvarchar,//(1)
    nchar,//(1)
    text,
    ntext,
    uniqueidentifier,
    rowversion,
    bit,
    tinyint,
    smallint,
    @int,
    bigint,
    smallmoney,
    money,
    numeric,
    @decimal,
    real,
    @float,
    smalldatetime,
    datetime,
    sql_variant,
    table,
    cursor,
    timestamp,
    xml,
    date,
    datetime2,
    datetimeoffset,
    filestream,
    time,
}

Why does viewWillAppear not get called when an app comes back from the background?

Swift 4.2 / 5

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground),
                                           name: Notification.Name.UIApplicationWillEnterForeground,
                                           object: nil)
}

@objc func willEnterForeground() {
   // do what's needed
}

'this' vs $scope in AngularJS controllers

I recommend you to read the following post: AngularJS: "Controller as" or "$scope"?

It describes very well the advantages of using "Controller as" to expose variables over "$scope".

I know you asked specifically about methods and not variables, but I think that it's better to stick to one technique and be consistent with it.

So for my opinion, because of the variables issue discussed in the post, it's better to just use the "Controller as" technique and also apply it to the methods.

Can vue-router open a link in a new tab?

If you are interested ONLY on relative paths like: /dashboard, /about etc, See other answers.

If you want to open an absolute path like: https://www.google.com to a new tab, you have to know that Vue Router is NOT meant to handle those.

However, they seems to consider that as a feature-request. #1280. But until they do that,



Here is a little trick you can do to handle external links with vue-router.

  • Go to the router configuration (probably router.js) and add this code:
/* Vue Router is not meant to handle absolute urls. */
/* So whenever we want to deal with those, we can use this.$router.absUrl(url) */
Router.prototype.absUrl = function(url, newTab = true) {
  const link = document.createElement('a')
  link.href = url
  link.target = newTab ? '_blank' : ''
  if (newTab) link.rel = 'noopener noreferrer' // IMPORTANT to add this
  link.click()
}

Now, whenever we deal with absolute URLs we have a solution. For example to open google to a new tab

this.$router.absUrl('https://www.google.com)

Remember that whenever we open another page to a new tab we MUST use noopener noreferrer.

Read more here

or Here

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

On my 64 bit system I noticed that the following directory existed:

/usr/include/c++/4.4/x86_64-linux-gnu/32/bits

It would then make sense that on my 32 bit system that had been setup for 64bit cross compiling there should be a corresponding directory like:

/usr/include/c++/4.4/i686-linux-gnu/64/bits

I double checked and this directory did not exist. Running g++ with the verbose parameter showed that the compiler was actually looking for something in this location:

jesse@shalored:~/projects/test$ g++ -v -m64 main.cpp 
Using built-in specs.
Target: i686-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.4.4-14ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.4 --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu
Thread model: posix
gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5) 
COLLECT_GCC_OPTIONS='-v' '-m64' '-shared-libgcc' '-mtune=generic'
 /usr/lib/gcc/i686-linux-gnu/4.4.5/cc1plus -quiet -v -imultilib 64 -D_GNU_SOURCE main.cpp -D_FORTIFY_SOURCE=2 -quiet -dumpbase main.cpp -m64 -mtune=generic -auxbase main -version -fstack-protector -o /tmp/ccMvIfFH.s
ignoring nonexistent directory "/usr/include/c++/4.4/i686-linux-gnu/64"
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../i686-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/include/c++/4.4
 /usr/include/c++/4.4/backward
 /usr/local/include
 /usr/lib/gcc/i686-linux-gnu/4.4.5/include
 /usr/lib/gcc/i686-linux-gnu/4.4.5/include-fixed
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
GNU C++ (Ubuntu/Linaro 4.4.4-14ubuntu5) version 4.4.5 (i686-linux-gnu)
    compiled by GNU C version 4.4.5, GMP version 4.3.2, MPFR version 3.0.0-p3.
GGC heuristics: --param ggc-min-expand=98 --param ggc-min-heapsize=128197
Compiler executable checksum: 1fe36891f4a5f71e4a498e712867261c
In file included from main.cpp:1:
/usr/include/c++/4.4/iostream:39: fatal error: bits/c++config.h: No such file or directory
compilation terminated.

The error regarding the ignoring nonexistent directory was the clue. Unfortunately, I still don't know what package I need to install to have this directory show up so I just copied the /usr/include/c++/4.4/x86_64-linux-gnu/bits directory from my 64 bit machine to /usr/include/c++/4.4/i686-linux-gnu/64/bits on my 32 machine.

Now compiling with just the -m64 works correctly. The major drawback is that this is still not the correct way to do things and I am guessing the next time Update Manager installs and update to g++ things may break.

Set value of textbox using JQuery

Make sure you have the right selector, and then wait until the page is ready and that the element exists until you run the function.

$(function(){
    $('#searchBar').val('hi')
});

As Derek points out, the ID is wrong as well.

Change to $('#main_search')

How do I implement basic "Long Polling"?

Here are some classes I use for long-polling in C#. There are basically 6 classes (see below).

  1. Controller: Processes actions required to create a valid response (db operations etc.)
  2. Processor: Manages asynch communication with the web page (itself)
  3. IAsynchProcessor: The service processes instances that implement this interface
  4. Sevice: Processes request objects that implement IAsynchProcessor
  5. Request: The IAsynchProcessor wrapper containing your response (object)
  6. Response: Contains custom objects or fields

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

For windows users, this can also be caused by filesystem corruption.

If all steps above do not correct the error:

  • Close Android Studio
  • Open Command Prompt as Administrator
  • Run a chkdsk /f on the drive your app is stored
  • Delete .idea folder
  • Restart Android Studio

difference between variables inside and outside of __init__()

This is very easy to understand if you track class and instance dictionaries.

class C:
   one = 42
   def __init__(self,val):
        self.two=val
ci=C(50)
print(ci.__dict__)
print(C.__dict__)

The result will be like this:

{'two': 50}
{'__module__': '__main__', 'one': 42, '__init__': <function C.__init__ at 0x00000213069BF6A8>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}

Note I set the full results in here but what is important that the instance ci dict will be just {'two': 50}, and class dictionary will have the 'one': 42 key value pair inside.

This is all you should know about that specific variables.

How to move columns in a MySQL table?

Change column position:

ALTER TABLE Employees 
   CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;

If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:

ALTER TABLE UserOrder 
   CHANGE order_id order_id INT(11) NOT NULL FIRST;

How can I directly view blobs in MySQL Workbench

there is few things that you can do

SELECT GROUP_CONCAT(CAST(name AS CHAR))
FROM product
WHERE  id   IN (12345,12346,12347)

If you want to order by the query you can order by cast as well like below

SELECT GROUP_CONCAT(name ORDER BY name))
FROM product
WHERE id   IN (12345,12346,12347)

as it says on this blog

http://www.kdecom.com/mysql-group-concat-blob-bug-solved/

What is the difference between a mutable and immutable string in C#?

Strings are mutable because .NET use string pool behind the scene. It means :

string name = "My Country";
string name2 = "My Country";

Both name and name2 are referring to same memory location from string pool. Now suppose you want to change name2 to :

name2 = "My Loving Country";

It will look in to string pool for the string "My Loving Country", if found you will get the reference of it other wise new string "My Loving Country" will be created in string pool and name2 will get reference of it. But it this whole process "My Country" was not changed because other variable like name is still using it. And that is the reason why string are IMMUTABLE.

StringBuilder works in different manner and don't use string pool. When we create any instance of StringBuilder :

var address  = new StringBuilder(500);

It allocate memory chunk of size 500 bytes for this instance and all operation just modify this memory location and this memory not shared with any other object. And that is the reason why StringBuilder is MUTABLE.

I hope it will help.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

You can try this:

NSLog(@"%@", NSStringFromCGPoint(cgPoint));

There are a number of functions provided by UIKit that convert the various CG structs into NSStrings. The reason it doesn't work is because %@ signifies an object. A CGPoint is a C struct (and so are CGRects and CGSizes).

StringIO in Python3

In order to make examples from here work with Python 3.5.2, you can rewrite as follows :

import io
data =io.BytesIO(b"1, 2, 3\n4, 5, 6") 
import numpy
numpy.genfromtxt(data, delimiter=",")

The reason for the change may be that the content of a file is in data (bytes) which do not make text until being decoded somehow. genfrombytes may be a better name than genfromtxt.

JS. How to replace html element with another element/text, represented in string?

As the Jquery replaceWith() code was too bulky, tricky and complicated, here's my own solution. =)

The best way is to use outerHTML property, but it is not crossbrowsered yet, so I did some trick, weird enough, but simple.

Here is the code

var str = '<a href="http://www.com">item to replace</a>'; //it can be anything
var Obj = document.getElementById('TargetObject'); //any element to be fully replaced
if(Obj.outerHTML) { //if outerHTML is supported
    Obj.outerHTML=str; ///it's simple replacement of whole element with contents of str var
}
else { //if outerHTML is not supported, there is a weird but crossbrowsered trick
    var tmpObj=document.createElement("div");
    tmpObj.innerHTML='<!--THIS DATA SHOULD BE REPLACED-->';
    ObjParent=Obj.parentNode; //Okey, element should be parented
    ObjParent.replaceChild(tmpObj,Obj); //here we placing our temporary data instead of our target, so we can find it then and replace it into whatever we want to replace to
    ObjParent.innerHTML=ObjParent.innerHTML.replace('<div><!--THIS DATA SHOULD BE REPLACED--></div>',str);
}

That's all

How do you tell if a string contains another string in POSIX sh?

There's Bash regular expressions. Or there's 'expr':

 if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi

Partly JSON unmarshal into a map in Go

This can be accomplished by Unmarshaling into a map[string]json.RawMessage.

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

To further parse sendMsg, you could then do something like:

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

For say, you can do the same thing and unmarshal into a string:

var str string
err = json.Unmarshal(objmap["say"], &str)

EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:

type sendMsg struct {
    User string
    Msg  string
}

Example: https://play.golang.org/p/OrIjvqIsi4-

Unable to find valid certification path to requested target - error even after cert imported

My problem was that a Cloud Access Security Broker, NetSkope, was installed on my work laptop through a software update. This was altering the certificate chain and I was still not able to connect to the server through my java client after importing the entire chain to my cacerts keystore. I disabled NetSkope and was able to successfully connect.

How to prevent robots from automatically filling up a form?

A very simple way is to provide some fields like <textarea style="display:none;" name="input"></textarea> and discard all replies that have this filled in.

Another approach is to generate the whole form (or just the field names) using Javascript; few bots can run it.

Anyway, you won't do much against live "bots" from Taiwan or India, that are paid $0.03 per one posted link, and make their living that way.

Android WebView, how to handle redirects in app instead of opening a browser

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
    super.onPageStarted(view, url, favicon);
    if (url.equals("your url")) {
        
            Intent intent = new Intent(view.getContext(), TransferAllDoneActivity.class);
            startActivity(intent);
        
    }
}

How to sort List<Integer>?

You can use Collections for to sort data:

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;

public class tes
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();

        lList.add(4);       
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);

        Collections.sort(lList);

        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }

    }
}

Validation to check if password and confirm password are same is not working

function validate()
{
  var a=documents.forms["yourformname"]["yourpasswordfieldname"].value;
  var b=documents.forms["yourformname"]["yourconfirmpasswordfieldname"].value;
  if(!(a==b))
  {
    alert("both passwords are not matching");
    return false;
  }
  return true;
}

Best way to move files between S3 buckets?

Here is a ruby class for performing this: https://gist.github.com/4080793

Example usage:

$ gem install aws-sdk
$ irb -r ./bucket_sync_service.rb
> from_creds = {aws_access_key_id:"XXX",
                aws_secret_access_key:"YYY",
                bucket:"first-bucket"}
> to_creds = {aws_access_key_id:"ZZZ",
              aws_secret_access_key:"AAA",
              bucket:"first-bucket"}
> syncer = BucketSyncService.new(from_creds, to_creds)
> syncer.debug = true # log each object
> syncer.perform

How can I simulate an anchor click via jquery?

Using Jure's script I made this, to easily "click" as many elements as you want.
I just used it Google Reader on 1600+ items and it worked perfectly (in Firefox)!

var e = document.createEvent('MouseEvents');
e.initEvent( 'click', true, true );
$(selector).each(function(){this.dispatchEvent(e);});

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

T-SQL Substring - Last 3 Characters

Because more ways to think about it are always good:

select reverse(substring(reverse(columnName), 1, 3))

Oracle SQL Developer and PostgreSQL

Oracle SQL Developer doesn't support connections to PostgreSQL. Use pgAdmin to connect to PostgreSQL instead, you can get it from the following URL http://www.pgadmin.org/download/windows.php

Specify the date format in XMLGregorianCalendar

Much simpler using only SimpleDateFormat, without passing all the parameters individual:

    String FORMATER = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    DateFormat format = new SimpleDateFormat(FORMATER);

    Date date = new Date();
    XMLGregorianCalendar gDateFormatted =
        DatatypeFactory.newInstance().newXMLGregorianCalendar(format.format(date));

Full example here.

Note: This is working only to remove the last 2 fields: milliseconds and timezone or to remove the entire time component using formatter yyyy-MM-dd.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

That's called SQL INJECTION. The ' tries to open/close a string in your mysql query. You should always escape any string that gets into your queries.

for example,

instead of this:

"VALUES ('$sender_id') "

do this:

"VALUES ('". mysql_real_escape_string($sender_id)  ."') "

(or equivalent, of course)

However, it's better to automate this, using PDO, named parameters, prepared statements or many other ways. Research about this and SQL Injection (here you have some techniques).

Hope it helps. Cheers

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

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

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

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

PuTTY Line discipline options

Explanation:

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

4.3.8 ‘Local echo’

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

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

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

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

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

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

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

How to compare two dates in Objective-C

Here's the function from Naveed Rafi's answer converted to Swift if anyone else is looking for it:

func isSameDate(#date1: NSDate, date2: NSDate) -> Bool {
    let calendar = NSCalendar()
    let date1comp = calendar.components(.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit, fromDate: date1)
    let date2comp = calendar.components(.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit, fromDate: date2)
    return (date1comp.year == date2comp.year) && (date1comp.month == date2comp.month) && (date1comp.day == date2comp.day)
}

Pushing an existing Git repository to SVN

I needed this as well, and with the help of Bombe's answer + some fiddling around, I got it working. Here's the recipe:

Import Git -> Subversion

1. cd /path/to/git/localrepo
2. svn mkdir --parents protocol:///path/to/repo/PROJECT/trunk -m "Importing git repo"
3. git svn init protocol:///path/to/repo/PROJECT -s
4. git svn fetch
5. git rebase origin/trunk
5.1.  git status
5.2.  git add (conflicted-files)
5.3.  git rebase --continue
5.4.  (repeat 5.1.)
6. git svn dcommit

After #3 you'll get a cryptic message like this:

Using higher level of URL: protocol:///path/to/repo/PROJECT => protocol:///path/to/repo

Just ignore that.

When you run #5, you might get conflicts. Resolve these by adding files with state "unmerged" and resuming rebase. Eventually, you'll be done; then sync back to the SVN repository, using dcommit. That's all.

Keeping repositories in sync

You can now synchronise from SVN to Git, using the following commands:

git svn fetch
git rebase trunk

And to synchronise from Git to SVN, use:

git svn dcommit

Final note

You might want to try this out on a local copy, before applying to a live repository. You can make a copy of your Git repository to a temporary place; simply use cp -r, as all data is in the repository itself. You can then set up a file-based testing repository, using:

svnadmin create /home/name/tmp/test-repo

And check a working copy out, using:

svn co file:///home/name/tmp/test-repo svn-working-copy

That'll allow you to play around with things before making any lasting changes.

Addendum: If you mess up git svn init

If you accidentally run git svn init with the wrong URL, and you weren't smart enough to take a backup of your work (don't ask ...), you can't just run the same command again. You can however undo the changes by issuing:

rm -rf .git/svn
edit .git/config

And remove the section [svn-remote "svn"] section.

You can then run git svn init anew.

Is it possible to change javascript variable values while debugging in Google Chrome?

It looks like not.

Put a breakpoint, when it stops switch to the console, try to set the variable. It does not error when you assign it a different value, but if you read it after the assignment, it's unmodified. :-/

Django template how to look up a dictionary value with a variable

For me creating a python file named template_filters.py in my App with below content did the job

# coding=utf-8
from django.template.base import Library

register = Library()


@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

usage is like what culebrón said :

{{ mydict|get_item:item.NAME }}

How to get the path of running java program

You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()

SQL Query for Selecting Multiple Records

You want to add the IN() clause to your WHERE

SELECT * 
FROM `Buses` 
WHERE `BusID` IN (Id1, ID2, ID3,.... put your ids here)

If you have a list of Ids stored in a table you can also do this:

SELECT * 
FROM `Buses` 
WHERE `BusID` IN (SELECT Id FROM table)

Does uninstalling a package with "pip" also remove the dependent packages?

You may have a try for https://github.com/cls1991/pef. It will remove package with its all dependencies.

How can I find out if an .EXE has Command-Line Options?

Just use IDA PRO (https://www.hex-rays.com/products/ida/index.shtml) to disassemble the file, and search for some known command line option (using Search...Text) - in that section you will then typically see all the command line options - for the program (LIB2NIST.exe) in the screenshot below, for example, it shows a documented command line option (/COM2TAG) but also some undocumented ones, like /L. Hope this helps?

enter image description here

Nth word in a string variable

STRING=(one two three four)
echo "${STRING[n]}"

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

Here is how to build a function that returns a result set that can be queried as if it were a table:

SQL> create type emp_obj is object (empno number, ename varchar2(10));
  2  /

Type created.

SQL> create type emp_tab is table of emp_obj;
  2  /

Type created.

SQL> create or replace function all_emps return emp_tab
  2  is
  3     l_emp_tab emp_tab := emp_tab();
  4     n integer := 0;
  5  begin
  6     for r in (select empno, ename from emp)
  7     loop
  8        l_emp_tab.extend;
  9        n := n + 1;
 10       l_emp_tab(n) := emp_obj(r.empno, r.ename);
 11     end loop;
 12     return l_emp_tab;
 13  end;
 14  /

Function created.

SQL> select * from table (all_emps);

     EMPNO ENAME
---------- ----------
      7369 SMITH
      7499 ALLEN
      7521 WARD
      7566 JONES
      7654 MARTIN
      7698 BLAKE
      7782 CLARK
      7788 SCOTT
      7839 KING
      7844 TURNER
      7902 FORD
      7934 MILLER

How to force a web browser NOT to cache images

I would use:

<img src="picture.jpg?20130910043254">

where "20130910043254" is the modification time of the file.

When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes.

I think there are two types of simple solutions: 1) those which come to mind first (straightforward solutions, because they are easy to come up with), 2) those which you end up with after thinking things over (because they are easy to use). Apparently, you won't always benefit if you chose to think things over. But the second options is rather underestimated, I believe. Just think why php is so popular ;)

Tab Escape Character?

For someone who needs quick reference of C# Escape Sequences that can be used in string literals:

\t     Horizontal tab (ASCII code value: 9)

\n     Line feed (ASCII code value: 10)

\r     Carriage return (ASCII code value: 13)

\'     Single quotation mark

\"     Double quotation mark

\\     Backslash

\?     Literal question mark

\x12     ASCII character in hexadecimal notation (e.g. for 0x12)

\x1234     Unicode character in hexadecimal notation (e.g. for 0x1234)

It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline which gets adjusted to current OS settings. With .Net Core it gets really important.

Listen to port via a Java socket

Try this piece of code, rather than ObjectInputStream.

BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
    String cominginText = "";
    try
    {
        cominginText = in.readLine ();
        System.out.println (cominginText);
    }
    catch (IOException e)
    {
        //error ("System: " + "Connection to server lost!");
        System.exit (1);
        break;
    }
}

Is quitting an application frowned upon?

If you specify API >= 16, Activity#finishAffinity() meets your needs.

how to get selected row value in the KendoUI

One way is to use the Grid's select() and dataItem() methods.

In single selection case, select() will return a single row which can be passed to dataItem()

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
// selectedItem has EntityVersionId and the rest of your model

For multiple row selection select() will return an array of rows. You can then iterate through the array and the individual rows can be passed into the grid's dataItem().

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function(index, row) {
  var selectedItem = entityGrid.dataItem(row);
  // selectedItem has EntityVersionId and the rest of your model
});

Changing background colour of tr element on mouseover

tr:hover td {background-color:#000;}

Using an HTTP PROXY - Python

You can do it even without the HTTP_PROXY environment variable. Try this sample:

import urllib2

proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

html = urllib2.urlopen("http://www.google.com").read()
print html

In your case it really seems that the proxy server is refusing the connection.


Something more to try:

import urllib2

#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"

proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}

proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)

req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html

Edit 2014: This seems to be a popular question / answer. However today I would use third party requests module instead.

For one request just do:

import requests

r = requests.get("http://www.google.com", 
                 proxies={"http": "http://61.233.25.166:80"})
print(r.text)

For multiple requests use Session object so you do not have to add proxies parameter in all your requests:

import requests

s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}

r = s.get("http://www.google.com")
print(r.text)

JavaScript dictionary with names

Try:

var myMappings = {
    "Name":     "10%",
    "Phone":    "10%",
    "Address":  "50%",
    "Zip":      "10%",
    "Comments": "20%"
}

// Access is like this
myMappings["Name"] // Returns "10%"
myMappings.Name // The same thing as above

// To loop through...
for(var title in myMappings) {
    // Do whatever with myMappings[title]
}