Programs & Examples On #Doctest

The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown. The test cases and expected output can be copied from an interactive Python interpreter session. During regression testing doctest alerts about failed cases.

pip is not able to install packages correctly: Permission denied error

Set up a virtualenv:

% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py 
% sudo python /tmp/get-pip.py

These commands install pip into the global site-packages directory.

% sudo pip install virtualenv

and ditto for virtualenv:

% mkdir -p ~/.virtualenvs

I like my virtualenvs under one tree in my home directory called .virtualenvs

% virtualenv ~/.virtualenvs/lxmltest

Creates a virtualenv.

% . ~/.virtualenvs/lxmltest/bin/activate

Removes the need to specify the full path to pip/python in this virtualenv.

% pip install lxml

Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest and start again from a new virtualenv.

How do I configure PyCharm to run py.test tests?

With 2018.3 it appears to automatically detect that I'm using pytest, which is nice, but it still doesn't allow running from the top level of the project. I had to run pytest for each tests directory individually.

However, I found that I could choose one of the configurations and manually edit it to run at the root of the project and that this worked. I have to manually choose it in the Configurations drop-down - can't right click on the root folder in the Project pane. But at least it allows me to run all tests at once.

Altering column size in SQL Server

You can use ALTER command to modify the table schema.

The syntax for modifying the column size is

ALTER table table_name modify COLUMN column_name varchar (size);

JavaScript: What are .extend and .prototype used for?

This seems to be the clearest and simplest example to me, this just appends property or replaces existing.

function replaceProperties(copyTo, copyFrom)  {
  for (var property in copyFrom) 
    copyTo[property] =  copyFrom[property]
  return copyTo
}

How can I convert a string to an int in Python?

>>> a = "123"
>>> int(a)
123

Here's some freebie code:

def getTwoNumbers():
    numberA = raw_input("Enter your first number: ")
    numberB = raw_input("Enter your second number: ")
    return int(numberA), int(numberB)

How to format a date using ng-model?

I use the following directive that makes me and most users very happy! It uses moment for parsing and formatting. It looks a little bit like the one by SunnyShah, mentioned earlier.

angular.module('app.directives')

.directive('appDatetime', function ($window) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            var moment = $window.moment;

            ngModel.$formatters.push(formatter);
            ngModel.$parsers.push(parser);

            element.on('change', function (e) {
                var element = e.target;
                element.value = formatter(ngModel.$modelValue);
            });

            function parser(value) {
                var m = moment(value);
                var valid = m.isValid();
                ngModel.$setValidity('datetime', valid);
                if (valid) return m.valueOf();
                else return value;
            }

            function formatter(value) {
                var m = moment(value);
                var valid = m.isValid();
                if (valid) return m.format("LLLL");
                else return value;

            }

        } //link
    };

}); //appDatetime

In my form i use it like this:

<label>begin: <input type="text" ng-model="doc.begin" app-datetime required /></label>
<label>end: <input type="text" ng-model="doc.end" app-datetime required /></label>

This will bind a timestamp (milliseconds since 1970) to doc.begin and doc.end.

How to use C++ in Go

Seems that currently SWIG is best solution for this:

http://www.swig.org/Doc2.0/Go.html

It supports inheritance and even allows to subclass C++ class with Go struct so when overridden methods are called in C++ code, Go code is fired.

Section about C++ in Go FAQ is updated and now mentions SWIG and no longer says "because Go is garbage-collected it will be unwise to do so, at least naively".

Algorithm to return all combinations of k elements from n

Short example in Python:

def comb(sofar, rest, n):
    if n == 0:
        print sofar
    else:
        for i in range(len(rest)):
            comb(sofar + rest[i], rest[i+1:], n-1)

>>> comb("", "abcde", 3)
abc
abd
abe
acd
ace
ade
bcd
bce
bde
cde

For explanation, the recursive method is described with the following example:

Example: A B C D E
All combinations of 3 would be:

  • A with all combinations of 2 from the rest (B C D E)
  • B with all combinations of 2 from the rest (C D E)
  • C with all combinations of 2 from the rest (D E)

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

There is a new spec called the Native File System API that allows you to do this properly like this:

const result = await window.chooseFileSystemEntries({ type: "save-file" });

There is a demo here, but I believe it is using an origin trial so it may not work in your own website unless you sign up or enable a config flag, and it obviously only works in Chrome. If you're making an Electron app this might be an option though.

Fragments onResume from back stack

If a fragment is put on backstack, Android simply destroys its view. The fragment instance itself is not killed. A simple way to start should to to listen to the onViewCreated event, an put you "onResume()" logic there.

boolean fragmentAlreadyLoaded = false;
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onViewCreated(view, savedInstanceState);

        if (savedInstanceState == null && !fragmentAlreadyLoaded) {
            fragmentAlreadyLoaded = true;

            // Code placed here will be executed once
        }

        //Code placed here will be executed even when the fragment comes from backstack
    }

How does Java import work?

In dynamic languages, when the interpreter imports, it simply reads a file and evaluates it.

In C, external libraries are located by the linker at compile time to build the final object if the library is statically compiled, while for dynamic libraries a smaller version of the linker is called at runtime which remaps addresses and so makes code in the library available to the executable.

In Java, import is simply used by the compiler to let you name your classes by their unqualified name, let's say String instead of java.lang.String. You don't really need to import java.lang.* because the compiler does it by default. However this mechanism is just to save you some typing. Types in Java are fully qualified class names, so a String is really a java.lang.String object when the code is run. Packages are intended to prevent name clashes and allow two classes to have the same simple name, instead of relying on the old C convention of prefixing types like this. java_lang_String. This is called namespacing.

BTW, in Java there's the static import construct, which allows to further save typing if you use lots of constants from a certain class. In a compilation unit (a .java file) which declares

import static java.lang.Math.*;

you can use the constant PI in your code, instead of referencing it through Math.PI, and the method cos() instead of Math.cos(). So for example you can write

double r = cos(PI * theta);

Once you understand that classes are always referenced by their fully qualified name in the final bytecode, you must understand how the class code is actually loaded. This happens the first time an object of that class is created, or the first time a static member of the class is accessed. At this time, the ClassLoader tries to locate the class and instantiate it. If it can't find the class a NoClassDefFoundError is thrown (or a a ClassNotFoundException if the class is searched programmatically). To locate the class, the ClassLoader usually checks the paths listed in the $CLASSPATH environment variable.

To solve your problem, it seems you need an applet element like this

<applet
  codebase = "http://san.redenetimoveis.com"
  archive="test.jar, core.jar"
  code="com.colorfulwolf.webcamapplet.WebcamApplet"      
  width="550" height="550" >

BTW, you don't need to import the archives in the standard JRE.

How to parse JSON using Node.js?

Parsing a JSON stream? Use JSONStream.

var request = require('request')
  , JSONStream = require('JSONStream')

request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
    .pipe(JSONStream.parse('rows.*'))
    .pipe(es.mapSync(function (data) {
      return data
    }))

https://github.com/dominictarr/JSONStream

Changing :hover to touch/click for mobile devices

I am a CSS noob but I have noticed that hover will work for touch screens so long as it's a "hoverable" element: image, link, button. You can do it all with CSS using the following trick.

Change your div background to an actual image tag within the div or create a dummy link around the entire div, it will then register as a hover when you touch the image.

Doing this will mean that you need the rest of your page to also be "hoverable" so when you touch outside of the image it recognizes that info-slide:hover has ended. My trick is to make all of my other content dummy links.

It's not very elegant but it works.

Having the output of a console application in Visual Studio instead of the console

regarding System.Diagnostics.Debug producing a lot of "junk" in the Output window: You can turn that off by right clicking in the output window. E.g. there's an item "Module Load Messages" which you want to disable and an item "Program Output" which you want to keep.

How do I set the default page of my application in IIS7?

I was trying do the same of making a particular file my default page, instead of directory structure. So in IIS server I had to go to Default Document, add the page that I want to make as default and at the same time, go to the Web.config file and update the defaultDocument header with "enabled=true". This worked for me. Hopefully it helps.

Use CSS to make a span not clickable

Not with CSS. You could do it with JavaScript easily, though, by canceling the default event handling for those elements. In jQuery:

$('a span:nth-child(2)').click(function(event) { event.preventDefault(); });

How to Serialize a list in java?

All standard implementations of java.util.List already implement java.io.Serializable.

So even though java.util.List itself is not a subtype of java.io.Serializable, it should be safe to cast the list to Serializable, as long as you know it's one of the standard implementations like ArrayList or LinkedList.

If you're not sure, then copy the list first (using something like new ArrayList(myList)), then you know it's serializable.

Implementing a Custom Error page on an ASP.Net website

Is it a spelling error in your closing tag ie:

</CustomErrors> instead of </CustomError>?

How to make a JFrame Modal in Swing java

not sure the contetns of your JFrame, if you ask some input from users, you can use JOptionPane, this also can set JFrame as modal

            JFrame frame = new JFrame();
            String bigList[] = new String[30];

            for (int i = 0; i < bigList.length; i++) {
              bigList[i] = Integer.toString(i);
            }

            JOptionPane.showInputDialog(
                    frame, 
                    "Select a item", 
                    "The List", 
                    JOptionPane.PLAIN_MESSAGE,
                    null,
                    bigList,
                    "none");
            }

Convert SVG image to PNG with PHP

I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I'm not sure such a library exists - I don't know any.

ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it's still the most promising way to go, it's the first thing I would look into if I were you.

Changing Fonts Size in Matlab Plots

To change the title font size, use the following example

title('mytitle','FontSize',12);

to the change the graph axes label font size, do the following

axes('FontSize',24);

How to convert an int to a hex string?

(int_variable).to_bytes(bytes_length, byteorder='big'|'little').hex()

For example:

>>> (434).to_bytes(4, byteorder='big').hex()
'000001b2'
>>> (434).to_bytes(4, byteorder='little').hex()
'b2010000'

Concatenate two JSON objects

One solution is to use a list/array:

var first_json = {"name":"joe", "age":27};
var second_json = {"name":"james", "age":32};

var jsons = new Array();
jsons.push(first_json);
jsons.push(second_json);

Result

jsons = [
    {"name":"joe", "age":27},
    {"name":"james", "age":32}
]

UnicodeDecodeError when reading CSV file in Pandas with Python

I am posting an answer to provide an updated solution and explanation as to why this problem can occur. Say you are getting this data from a database or Excel workbook. If you have special characters like La Cañada Flintridge city, well unless you are exporting the data using UTF-8 encoding, you're going to introduce errors. La Cañada Flintridge city will become La Ca\xf1ada Flintridge city. If you are using pandas.read_csv without any adjustments to the default parameters, you'll hit the following error

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 5: invalid continuation byte

Fortunately, there are a few solutions.

Option 1, fix the exporting. Be sure to use UTF-8 encoding.

Option 2, if fixing the exporting problem is not available to you, and you need to use pandas.read_csv, be sure to include the following paramters, engine='python'. By default, pandas uses engine='C' which is great for reading large clean files, but will crash if anything unexpected comes up. In my experience, setting encoding='utf-8' has never fixed this UnicodeDecodeError. Also, you do not need to use errors_bad_lines, however, that is still an option if you REALLY need it.

pd.read_csv(<your file>, engine='python')

Option 3: solution is my preferred solution personally. Read the file using vanilla Python.

import pandas as pd

data = []

with open(<your file>, "rb") as myfile:
    # read the header seperately
    # decode it as 'utf-8', remove any special characters, and split it on the comma (or deliminator)
    header = myfile.readline().decode('utf-8').replace('\r\n', '').split(',')
    # read the rest of the data
    for line in myfile:
        row = line.decode('utf-8', errors='ignore').replace('\r\n', '').split(',')
        data.append(row)

# save the data as a dataframe
df = pd.DataFrame(data=data, columns = header)

Hope this helps people encountering this issue for the first time.

How to return a string value from a Bash function

You can echo a string, but catch it by piping (|) the function to something else.

You can do it with expr, though ShellCheck reports this usage as deprecated.

Is it safe to delete the "InetPub" folder?

If you reconfigure IIS7 to use your new location, then there's no problem. Just test that the new location is working, before deleting the old location.

Change IIS7 Inetpub path

  • Open %windir%\system32\inetsrv\config\applicationhost.config and search for

%SystemDrive%\inetpub\wwwroot

  • Change the path.

How to use SortedMap interface in Java?

I would use TreeMap, which implements SortedMap. It is designed exactly for that.

Example:

Map<Integer, String> map = new TreeMap<Integer, String>();

// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}

See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

How to compare two tags with git?

For a side-by-side visual representation, I use git difftool with openDiff set to the default viewer.

Example usage:

git difftool tags/<FIRST TAG> tags/<SECOND TAG>

If you are only interested in a specific file, you can use:

git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>

As a side-note, the tags/<TAG>s can be replaced with <BRANCH>es if you are interested in diffing branches.

Is it possible to add an HTML link in the body of a MAILTO link

Section 2 of RFC 2368 says that the body field is supposed to be in text/plain format, so you can't do HTML.

However even if you use plain text it's possible that some modern mail clients would render a URL as a clickable link anyway, though.

How do I skip a header from CSV files in Spark?

It's an option that you pass to the read() command:

context = new org.apache.spark.sql.SQLContext(sc)

var data = context.read.option("header","true").csv("<path>")

Ignore Typescript Errors "property does not exist on value of type"

In my particular project I couldn't get it to work, and used declare var $;. Not a clean/recommended solution, it doesnt recognise the JQuery variables, but I had no errors after using that (and had to for my automatic builds to succeed).

Best way to find the months between two dates

just like range function, when month is 13, go to next year

def year_month_range(start_date, end_date):
    '''
    start_date: datetime.date(2015, 9, 1) or datetime.datetime
    end_date: datetime.date(2016, 3, 1) or datetime.datetime
    return: datetime.date list of 201509, 201510, 201511, 201512, 201601, 201602
    '''
    start, end = start_date.strftime('%Y%m'), end_date.strftime('%Y%m')
    assert len(start) == 6 and len(end) == 6
    start, end = int(start), int(end)

    year_month_list = []
    while start < end:
        year, month = divmod(start, 100)
        if month == 13:
            start += 88  # 201513 + 88 = 201601
            continue
        year_month_list.append(datetime.date(year, month, 1))

        start += 1
    return year_month_list

example in python shell

>>> import datetime
>>> s = datetime.date(2015,9,1)
>>> e = datetime.date(2016, 3, 1)
>>> year_month_set_range(s, e)
[datetime.date(2015, 11, 1), datetime.date(2015, 9, 1), datetime.date(2016, 1, 1), datetime.date(2016, 2, 1),
 datetime.date(2015, 12, 1), datetime.date(2015, 10, 1)]

MVC Calling a view from a different controller

You can move you read.aspx view to Shared folder. It is standard way in such circumstances

Can I have multiple primary keys in a single table?

Some people use the term "primary key" to mean exactly an integer column that gets its values generated by some automatic mechanism. For example AUTO_INCREMENT in MySQL or IDENTITY in Microsoft SQL Server. Are you using primary key in this sense?

If so, the answer depends on the brand of database you're using. In MySQL, you can't do this, you get an error:

mysql> create table foo (
  id int primary key auto_increment, 
  id2 int auto_increment
);
ERROR 1075 (42000): Incorrect table definition; 
there can be only one auto column and it must be defined as a key

In some other brands of database, you are able to define more than one auto-generating column in a table.

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

You have quite a few options for this:

1 - If you can find an SVG file for the map you want, you can use something like RaphaelJS or SnapSVG to add click listeners for your states/regions, this solution is the most customizable...

2 - You can use dedicated tools such as clickablemapbuilder (free) or makeaclickablemap (i think free also).

[disclaimer] Im the author of clickablemapbuilder.com :)

Make index.html default, but allow index.php to be visited if typed in

By default, the DirectoryIndex is set to:

DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml

Apache will look for each of the above files, in order, and serve the first one it finds when a visitor requests just a directory. If the webserver finds no files in the current directory that match names in the DirectoryIndex directive, then a directory listing will be displayed to the browser, showing all files in the current directory.

The order should be DirectoryIndex index.html index.php // default is index.html

Reference: Here.

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

Handling JSON Post Request in Go

You need to read from req.Body. The ParseForm method is reading from the req.Body and then parsing it in standard HTTP encoded format. What you want is to read the body and parse it in JSON format.

Here's your code updated.

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "io/ioutil"
)

type test_struct struct {
    Test string
}

func test(rw http.ResponseWriter, req *http.Request) {
    body, err := ioutil.ReadAll(req.Body)
    if err != nil {
        panic(err)
    }
    log.Println(string(body))
    var t test_struct
    err = json.Unmarshal(body, &t)
    if err != nil {
        panic(err)
    }
    log.Println(t.Test)
}

func main() {
    http.HandleFunc("/test", test)
    log.Fatal(http.ListenAndServe(":8082", nil))
}

google chrome extension :: console.log() from background page?

Any extension page (except content scripts) has direct access to the background page via chrome.extension.getBackgroundPage().

That means, within the popup page, you can just do:

chrome.extension.getBackgroundPage().console.log('foo');

To make it easier to use:

var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');

Now if you want to do the same within content scripts you have to use Message Passing to achieve that. The reason, they both belong to different domains, which make sense. There are many examples in the Message Passing page for you to check out.

Hope that clears everything.

How can I get a specific field of a csv file?

import csv
inf = csv.reader(open('yourfile.csv','r'))
for row in inf:
  print row[1]

Using DateTime in a SqlParameter for Stored Procedure, format error

Here is how I add parameters:

sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB

I am assuming when you write out DOB there are no quotes.

Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.

Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?

How do I decompile a .NET EXE into readable C# source code?

When Red Gate said there would no longer be a free version of .Net Reflector, I started using ILSpy and Telerik's JustDecompile. I have found ILSpy to decompile more accurately than JustDecompile (which is still in Beta). Red Gate has changed their decision and still have a free version of .Net Reflector, but now I like ILSpy.

From the ILSpy website (https://github.com/icsharpcode/ILSpy/):

ILSpy is the open-source .NET assembly browser and decompiler.

ILSpy Features

  • Assembly browsing
  • IL Disassembly
  • Decompilation to C#
  • Supports lambdas and 'yield return'
  • Shows XML documentation
  • Saving of resources
  • Search for types/methods/properties (substring)
  • Hyperlink-based type/method/property navigation
  • Base/Derived types navigation
  • Navigation history
  • BAML to XAML decompiler
  • Save Assembly as C# Project
  • Find usage of field/method
  • Extensible via plugins (MEF)

Update:

April 15, 2012, ILSpy 2.0 was released. New features compared with version 1.0:

  • Assembly Lists
  • Support for decompiling Expression trees
  • Support for lifted operatores on nullables
  • Decompile to Visual Basic
  • Search for multiple strings separated by space (searching for "Assembly manager" in ILSpy.exe would find AssemblyListManager)
  • Clicking on a local variable will highlight all other occurrences of that variable
  • Ctrl+F can be used to search within the decompiled code view

Update:

  • ILSpy 2.1 supports async/await decompilation

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

Why won't my PHP app send a 404 error?

Your code is technically correct. If you looked at the headers of that blank page, you'd see a 404 header, and other computers/programs would be able to correctly identify the response as file not found.

Of course, your users are still SOL. Normally, 404s are handled by the web server.

  • User: Hey, do you have anything for me at this URI webserver?
  • Webserver: No, I don't, 404! Here's a page to display for 404s.

The problem is, once the web server starts processing the PHP page, it's already passed the point where it would handle a 404

  • User: Hey, do you have anything for me at this URI webserver?
  • Webserver: Yes, I do, it's a PHP page. It'll tell you what the response code is
  • PHP: Hey, OMG 404!!!!!!!
  • Webserver: Well crap, the 404 page people have already gone home, so I'll just send along whatever PHP gave me

In addition to providing a 404 header, PHP is now responsible for outputting the actual 404 page.

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

You can take the SelectedItem and cast it back to your class and access its properties.

 MessageBox.Show(((ComboboxItem)ComboBox_Countries_In_Silvers.SelectedItem).Value);

Edit You can try using DataTextField and DataValueField, I used it with DataSource.

ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";

Show animated GIF

I wanted to put the .gif file in a GUI but displayed with other elements. And the .gif file would be taken from the java project and not from an URL.

1 - Top of the interface would be a list of elements where we can choose one

2 - Center would be the animated GIF

3 - Bottom would display the element chosen from the list

Here is my code (I need 2 java files, the first (Interf.java) calls the second (Display.java)):

1 - Interf.java

public class Interface_for {

    public static void main(String[] args) {

        Display Fr = new Display();

    }
}

2 - Display.java

INFOS: Be shure to create a new source folder (NEW > source folder) in your java project and put the .gif inside for it to be seen as a file.

I get the gif file with the code below, so I can it export it in a jar project(it's then animated).

URL url = getClass().getClassLoader().getResource("fire.gif");

  public class Display extends JFrame {
  private JPanel container = new JPanel();
  private JComboBox combo = new JComboBox();
  private JLabel label = new JLabel("A list");
  private JLabel label_2 = new JLabel ("Selection");

  public Display(){
    this.setTitle("Animation");
    this.setSize(400, 350);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    container.setLayout(new BorderLayout());
    combo.setPreferredSize(new Dimension(190, 20));
    //We create te list of elements for the top of the GUI
    String[] tab = {"Option 1","Option 2","Option 3","Option 4","Option 5"};
    combo = new JComboBox(tab);

    //Listener for the selected option
    combo.addActionListener(new ItemAction());

    //We add elements from the top of the interface
    JPanel top = new JPanel();
    top.add(label);
    top.add(combo);
    container.add(top, BorderLayout.NORTH);

    //We add elements from the center of the interface
    URL url = getClass().getClassLoader().getResource("fire.gif");
    Icon icon = new ImageIcon(url);
    JLabel center = new JLabel(icon);
    container.add(center, BorderLayout.CENTER);

    //We add elements from the bottom of the interface
    JPanel down = new JPanel();
    down.add(label_2);
    container.add(down,BorderLayout.SOUTH);

    this.setContentPane(container);
    this.setVisible(true);
    this.setResizable(false);
  }
  class ItemAction implements ActionListener{
      public void actionPerformed(ActionEvent e){
          label_2.setText("Chosen option: "+combo.getSelectedItem().toString());
      }
  }
}

Check If array is null or not in php

This checks if the array is empty

if (!empty($result) {
    // do stuf if array is not empty
} else {
    // do stuf if array is empty
}

This checks if the array is null or not

if (is_null($result) {
   // do stuf if array is null
} else {
   // do stuf if array is not null
}

In plain English, what does "git reset" do?

The post Reset Demystified in the blog Pro Git gives a very no-brainer explanation on git reset and git checkout.

After all the helpful discussion at the top of that post, the author reduces the rules to the following simple three steps:

That is basically it. The reset command overwrites these three trees in a specific order, stopping when you tell it to.

  1. Move whatever branch HEAD points to (stop if --soft)
  2. THEN, make the Index look like that (stop here unless --hard)
  3. THEN, make the Working Directory look like that

There are also --merge and --keep options, but I would rather keep things simpler for now - that will be for another article.

Error "can't use subversion command line client : svn" when opening android project checked out from svn

Android Studio cannot find the svn command because it's not on PATH, and it doesn't know where svn is installed.

One way to fix is to edit the PATH environment variable: add the directory that contains svn.exe. You will need to restart Android Studio to make it re-read the PATH variable.

Another way is to set the absolute path of svn.exe in the Use command client box in the settings screen that you included in your post.

UPDATE

According to this other post, TortoiseSVN doesn't include the command line tools by default. But you can re-run the installer and enable it. That will add svn.exe to PATH, and Android Studio will correctly pick it up.

How to convert a string with comma-delimited items to a list in Python?

If you actually want arrays:

>>> from array import array
>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> myarray = array('c', text)
>>> myarray
array('c', 'abc')
>>> myarray[0]
'a'
>>> myarray[1]
'b'

If you do not need arrays, and only want to look by index at your characters, remember a string is an iterable, just like a list except the fact that it is immutable:

>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> text[0]
'a'

How do I force git to use LF instead of CR+LF under windows?

The proper way to get LF endings in Windows is to first set core.autocrlf to false:

git config --global core.autocrlf false

You need to do this if you are using msysgit, because it sets it to true in its system settings.

Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto in your .gitattributes for all files:

* text=auto

And set core.eol to lf:

git config --global core.eol lf

Now you can also switch single repos to crlf (in the working directory!) by running

git config core.eol crlf

After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:

git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f

If you now want git to also normalize the files in your working directory, run these commands:

git ls-files -z | xargs -0 rm
git checkout .

C++ equivalent of StringBuffer/StringBuilder?

I wanted to add something new because of the following:

At a first attemp I failed to beat

std::ostringstream 's operator<<

efficiency, but with more attemps I was able to make a StringBuilder that is faster in some cases.

Everytime I append a string I just store a reference to it somewhere and increase the counter of the total size.

The real way I finally implemented it (Horror!) is to use a opaque buffer(std::vector < char > ):

  • 1 byte header (2 bits to tell if following data is :moved string, string or byte[])
  • 6 bits to tell lenght of byte[]

for byte [ ]

  • I store directly bytes of short strings (for sequential memory access)

for moved strings (strings appended with std::move)

  • The pointer to a std::string object (we have ownership)
  • set a flag in the class if there are unused reserved bytes there

for strings

  • The pointer to a std::string object (no ownership)

There's also one small optimization, if last inserted string was mov'd in, it checks for free reserved but unused bytes and store further bytes in there instead of using the opaque buffer (this is to save some memory, it actually make it slightly slower, maybe depend also on the CPU, and it is rare to see strings with extra reserved space anyway)

This was finally slightly faster than std::ostringstream but it has few downsides:

  • I assumed fixed lenght char types (so 1,2 or 4 bytes, not good for UTF8), I'm not saying it will not work for UTF8, Just I don't checked it for laziness.
  • I used bad coding practise (opaque buffer, easy to make it not portable, I believe mine is portable by the way)
  • Lacks all features of ostringstream
  • If some referenced string is deleted before mergin all the strings: undefined behaviour.

conclusion? use std::ostringstream

It already fix the biggest bottleneck while ganing few % points in speed with mine implementation is not worth the downsides.

Easiest way to flip a boolean value?

This seems to be a free-for-all ... Heh. Here's another varation, which I guess is more in the category "clever" than something I'd recommend for production code:

flipVal ^= (wParam == VK_F11);
otherVal ^= (wParam == VK_F12);

I guess it's advantages are:

  • Very terse
  • Does not require branching

And a just as obvious disadvantage is

  • Very terse

This is close to @korona's solution using ?: but taken one (small) step further.

How to get the location of the DLL currently executing?

If you're working with an asp.net application and you want to locate assemblies when using the debugger, they are usually put into some temp directory. I wrote the this method to help with that scenario.

private string[] GetAssembly(string[] assemblyNames)
{
    string [] locations = new string[assemblyNames.Length];


    for (int loop = 0; loop <= assemblyNames.Length - 1; loop++)       
    {
         locations[loop] = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.ManifestModule.Name == assemblyNames[loop]).Select(a => a.Location).FirstOrDefault();
    }
    return locations;
}

For more details see this blog post http://nodogmablog.bryanhogan.net/2015/05/finding-the-location-of-a-running-assembly-in-net/

If you can't change the source code, or redeploy, but you can examine the running processes on the computer use Process Explorer. I written a detailed description here.

It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.

I've written a full description of how do this for a dll inside IIS - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/

(SC) DeleteService FAILED 1072

make sure the service is stopped, the services control panel is closed, and no open file handles are open by the service.

Also make sure ProcessExplorer is not running.

Jquery mouseenter() vs mouseover()

You see the behavior when your target element contains child elements:

http://jsfiddle.net/ZCWvJ/7/

Each time your mouse enters or leaves a child element, mouseover is triggered, but not mouseenter.

_x000D_
_x000D_
$('#my_div').bind("mouseover mouseenter", function(e) {_x000D_
  var el = $("#" + e.type);_x000D_
  var n = +el.text();_x000D_
  el.text(++n);_x000D_
});
_x000D_
#my_div {_x000D_
  padding: 0 20px 20px 0;_x000D_
  background-color: #eee;_x000D_
  margin-bottom: 10px;_x000D_
  width: 90px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#my_div>div {_x000D_
  float: left;_x000D_
  margin: 20px 0 0 20px;_x000D_
  height: 25px;_x000D_
  width: 25px;_x000D_
  background-color: #aaa;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
_x000D_
<div>MouseEnter: <span id="mouseenter">0</span></div>_x000D_
<div>MouseOver: <span id="mouseover">0</span></div>_x000D_
_x000D_
<div id="my_div">_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery form validation on button click

Within your click handler, the mistake is the .validate() method; it only initializes the plugin, it does not validate the form.

To eliminate the need to have a submit button within the form, use .valid() to trigger a validation check...

$('#btn').on('click', function() {
    $("#form1").valid();
});

jsFiddle Demo

.validate() - to initialize the plugin (with options) once on DOM ready.

.valid() - to check validation state (boolean value) or to trigger a validation test on the form at any time.

Otherwise, if you had a type="submit" button within the form container, you would not need a special click handler and the .valid() method, as the plugin would capture that automatically.

Demo without click handler


EDIT:

You also have two issues within your HTML...

<input id="field1" type="text" class="required">
  • You don't need class="required" when declaring rules within .validate(). It's redundant and superfluous.

  • The name attribute is missing. Rules are declared within .validate() by their name. The plugin depends upon unique name attributes to keep track of the inputs.

Should be...

<input name="field1" id="field1" type="text" />

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.6;
  background: rgba(200, 54, 54, 0.5);  
  background-color: yellow;
  filter: alpha(opacity=50);
  zoom: 1;  
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";  
  -moz-opacity: 0.5; 
  -khtml-opacity: 0.5;  
}

How can I limit the visible options in an HTML <select> dropdown?

You can try this

_x000D_
_x000D_
<select name="select1" onmousedown="if(this.options.length>8){this.size=8;}"  onchange='this.size=0;' onblur="this.size=0;">_x000D_
             <option value="1">This is select number 1</option>_x000D_
             <option value="2">This is select number 2</option>_x000D_
             <option value="3">This is select number 3</option>_x000D_
             <option value="4">This is select number 4</option>_x000D_
             <option value="5">This is select number 5</option>_x000D_
             <option value="6">This is select number 6</option>_x000D_
             <option value="7">This is select number 7</option>_x000D_
             <option value="8">This is select number 8</option>_x000D_
             <option value="9">This is select number 9</option>_x000D_
             <option value="10">This is select number 10</option>_x000D_
             <option value="11">This is select number 11</option>_x000D_
             <option value="12">This is select number 12</option>_x000D_
           </select>
_x000D_
_x000D_
_x000D_

It worked for me

React-router v4 this.props.history.push(...) not working

For me (react-router v4, react v16) the problem was that I had the navigation component all right:

import { Link, withRouter } from 'react-router-dom'

class MainMenu extends Component {

  render() {
    return (
            ...
            <NavLink to="/contact">Contact</NavLink>
            ...
    );
  }
}

export default withRouter(MainMenu);

Both using either

to="/contact" 

or

OnClick={() => this.props.history.push('/contact')}; 

The behavior was still the same - the URL in browser changed but wrong components were rendered, the router was called with the same old URL.

The culprit was in the router definition. I had to move the MainMenu component as a child of the Router component!

// wrong placement of the component that calls the router
<MainMenu history={this.props.history} />
<Router>
   <div>
     // this is the right place for the component!
     <MainMenu history={this.props.history} />
     <Route path="/" exact component={MainPage} />
     <Route path="/contact/" component={MainPage} />
   </div>
</Router>

Why must wait() always be in synchronized block

We all know that wait(), notify() and notifyAll() methods are used for inter-threaded communications. To get rid of missed signal and spurious wake up problems, waiting thread always waits on some conditions. e.g.-

boolean wasNotified = false;
while(!wasNotified) {
    wait();
}

Then notifying thread sets wasNotified variable to true and notify.

Every thread has their local cache so all the changes first get written there and then promoted to main memory gradually.

Had these methods not invoked within synchronized block, the wasNotified variable would not be flushed into main memory and would be there in thread's local cache so the waiting thread will keep waiting for the signal although it was reset by notifying thread.

To fix these types of problems, these methods are always invoked inside synchronized block which assures that when synchronized block starts then everything will be read from main memory and will be flushed into main memory before exiting the synchronized block.

synchronized(monitor) {
    boolean wasNotified = false;
    while(!wasNotified) {
        wait();
    }
}

Thanks, hope it clarifies.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Python conditional assignment operator

I am not sure I understand the question properly here ... Trying to "read" the value of an "undefined" variable name will trigger a NameError. (see here, that Python has "names", not variables...).

== EDIT ==

As pointed out in the comments by delnan, the code below is not robust and will break in numerous situations ...

Nevertheless, if your variable "exists", but has some sort of dummy value, like None, the following would work :

>>> my_possibly_None_value = None
>>> myval = my_possibly_None_value or 5
>>> myval
5
>>> my_possibly_None_value = 12
>>> myval = my_possibly_None_value or 5
>>> myval
12
>>> 

(see this paragraph about Truth Values)

Finding rows that don't contain numeric data in Oracle

I've found this useful:

 select translate('your string','_0123456789','_') from dual

If the result is NULL, it's numeric (ignoring floating point numbers.)

However, I'm a bit baffled why the underscore is needed. Without it the following also returns null:

 select translate('s123','0123456789', '') from dual

There is also one of my favorite tricks - not perfect if the string contains stuff like "*" or "#":

 SELECT 'is a number' FROM dual WHERE UPPER('123') = LOWER('123')

Reload .profile in bash shell script (in unix)?

The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.

Find Locked Table in SQL Server

sp_lock

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)

EDIT :

There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.

http://jsfiddle.net/P2QhE/

Javascript code embedded aswell:

$(document).ready(function () {
    var map;
    var elevator;
    var myOptions = {
        zoom: 1,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: 'terrain'
    };
    map = new google.maps.Map($('#map_canvas')[0], myOptions);

    var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];

    for (var x = 0; x < addresses.length; x++) {
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
            var p = data.results[0].geometry.location
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            new google.maps.Marker({
                position: latlng,
                map: map
            });

        });
    }

}); 

adding 1 day to a DATETIME format value

The DateTime constructor takes a parameter string time. $time can be different things, it has to respect the datetime format.

There are some valid values as examples :

  • 'now' (the default value)
  • 2017-10-19
  • 2017-10-19 11:59:59
  • 2017-10-19 +1day

So, in your case you can use the following.

$dt = new \DateTime('now +1 day'); //Tomorrow
$dt = new \DateTime('2016-01-01 +1 day'); //2016-01-02

What are 'get' and 'set' in Swift?

A simple question should be followed by a short, simple and clear answer.

  • When we are getting a value of the property it fires its get{} part.

  • When we are setting a value to the property it fires its set{} part.

PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{} part.

Example:

var A:Int = 0
var B:Int = 0

var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
     B = newValue
     }
}

//When we are getting a value of C it fires get{} part of C property
A = C 
A            //Now A = 1

//When we are setting a value to C it fires set{} part of C property
C = 2
B            //Now B = 2

Python's most efficient way to choose longest string in list?

What should happen if there are more than 1 longest string (think '12', and '01')?

Try that to get the longest element

max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])

And then regular foreach

for st in mylist:
    if len(st)==max_length:...

Determine function name from within that function (without using traceback)

import sys

def func_name():
    """
    :return: name of caller
    """
    return sys._getframe(1).f_code.co_name

class A(object):
    def __init__(self):
        pass
    def test_class_func_name(self):
        print(func_name())

def test_func_name():
    print(func_name())

Test:

a = A()
a.test_class_func_name()
test_func_name()

Output:

test_class_func_name
test_func_name

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

It seems there is no way to do this without custom view. You can get the title view:

View decor = getWindow().getDecorView();
TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "android"));

But changing of gravity or layout_gravity doesn't have an effect. The problem in the ActionBarView, which layout its children by itself so changing of layout params of its children also doesn't have an effect. To see this excecute following code:

ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "android"));
View v = actionBar.getChildAt(0);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity= Gravity.CENTER;
v.setLayoutParams(p);
v.setBackgroundColor(Color.BLACK);

Change Input to Upper Case

Javascript has a toUpperCase() method. http://www.w3schools.com/jsref/jsref_toUpperCase.asp

So wherever you think best to put it in your code, you would have to do something like

$(".keywords").val().toUpperCase()

HTML/CSS font color vs span style

You should use <span>, because as specified by the spec, <font> has been deprecated and probably won't display as you intend.

How to make an authenticated web request in Powershell?

For those that need Powershell to return additional information like the Http StatusCode, here's an example. Included are the two most likely ways to pass in credentials.

Its a slightly modified version of this SO answer:
How to obtain numeric HTTP status codes in PowerShell

$req = [system.Net.WebRequest]::Create($url)
# method 1 $req.UseDefaultCredentials = $true
# method 2 $req.Credentials = New-Object System.Net.NetworkCredential($username, $pwd, $domain); 
try
{
    $res = $req.GetResponse()
}
catch [System.Net.WebException]
{
    $res = $_.Exception.Response
}

$int = [int]$res.StatusCode
$status = $res.StatusCode
return "$int $status"

(413) Request Entity Too Large | uploadReadAheadSize

For anyone else ever looking for an IIS WCF error 413 : Request entity to large and using a WCF service in Sharepoint, this is the information for you. The settings in the application host and web.config suggested in other sites/posts don't work in SharePoint if using the MultipleBaseAddressBasicHttpBindingServiceHostFactory. You can use SP Powershell to get the SPWebService.Content service, create a new SPWcvSettings object and update the settings as above for your service (they won't exist). Remember to just use the name of the service (e.g. [yourservice.svc]) when creating and adding the settings. See this site for more info https://robertsep.wordpress.com/2010/12/21/set-maximum-upload-filesize-sharepoint-wcf-service

How to get a unique device ID in Swift?

The value of identifierForVendor changes when the user deletes all of that vendor’s apps from the device, if you want to keep the unique ID even for the subsequent fresh installations, you can try to use the following function

func vendorIdentifierForDevice()->String {
    //Get common part of Applicatoin Bundle ID, Note : getCommonPartOfApplicationBundleID is to be defined.
    let commonAppBundleID = getCommonPartOfApplicationBundleID()
    //Read from KeyChain using bunndle ID, Note : readFromKeyChain is to be defined.
    if let vendorID = readFromKeyChain(commonAppBundleID) {
        return vendorID
    } else {
        var vendorID = NSUUID().uuidString
        //Save to KeyChain using bunndle ID, Note : saveToKeyChain is to be defined.
        saveToKeyChain(commonAppBundleID, vendorID)
        return vendorID
    }
}

Decompile .smali files on an APK

No, APK Manager decompiles the .dex file into .smali and binary .xml to human readable xml.

The sequence (based on APK Manager 4.9) is 22 to select the package, and then 9 to decompile it. If you press 1 instead of 9, then you will just unpack it (useful only if you want to exchange .png images).

There is no tool available to decompile back to .java files and most probably it won't be any. There is an alternative, which is using dex2jar to transform the dex file in to a .class file, and then use a jar decompiler (such as the free jd-gui) to plain text java. The process is far from optimal, though, and it won't generate working code, but it's decent enough to be able to read it.

dex2jar: https://github.com/pxb1988/dex2jar

jd-gui: http://jd.benow.ca/

Edit: I knew there was somewhere here in SO a question with very similar answers... decompiling DEX into Java sourcecode

how to get the last character of a string?

Use substr with parameter -1:

"linto.yahoo.com.".substr(-1);

equals "."

Note:

To extract characters from the end of the string, use a negative start number (This does not work in IE 8 and earlier).

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

in my case adding <clear /> just after <connectionStrings> worked like charm

Using helpers in model: how do I include helper dependencies?

Just change the first line as follows :

include ActionView::Helpers

that will make it works.

UPDATE: For Rails 3 use:

ActionController::Base.helpers.sanitize(str)

Credit goes to lornc's answer

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Don't use the length parameter as it will not work with all browsers. The best way is to set a style on the input tag.

<input style="width:100px" />

How do I see if Wi-Fi is connected on Android?

This is an easier solution. See Stack Overflow question Checking Wi-Fi enabled or not on Android.

P.S. Do not forget to add the code to the manifest.xml file to allow permission. As shown below.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>

How do I set multipart in axios with react?

If you are sending alphanumeric data try changing

'Content-Type': 'multipart/form-data'

to

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

If you are sending non-alphanumeric data try to remove 'Content-Type' at all.

If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)

How to upgrade all Python packages with pip

This option seems to me more straightforward and readable:

pip install -U `pip list --outdated | awk 'NR>2 {print $1}'`

The explanation is that pip list --outdated outputs a list of all the outdated packages in this format:

Package   Version Latest Type 
--------- ------- ------ -----
fonttools 3.31.0  3.32.0 wheel
urllib3   1.24    1.24.1 wheel
requests  2.20.0  2.20.1 wheel

In the awk command, NR>2 skips the first two records (lines) and {print $1} selects the first word of each line (as suggested by SergioAraujo, I removed tail -n +3 since awk can indeed handle skipping records).

How can I send an email through the UNIX mailx command?

Here is a multifunctional function to tackle mail sending with several attachments:

enviaremail() {
values=$(echo "$@" | tr -d '\n')
listargs=()
listargs+=($values)
heirloom-mailx $( attachment=""
for (( a = 5; a < ${#listargs[@]}; a++ )); do
attachment=$(echo "-a ${listargs[a]} ")
echo "${attachment}"
done) -v -s "${titulo}" \
-S smtp-use-starttls \
-S ssl-verify=ignore \
-S smtp-auth=login \
-S smtp=smtp://$1 \
-S from="${2}" \
-S smtp-auth-user=$3 \
-S smtp-auth-password=$4 \
-S ssl-verify=ignore \
$5 < ${cuerpo}
}

function call: enviaremail "smtp.mailserver:port" "from_address" "authuser" "'pass'" "destination" "list of attachments separated by space"

Note: Remove the double quotes in the call

In addition please remember to define externally the $titulo (subject) and $cuerpo (body) of the email prior to using the function

Python dictionary: Get list of values for list of keys

reduce(lambda x,y: mydict.get(y) and x.append(mydict[y]) or x, mykeys,[])

incase there are keys not in dict.

What is the difference between decodeURIComponent and decodeURI?

js> s = "http://www.example.com/string with + and ? and & and spaces";
http://www.example.com/string with + and ? and & and spaces
js> encodeURI(s)
http://www.example.com/string%20with%20+%20and%20?%20and%20&%20and%20spaces
js> encodeURIComponent(s)
http%3A%2F%2Fwww.example.com%2Fstring%20with%20%2B%20and%20%3F%20and%20%26%20and%20spaces

Looks like encodeURI produces a "safe" URI by encoding spaces and some other (e.g. nonprintable) characters, whereas encodeURIComponent additionally encodes the colon and slash and plus characters, and is meant to be used in query strings. The encoding of + and ? and & is of particular importance here, as these are special chars in query strings.

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

How can I update NodeJS and NPM to the next versions?

I found one plugin which can help to update all npm packages.

First, you need to install an npm-check-updates plugin.here is the link npm-check-updates

npm i -g npm-check-updates

So this utility is installed globally, you can invoke it by simply writing as follow.

1) ncu -u Here ncu is npm check updates.

2) npm install

So with these two commands, you can easily update npm packages.I hope this will help you to update packages easily.

Creating a LinkedList class from scratch

Pleas find bellow Program

class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class LinkedListManual {

    Node node;

    public void pushElement(int next_node) {
        Node nd = new Node(next_node);
        nd.next = node;
        node = nd;
    }

    public int getSize() {
        Node temp = node;
        int count = 0;
        while (temp != null) {
            count++;
            temp = temp.next;
        }
        return count;
    }

    public void getElement() {
        Node temp = node;
        while (temp != null) {
            System.out.println(temp.data);
            temp = temp.next;
        }
    }

    public static void main(String[] args) {
        LinkedListManual obj = new LinkedListManual();
        obj.pushElement(1);
        obj.pushElement(2);
        obj.pushElement(3);
        obj.getElement(); //get element
        System.out.println(obj.getSize());  //get size of link list
    }

}

Removing Spaces from a String in C?

#include<stdio.h>
#include<string.h>
main()
{
  int i=0,n;
  int j=0;
  char str[]="        Nar ayan singh              ";
  char *ptr,*ptr1;
  printf("sizeof str:%ld\n",strlen(str));
  while(str[i]==' ')
   {
     memcpy (str,str+1,strlen(str)+1);
   }
  printf("sizeof str:%ld\n",strlen(str));
  n=strlen(str);
  while(str[n]==' ' || str[n]=='\0')
    n--;
  str[n+1]='\0';
  printf("str:%s ",str);
  printf("sizeof str:%ld\n",strlen(str));
}

Removing viewcontrollers from navigation stack

Swift 2.0:

  var navArray:Array = (self.navigationController?.viewControllers)!
  navArray.removeAtIndex(navArray.count-2)
  self.navigationController?.viewControllers = navArray

Best way to store password in database

As a key-hardened salted hash, using a secure algorithm such as sha-512.

Unable to call the built in mb_internal_encoding method?

For Debian/Ubuntu:

sudo apt-get install php7.0-mbstring

Not connecting to SQL Server over VPN

SQL Server uses the TCP port 1433. This is probably blocked either by the VPN tunnel or by a firewall on the server.

Matching an empty input box using CSS

If only the field is required you could go with input:valid

_x000D_
_x000D_
#foo-thing:valid + .msg { visibility: visible!important; }      
_x000D_
 <input type="text" id="foo-thing" required="required">_x000D_
 <span class="msg" style="visibility: hidden;">Yay not empty</span>
_x000D_
_x000D_
_x000D_

See live on jsFiddle

OR negate using #foo-thing:invalid (credit to @SamGoody)

height style property doesn't work in div elements

You're loosing your height attribute because you're changing the block element to inline (it's now going to act like a <p>). You're probably picking up that 14px height because of the text height inside your in-line div.

Inline-block may work for your needs, but you may have to implement a work around or two for cross-browser support.

IE supports inline-block, but only for elements that are natively inline.

async/await - when to return a Task vs void?

1) Normally, you would want to return a Task. The main exception should be when you need to have a void return type (for events). If there's no reason to disallow having the caller await your task, why disallow it?

2) async methods that return void are special in another aspect: they represent top-level async operations, and have additional rules that come into play when your task returns an exception. The easiest way is to show the difference is with an example:

static async void f()
{
    await h();
}

static async Task g()
{
    await h();
}

static async Task h()
{
    throw new NotImplementedException();
}

private void button1_Click(object sender, EventArgs e)
{
    f();
}

private void button2_Click(object sender, EventArgs e)
{
    g();
}

private void button3_Click(object sender, EventArgs e)
{
    GC.Collect();
}

f's exception is always "observed". An exception that leaves a top-level asynchronous method is simply treated like any other unhandled exception. g's exception is never observed. When the garbage collector comes to clean up the task, it sees that the task resulted in an exception, and nobody handled the exception. When that happens, the TaskScheduler.UnobservedTaskException handler runs. You should never let this happen. To use your example,

public static async void AsyncMethod2(int num)
{
    await Task.Factory.StartNew(() => Thread.Sleep(num));
}

Yes, use async and await here, they make sure your method still works correctly if an exception is thrown.

for more information see: http://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Excel VBA date formats

To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.

Sub test_date_or_String()
 Set c = ActiveCell
 c.NumberFormat = "@"
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
 c.NumberFormat = "m/d/yyyy"
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date    
End Sub

How to remove specific element from an array using python

There is an alternative solution to this problem which also deals with duplicate matches.

We start with 2 lists of equal length: emails, otherarray. The objective is to remove items from both lists for each index i where emails[i] == '[email protected]'.

This can be achieved using a list comprehension and then splitting via zip:

emails = ['[email protected]', '[email protected]', '[email protected]']
otherarray = ['some', 'other', 'details']

from operator import itemgetter

res = [(i, j) for i, j in zip(emails, otherarray) if i!= '[email protected]']
emails, otherarray = map(list, map(itemgetter(0, 1), zip(*res)))

print(emails)      # ['[email protected]', '[email protected]']
print(otherarray)  # ['some', 'details']

Bind class toggle to window scroll event

This is my solution, it's not that tricky and allow you to use it for several markup throught a simple ng-class directive. Like so you can choose the class and the scrollPos for each case.

Your App.js :

angular.module('myApp',[])
    .controller('mainCtrl',function($window, $scope){
        $scope.scrollPos = 0;

        $window.onscroll = function(){
            $scope.scrollPos = document.body.scrollTop || document.documentElement.scrollTop || 0;
            $scope.$apply(); //or simply $scope.$digest();
        };
    });

Your index.html :

<html ng-app="myApp">
    <head></head>
    <body>
        <section ng-controller="mainCtrl">
            <p class="red" ng-class="{fix:scrollPos >= 100}">fix me when scroll is equals to 100</p>
            <p class="blue" ng-class="{fix:scrollPos >= 150}">fix me when scroll is equals to 150</p>
        </section>
    </body>
</html>

working JSFiddle here

EDIT :

As $apply() is actually calling $rootScope.$digest() you can directly use $scope.$digest() instead of $scope.$apply() for better performance depending on context.
Long story short : $apply() will always work but force the $digest on all scopes that may cause perfomance issue.

How to connect android emulator to the internet

I have Mac OS X 10.7.2, Eclipse Helios Service Release 2. I also work via Proxy and my IP settings are via DHCP. I solved this issue firstly using this article http://www.gitshah.com/2011/02/android-fixing-no-internet-connection.html, then I removed Emulator settings and just go to Run->Run Configurations->Target->Additional Emulator Command Line Options and type there -http-proxy xxx.xx.111.1:3128 . Also I would like to say that when I typed also a DNS like this: -dns-server xxx.xx.111.1 -http-proxy xxx.xx.111.1:3128 it did not work, but when I removed DNS it worked. Also I would like to note, that Additional Emulator Command Line Options are not visible without scrolling to the bottom of that window. I also want to note, that when you change emulator options, all apps will work. But If you write Additional Emulator Command Line Options, you need to write them every time for every app target in Run Configurations.

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

Spring Boot @Value Properties

I had the same issue get value for my property in my service class. I resolved it by using @ConfigurationProperties instead of @Value.

  1. create a class like this:
    import org.springframework.boot.context.properties.ConfigurationProperties;

    @ConfigurationProperties(prefix = "file")
    public class FileProperties {
        private String directory;

        public String getDirectory() {
            return directory;
        }

        public void setDirectory(String dir) {
            this.directory = dir;
        }
    }

  1. add the following to your BootApplication class:
    @EnableConfigurationProperties({
        FileProperties.class
    })
  1. Inject FileProperties to your PrintProperty class, then you can get hold of the property through the getter method.

Determine the number of NA values in a column

A quick and easy Tidyverse solution to get a NA count for all columns is to use summarise_all() which I think makes a much easier to read solution than using purrr or sapply

library(tidyverse)
# Example data
df <- tibble(col1 = c(1, 2, 3, NA), 
             col2 = c(NA, NA, "a", "b"))

df %>% summarise_all(~ sum(is.na(.)))
#> # A tibble: 1 x 2
#>    col1  col2
#>   <int> <int>
#> 1     1     2

Executing multiple commands from a Windows cmd script

Not sure why the first command is stopping. If you can make it parallel, you can try something like

start cmd.exe /C 1.bat      
start cmd.exe /C 2.bat

Disable keyboard on EditText

I found this solution which works for me. It also places the cursor, when clicked on EditText at the correct position.

EditText editText = (EditText)findViewById(R.id.edit_mine);
// set OnTouchListener to consume the touch event
editText.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            v.onTouchEvent(event);   // handle the event first
            InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  // hide the soft keyboard 
            }                
            return true;
        }
    });

How to automatically generate a stacktrace when my program crashes

I forgot about the GNOME tech of "apport", but I don't know much about using it. It is used to generate stacktraces and other diagnostics for processing and can automatically file bugs. It's certainly worth checking in to.

Get all column names of a DataTable into string array using (LINQ/Predicate)

I'd suggest using such extension method:

public static class DataColumnCollectionExtensions
{
    public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
    {
        return source.Cast<DataColumn>();
    }
}

And therefore:

string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();

You may also implement one more extension method for DataTable class to reduce code:

public static class DataTableExtensions
{
    public static IEnumerable<DataColumn> GetColumns(this DataTable source)
    {
        return source.Columns.AsEnumerable();
    }
}

And use it as follows:

string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();

CSS transition effect makes image blurry / moves image 1px, in Chrome?

Had the same problem with embeded youtube iframe (Translations were used for centering iframe element). None of the solutions above worked until tried reset css filters and magic happened.

Structure:

<div class="translate">
     <iframe/>
</div>

Style [before]

.translate {
  transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
}

Style [after]

.translate {
  transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
  filter: blur(0);
  -webkit-filter: blur(0);
}

Fixed footer in Bootstrap

Add z-index:-9999; to this method, or it will cover your top bar if you have 1.

Possible to view PHP code of a website?

Noone cand read the file except for those who have access to the file. You must make the code readable (but not writable) by the web server. If the php code handler is running properly you can't read it by requesting by name from the web server.

If someone compromises your server you are at risk. Ensure that the web server can only write to locations it absolutely needs to. There are a few locations under /var which should be properly configured by your distribution. They should not be accessible over the web. /var/www should not be writable, but may contain subdirectories written to by the web server for dynamic content. Code handlers should be disabled for these.

Ensure you don't do anything in your php code which can lead to code injection. The other risk is directory traversal using paths containing .. or begining with /. Apache should already be patched to prevent this when it is handling paths. However, when it runs code, including php, it does not control the paths. Avoid anything that allows the web client to pass a file path.

Obtain form input fields using jQuery?

For multiple select elements (<select multiple="multiple">), I modified the solution from @Jason Norwood-Young to get it working.

The answer (as posted) only takes the value from the first element that was selected, not all of them. It also didn't initialize or return data, the former throwing a JavaScript error.

Here is the new version:

function _get_values(form) {
  let data = {};
  $(form).find('input, textarea, select').each(function(x, field) {
    if (field.name) {
      if (field.name.indexOf('[]') > 0) {
        if (!$.isArray(data[field.name])) {
          data[field.name] = new Array();
        }
        for (let i = 0; i < field.selectedOptions.length; i++) {
          data[field.name].push(field.selectedOptions[i].value);
        }

      } else {
        data[field.name] = field.value;
      }
    }

  });
  return data
}

Usage:

_get_values($('#form'))

Note: You just need to ensure that the name of your select has [] appended to the end of it, for example:

<select name="favorite_colors[]" multiple="multiple">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</select>

How to TryParse for Enum value?

In the end you have to implement this around Enum.GetNames:

public bool TryParseEnum<T>(string str, bool caseSensitive, out T value) where T : struct {
    // Can't make this a type constraint...
    if (!typeof(T).IsEnum) {
        throw new ArgumentException("Type parameter must be an enum");
    }
    var names = Enum.GetNames(typeof(T));
    value = (Enum.GetValues(typeof(T)) as T[])[0];  // For want of a better default
    foreach (var name in names) {
        if (String.Equals(name, str, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) {
            value = (T)Enum.Parse(typeof(T), name);
            return true;
        }
    }
    return false;
}

Additional notes:

  • Enum.TryParse is included in .NET 4. See here http://msdn.microsoft.com/library/dd991876(VS.100).aspx
  • Another approach would be to directly wrap Enum.Parse catching the exception thrown when it fails. This could be faster when a match is found, but will likely to slower if not. Depending on the data you are processing this may or may not be a net improvement.

EDIT: Just seen a better implementation on this, which caches the necessary information: http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5

How to check if $? is not equal to zero in unix shell scripting?

I don't know how you got a string in $? but you can do:

if [[ "x$?" == "x0" ]]; then
   echo good
fi

How to select/get drop down option in Selenium 2

Take a look at the section about filling in forms using webdriver in the selenium documentation and the javadoc for the Select class.

To select an option based on the label:

Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");

To get the first selected value:

WebElement option = select.getFirstSelectedOption()

How do I make an image smaller with CSS?

Here's what I've done:

.resize {
    width: 400px;
    height: auto;
}

.resize {
    width: 300px;
    height: auto;
}

<img class="resize" src="example.jpg"/>

This will keep the image aspect ratio the same.

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

SQL Query to add a new column after an existing column in SQL Server 2005

It is a bad idea to select * from anything, period. This is why SSMS adds every field name, even if there are hundreds, instead of select *. It is extremely inefficient regardless of how large the table is. If you don't know what the fields are, its still more efficient to pull them out of the INFORMATION_SCHEMA database than it is to select *.

A better query would be:

SELECT 
 COLUMN_NAME, 
 Case 
  When DATA_TYPE In ('varchar', 'char', 'nchar', 'nvarchar', 'binary') 
  Then convert(varchar(MAX), CHARACTER_MAXIMUM_LENGTH)  
  When DATA_TYPE In ('numeric', 'int', 'smallint', 'bigint', 'tinyint') 
  Then convert(varchar(MAX), NUMERIC_PRECISION) 
  When DATA_TYPE = 'bit' 
  Then convert(varchar(MAX), 1)
  When DATA_TYPE IN ('decimal', 'float') 
  Then convert(varchar(MAX), Concat(Concat(NUMERIC_PRECISION, ', '), NUMERIC_SCALE)) 
  When DATA_TYPE IN ('date', 'datetime', 'smalldatetime', 'time', 'timestamp') 
  Then '' 
 End As DATALEN, 
 DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
Where 
 TABLE_NAME = ''

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

wmic can call an uninstaller. I haven't tried this, but I think it might work.

wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall

If you don't know exactly what the program calls itself, do

wmic product get name | sort

and look for it. You can also uninstall using SQL-ish wildcards.

wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall

... for example would perform a case-insensitive search for *j2se* and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se% is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%.)

If wmic prompts for y/n confirmation before completing the uninstall, try this:

echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall

... to pass a y to it before it even asks.

I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.

In Java, how do I get the difference in seconds between 2 dates?

You should do

org.joda.time.Seconds.secondBetween(date1, date2)

How to remove trailing whitespaces with sed?

Thanks to codaddict for suggesting the -i option.

The following command solves the problem on Snow Leopard

sed -i '' -e's/[ \t]*$//' "$1"

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

if you want to use parentheses in laravel 4 and don't forget return
In Laravel 4 (at least) you need to use $a, $b in parentheses as in the example

$a = 1;
$b = 1;
$c = 1;
$d = 1;
Model::where(function ($query) use ($a, $b) {
    return $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
    return $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
});

This is my result: enter image description here

How can you tell when a layout has been drawn?

Better with kotlin extension functions

inline fun View.waitForLayout(crossinline yourAction: () -> Unit) {
    val vto = viewTreeObserver
    vto.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            when {
                vto.isAlive -> {
                    vto.removeOnGlobalLayoutListener(this)
                    yourAction()
                }
                else -> viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        }
    })
}

Incrementing a variable inside a Bash loop

You're getting final 0 because your while loop is being executed in a sub (shell) process and any changes made there are not reflected in the current (parent) shell.

Correct script:

while read -r country _; do
  if [ "US" = "$country" ]; then
        ((USCOUNTER++))
        echo "US counter $USCOUNTER"
  fi
done < "$FILE"

Android Call an method from another class

In Class1:

Class2 inst = new Class2();
inst.UpdateEmployee();

Which to use <div class="name"> or <div id="name">?

They do not do the same thing.id is used to target a specific element, classname can be used to target multiple elements.

Example:

<div id="mycolor1" class="mycolor2">     hello world </div>
<div class="mycolor2">     hello world2 </div>
<div class="mycolor2">     hello world3 </div>

Now, you can refer all the divs with classname mycolor2 at once using

.mycolor2{ color: red } //for example - in css

This would set all nodes with class mycolor2 to red.

However, if you want to set specifically mycolor1 to blue , you can target it specifically like this:

#mycolor1{ color: blue; }

How to clear gradle cache?

To clear your gradle cache in android studio:

  1. open terminal and
  2. run gradlew clean

How to force Selenium WebDriver to click on element which is not currently visible?

There are many good answers on this page.

  1. I typically start with maximize.window(), actually I do this in the driver Factory or wherever you initialize your driver. This is something done by default - always.
  2. Its usually a wait for element because of some javascript delay.

Both are discussed in various details above. The answer I didn't see was ScrollToElement. It sounds like you are processing a list of elements, while processing you are creating more elements, checkboxes. This can cause elements in your list to move off the visible page. Sometimes you can see the element with the naked eye but you just can't click on it. When processing lists you sometimes have to interject scrolling.

  • Set a break point and check to see if the element you are using is at the window edge, top/bottom right/left. Sometimes when this is the case you can't get to it via selenium but you can manually click with your mouse.

Because I run across this I created a PageScroll.java and put my scrolling scripts there. Here are a few of the methods from this class:

public static void scrollToTop(WebDriver driver) {
      ((JavascriptExecutor) driver)
        .executeScript("window.scrollTo(0,0)");
    }

    public static void scrollToBottom(WebDriver driver) {
      ((JavascriptExecutor) driver)
        .executeScript("window.scrollTo(0, document.body.scrollHeight)");
    }

    public static void scrollToElementTop(WebDriver driver, WebElement element) {
      ((JavascriptExecutor) driver).executeScript(
        "arguments[0].scrollIntoView(true);", element);
    }

    public static void scrollToElementBottom(WebDriver driver, WebElement element) {
      ((JavascriptExecutor) driver).executeScript(
        "arguments[0].scrollIntoView(false);", element);
    }

see Scroll Element into View with Selenium for more examples

Programmatically find the number of cores on a machine

One more Windows recipe: use system-wide environment variable NUMBER_OF_PROCESSORS:

printf("%d\n", atoi(getenv("NUMBER_OF_PROCESSORS")));

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Font.createFont(..) set color and size (java.awt.Font)

Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :

JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);

JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);

The background color of label is maroon with yellow font color.

Visual Studio 2015 doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++

What is the purpose of the "final" keyword in C++11 for functions?

The final keyword allows you to declare a virtual method, override it N times, and then mandate that 'this can no longer be overridden'. It would be useful in restricting use of your derived class, so that you can say "I know my super class lets you override this, but if you want to derive from me, you can't!".

struct Foo
{
   virtual void DoStuff();
}

struct Bar : public Foo
{
   void DoStuff() final;
}

struct Babar : public Bar
{
   void DoStuff(); // error!
}

As other posters pointed out, it cannot be applied to non-virtual functions.

One purpose of the final keyword is to prevent accidental overriding of a method. In my example, DoStuff() may have been a helper function that the derived class simply needs to rename to get correct behavior. Without final, the error would not be discovered until testing.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

parsing a tab-separated file in Python

I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)

Anyway, here's my take:

Say these are the tab-separated values in your input file:

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20

then this:

with open("tab-separated-values.txt") as inp:
    print( list(zip(*(line.strip().split('\t') for line in inp))) )

would produce the following:

[('1', '6', '11', '16'), 
 ('2', '7', '12', '17'), 
 ('3', '8', '13', '18'), 
 ('4', '9', '14', '19'), 
 ('5', '10', '15', '20')]

As you can see, it put the k-th element of each row into the k-th array.

Compare two Timestamp in java

Use the before and after methods: Javadoc

if (mytime.after(fromtime) && mytime.before(totime))

ALTER table - adding AUTOINCREMENT in MySQL

ALTER TABLE t_name modify c_name INT(10) AUTO_INCREMENT PRIMARY KEY;

What is the opposite of :hover (on mouse leave)?

No there is no explicit property for mouse leave in CSS.

You could use :hover on all the other elements except the item in question to achieve this effect. But Im not sure how practical that would be.

I think you have to look at a JS / jQuery solution.

Using psql to connect to PostgreSQL in SSL mode

psql below 9.2 does not accept this URL-like syntax for options.

The use of SSL can be driven by the sslmode=value option on the command line or the PGSSLMODE environment variable, but the default being prefer, SSL connections will be tried first automatically without specifying anything.

Example with a conninfo string (updated for psql 8.4)

psql "sslmode=require host=localhost dbname=test"

Read the manual page for more options.

Retrieving JSON Object Literal from HttpServletRequest

If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..

If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.

How do I read any request header in PHP

This small PHP snippet can be helpful to you:

<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>

Google Maps v3 - limit viewable area and zoom level

This can be used to re-center the map to a specific location. Which is what I needed.

    var MapBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(35.676263, 13.949096),
    new google.maps.LatLng(36.204391, 14.89038));

    google.maps.event.addListener(GoogleMap, 'dragend', function ()
    {
        if (MapBounds.contains(GoogleMap.getCenter()))
        {
            return;
        }
        else
        {
            GoogleMap.setCenter(new google.maps.LatLng(35.920242, 14.428825));
        }
    });

Detecting input change in jQuery?

There are jQuery events like keyup and keypress which you can use with input HTML Elements. You could additionally use the blur() event.

Android Gradle Could not reserve enough space for object heap

I tried several solutions, nothing seemed to work. Setting my system JDK to match Android Studio's solved the problem.

Ensure your system java

java -version

Is the same as Androids

File > Project Structure > JDK Location

How to detect the screen resolution with JavaScript?

Trying to get this on a mobile device requires a few more steps. screen.availWidth stays the same regardless of the orientation of the device.

Here is my solution for mobile:

function getOrientation(){
    return Math.abs(window.orientation) - 90 == 0 ? "landscape" : "portrait";
};
function getMobileWidth(){
    return getOrientation() == "landscape" ? screen.availHeight : screen.availWidth;
};
function getMobileHeight(){
    return getOrientation() == "landscape" ? screen.availWidth : screen.availHeight;
};

Add Twitter Bootstrap icon to Input box

Bootstrap 4.x with 3 different way.

  1. Icon with default bootstrap Style Icon with default bootstrap Style

    <div class="input-group">
          <input type="text" class="form-control" placeholder="From" aria-label="from" aria-describedby="from">
          <div class="input-group-append">
            <span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>
          </div>
        </div>
    
  2. Icon Inside Input with default bootstrap class Icon Inside Input with default bootstrap class

    <div class="input-group">
          <input type="text" class="form-control border-right-0" placeholder="From" aria-label="from" aria-describedby="from">
          <div class="input-group-append">
            <span class="input-group-text bg-transparent"><i class="fas fa-map-marker-alt"></i></span>
          </div>
    
    </div>
    
  3. Icon Inside Input with small custom css Icon Inside Input with small custom css

    <div class="input-group">
          <input type="text" class="form-control rounded-right" placeholder="From" aria-label="from" aria-describedby="from">
            <span class="icon-inside"><i class="fas fa-map-marker-alt"></i></span>
        </div> 
    

    Custom Css

    .icon-inside {
          position: absolute;
          right: 10px;
          top: calc(50% - 12px);
          pointer-events: none;
          font-size: 16px;
          font-size: 1.125rem;
          color: #c4c3c3;
          z-index:3;
        }
    

_x000D_
_x000D_
.icon-inside {_x000D_
      position: absolute;_x000D_
      right: 10px;_x000D_
      top: calc(50% - 12px);_x000D_
      pointer-events: none;_x000D_
      font-size: 16px;_x000D_
      font-size: 1.125rem;_x000D_
      color: #c4c3c3;_x000D_
      z-index:3;_x000D_
    }
_x000D_
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />_x000D_
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">_x000D_
_x000D_
    <div class="container">_x000D_
    <h5 class="mt-3">Icon <small>with default bootstrap Style</small><h5>_x000D_
    <div class="input-group">_x000D_
      <input type="text" class="form-control" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
      <div class="input-group-append">_x000D_
        <span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>_x000D_
      </div>_x000D_
    </div>_x000D_
_x000D_
    <h5 class="mt-3">Icon Inside Input <small>with default bootstrap class</small><h5>_x000D_
    <div class="input-group">_x000D_
      <input type="text" class="form-control border-right-0" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
      <div class="input-group-append">_x000D_
        <span class="input-group-text bg-transparent"><i class="fas fa-map-marker-alt"></i></span>_x000D_
      </div>_x000D_
    </div>_x000D_
_x000D_
    <h5 class="mt-3">Icon Inside Input<small> with small custom css</small><h5>_x000D_
    <div class="input-group">_x000D_
      <input type="text" class="form-control rounded-right" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
        <span class="icon-inside"><i class="fas fa-map-marker-alt"></i></span>_x000D_
    </div>_x000D_
_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Passing an array using an HTML form hidden element

Use:

$postvalue = array("a", "b", "c");
foreach($postvalue as $value)
{
    echo '<input type="hidden" name="result[]" value="'. $value. '">';
}

And you will get $_POST['result'] as an array.

print_r($_POST['result']);

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

The only thing that worked for me:

g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);    

Can I get a patch-compatible output from git-diff?

A useful trick to avoid creating temporary patch files:

git diff | patch -p1 -d [dst-dir]

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript.

The CSS:

.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}

I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.

Very smooth.

get dictionary key by value

I was in a situation where Linq binding was not available and had to expand lambda explicitly. It resulted in a simple function:

public static T KeyByValue<T, W>(this Dictionary<T, W> dict, W val)
{
    T key = default;
    foreach (KeyValuePair<T, W> pair in dict)
    {
        if (EqualityComparer<W>.Default.Equals(pair.Value, val))
        {
            key = pair.Key;
            break;
        }
    }
    return key;
}

Call it like follows:

public static void Main()
{
    Dictionary<string, string> dict = new Dictionary<string, string>()
    {
        {"1", "one"},
        {"2", "two"},
        {"3", "three"}
    };

    string key = KeyByValue(dict, "two");       
    Console.WriteLine("Key: " + key);
}

Works on .NET 2.0 and in other limited environments.

Create a view with ORDER BY clause

Please try the below logic.

SELECT TOP(SELECT COUNT(SNO) From MyTable) * FROM bar WITH(NOLOCK) ORDER BY SNO

Spring-boot default profile for integration tests

As far as I know there is nothing directly addressing your request - but I can suggest a proposal that could help:

You could use your own test annotation that is a meta annotation comprising @SpringBootTest and @ActiveProfiles("test"). So you still need the dedicated profile but avoid scattering the profile definition across all your test.

This annotation will default to the profile test and you can override the profile using the meta annotation.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringBootTest
@ActiveProfiles
public @interface MyApplicationTest {
  @AliasFor(annotation = ActiveProfiles.class, attribute = "profiles") String[] activeProfiles() default {"test"};
}

Media Queries - In between two widths

just wanted to leave my .scss example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.

Im looking forward for your feedback!

// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;

// Prepare your "function"
@mixin in-between {
     @media (min-width:$widthSmall) and (max-width:$widthMedium) {
        @content;
     }
}


// Apply your "function"
main {
   @include in-between {
      //Do something between two media queries
      padding-bottom: 20px;
   }
}

How do I find duplicates across multiple columns?

 SELECT name, city, count(*) as qty 
 FROM stuff 
 GROUP BY name, city HAVING count(*)> 1

Loop code for each file in a directory

scandir:

$files = scandir('folder/');
foreach($files as $file) {
  //do your work here
}

or glob may be even better for your needs:

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}

Generating Unique Random Numbers in Java

I re-factored Anand's answer to make use not only of the unique properties of a Set but also use the boolean false returned by the set.add() when an add to the set fails.

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class randomUniqueNumberGenerator {

    public static final int SET_SIZE_REQUIRED = 10;
    public static final int NUMBER_RANGE = 100;

    public static void main(String[] args) {
        Random random = new Random();

        Set set = new HashSet<Integer>(SET_SIZE_REQUIRED);

        while(set.size()< SET_SIZE_REQUIRED) {
            while (set.add(random.nextInt(NUMBER_RANGE)) != true)
                ;
        }
        assert set.size() == SET_SIZE_REQUIRED;
        System.out.println(set);
    }
}

Calculating width from percent to pixel then minus by pixel in LESS CSS

You can escape the calc arguments in order to prevent them from being evaluated on compilation.

Using your example, you would simply surround the arguments, like this:

calc(~'100% - 10px')

Demo : http://jsfiddle.net/c5aq20b6/


I find that I use this in one of the following three ways:

Basic Escaping

Everything inside the calc arguments is defined as a string, and is totally static until it's evaluated by the client:

LESS Input

div {
    > span {
        width: calc(~'100% - 10px');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Interpolation of Variables

You can insert a LESS variable into the string:

LESS Input

div {
    > span {
        @pad: 10px;
        width: calc(~'100% - @{pad}');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Mixing Escaped and Compiled Values

You may want to escape a percentage value, but go ahead and evaluate something on compilation:

LESS Input

@btnWidth: 40px;
div {
    > span {
        @pad: 10px;
        width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
    }
}

CSS Output

div > span {
  width: calc((100% - 10px) - 80px);
}

Source: http://lesscss.org/functions/#string-functions-escape.

How to create a new text file using Python

Looks like you forgot the mode parameter when calling open, try w:

file = open("copy.txt", "w") 
file.write("Your text goes here") 
file.close() 

The default value is r and will fail if the file does not exist

'r' open for reading (default)
'w' open for writing, truncating the file first

Other interesting options are

'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists

See Doc for Python2.7 or Python3.6

-- EDIT --

As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

How to enable MySQL Query Log?

for mysql>=5.5 only for slow queries (1 second and more) my.cfg

[mysqld]
slow-query-log = 1
slow-query-log-file = /var/log/mysql/mysql-slow.log
long_query_time = 1
log-queries-not-using-indexes

How to convert an Instant to a date format?

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);

Swift days between two NSDates

This returns an absolute difference in days between some Date and today:

extension Date {
  func daysFromToday() -> Int {
    return abs(Calendar.current.dateComponents([.day], from: self, to: Date()).day!)
  }
}

and then use it:

if someDate.daysFromToday() >= 7 {
  // at least a week from today
}

What's the difference between lists enclosed by square brackets and parentheses in Python?

Square brackets are lists while parentheses are tuples.

A list is mutable, meaning you can change its contents:

>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]

while tuples are not:

>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:

>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Note that, as many people have pointed out, you can add tuples together. For example:

>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)

However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:

>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)

Whereas, if you were to construct this same example with a list, y would also be updated:

>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]

How to convert an IPv4 address into a integer in C#?

public bool TryParseIPv4Address(string value, out uint result)
{
    IPAddress ipAddress;

    if (!IPAddress.TryParse(value, out ipAddress) ||
        (ipAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork))
    {
        result = 0;
        return false;
    }

    result = BitConverter.ToUInt32(ipAddress.GetAddressBytes().Reverse().ToArray(), 0);
    return true;
}

SET NOCOUNT ON usage

At the risk of making things more complicated, I encourage a slightly different rule to all those I see above:

  • Always set NOCOUNT ON at the top of a proc, before you do any work in the proc, but also always SET NOCOUNT OFF again, before returning any recordsets from the stored proc.

So "generally keep nocount on, except when you are actually returning a resultset". I don't know any ways that this can break any client code, it means client code never needs to know anything about the proc internals, and it isn't particularly onerous.

How to build a RESTful API?

(1) How do I ... build those URI's? Do I need to write a PHP code at that URI?

There is no standard for how an API URI scheme should be set up, but it's common to have slash-separated values. For this you can use...

$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));

...to get an array of slash-separated values in the URI after the file name.

Example: Assuming you have an API file api.php in your application somewhere and you do a request for api.php/members/3, then $apiArgArray will be an array containing ['members', '3']. You can then use those values to query your database or do other processing.

(2) How do I build the JSON objects to return as a response?

You can take any PHP object and turn it into JSON with json_encode. You'll also want to set the appropriate header.

header('Content-Type: application/json');
$myObject = (object) array( 'property' => 'value' ); // example
echo json_encode($myObject); // outputs JSON text

All this is good for an API that returns JSON, but the next question you should ask is:

(3) How do I make my API RESTful?

For that we'll use $_SERVER['REQUEST_METHOD'] to get the method being used, and then do different things based on that. So the final result is something like...

header('Content-Type: application/json');
$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
$returnObject = (object) array();
/* Based on the method, use the arguments to figure out
   whether you're working with an individual or a collection, 
   then do your processing, and ultimately set $returnObject */
switch ($_SERVER['REQUEST_METHOD']) {
  case 'GET':
    // List entire collection or retrieve individual member
    break;
  case 'PUT':       
    // Replace entire collection or member
    break;  
  case 'POST':      
    // Create new member
    break;
  case 'DELETE':    
    // Delete collection or member
    break;
}
echo json_encode($returnObject);

Sources: https://stackoverflow.com/a/897311/1766230 and http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

You can always check the latest gradle plugin version here: https://bintray.com/android/android-tools/com.android.tools.build.gradle

So as of today you should use:

classpath 'com.android.tools.build:gradle:2.2.2'

accordingly.

OpenCV Python rotate image by X degrees around specific point

You can easily rotate the images using opencv python-

def funcRotate(degree=0):
    degree = cv2.getTrackbarPos('degree','Frame')
    rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
    rotated_image = cv2.warpAffine(original, rotation_matrix, (width, height))
    cv2.imshow('Rotate', rotated_image)

If you are thinking of creating a trackbar, then simply create a trackbar using cv2.createTrackbar() and the call the funcRotate()fucntion from your main script. Then you can easily rotate it to any degree you want. Full details about the implementation can be found here as well- Rotate images at any degree using Trackbars in opencv

Git undo changes in some files

git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index

Checking whether a String contains a number value in Java

You could use a regex to find out if the String contains a number. Take a look at the matches() method.

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

Actually although the answer of bmdhacks is almost good, there is a slight chance the second script to run after first checked the lockfile and before it wrote it. So they both will write the lock file and they will both be running. Here is how to make it work for sure:

lockfile=/var/lock/myscript.lock

if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null ; then
  trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
else
  # or you can decide to skip the "else" part if you want
  echo "Another instance is already running!"
fi

The noclobber option will make sure that redirect command will fail if file already exists. So the redirect command is actually atomic - you write and check the file with one command. You don't need to remove the lockfile at the end of file - it'll be removed by the trap. I hope this helps to people that will read it later.

P.S. I didn't see that Mikel already answered the question correctly, although he didn't include the trap command to reduce the chance the lock file will be left over after stopping the script with Ctrl-C for example. So this is the complete solution

Create a .csv file with values from a Python list

You could use the string.join method in this case.

Split over a few of lines for clarity - here's an interactive session

>>> a = ['a','b','c']
>>> first = '", "'.join(a)
>>> second = '"%s"' % first
>>> print second
"a", "b", "c"

Or as a single line

>>> print ('"%s"') % '", "'.join(a)
"a", "b", "c"

However, you may have a problem is your strings have got embedded quotes. If this is the case you'll need to decide how to escape them.

The CSV module can take care of all of this for you, allowing you to choose between various quoting options (all fields, only fields with quotes and seperators, only non numeric fields, etc) and how to esacpe control charecters (double quotes, or escaped strings). If your values are simple, string.join will probably be OK but if you're having to manage lots of edge cases, use the module available.

How to get method parameter names?

In a decorator method, you can list arguments of the original method in this way:

import inspect, itertools 

def my_decorator():

        def decorator(f):

            def wrapper(*args, **kwargs):

                # if you want arguments names as a list:
                args_name = inspect.getargspec(f)[0]
                print(args_name)

                # if you want names and values as a dictionary:
                args_dict = dict(itertools.izip(args_name, args))
                print(args_dict)

                # if you want values as a list:
                args_values = args_dict.values()
                print(args_values)

If the **kwargs are important for you, then it will be a bit complicated:

        def wrapper(*args, **kwargs):

            args_name = list(OrderedDict.fromkeys(inspect.getargspec(f)[0] + kwargs.keys()))
            args_dict = OrderedDict(list(itertools.izip(args_name, args)) + list(kwargs.iteritems()))
            args_values = args_dict.values()

Example:

@my_decorator()
def my_function(x, y, z=3):
    pass


my_function(1, y=2, z=3, w=0)
# prints:
# ['x', 'y', 'z', 'w']
# {'y': 2, 'x': 1, 'z': 3, 'w': 0}
# [1, 2, 3, 0]

How to set a parameter in a HttpServletRequest?

You can't, not using the standard API. HttpServletRequest represent a request received by the server, and so adding new parameters is not a valid option (as far as the API is concerned).

You could in principle implement a subclass of HttpServletRequestWrapper which wraps the original request, and intercepts the getParameter() methods, and pass the wrapped request on when you forward.

If you go this route, you should use a Filter to replace your HttpServletRequest with a HttpServletRequestWrapper:

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    if (servletRequest instanceof HttpServletRequest) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // Check wether the current request needs to be able to support the body to be read multiple times
        if (MULTI_READ_HTTP_METHODS.contains(request.getMethod())) {
            // Override current HttpServletRequest with custom implementation
            filterChain.doFilter(new HttpServletRequestWrapper(request), servletResponse);
            return;
        }
    }
    filterChain.doFilter(servletRequest, servletResponse);
}

How to pass datetime from c# to sql correctly?

I had many issues involving C# and SqlServer. I ended up doing the following:

  1. On SQL Server I use the DateTime column type
  2. On c# I use the .ToString("yyyy-MM-dd HH:mm:ss") method

Also make sure that all your machines run on the same timezone.

Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...

Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).

EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.

sequelize findAll sort order in nodejs

I don't think this is possible in Sequelize's order clause, because as far as I can tell, those clauses are meant to be binary operations applicable to every element in your list. (This makes sense, too, as it's generally how sorting a list works.)

So, an order clause can do something like order a list by recursing over it asking "which of these 2 elements is older?" Whereas your ordering is not reducible to a binary operation (compare_bigger(1,2) => 2) but is just an arbitrary sequence (2,4,11,2,9,0).

When I hit this issue with findAll, here was my solution (sub in your returned results for numbers):

var numbers = [2, 20, 23, 9, 53];
var orderIWant = [2, 23, 20, 53, 9];
orderIWant.map(x => { return numbers.find(y => { return y === x })});

Which returns [2, 23, 20, 53, 9]. I don't think there's a better tradeoff we can make. You could iterate in place over your ordered ids with findOne, but then you're doing n queries when 1 will do.

SyntaxError: cannot assign to operator

What do you think this is supposed to be: ((t[1])/length) * t[1] += string

Python can't parse this, it's a syntax error.

Adjust list style image position?

I had the same problem, but i could not use the background option (and didn't want to use multiple backgrounds) so i thought of another solution

this is an example for a menu that has a square like indicator for the active/current menu item (the default list style is set to none in another rule)

nav ul li.active>a:before{
    content: "¦";
    position: absolute;
    top: -22px;
    left: 55px;
    font-size: 33px;

}

it creates a square by using a square character with the ":before" pseudo class and it is freely positionable by using absolute positioning.

Transparent scrollbar with css

To control the background-color of the scrollbar, you need to target the primary element, instead of -track.

::-webkit-scrollbar {
    background-color: blue;
}

::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}

I haven't succeeded in rendering it transparent, but I did manage to set its color.

Since this is limited to webkit, it is still preferable to use JS with a polyfill: CSS customized scroll bar in div

Redirect to specified URL on PHP script completion?

You could always just use the tag to refresh the page - or maybe just drop the necessary javascript into the page at the end that would cause the page to redirect. You could even throw that in an onload function, so once its finished, the page is redirected

<?php

  echo $htmlHeader;
  while($stuff){
    echo $stuff;
  }
  echo "<script>window.location = 'http://www.yourdomain.com'</script>";
?>

Efficient way to remove ALL whitespace from String?

If you need superb performance, you should avoid LINQ and regular expressions in this case. I did some performance benchmarking, and it seems that if you want to strip white space from beginning and end of the string, string.Trim() is your ultimate function.

If you need to strip all white spaces from a string, the following method works fastest of all that has been posted here:

    public static string RemoveWhitespace(this string input)
    {
        int j = 0, inputlen = input.Length;
        char[] newarr = new char[inputlen];

        for (int i = 0; i < inputlen; ++i)
        {
            char tmp = input[i];

            if (!char.IsWhiteSpace(tmp))
            {
                newarr[j] = tmp;
                ++j;
            }
        }
        return new String(newarr, 0, j);
    }

Why should hash functions use a prime number modulus?

I'd like to add something for Steve Jessop's answer(I can't comment on it since I don't have enough reputation). But I found some helpful material. His answer is very help but he made a mistake: the bucket size should not be a power of 2. I'll just quote from the book "Introduction to Algorithm" by Thomas Cormen, Charles Leisersen, et al on page263:

When using the division method, we usually avoid certain values of m. For example, m should not be a power of 2, since if m = 2^p, then h(k) is just the p lowest-order bits of k. Unless we know that all low-order p-bit patterns are equally likely, we are better off designing the hash function to depend on all the bits of the key. As Exercise 11.3-3 asks you to show, choosing m = 2^p-1 when k is a character string interpreted in radix 2^p may be a poor choice, because permuting the characters of k does not change its hash value.

Hope it helps.

UITableViewCell Selected Background Color on Multiple Selection

By adding a custom view with the background color of your own you can have a custom selection style in table view.

let customBGColorView = UIView()
customBGColorView.backgroundColor = UIColor(hexString: "#FFF900")
cellObj.selectedBackgroundView = customBGColorView

Add this 3 line code in cellForRowAt method of TableView. I have used an extension in UIColor to add color with hexcode. Put this extension code at the end of any Class(Outside the class's body).

extension UIColor {    
convenience init(hexString: String) {
    let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
    var int = UInt32()
    Scanner(string: hex).scanHexInt32(&int)
    let a, r, g, b: UInt32
    switch hex.characters.count {
    case 3: // RGB (12-bit)
        (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
    case 6: // RGB (24-bit)
        (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
    case 8: // ARGB (32-bit)
        (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
    default:
        (a, r, g, b) = (255, 0, 0, 0)
    }
    self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
  }
}

Right Align button in horizontal LinearLayout

Use layout width in the button like android:layout_width="75dp"

GROUP BY and COUNT in PostgreSQL

I think you just need COUNT(DISTINCT post_id) FROM votes.

See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.

EDIT: Corrected my careless mistake per Erwin's comment.

What's the simplest way to list conflicted files in Git?

As highlighted in other answer(s) we can simply use command git status and then look for files listed under Unmerged paths:

linking jquery in html

I had a similar issue, but in my case, it was my CSS file.

I had loaded my CSS file before the JQuery library, since my jquery function was interaction with my css file, my jquery function wasn't working. I found this weird, but when I loaded the CSS file after loading the JQuery library, it worked.

This might not be directly related to the Question, but it may help others who might be facing a similar problem.

My issue:

    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <script type="text/javascript" src="slider.js"></script>

My solution:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="slider.js"></script>

How to convert an address into a Google Maps Link (NOT MAP)

On http://www.labnol.org/internet/tools/short-urls-for-google-maps/6604/ they show a short URL that works pretty well

Google Maps URLs are pretty unwieldy especially when sending over an IM, tweet or email. MapOf.it provides you a quick way to link to Google Maps by simply specifying the address of the location as a search parameter.

http://mapof.it/

I used it for a few applications I've designed and it worked like a charm.

Is Ruby pass by reference or by value?

In traditional terminology, Ruby is strictly pass-by-value. But that's not really what you're asking here.

Ruby doesn't have any concept of a pure, non-reference value, so you certainly can't pass one to a method. Variables are always references to objects. In order to get an object that won't change out from under you, you need to dup or clone the object you're passed, thus giving an object that nobody else has a reference to. (Even this isn't bulletproof, though — both of the standard cloning methods do a shallow copy, so the instance variables of the clone still point to the same objects that the originals did. If the objects referenced by the ivars mutate, that will still show up in the copy, since it's referencing the same objects.)

C# Get/Set Syntax Usage

By the way, in C# 3.5 you can instantiate your object's properties like so:

Person TOM=new Person 
{ 
   title = "My title", ID = 1 
};

But again, properties must be public.

Bitbucket fails to authenticate on git pull

I know that this is an old question, but I thought I would provide the solution that worked for me. I signed up for bitbucket using my google account and did not have a password. Turns out the password is my Atlassian account password. If you have an Atlassian account then try this password to see if it works.

How to let PHP to create subdomain automatically for each user?

First, you need to make sure your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named *. I also specified a folder called subdomains as the document root for wildcard subdomains. Add this to a .htaccess file in your subdomains folder:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]

Finally, all you need to do is create a folder in your subdomains folder, then place the subdomain's files in that directory.

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

jquery AJAX and json format

You aren't actually sending JSON. You are passing an object as the data, but you need to stringify the object and pass the string instead.

Your dataType: "json" only tells jQuery that you want it to parse the returned JSON, it does not mean that jQuery will automatically stringify your request data.

Change to:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({
            first_name: $("#namec").val(),
            last_name: $("#surnamec").val(),
            email: $("#emailc").val(),
            mobile: $("#numberc").val(),
            password: $("#passwordc").val()
        }),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
});