Programs & Examples On #Saving data

Why do some functions have underscores "__" before and after the function name?

This convention is used for special variables or methods (so-called “magic method”) such as __init__ and __len__. These methods provides special syntactic features or do special things.

For example, __file__ indicates the location of Python file, __eq__ is executed when a == b expression is executed.

A user of course can make a custom special method, which is a very rare case, but often might modify some of the built-in special methods (e.g. you should initialize the class with __init__ that will be executed at first when an instance of a class is created).

class A:
    def __init__(self, a):  # use special method '__init__' for initializing
        self.a = a
    def __custom__(self):  # custom special method. you might almost do not use it
        pass

How to set a tkinter window to a constant size

There are 2 solutions for your problem:

  1. Either you set a fixed size of the Tkinter window; mw.geometry('500x500')

OR

  1. Make the Frame adjust to the size of the window automatically;back.place(x = 0, y = 0, relwidth = 1, relheight = 1)

*The second option should be used in place of back.pack()

How to change a css class style through Javascript?

You may also be interested in modifying it using jQuery: http://api.jquery.com/category/css/

Change Primary Key

Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:

ALTER TABLE city
DROP CONSTRAINT pk_city;

ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.

Get mouse wheel events in jQuery?

This is working in each IE, Firefox and Chrome's latest versions.

$(document).ready(function(){
        $('#whole').bind('DOMMouseScroll mousewheel', function(e){
            if(e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
                alert("up");
            }
            else{
                alert("down");
            }
        });
    });

gcc makefile error: "No rule to make target ..."

In my case, the error message referred to an old filename, which did no longer exist because it was renamed. It turned out that the outdated information did not come from the Makefile, but from files in .deps directories.

I ran into this error after copying files from one machine to another. In that process, I assume the timestamps got in an inconsistent state, which confused "make" when running multiple jobs in parallel (similar to this bug report).

Sequential builds with make -j 1 were not affected, but it took me a while to realize because I was using an alias (make -j 8).

To clean up the state, I removed all .deps files and regenerated the Makefile. These are the commands that I used:

find | grep '.deps' | xargs rm
find | grep '.deps' | xargs rmdir
autoreconf --install # (optional, but my project is using autotools) 
./configure

After that, building worked again.

html vertical align the text inside input type button

I was having a similar issue with my button. I included line-height: 0; and it appears to have worked. Also mentioned by @anddero.

button[type=submit] {
  background-color: #4056A1;
  border-radius: 12px;
  border: 1px solid #4056A1;
  color: white;
  padding: 16px 32px;
  text-decoration: none;
  margin: 2px 1px;
  cursor: pointer;
  display: inline-block;
  font-size: 16px;
  height: 20px;
  line-height: 0;
}

SQL Server 2008 R2 can't connect to local database in Management Studio

Okay so there might be various reasons behind Sql Server Management Studio's(SSMS) above behaviour:

1.It seems that if our SSMS hasn't been opened for quite some while, the OS puts it to sleep.The solution is to manually activate our SQL server as shown below:

  • Go to Computer Management-->Services and Applications-->Services. As you see that the status of this service is currently blank which means that it has stopped. enter image description here
  • Double click the SQL Server option and a wizard box will popup as shown below.Set the startup type to "Automatic" and click on the start button which will start our SQL service. enter image description here enter image description here
  • Now check the status of your SQL Server. It will display as "Running". enter image description here
  • Also you need to check that other associated services which are also required by our SQL Server to fully function are also up and running such as SQL Server Browser,SQL Server Agent,etc.

2.The second reason could be due to incorrect credentials entered.So enter in the correct credentials.

3.If you happen to forget your credentials then follow the below steps:

  • First what you could do is sign in using "Windows Authentication" instead of "SQL Server Authentication".This will work only if you are logged in as administrator.
  • Second case what if you forget your local server name? No issues simply use "." instead of your server name and it should work. enter image description here

NOTE: This will only work for local server and not for remote server.To connect to a remote server you need to have an I.P. address of your remote server.

jQuery onclick toggle class name

jQuery has a toggleClass function:

<button class="switch">Click me</button>

<div class="text-block collapsed pressed">some text</div>

<script>    
    $('.switch').on('click', function(e) {
      $('.text-block').toggleClass("collapsed pressed"); //you can list several class names 
      e.preventDefault();
    });
</script>

How do I get the web page contents from a WebView?

Have you considered fetching the HTML separately, and then loading it into a webview?

String fetchContent(WebView view, String url) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    HttpEntity entity = response.getEntity();
    String html = EntityUtils.toString(entity); // assume html for simplicity
    view.loadDataWithBaseURL(url, html, "text/html", "utf-8", url); // todo: get mime, charset from entity
    if (statusCode != 200) {
        // handle fail
    }
    return html;
}

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

I had the same problem cause i had no public keys, so i did:

heroku keys:clear
heroku keys:add

That will generate a public key and then it works well

SSH to Vagrant box in Windows?

I also met the same problem before.

  1. In the homestead folder, use bash init.sh.

  2. If you don't have .ssh folder in D:/Users/your username/, you need to get a pair of ssh keys, ssh-keygen -t rsa -C "you@homestead".

  3. Edit Homestead.yaml(homestead/), authoriza: ~/.ssh/id_rsa.pub.

  4. keys: - ~/.ssh/id_rsa

5.

folders:
    - map: (share directory path in the host computer) 
      to: /home/vagrant/Code

sites:
    - map: homestead.app
      to: /home/vagrant/Code
  1. You need to use git bash desktop app.

  2. Open git bash desktop app. vagrant up

  3. vagrant ssh

How can I select the row with the highest ID in MySQL?

This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery

SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Straight from the ECMA-262, Fifth Edition ECMAScript Specification:

7.9.1 Rules of Automatic Semicolon Insertion

There are three basic rules of semicolon insertion:

  1. When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
    • The offending token is separated from the previous token by at least one LineTerminator.
    • The offending token is }.
  2. When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
  3. When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation "[no LineTerminator here]" within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a for statement (see 12.6.3).

How to show one layout on top of the other programmatically in my case?

Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...

Here is an example where a TextView is displayed on top of an ImageView:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <ImageView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 

    android:scaleType="center"
    android:src="@drawable/golden_gate" />

  <TextView
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="20dip"
    android:layout_gravity="center_horizontal|bottom"

    android:padding="12dip"

    android:background="#AA000000"
    android:textColor="#ffffffff"

    android:text="Golden Gate" />

</FrameLayout>

Here is the result

Getting the IP Address of a Remote Socket Endpoint

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.remoteendpoint.aspx

You can then call the IPEndPoint..::.Address method to retrieve the remote IPAddress, and the IPEndPoint..::.Port method to retrieve the remote port number.

More from the link (fixed up alot heh):

Socket s;

IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;

if (remoteIpEndPoint != null)
{
    // Using the RemoteEndPoint property.
    Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);
}

if (localIpEndPoint != null)
{
    // Using the LocalEndPoint property.
    Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);
}

Replace spaces with dashes and make all letters lower-case

Above answer can be considered to be confusing a little. String methods are not modifying original object. They return new object. It must be:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str

How to change options of <select> with jQuery?

You can remove the existing options by using the empty method, and then add your new options:

var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);

If you have your new options in an object you can:

var newOptions = {"Option 1": "value1",
  "Option 2": "value2",
  "Option 3": "value3"
};

var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
  $el.append($("<option></option>")
     .attr("value", value).text(key));
});

Edit: For removing the all the options but the first, you can use the :gt selector, to get all the option elements with index greater than zero and remove them:

$('#selectId option:gt(0)').remove(); // remove all options, but not the first 

validation of input text field in html using javascript

<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
    First Name: <input type="text" id="name" /> <br />
    <span id="nameErrMsg" class="error"></span> <br />
    <!-- ... all your other stuff ... -->
</form>
  <p>
    1.word should be atleast 5 letter<br>
    2.No space should be encountered<br>
    3.No numbers and special characters allowed<br>
    4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
  </p>
  <button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>


validateForm = function () {
    return checkName();
}

function checkName() {
    var x = document.myForm;
    var input = x.name.value;
    var errMsgHolder = document.getElementById('nameErrMsg');
    if (input.length < 5) {
        errMsgHolder.innerHTML =
            'Please enter a name with at least 5 letters';
        return false;
    } else if (!(/^\S{3,}$/.test(input))) {
        errMsgHolder.innerHTML =
            'Name cannot contain whitespace';
        return false;
    }else if(!(/^[a-zA-Z]+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'Only alphabets allowed'
    }
    else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'per 3 alphabets allowed'
    }
    else {
        errMsgHolder.innerHTML = '';
        return undefined;
    }       

}

.error {
color: #E00000;
 }

Is either GET or POST more secure than the other?

There are no security unless https is used - and with https, the transfer security is the same between GET and POST.

But one important aspect is the difference for client and server when it comes to remembering requests. This is very important to remember when considering GET or POST for a login.

With POST, the password is processed by the server application and then throw away, since a good design would not store passwords - only cryptographically secure hashes - in the database.

But with GET, the server log would end up containing the requests complete with the query parameters. So however good the password hashes in the database are, the server log would still contain passwords in clear text. And unless the file system is encrypted, the server disk would contain these passwords even after the log files have been erased.

The same problem happens when using access tokens as query parameters. And this is also a reason why it is meaningful to consider supplying any access token in the HTTP header data - such as by using a bearer token in the Authorization header.

The server logs are often the weakest part of a web service, allowing an attacker to elevate their access rights from leaked information.

Create dataframe from a matrix

Using dplyr and tidyr:

library(dplyr)
library(tidyr)

df <- as_data_frame(mat) %>%      # convert the matrix to a data frame
  gather(name, val, C_0:C_1) %>%  # convert the data frame from wide to long
  select(name, time, val)         # reorder the columns

df
# A tibble: 6 x 3
   name  time   val
  <chr> <dbl> <dbl>
1   C_0   0.0   0.1
2   C_0   0.5   0.2
3   C_0   1.0   0.3
4   C_1   0.0   0.3
5   C_1   0.5   0.4
6   C_1   1.0   0.5

How to find elements by class

How to find elements by class

I'm having trouble parsing html elements with "class" attribute using Beautifulsoup.

You can easily find by one class, but if you want to find by the intersection of two classes, it's a little more difficult,

From the documentation (emphasis added):

If you want to search for tags that match two or more CSS classes, you should use a CSS selector:

css_soup.select("p.strikeout.body")
# [<p class="body strikeout"></p>]

To be clear, this selects only the p tags that are both strikeout and body class.

To find for the intersection of any in a set of classes (not the intersection, but the union), you can give a list to the class_ keyword argument (as of 4.1.2):

soup = BeautifulSoup(sdata)
class_list = ["stylelistrow"] # can add any other classes to this list.
# will find any divs with any names in class_list:
mydivs = soup.find_all('div', class_=class_list) 

Also note that findAll has been renamed from the camelCase to the more Pythonic find_all.

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

Remove non-ASCII characters from CSV

This worked for me:

sed -i 's/[^[:print:]]//g'

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

Check the file which you are okay to overwrite and lose local changes and then

git checkout --ours ${filePath}
git merge upstream/master

How to get rows count of internal table in abap?

data: vcnt(4).

clear vcnt.

LOOP at itab WHERE value = '1'.
  add 1 to vcnt.
ENDLOOP.

The answer will be 3. (vcnt = 3).

git - remote add origin vs remote set-url origin

git remote add => ADDS a new remote.

git remote set-url => UPDATES existing remote.


  1. The remote name that comes after add is a new remote name that did not exist prior to that command.
  2. The remote name that comes after set-url should already exist as a remote name to your repository.

git remote add myupstream someurl => myupstream remote name did not exist now creating it with this command.

git remote set-url upstream someurl => upstream remote name already exist i'm just changing it's url.


git remote add myupstream https://github.com/nodejs/node => **ADD** If you don't already have upstream
git remote set-url upstream https://github.com/nodejs/node # => **UPDATE** url for upstream

docker : invalid reference format

I was executing the whole command in one line, as it was mentioned as such

$ docker run --name testproject-agent \
-e TP_API_KEY="REPLACE_WITH_YOUR_KEY" \
-e TP_AGENT_ALIAS="My First Agent" \
testproject/agent:latest

But its supposed to be a multiline command, and I copied the command line by line and pressed enter after every line and bam! it worked.

Sometimes when you copy off of the web, the new-line character gets omitted, hence my suggestion to try manually introducing the new line.

Changing upload_max_filesize on PHP

This solution can be applied only if the issue is on a WordPress installation!

If you don't have FTP access or too lazy to edit files,

You can use Increase Maximum Upload File Size plugin to increase the maximum upload file size.

c# .net change label text

Old question, but I had this issue as well, so after assigning the Text property, calling Refresh() will update the text.

Label1.Text = "Du har nu lånat filmen:" + test;
Refresh();

Nullable type as a generic parameter possible?

Multiple generic constraints can't be combined in an OR fashion (less restrictive), only in an AND fashion (more restrictive). Meaning that one method can't handle both scenarios. The generic constraints also cannot be used to make a unique signature for the method, so you'd have to use 2 separate method names.

However, you can use the generic constraints to make sure that the methods are used correctly.

In my case, I specifically wanted null to be returned, and never the default value of any possible value types. GetValueOrDefault = bad. GetValueOrNull = good.

I used the words "Null" and "Nullable" to distinguish between reference types and value types. And here is an example of a couple extension methods I wrote that compliments the FirstOrDefault method in System.Linq.Enumerable class.

    public static TSource FirstOrNull<TSource>(this IEnumerable<TSource> source)
        where TSource: class
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a class is null
        return result;
    }

    public static TSource? FirstOrNullable<TSource>(this IEnumerable<TSource?> source)
        where TSource : struct
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a nullable is null
        return result;
    }

Delete forked repo from GitHub

There are multiple answers pointing out, that editing/deleting the fork doesn't affect the original repository. Those answers are correct. I will try to add something to that answer and explain why in my answer.

A fork is just a copy of a repository with a fork relationship.

As you can copy a file or a directory locally to another place and delete the copy, it won't affect the original.

Fork relationship means, that you can easily tell github that it should send a pull request (with your changes) from your fork to the original repository because github knows that your repository is a copy of the original repository(with a few changes on both sides).

Just for anybodies information, a pull request(or merge request) contains code that has been changed in the fork and is submitted to the original repository. Users with push/write access(may be different in other git servers) on the original repository are allowed to merge the changes of the pull request into the original repository(copy the changes of the PR to the original repository).

How to enable file upload on React's Material UI simple input?

Just the same as what should be but change the button component to be label like so

<form id='uploadForm'
      action='http://localhost:8000/upload'
      method='post'
      encType="multipart/form-data">
    <input type="file" id="sampleFile" style="display: none;" />
    <Button htmlFor="sampleFile" component="label" type={'submit'}>Upload</Button> 
</form>

JBoss default password

just commenting the line of user and password in file ./server/default/conf/props jmx-console-users.properties worked for me

writing to existing workbook using xlwt

The code example is exactly this:

from xlutils.copy import copy
from xlrd import *
w = copy(open_workbook('book1.xls'))
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

You'll need to create book1.xls to test, but you get the idea.

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

You can install the Microsoft Report Viewer 2012 Runtime and change your references so they point to the ones installed by the runtime.

http://www.microsoft.com/en-gb/download/details.aspx?id=35747

I have installed the runtime without it asking for SQL Server 2012. Before installing try uninstalling any previous versions of report viewer.

How can I make an "are you sure" prompt in a Windows batchfile?

If you want to the batch program to exit back to the prompt and not close the prompt (A.K.A cmd.exe) you can use "exit /b".

This may help.

set /p _sure="Are you sure?"
::The underscore is used to ensure that "sure" is not an enviroment
::varible
if /I NOT "_sure"=="y" (
::the /I makes it so you can
exit /b
) else (
::Any other modifications...
)

Or if you don't want to use as many lines...

Set /p _sure="Are you sure?"
if /I NOT "_sure"=="y" exit /b
::Any other modifications and commands.

Hope this helps...

Append String in Swift

In Swift, appending strings is as easy as:

let stringA = "this is a string"
let stringB = "this is also a string"
let stringC = stringA + stringB

Or you can use string interpolation.

let stringC = "\(stringA) \(stringB)"

Notice there will now be whitespace between them.

Note: I see the other answers are using var a lot. The strings aren't changing and therefore should be declared using let. I know this is a small exercise, but it's good to get into the habit of best practices. Especially because that's a big feature of Swift.

Rotating and spacing axis labels in ggplot2

To make the text on the tick labels fully visible and read in the same direction as the y-axis label, change the last line to

q + theme(axis.text.x=element_text(angle=90, hjust=1))

How to cherry-pick from a remote branch?

I solved this issue by going on the branch with the commit I want to cherry pick.

git checkout <branch With Commit To Cherry-Pick>

use log to find commit hash

git log

when you've found your hash cut and paste on note pad. if using command just scroll up to get the hash then checkout the branch you want to place the commit in.

git checkout < branch I Want To Place My Cherry-Picked-Hash In>

finally call cherry-pick from git (note) -x is to append your cherry-pick message to the original. "When recording the commit, append a line that says "(cherry picked from commit …?)" to the original commit message in order to indicate which commit this change was cherry-picked from. "

git cherry-pick -x <your hash commit to add to the current branch>

Naming threads and thread-pools of ExecutorService

Thought I'd throw in some simplified examples, just so the options are all out there:

Unique number (could also put this into a method):

AtomicInteger threadNum = new AtomicInteger(0);
ExecutorService e = Executors.newSingleThreadExecutor(r -> new Thread(r, "my-name-" + threadNum.incrementAndGet()));

Unique number and "probably" unique name (if you're generating new Runnable objects). Useful if starting off the threads is within a method that gets called more than once, for instance:

AtomicInteger threadNum = new AtomicInteger(0);
ExecutorService e = Executors.newSingleThreadExecutor(r -> new Thread(r, "my-name-" + threadNum.incrementAndGet() + "-" + r.hashCode()));

If you really wanted a unique name each time you'd need a class with a static var (and could also add a static pool number prefix in there as well, see other answers).

and an equivalent in JDK < 8 (you don't need a new class for it, or could return a ThreadFactory out of a method):

Executors.newSingleThreadExecutor(new ThreadFactory() {
      AtomicInteger threadCount = new AtomicInteger(0);

      @Override
      public Thread newThread(Runnable r) {
        return new Thread(r, "your-name-" + threadCount.getAndIncrement() + "-" + r.hashCode()); // could also use Integer.toHexString(r.hashCode()) for shorter
      }
    }));

And could make that into a method for the "you-name-" aspect as a variable. Or use a separate class with a constructor like the other answers all seem to.

How to get the first non-null value in Java?

If there are only two references to test and you are using Java 8, you could use

Object o = null;
Object p = "p";
Object r = Optional.ofNullable( o ).orElse( p );
System.out.println( r );   // p

If you import static Optional the expression is not too bad.

Unfortunately your case with "several variables" is not possible with an Optional-method. Instead you could use:

Object o = null;
Object p = null;
Object q = "p";

Optional<Object> r = Stream.of( o, p, q ).filter( Objects::nonNull ).findFirst();
System.out.println( r.orElse(null) );   // p

How can I get a list of all values in select box?

You had two problems:

1) The order in which you included the HTML. Try changing the dropdown from "onLoad" to "no wrap - head" in the JavaScript settings of your fiddle.

2) Your function prints the values. What you're actually after is the text

x.options[i].text; instead of x.options[i].value;

http://jsfiddle.net/WfBRr/5/

How to define a List bean in Spring?

Import the spring util namespace. Then you can define a list bean as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/util
                    http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<util:list id="myList" value-type="java.lang.String">
    <value>foo</value>
    <value>bar</value>
</util:list>

The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute list-class.

Multiple returns from a function

Functions in PHP can return only one variable. you could use variables with global scope, you can return array, or you can pass variable by reference to the function and than change value,.. but all of that will decrease readability of your code. I would suggest that you look into the classes.

Make scrollbars only visible when a Div is hovered over?

One trick for this, for webkit browsers, is to create an invisible scrollbar, and then make it appear on hover. This method does not affect the scrolling area width as the space needed for the scrollbar is already there.

Something like this:

_x000D_
_x000D_
body {_x000D_
  height: 500px;_x000D_
  &::-webkit-scrollbar {_x000D_
    background-color: transparent;_x000D_
    width: 10px;_x000D_
  }_x000D_
  &::-webkit-scrollbar-thumb {_x000D_
    background-color: transparent;_x000D_
  }_x000D_
}_x000D_
_x000D_
body:hover {_x000D_
  &::-webkit-scrollbar-thumb {_x000D_
    background-color: black;_x000D_
  }_x000D_
}_x000D_
_x000D_
.full-width {_x000D_
  width: 100%;_x000D_
  background: blue;_x000D_
  padding: 30px;_x000D_
  color: white;_x000D_
}
_x000D_
some content here_x000D_
_x000D_
<div class="full-width">does not change</div>
_x000D_
_x000D_
_x000D_

How to remove duplicates from Python list and keep order?

> but I don't know how to retrieve the list members from the hash in alphabetical order.

Not really your main question, but for future reference Rod's answer using sorted can be used for traversing a dict's keys in sorted order:

for key in sorted(my_dict.keys()):
   print key, my_dict[key]
   ...

and also because tuple's are ordered by the first member of the tuple, you can do the same with items:

for key, val in sorted(my_dict.items()):
    print key, val
    ...

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)

I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.

Hope that helps.

How to convert number of minutes to hh:mm format in TSQL?

In case someone is interested in getting results as 60 becomes 01:00 hours, 120 becomes 02:00 hours, 150 becomes 02:30 hours, this function might help:

    create FUNCTION [dbo].[MinutesToHHMM]
(
    @minutes int 
)
RETURNS varchar(30)
AS

BEGIN
declare @h int
        set @h= @minutes / 60
        declare @mins varchar(2)
        set @mins= iif(@minutes%60<10,concat('0',cast((@minutes % 60) as varchar(2))),cast((@minutes % 60) as varchar(2)))
return iif(@h <10, concat('0', cast(@h as varchar(5)),':',@mins)
        ,concat(cast(@h as varchar(5)),':',@mins))

end

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I had this issue and realized that the file cgi-bin/php-fcgi had no execution rights.

It had 644 mode while is should have 755 mode.

Setting the correct mode was impossible (probably because the file was opened or sth), so I copied that file from another domain directory where it had proper rights already set and that fixed everything.

How to create a GUID/UUID in Python

If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.

Ex:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')

What does the term "canonical form" or "canonical representation" in Java mean?

The OP's questions about canonical form and how it can improve performance of the equals method can both be answered by extending the example provided in Effective Java.

Consider the following class:

public final class CaseInsensitiveString {

  private final String s;

  public CaseInsensitiveString(String s) {
    this.s = Objects.requireNonNull(s);
  }

  @Override 
  public boolean equals(Object o) {
    return o instanceof CaseInsensitiveString && ((CaseInsensitiveString) o).s.equalsIgnoreCase(s);
  }
}

The equals method in this example has added cost by using String's equalsIgnoreCase method. As mentioned in the text

you may want to store a canonical form of the field so the equals method can do a cheap exact comparison on canonical forms rather than a more costly nonstandard comparison.

What does Joshua Bloch mean when he says canonical form? Well, I think Dónal's concise answer is very appropriate. We can store the underlying String field in the CaseInsensitiveString example in a standard way, perhaps the uppercase form of the String. Now, you can reference this canonical form of the CaseInsensitiveString, its uppercase variant, and perform cheap evaluations in your equals and hashcode methods.

java: run a function after a specific number of seconds

My code is as follows:

new java.util.Timer().schedule(

    new java.util.TimerTask() {
        @Override
        public void run() {
            // your code here, and if you have to refresh UI put this code: 
           runOnUiThread(new   Runnable() {
                  public void run() {
                            //your code

                        }
                   });
        }
    }, 
    5000 
);

How can I select random files from a directory in bash?

Here's a script that uses GNU sort's random option:

ls |sort -R |tail -$N |while read file; do
    # Something involving $file, or you can leave
    # off the while to just get the filenames
done

How to deserialize JS date using Jackson?

There is a good blog about this topic: http://www.baeldung.com/jackson-serialize-dates Use @JsonFormat looks the most simple way.

public class Event {
    public String name;

    @JsonFormat
      (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
    public Date eventDate;
}

rsync copy over only certain types of files using include option

Wrote this handy function and put in my bash scripts or ~/.bash_aliases. Tested sync'ing locally on Linux with bash and awk installed. It works

selrsync(){
# selective rsync to sync only certain filetypes;
# based on: https://stackoverflow.com/a/11111793/588867
# Example: selrsync 'tsv,csv' ./source ./target --dry-run
types="$1"; shift; #accepts comma separated list of types. Must be the first argument.
includes=$(echo $types| awk  -F',' \
    'BEGIN{OFS=" ";}
    {
    for (i = 1; i <= NF; i++ ) { if (length($i) > 0) $i="--include=*."$i; } print
    }')
restargs="$@"

echo Command: rsync -avz --prune-empty-dirs --include="*/" $includes --exclude="*" "$restargs"
eval rsync -avz --prune-empty-dirs --include="*/" "$includes" --exclude="*" $restargs
}

Avantages:

short handy and extensible when one wants to add more arguments (i.e. --dry-run).

Example:

selrsync 'tsv,csv' ./source ./target --dry-run

Can you do a partial checkout with Subversion?

Subversion 1.5 introduces sparse checkouts which may be something you might find useful. From the documentation:

... sparse directories (or shallow checkouts) ... allows you to easily check out a working copy—or a portion of a working copy—more shallowly than full recursion, with the freedom to bring in previously ignored files and subdirectories at a later time.

POST data in JSON format

Another example is available here:

Sending a JSON to server and retrieving a JSON in return, without JQuery

Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.

Method to Add new or update existing item in Dictionary

Could there be any problem if i replace Method-1 by Method-2?

No, just use map[key] = value. The two options are equivalent.


Regarding Dictionary<> vs. Hashtable: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false); and the add parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.

Reading Xml with XmlReader in C#

I am not experiented .But i think XmlReader is unnecessary. It is very hard to use.
XElement is very easy to use.
If you need performance ( faster ) you must change file format and use StreamReader and StreamWriter classes.

How to diff a commit with its parent?

Use git show $COMMIT. It'll show you the log message for the commit, and the diff of that particular commit.

MySQL Creating tables with Foreign Keys giving errno: 150

Also worth checking that you aren't accidentally operating on the wrong database. This error will occur if the foreign table does not exist. Why does MySQL have to be so cryptic?

Prevent PDF file from downloading and printing

  1. Convert pdf to image.
  2. Use image tag to display the image.
  3. Disable right click on the image.

jQuery: count number of rows in a table

I found this to work really well if you want to count rows without counting the th and any rows from tables inside of tables:

var rowCount = $("#tableData > tbody").children().length;

Angular 2 http post params and body

Seems like you use Angular 4.3 version, I also faced with same problem. Use Angular 4.0.1 and post with code by @trichetricheand and it will work. I am also not sure how to solve it on Angular 4.3 :S

PyLint "Unable to import" error - how to set PYTHONPATH?

just add this code in .vscode/settings.json file

,"python.linting.pylintPath": "venv/bin/pylint"

This will notify the location of pylint(which is an error checker for python)

Stop mouse event propagation

Adding to the answer from @AndroidUniversity. In a single line you can write it like so:

<component (click)="$event.stopPropagation()"></component>

X-Frame-Options: ALLOW-FROM in firefox and chrome

ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options

You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?

text flowing out of div

This did the trick for me:

{word-break: break-all; }

Push to GitHub without a password using ssh-key

Using the command line:

Enter ls -al ~/.ssh to see if existing SSH keys are present.

In the terminal is shows: No directory exist

Then generate a new SSH key

Step 1.

ssh-keygen -t rsa -b 4096 -C "[email protected]"

step 2.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): <here is file name and enter the key>

step 3.

Enter passphrase (empty for no passphrase): [Type a password]

Enter same passphrase again: [Type password again]

Java: how to initialize String[]?

I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).

public class StringTest {
    public static void main(String[] args) {
        String[] errorSoon = new String[100];
        errorSoon[0] = "Error, why?";
        //another approach would be direct initialization
        String[] errorsoon = {"Error , why?"};   
    }
}

Is there a destructor for Java?

No Java doesn't have any destructors .The main reason behind it in Java is the Garbage Collectors that passively works in the background always and all the objects are made in the heap memory , that is the place where GC works .In c++ there we have to explicitly call the delete function since there is no Garbage collector like thing.

How to verify Facebook access token?

Just wanted to let you know that up until today I was first obtaining an app access token (via GET request to Facebook), and then using the received token as the app-token-or-admin-token in:

GET graph.facebook.com/debug_token?
    input_token={token-to-inspect}
    &access_token={app-token-or-admin-token}

However, I just realized a better way of doing this (with the added benefit of requiring one less GET request):

GET graph.facebook.com/debug_token?
    input_token={token-to-inspect}
    &access_token={app_id}|{app_secret}

As described in Facebook's documentation for Access Tokens here.

Calling Member Functions within Main C++

If you want to make your code work as above, the function printInformation() needs to be declared and implemented as a static function.

If, on the other hand, it is supposed to print information about a specific object, you need to create the object first.

How to get pip to work behind a proxy server

First Try to set proxy using the following command

SET HTTPS_PROXY=http://proxy.***.com:PORT#

Then Try using the command

pip install ModuleName

What does the M stand for in C# Decimal literal notation?

Well, i guess M represent the mantissa. Decimal can be used to save money, but it doesn't mean, decimal only used for money.

How do I remove the space between inline/inline-block elements?

Add white-space: nowrap to the container element:

CSS:

* {
    box-sizing: border-box;
}
.row {
    vertical-align: top;
    white-space: nowrap;
}
.column{
    float: left;
    display: inline-block;
    width: 50% // Or whatever in your case
}

HTML:

<div class="row">
    <div class="column"> Some stuff</div>
    <div class="column">Some other stuff</div>
</div>

Here is the Plunker.

Automatic prune with Git fetch or pull

Since git 1.8.5 (Q4 2013):

"git fetch" (hence "git pull" as well) learned to check "fetch.prune" and "remote.*.prune" configuration variables and to behave as if the "--prune" command line option was given.

That means that, if you set remote.origin.prune to true:

git config remote.origin.prune true

Any git fetch or git pull will automatically prune.

Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename misbehave.
See "How do I rename a git remote?".


See more at commit 737c5a9:

Without "git fetch --prune", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune".

To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "fetch.prune" and "remote.<name>.prune":

  • "fetch.prune" allows to enable prune for all fetch operations.
  • "remote.<name>.prune" allows to change the behaviour per remote.

The latter will naturally override the former, and the --[no-]prune option from the command line will override the configured default.

Since --prune is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.

How do I use Join-Path to combine more than two strings into a file path?

If you are still using .NET 2.0, then [IO.Path]::Combine won't have the params string[] overload which you need to join more than two parts, and you'll see the error Cannot find an overload for "Combine" and the argument count: "3".

Slightly less elegant, but a pure PowerShell solution is to manually aggregate path parts:

Join-Path C: (Join-Path  "Program Files" "Microsoft Office")

or

Join-Path  (Join-Path  C: "Program Files") "Microsoft Office"

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.

Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.

How to access a preexisting collection with Mongoose?

You can do something like this, than you you'll access the native mongodb functions inside mongoose:

var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/local');

var connection = mongoose.connection;

connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {

    connection.db.collection("YourCollectionName", function(err, collection){
        collection.find({}).toArray(function(err, data){
            console.log(data); // it will print your collection data
        })
    });

});

How to set a background image in Xcode using swift?

SWIFT 4

view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage

.gitignore after commit

I had to remove .idea and target folders and after reading all comments this worked for me:

git rm -r .idea
git rm -r target
git commit -m 'removed .idea folder'

and then push to master

How to use class from other files in C# with visual studio?

namespace TestCSharp2
{
    **public** class Class2
    {
        int i;
        public void setValue(int i)
        {
            this.i = i;
        }
        public int getValue()
        {
        return this.i;
        }
    }
}

Add the 'Public' declaration before 'class Class2'.

C: What is the difference between ++i and i++?

The difference can be understood by this simple C++ code below:

int i, j, k, l;
i = 1; //initialize int i with 1
j = i+1; //add 1 with i and set that as the value of j. i is still 1
k = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1
l = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l.
cout << i << ' ' << j << ' ' << k << ' '<< l << endl;
return 0;

VBA Date as integer

Public SUB test()
    Dim mdate As Date
    mdate = now()
    MsgBox (Round(CDbl(mdate), 0))
End SUB

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

Integrating the ZXing library directly into my Android application

2020 UPDATE: Just add this to your Gradle file. It works perfectly!

repositories {
   jcenter()
}
implementation 'me.dm7.barcodescanner:zxing:1.9.13'

How to get base64 encoded data from html image

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

How to delete stuff printed to console by System.out.println()?

The easiest ways to do this would be:

System.out.println("\f");

System.out.println("\u000c");

How to avoid .pyc files?

You could make the directories that your modules exist in read-only for the user that the Python interpreter is running as.

I don't think there's a more elegant option. PEP 304 appears to have been an attempt to introduce a simple option for this, but it appears to have been abandoned.

I imagine there's probably some other problem you're trying to solve, for which disabling .py[co] would appear to be a workaround, but it'll probably be better to attack whatever this original problem is instead.

Angular update object in object array

updateValue(data){    
     // retriving index from array
     let indexValue = this.items.indexOf(data);
    // changing specific element in array
     this.items[indexValue].isShow =  !this.items[indexValue].isShow;
}

How to specify in crontab by what user to run script?

You can also try using runuser (as root) to run a command as a different user

*/1 * * * * runuser php5 \
            --command="/var/www/web/includes/crontab/queue_process.php \
                       >> /var/www/web/includes/crontab/queue.log 2>&1"

See also: man runuser

How to create a fixed sidebar layout with Bootstrap 4?

I used this in my code:

<div class="sticky-top h-100">
    <nav id="sidebar" class="vh-100">
        ....

this cause your sidebar height become 100% and fixed at top.

How to check if a column exists in a datatable

It is much more accurate to use IndexOf:

If dt.Columns.IndexOf("ColumnName") = -1 Then
    'Column not exist
End If

If the Contains is used it would not differentiate between ColumName and ColumnName2.

Python object deleting itself

Indeed, Python does garbage collection through reference counting. As soon as the last reference to an object falls out of scope, it is deleted. In your example:

a = A()
a.kill()

I don't believe there's any way for variable 'a' to implicitly set itself to None.

How to format a java.sql Timestamp for displaying?

If you're using MySQL and want the database itself to perform the conversion, use this:

DATE_FORMAT(date,format)

If you prefer to format using Java, use this:

java.text.SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("M/dd/yyyy");
dateFormat.format( new Date() );

How to rename array keys in PHP?

foreach ($basearr as &$row)
{
    $row['value'] = $row['url'];
    unset( $row['url'] );
}

unset($row);

What is the maximum size of a web browser's cookie's key?

You can also use web storage too if the app specs allows you that (it has support for IE8+).

It has 5M (most browsers) or 10M (IE) of memory at its disposal.

"Web Storage (Second Edition)" is the API and "HTML5 Local Storage" is a quick start.

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

Error "can't load package: package my_prog: found packages my_prog and main"

Make sure that your package is installed in your $GOPATH directory or already inside your workspace/package.

For example: if your $GOPATH = "c:\go", make sure that the package inside C:\Go\src\pkgName

Dynamically update values of a chartjs chart

You can check instance of Chart by using Chart.instances. This will give you all the charts instances. Now you can iterate on that instances and and change the data, which is present inside config. suppose you have only one chart in your page.

for (var _chartjsindex in Chart.instances) {
/* 
 * Here in the config your actual data and options which you have given at the 
   time of creating chart so no need for changing option only you can change data
*/
 Chart.instances[_chartjsindex].config.data = [];
 // here you can give add your data
 Chart.instances[_chartjsindex].update();
 // update will rewrite your whole chart with new value
 }

Align DIV to bottom of the page

Simple 2020 no-tricks method:

body {
    display: flex;
    flex-direction: column;
}

#footer {
    margin-top: auto;
}

jQuery Change event on an <input> element - any way to retain previous value?

A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented here

e.g

<script>
    //look no global needed:)

    $(document).ready(function(){
        // Get the initial value
       var $el = $('#myInputElement');
       $el.data('oldVal',  $el.val() );


       $el.change(function(){
            //store new value
            var $this = $(this);
            var newValue = $this.data('newVal', $this.val());
       })
       .focus(function(){
            // Get the value when input gains focus
            var oldValue = $(this).data('oldVal');
       });
    });
</script>
<input id="myInputElement" type="text">

How do I add space between items in an ASP.NET RadioButtonList

Use css to add a right margin to those particular elements. Generally I would build the control, then run it to see what the resulting html structure is like, then make the css alter just those elements.

Preferably you do this by setting the class. Add the CssClass="myrblclass" attribute to your list declaration.

You can also add attributes to the items programmatically, which will come out the other side.

rblMyRadioButtonList.Items[x].Attributes.CssStyle.Add("margin-right:5px;")

This may be better for you since you can add that attribute for all but the last one.

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

Html Agility Pack get all elements by class

I used this extension method a lot in my project. Hope it will help one of you guys.

public static bool HasClass(this HtmlNode node, params string[] classValueArray)
    {
        var classValue = node.GetAttributeValue("class", "");
        var classValues = classValue.Split(' ');
        return classValueArray.All(c => classValues.Contains(c));
    }

C# how to wait for a webpage to finish loading before continuing

yuna and bnl code failed in the case below;

failing example:

1st one waits for completed.but, 2nd one with the invokemember("submit") didnt . invoke works. but ReadyState.Complete acts like its Completed before its REALLY completed:

wb.Navigate(url);
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("ok this waits Complete");

//navigates to new page
wb.Document.GetElementById("formId").InvokeMember("submit");
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("webBrowser havent navigated  yet. it gave me previous page's html.");  
var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;

how to fix this unwanted situation:

usage

    public myForm1 {

        myForm1_load() { }

        // func to make browser wait is inside the Extended class More tidy.
        WebBrowserEX wbEX = new WebBrowserEX();

        button1_click(){
            wbEX.Navigate("site1.com");
            wbEX.waitWebBrowserToComplete(wb);

            wbEX.Document.GetElementById("input1").SetAttribute("Value", "hello");
            //submit does navigation
            wbEX.Document.GetElementById("formid").InvokeMember("submit");
            wbEX.waitWebBrowserToComplete(wb);
            // this actually waits for document Compelete. worked for me.

            var processedHtml = wbEX.Document.GetElementsByTagName("HTML")[0].OuterHtml;
            var rawHtml = wbEX.DocumentText;
         }
     }

//put this  extended class in your code.
//(ie right below form class, or seperate cs file doesnt matter)
public class WebBrowserEX : WebBrowser
{
   //ctor
   WebBrowserEX()
   {
     //wired aumatically here. we dont need to worry our sweet brain.
     this.DocumentCompleted += (o, e) => { webbrowserDocumentCompleted = true;};
   }
     //instead of checking  readState, get state from DocumentCompleted Event 
     // via bool value
     bool webbrowserDocumentCompleted = false;
     public void waitWebBrowserToComplete()
     {
       while (!webbrowserDocumentCompleted )
       { Application.DoEvents();  }
       webbrowserDocumentCompleted = false;
     }

 }

How to make --no-ri --no-rdoc the default for gem install?

A oneliner for the windows 7 users:

(echo install: --no-document && echo update: --no-document) >> c:\ProgramData\gemrc

What is newline character -- '\n'

sed can be put into multi-line search & replace mode to match newline characters \n.

To do so sed first has to read the entire file or string into the hold buffer ("hold space") so that it then can treat the file or string contents as a single line in "pattern space".

To replace a single newline portably (with respect to GNU and FreeBSD sed) you can use an escaped "real" newline.

# cf. http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/
echo 'California
Massachusetts
Arizona' | 
sed -n -e '
# if the first line copy the pattern to the hold buffer
1h
# if not the first line then append the pattern to the hold buffer
1!H
# if the last line then ...
$ {
# copy from the hold to the pattern buffer
g
# double newlines
s/\n/\
\
/g
s/$/\
/
p
}'

# output
# California
#
# Massachusetts
#
# Arizona
#

There is, however, a much more convenient was to achieve the same result:

echo 'California
Massachusetts
Arizona' | 
   sed G

How to set the color of an icon in Angular Material?

<mat-icon style="-webkit-text-fill-color:blue">face</mat-icon>

connecting to MySQL from the command line

One way to connect to MySQL directly using proper MySQL username and password is:

mysql --user=root --password=mypass

Here,

root is the MySQL username
mypass is the MySQL user password

This is useful if you have a blank password.

For example, if you have MySQL user called root with an empty password, just use

mysql --user=root --password=

Converting array to list in Java

you have to cast in to array

Arrays.asList((Object[]) array)

Rails 4: how to use $(document).ready() with turbo-links

Tested so many solution finally came to this. This many your code is definitely not called twice.

_x000D_
_x000D_
      var has_loaded=false;_x000D_
      var ready = function() {_x000D_
        if(!has_loaded){_x000D_
          has_loaded=true;_x000D_
           _x000D_
          // YOURJS here_x000D_
        }_x000D_
      }_x000D_
_x000D_
      $(document).ready(ready);_x000D_
      $(document).bind('page:change', ready);
_x000D_
_x000D_
_x000D_

Get user's current location

<?php
$query = @unserialize (file_get_contents('http://ip-api.com/php/'));
if ($query && $query['status'] == 'success') {
echo 'Hey user from ' . $query['country'] . ', ' . $query['city'] . '!';
}
foreach ($query as $data) {
    echo $data . "<br>";
}
?>

Try this code using this source. it works!

What is the difference between & vs @ and = in angularJS

@ allows a value defined on the directive attribute to be passed to the directive's isolate scope. The value could be a simple string value (myattr="hello") or it could be an AngularJS interpolated string with embedded expressions (myattr="my_{{helloText}}"). Think of it as "one-way" communication from the parent scope into the child directive. John Lindquist has a series of short screencasts explaining each of these. Screencast on @ is here: https://egghead.io/lessons/angularjs-isolate-scope-attribute-binding

& allows the directive's isolate scope to pass values into the parent scope for evaluation in the expression defined in the attribute. Note that the directive attribute is implicitly an expression and does not use double curly brace expression syntax. This one is tougher to explain in text. Screencast on & is here: https://egghead.io/lessons/angularjs-isolate-scope-expression-binding

= sets up a two-way binding expression between the directive's isolate scope and the parent scope. Changes in the child scope are propagated to the parent and vice-versa. Think of = as a combination of @ and &. Screencast on = is here: https://egghead.io/lessons/angularjs-isolate-scope-two-way-binding

And finally here is a screencast that shows all three used together in a single view: https://egghead.io/lessons/angularjs-isolate-scope-review

UTF-8 output from PowerShell

This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.

When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.

As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.

Caching example:

102 [C:\Users\leeholm]
>> $r1 = [Console]::Out

103 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US



104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

105 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US

Error renaming a column in MySQL

Renaming a column in MySQL :

ALTER TABLE mytable CHANGE current_column_name new_column_name DATATYPE;

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I was facing the same issue. In my case, I had a dependency of httpclient with an older version while sendgrid required a newer version of httpclient. Just make sure that the version of httpclient is correct in your dependencies and it would work fine.

How to NodeJS require inside TypeScript file?

Use typings to access node functions from TypeScript:

typings install env~node --global

If you don't have typings install it:

npm install typings --global

How do I extract Month and Year in a MySQL date and compare them?

in Mysql Doku: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract

SELECT EXTRACT( YEAR_MONTH FROM `date` ) 
FROM `Table` WHERE Condition = 'Condition';

Convert to date format dd/mm/yyyy

Try this:

$old_date = Date_create("2010-04-19 18:31:27");
$new_date = Date_format($old_date, "d/m/Y");

libaio.so.1: cannot open shared object file

In case one does not have sudo privilege, but still needs to install the library.

Download source for the software/library using:

apt-get source libaio

or

wget https://src.fedoraproject.org/lookaside/pkgs/libaio/libaio-0.3.110.tar.gz/2a35602e43778383e2f4907a4ca39ab8/libaio-0.3.110.tar.gz

unzip the library

Install with the following command to user-specific library:

make prefix=`pwd`/usr install #(Copy from INSTALL file of libaio-0.3.110)

or

make prefix=/path/to/your/lib/libaio install

Include libaio library into LD_LIBRARY_PATH for your app:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/your/lib/libaio/lib

Now, your app should be able to find libaio.so.1

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Just in case anyone hits the same problem whilst using WPF (rather than WCF or Silverlight):

I had this error, when connecting to a Web Service. When my code was in the "main" WPF Application solution, no problem, it worked perfectly. But when I moved the code to the more sensible DAL-layer solution, it would throw the exception.

Could not find default endpoint element that references contract 'MyWebService.MyServiceSoap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

As has been stated by "Sprite" in this thread, you need to manually copy the tag.

For WPF apps, this means copying the tag from the app.config in my DAL solution to the app.config in the main WPF Application solution.

Implementing a Custom Error page on an ASP.Net website

Try this way, almost same.. but that's what I did, and working.

<configuration>
    <system.web>
       <customErrors mode="On" defaultRedirect="apperror.aspx">
          <error statusCode="404" redirect="404.aspx" />
          <error statusCode="500" redirect="500.aspx" />
       </customErrors>
    </system.web>
</configuration> 

or try to change the 404 error page from IIS settings, if required urgently.

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

Pandas - Get first row value of a given column

To select the ith row, use iloc:

In [31]: df_test.iloc[0]
Out[31]: 
ATime     1.2
X         2.0
Y        15.0
Z         2.0
Btime     1.2
C        12.0
D        25.0
E        12.0
Name: 0, dtype: float64

To select the ith value in the Btime column you could use:

In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2

There is a difference between df_test['Btime'].iloc[0] (recommended) and df_test.iloc[0]['Btime']:

DataFrames store data in column-based blocks (where each block has a single dtype). If you select by column first, a view can be returned (which is quicker than returning a copy) and the original dtype is preserved. In contrast, if you select by row first, and if the DataFrame has columns of different dtypes, then Pandas copies the data into a new Series of object dtype. So selecting columns is a bit faster than selecting rows. Thus, although df_test.iloc[0]['Btime'] works, df_test['Btime'].iloc[0] is a little bit more efficient.

There is a big difference between the two when it comes to assignment. df_test['Btime'].iloc[0] = x affects df_test, but df_test.iloc[0]['Btime'] may not. See below for an explanation of why. Because a subtle difference in the order of indexing makes a big difference in behavior, it is better to use single indexing assignment:

df.iloc[0, df.columns.get_loc('Btime')] = x

df.iloc[0, df.columns.get_loc('Btime')] = x (recommended):

The recommended way to assign new values to a DataFrame is to avoid chained indexing, and instead use the method shown by andrew,

df.loc[df.index[n], 'Btime'] = x

or

df.iloc[n, df.columns.get_loc('Btime')] = x

The latter method is a bit faster, because df.loc has to convert the row and column labels to positional indices, so there is a little less conversion necessary if you use df.iloc instead.


df['Btime'].iloc[0] = x works, but is not recommended:

Although this works, it is taking advantage of the way DataFrames are currently implemented. There is no guarantee that Pandas has to work this way in the future. In particular, it is taking advantage of the fact that (currently) df['Btime'] always returns a view (not a copy) so df['Btime'].iloc[n] = x can be used to assign a new value at the nth location of the Btime column of df.

Since Pandas makes no explicit guarantees about when indexers return a view versus a copy, assignments that use chained indexing generally always raise a SettingWithCopyWarning even though in this case the assignment succeeds in modifying df:

In [22]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [24]: df['bar'] = 100
In [25]: df['bar'].iloc[0] = 99
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

In [26]: df
Out[26]: 
  foo  bar
0   A   99  <-- assignment succeeded
2   B  100
1   C  100

df.iloc[0]['Btime'] = x does not work:

In contrast, assignment with df.iloc[0]['bar'] = 123 does not work because df.iloc[0] is returning a copy:

In [66]: df.iloc[0]['bar'] = 123
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [67]: df
Out[67]: 
  foo  bar
0   A   99  <-- assignment failed
2   B  100
1   C  100

Warning: I had previously suggested df_test.ix[i, 'Btime']. But this is not guaranteed to give you the ith value since ix tries to index by label before trying to index by position. So if the DataFrame has an integer index which is not in sorted order starting at 0, then using ix[i] will return the row labeled i rather than the ith row. For example,

In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])

In [2]: df
Out[2]: 
  foo
0   A
2   B
1   C

In [4]: df.ix[1, 'foo']
Out[4]: 'C'

How do I run Visual Studio as an administrator by default?

Right click on icon --> Properties --> Advanced --> Check checkbox run as Administrator and everytime it will open under Admin Mode (Same for Windows 8)

Send FormData with other field in AngularJS

Using $resource in AngularJS you can do:

task.service.js

$ngTask.factory("$taskService", [
    "$resource",
    function ($resource) {
        var taskModelUrl = 'api/task/';
        return {
            rest: {
                taskUpload: $resource(taskModelUrl, {
                    id: '@id'
                }, {
                    save: {
                        method: "POST",
                        isArray: false,
                        headers: {"Content-Type": undefined},
                        transformRequest: angular.identity
                    }
                })
            }
        };
    }
]);

And then use it in a module:

task.module.js

$ngModelTask.controller("taskController", [
    "$scope",
    "$taskService",
    function (
        $scope,
        $taskService,
    ) {
    $scope.saveTask = function (name, file) {
        var newTask,
            payload = new FormData();
        payload.append("name", name);
        payload.append("file", file);
        newTask = $taskService.rest.taskUpload.save(payload);
        // check if exists
    }
}

Opening A Specific File With A Batch File?

start wgnplot.exe "c:\path to file to open\foo.dat"

href image link download on click

<a href="download.php?file=path/<?=$row['file_name']?>">Download</a>

download.php:

<?php

$file = $_GET['file'];

download_file($file);

function download_file( $fullPath ){

  // Must be fresh start
  if( headers_sent() )
    die('Headers Sent');

  // Required for some browsers
  if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

  // File Exists?
  if( file_exists($fullPath) ){

    // Parse Info / Get Extension
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);

    // Determine Content Type
    switch ($ext) {
      case "pdf": $ctype="application/pdf"; break;
      case "exe": $ctype="application/octet-stream"; break;
      case "zip": $ctype="application/zip"; break;
      case "doc": $ctype="application/msword"; break;
      case "xls": $ctype="application/vnd.ms-excel"; break;
      case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
      case "gif": $ctype="image/gif"; break;
      case "png": $ctype="image/png"; break;
      case "jpeg":
      case "jpg": $ctype="image/jpg"; break;
      default: $ctype="application/force-download";
    }

    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$fsize);
    ob_clean();
    flush();
    readfile( $fullPath );

  } else
    die('File Not Found');

}
?>

Text on image mouseover?

For people coming from the future, you can now do this purely in CSS.

_x000D_
_x000D_
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; 
  margin: 5rem;
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  width: 120px;
  bottom: 100%;
  left: 50%;
  margin-left: -60px;

  position: absolute;
  z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
_x000D_
<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>
_x000D_
_x000D_
_x000D_

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

how to make a countdown timer in java

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class Stopwatch {
static int interval;
static Timer timer;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Input seconds => : ");
    String secs = sc.nextLine();
    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval = Integer.parseInt(secs);
    System.out.println(secs);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            System.out.println(setInterval());

        }
    }, delay, period);
}

private static final int setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}
}

Try this.

How to git-svn clone the last n revisions from a Subversion repository?

I find myself using the following often to get a limited number of revisions out of our huge subversion tree (we're soon reaching svn revision 35000).

# checkout a specific revision
git svn clone -r N svn://some/repo/branch/some-branch
# enter it and get all commits since revision 'N'
cd some-branch
git svn rebase

And a good way to find out where a branch started is to do a svn log it and find the first one on the branch (the last one listed when doing):

svn log --stop-on-copy svn://some/repo/branch/some-branch

So far I have not really found the hassle worth it in tracking all branches. It takes too much time to clone and svn and git don't work together as good as I would like. I tend to create patch files and apply them on the git clone of another svn branch.

What is the easiest way to get current GMT time in Unix timestamp format?

Does this help?

from datetime import datetime
import calendar

d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime

How to convert Python UTC datetime object to UNIX timestamp

What's the "Content-Length" field in HTTP header?

rfc2616

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

It doesn't matter what the content-type is.

Extension at post below.

max(length(field)) in mysql

SELECT  name, LENGTH(name) AS mlen
FROM    mytable
ORDER BY
        mlen DESC
LIMIT 1

SQL Query - how do filter by null or not null

WHERE something IS NULL

and

WHERE something IS NOT NULL

Phone number formatting an EditText in Android

More like clean:

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

String text = etyEditText.getText();
    int textlength = etyEditText.getText().length();

    if (text.endsWith("(") ||text.endsWith(")")|| text.endsWith(" ") || text.endsWith("-")  )
                return;

    switch (textlength){
        case 1:
            etyEditText.setEditText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
            etyEditText.setSelection(etyEditText.getText().length());
            break;
        case 5:
            etyEditText.setEditText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
            etyEditText.setSelection(etyEditText.getText().length());
            break;
        case 6:
            etyEditText.setEditText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
            etyEditText.setSelection(etyEditText.getText().length());
            break;
        case 10:
            etyEditText.setEditText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
            etyEditText.setSelection(etyEditText.getText().length());
            break;
    }

}

Chosen Jquery Plugin - getting selected values

Like from any regular input/select/etc...:

$("form.my-form .chosen-select").val()

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I've run into the very same issue, when mistakenly named variable with the very same name, as function.

So this:

isLive = isLive(data);

failed, generating OP's mentioned error message.

Fix to this was as simple as changing above line to:

isItALive = isLive(data);

I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

Simply create an object of Base64 and use it to encode or decode, when using org.apache.commons.codec.binary.Base64 library

To Encode

Base64 ed=new Base64();

String encoded=new String(ed.encode("Hello".getBytes()));

Replace "Hello" with the text to be encoded in String Format.

To Decode

Base64 ed=new Base64();

String decoded=new String(ed.decode(encoded.getBytes()));

Here encoded is the String variable to be decoded

Determine the data types of a data frame's columns

Simply pass your data frame into the following function:

data_types <- function(frame) {
  res <- lapply(frame, class)
  res_frame <- data.frame(unlist(res))
  barplot(table(res_frame), main="Data Types", col="steelblue", ylab="Number of Features")
}

to produce a plot of all data types in your data frame. For the iris dataset we get the following:

data_types(iris)

enter image description here

How do I call ::CreateProcess in c++ to launch a Windows executable?

There is an example at http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx

Just replace the argv[1] with your constant or variable containing the program.

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]\n", argv[0]);
        return;
    }

    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        argv[1],        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    ) 
    {
        printf( "CreateProcess failed (%d).\n", GetLastError() );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

Fitting iframe inside a div

I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:

div {
    width: 100%;
    height: 0;
    padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
    position: relative;
}

div iframe {
    width: 100%;
    height: 100%;
    position: absolute;
    display: block;
    top: 0;
    left: 0;
}

Just did it now for a client, and it seems to be working: http://themilkrunsa.co.za/

MongoError: connect ECONNREFUSED 127.0.0.1:27017

In my particular instance, I was connected to a VPN and that was blocking the localhost connection to MongoDB somehow. It worked when I disconnected my VPN. It's a special case, but good to know nonetheless. So anything impeding your network connectivity, Get that fixed.

Could not open a connection to your authentication agent

This worked for me.

In the CMD window, type the following command:

cd path-to-Git/bin # (for example,cd C:\Program Files\Git\bin)
bash
exec ssh-agent bash
ssh-add path/to/.ssh/id_rsa

SQL search multiple values in same field

This has been partially answered here: MySQL Like multiple values

I advise against

$search = explode( ' ', $search );

and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;

$search = str_replace('"', "''", search );

But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.

function makeSQL_search_pattern($search) {
    search_pattern = false;
    //escape the special regex chars
    $search = str_replace('"', "''", $search);
    $search = str_replace('^', "\\^", $search);
    $search = str_replace('$', "\\$", $search);
    $search = str_replace('.', "\\.", $search);
    $search = str_replace('[', "\\[", $search);
    $search = str_replace(']', "\\]", $search);
    $search = str_replace('|', "\\|", $search);
    $search = str_replace('*', "\\*", $search);
    $search = str_replace('+', "\\+", $search);
    $search = str_replace('{', "\\{", $search);
    $search = str_replace('}', "\\}", $search);
    $search = explode(" ", $search);
    for ($i = 0; $i < count($search); $i++) {
        if ($i > 0 && $i < count($search) ) {
           $search_pattern .= "|";
        }
        $search_pattern .= $search[$i];
    }
    return search_pattern;
}

$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();

I have not tested this code, but this is what I would do in your case. I hope this helps.

ConnectivityManager getNetworkInfo(int) deprecated

Many answers still use getNetworkType below 23 which is deprecated; use below code to check if the device has an internet connection.

public static boolean isNetworkConnected(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
            return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
        } else {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnected();
        }
    }

    return false;
}

..

And, do not forget to add this line in Manifest

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

Java 8 optional: ifPresent return object orElseThrow exception

Two options here:

Replace ifPresent with map and use Function instead of Consumer

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object
            .map(obj -> {
                String result = "result";
                //some logic with result and return it
                return result;
            })
            .orElseThrow(MyCustomException::new);
}

Use isPresent:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    if (object.isPresent()) {
        String result = "result";
        //some logic with result and return it
        return result;
    } else {
        throw new MyCustomException();
    }
}

Git asks for username every time I push

You can accomplish this in the .git/config file of your local repository. This file contains a section called 'remote' with an entry called 'url'. The 'url' entry should contains the https link of repository you're talking about.

When you prefix the host 'url' with your username, git shouldn't be asking for your username anymore. Here's an example:

url = https://[email protected]

How can I change property names when serializing with Json.net?

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

How to change Maven local repository in eclipse

Here is settings.xml --> C:\maven\conf\settings.xml

Linq style "For Each"

There isn't anything like that in standard Linq, but there is a ForEach operator in MoreLinq.

SVN how to resolve new tree conflicts when file is added on two branches

I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.

The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?

Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.

ConfigurationManager.AppSettings - How to modify and save?

Perhaps you should look at adding a Settings File. (e.g. App.Settings) Creating this file will allow you to do the following:

string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";

This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!

The result is a Application or User contextual setting.

Have a look in the "add new item" menu for the setting file.

Why does the 'int' object is not callable error occur when using the sum() function?

This means that somewhere else in your code, you have something like:

sum = 0

Which shadows the builtin sum (which is callable) with an int (which isn't).

Convert java.util.Date to String

public static void main(String[] args) 
{
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    System.out.println(form.format(d));
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that
}

Detect Safari using jQuery

Apparently the only reliable and accepted solution would be to do feature detection like this:

browser_treats_urls_like_safari_does = false;
var last_location_hash = location.hash;
location.hash = '"blah"';
if (location.hash == '#%22blah%22')
    browser_treats_urls_like_safari_does = true;
location.hash = last_location_hash;

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

I've found that if the input has no name (e.g. the name attribute is not set), the browser can't autocomplete the field. I know this is not a solution for everyone, but if you submit your form through AJAX, you may try this.

C# "as" cast vs classic cast

I think the best 'rule' would be to only use the 'as' keyword when it's expected that your subject won't be the object you're casting to:

var x = GiveMeSomething();

var subject = x as String;

if(subject != null)
{
  // do what you want with a string
}
else
{
  // do what you want with NOT a string
}

However, when your subject SHOULD be of the type you're casting to, use a 'classic cast', as you call it. Because if it isn't the type you're expecting, you'll get an exception which fits the exceptional situation.

Remove elements from collection while iterating

You can't do the second, because even if you use the remove() method on Iterator, you'll get an Exception thrown.

Personally, I would prefer the first for all Collection instances, despite the additional overheard of creating the new Collection, I find it less prone to error during edit by other developers. On some Collection implementations, the Iterator remove() is supported, on other it isn't. You can read more in the docs for Iterator.

The third alternative, is to create a new Collection, iterate over the original, and add all the members of the first Collection to the second Collection that are not up for deletion. Depending on the size of the Collection and the number of deletes, this could significantly save on memory, when compared to the first approach.

What does PHP keyword 'var' do?

The var keyword is used to declare variables in a class in PHP 4:

class Foo {
    var $bar;
}

With PHP 5 property and method visibility (public, protected and private) was introduced and thus var is deprecated.

How to get the instance id from within an ec2 instance?

In the question you have mentioned the user as root, one thing I should mention is that the instance ID is not dependent on the user.

For Node developers,

var meta  = new AWS.MetadataService();

meta.request("/latest/meta-data/instance-id", function(err, data){
    console.log(data);
});

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

An alternative that works for me is to simply convert to a CSV.

Check if a string is not NULL or EMPTY

if (!$variablename) { Write-Host "variable is null" }

I hope this simple answer will is resolve the question. Source

Adding/removing items from a JavaScript object with jQuery

That's not JSON at all, it's just Javascript objects. JSON is a text representation of data, that uses a subset of the Javascript syntax.

The reason that you can't find any information about manipulating JSON using jQuery is because jQuery has nothing that can do that, and it's generally not done at all. You manipulate the data in the form of Javascript objects, and then turn it into a JSON string if that is what you need. (jQuery does have methods for the conversion, though.)

What you have is simply an object that contains an array, so you can use all the knowledge that you already have. Just use data.items to access the array.

For example, to add another item to the array using dynamic values:

// The values to put in the item
var id = 7;
var name = "The usual suspects";
var type = "crime";
// Create the item using the values
var item = { id: id, name: name, type: type };
// Add the item to the array
data.items.push(item);

Add a pipe separator after items in an unordered list unless that item is the last on a line

Slightly modified SCSS version which gives you control of the pipe | size and will eliminate padding from first and last list items while respects borders.


$pipe-list-height: 20px;
$pipe-list-padding: 15px;

.pipe-list {
    position: relative;
    overflow: hidden;
    height: $pipe-list-height;

    > ul {
        display: flex;
        flex-direction: row;

        > li {
            position: relative;
            padding: 0 $pipe-list-padding;

            &:after {
                content: " ";
                position: absolute;
                border-right: 1px solid gray;
                top: 10%;
                right: 0;
                height: 75%;
                margin-top: auto;
                margin-bottom: auto;
            }

            &:first-child {
                padding-left: 0;
            }

            &:last-child {
                padding-right: 0;

                &:after {
                    border-right: none;
                }
            }
        }
    }
}
<div class="pipe-list">
  <ul>
    <li>Link</li>
    <li>Link</li>
    <li>Link</li>
  </ul>
</div>

Git - Ignore node_modules folder everywhere

Add this

node_modules/

to .gitignore file to ignore all directories called node_modules in current folder and any subfolders

How to merge multiple dicts with same key or different key?

From blubb answer:

You can also directly form the tuple using values from each list

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = (d1[k], d2[k])

This might be useful if you had a specific ordering for your tuples

ds = [d1, d2, d3, d4]
d = {}
for k in d1.keys():
  d[k] = (d3[k], d1[k], d4[k], d2[k]) #if you wanted tuple in order of d3, d1, d4, d2

A simple jQuery form validation script

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

How to set selected index JComboBox by value

public boolean  preencherjTextCombox (){
       int x = Integer.parseInt(TableModelo.getModel().getValueAt(TableModelo.getSelectedRow(),0).toString());

       modeloobj = modelosDAO.pesquisar(x);
       Combmarcass.getModel().setSelectedItem(modeloobj.getMarca());  
       txtCodigo.setText(String.valueOf(modeloobj.getCodigo()));
       txtDescricao.setText(String.valueOf(modeloobj.getDescricao()));
       txtPotencia.setText(String.valueOf(modeloobj.getPotencia()));  

       return true;
   }

Change Background color (css property) using Jquery

The code below will change the div to blue.

<script>
 $(document).ready(function(){ 
   $("#co").click({
            $("body").css("background-color","blue");
      });
    }); 
</script>
<body>
      <div id="co">hello</div>
</body>

python-pandas and databases like mysql

For Postgres users

import psycopg2
import pandas as pd

conn = psycopg2.connect("database='datawarehouse' user='user1' host='localhost' password='uberdba'")

customers = 'select * from customers'

customers_df = pd.read_sql(customers,conn)

customers_df

Disable same origin policy in Chrome

On a Windows PC, use an older version of Chrome and the command will work for all you guys. I downgraded my Chrome to 26 version and it worked.

How to replace local branch with remote branch entirely in Git?

The safest and most complete way to replace the current local branch with the remote:

git stash
git merge --abort
git rebase --abort
git branch -M yourBranch replaced_yourBranch
git fetch origin yourBranch:yourBranch
git checkout yourBranch

The stash line saves the changes that you have not committed. The branch line moves your branch to a different name, freeing up the original name. The fetch line retrieves the latest copy of the remote. The checkout line recreates the original branch as a tracking branch.

Or as a bash function:

replaceWithRemote() {
    yourBranch=${1:-`git rev-parse --abbrev-ref HEAD`}
    git stash
    git merge --abort
    git rebase --abort
    git branch -M ${yourBranch} replaced_${yourBranch}_`git rev-parse --short HEAD`
    git fetch origin ${yourBranch}:${yourBranch}
    git checkout ${yourBranch}
}

which renames the current branch to something like replaced_master_98d258f.

How to remove new line characters from a string?

The right choice really depends on how big the input string is and what the perforce and memory requirement are, but I would use a regular expression like

string result = Regex.Replace(s, @"\r\n?|\n|\t", String.Empty);

Or if we need to apply the same replacement multiple times, it is better to use a compiled version for the Regex like

var regex = new Regex(@"\r\n?|\n|\t", RegexOptions.Compiled); 
string result = regex.Replace(s, String.Empty);

NOTE: different scenarios requite different approaches to achieve the best performance and the minimum memory consumption

What charset does Microsoft Excel use when saving files?

Russian Edition offers CSV, CSV (Macintosh) and CSV (DOS).

When saving in plain CSV, it uses windows-1251.

I just tried to save French word Résumé along with the Russian text, it saved it in HEX like 52 3F 73 75 6D 3F, 3F being the ASCII code for question mark.

When I opened the CSV file, the word, of course, became unreadable (R?sum?)

How can you profile a Python script?

I ran into a handy tool called SnakeViz when researching this topic. SnakeViz is a web-based profiling visualization tool. It is very easy to install and use. The usual way I use it is to generate a stat file with %prun and then do analysis in SnakeViz.

The main viz technique used is Sunburst chart as shown below, in which the hierarchy of function calls is arranged as layers of arcs and time info encoded in their angular widths.

The best thing is you can interact with the chart. For example, to zoom in one can click on an arc, and the arc and its descendants will be enlarged as a new sunburst to display more details.

enter image description here

How to include duplicate keys in HashMap?

You can't have duplicate keys in a Map. You can rather create a Map<Key, List<Value>>, or if you can, use Guava's Multimap.

Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "rohit");
multimap.put(1, "jain");

System.out.println(multimap.get(1));  // Prints - [rohit, jain]

And then you can get the java.util.Map using the Multimap#asMap() method.

How to open google chrome from terminal?

UPDATE:

  1. How do I open google chrome from the terminal?

Thank you for the quick response. open http://localhost/ opened that domain in my default browser on my Mac.

  1. What alias could I use to open the current git project in the browser?

I ended up writing this alias, did the trick:

# Opens git file's localhost; ${PWD##*/} is the current directory's name
alias lcl='open "http://localhost/${PWD##*/}/"'

Thank you again!

Get Number of Rows returned by ResultSet in Java

this my solution

 ResultSet rs=Statement.executeQuery("query");

    int rowCount=0;


    if (!rs.isBeforeFirst()) 
      {

           System.out.println("No DATA" );
        } else {
            while (rs.next()) {
                rowCount++; 
            System.out.println("data1,data2,data3...etc..");
            }
            System.out.println(rowCount);
            rowCount=0;
            rs.close();
            Statement.close();
      }

Fill background color left to right CSS

The thing you will need to do here is use a linear gradient as background and animate the background position. In code:

Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.

background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;

On hover, change the background position to right bottom and with transition:all 2s ease;, the position will change gradually (it's nicer with linear tough) background-position:right bottom;

http://jsfiddle.net/75Umu/3/

As for the -vendor-prefix'es, see the comments to your question

extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).

background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;

Demo:

_x000D_
_x000D_
div {
    font: 22px Arial;
    display: inline-block;
    padding: 1em 2em;
    text-align: center;
    color: white;
    background: red; /* default color */

    /* "to left" / "to right" - affects initial color */
    background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
    background-size: 200%;
    transition: .5s ease-out;
}
div:hover {
    background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
_x000D_
_x000D_

HTML favicon won't show on google chrome

Your html is completely wrong for starters, there should not be a div within your head section, nor after your body section. I suggest you look into correct html first before starting to work with favicons etc.

How to clear File Input

Clear file input with jQuery

$("#fileInputId").val(null);

Clear file input with JavaScript

document.getElementById("fileInputId").value = null;

Forward slash in Java Regex

Double escaping is required when presented as a string.

Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html

That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.

Extract digits from string - StringUtils Java

Use a regex such as [^0-9] to remove all non-digits.

From there, just use Integer.parseInt(String);

How to use environment variables in docker compose

You cannot ... yet. But this is an alternative, think like a docker-composer.yml generator:

https://gist.github.com/Vad1mo/9ab63f28239515d4dafd

Basically a shell script that will replace your variables. Also you can use Grunt task to build your docker compose file at the end of your CI process.

Test if registry value exists

My version:

Function Test-RegistryValue($Key, $Name)
{
    (Get-ChildItem (Split-Path -Parent -Path $Key) | Where-Object {$_.PSChildName -eq (Split-Path -Leaf $Key)}).Property -contains $Name
}

passing JSON data to a Spring MVC controller

You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.

In the Controller, you can use the javax.json to convert and manipulate this.

Download and add the .jar to the project libs and import the JsonObject.

To create an json object, you can use

JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();

To read it from String, you can use

JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();

how to know status of currently running jobs

DECLARE @StepCount INT
SELECT @StepCount = COUNT(1)
FROM msdb.dbo.sysjobsteps
WHERE job_id = '0523333-5C24-1526-8391-AA84749345666' --JobID


SELECT
         [JobName]
        ,[JobStepID]
        ,[JobStepName]
        ,[JobStepStatus]
        ,[RunDateTime]
        ,[RunDuration]
    FROM
    (
        SELECT 
                j.[name] AS [JobName]
            ,Jh.[step_id] AS [JobStepID]
            ,jh.[step_name] AS [JobStepName]
            ,CASE 
                WHEN jh.[run_status] = 0 THEN 'Failed'
                WHEN jh.[run_status] = 1 THEN 'Succeeded'
                WHEN jh.[run_status] = 2 THEN 'Retry (step only)'
                WHEN jh.[run_status] = 3 THEN 'Canceled'
                WHEN jh.[run_status] = 4 THEN 'In-progress message'
                WHEN jh.[run_status] = 5 THEN 'Unknown'
                ELSE 'N/A'
                END AS [JobStepStatus]
            ,msdb.dbo.agent_datetime(run_date, run_time) AS [RunDateTime]
            ,CAST(jh.[run_duration]/10000 AS VARCHAR)  + ':' + CAST(jh.[run_duration]/100%100 AS VARCHAR) + ':' + CAST(jh.[run_duration]%100 AS VARCHAR) AS [RunDuration]
            ,ROW_NUMBER() OVER 
            (
                PARTITION BY jh.[run_date]
                ORDER BY jh.[run_date] DESC, jh.[run_time] DESC
            ) AS [RowNumber]
        FROM 
            msdb.[dbo].[sysjobhistory] jh
            INNER JOIN msdb.[dbo].[sysjobs] j
                ON jh.[job_id] = j.[job_id]
        WHERE 
            j.[name] = 'ProcessCubes' --Job Name
            AND jh.[step_id] > 0
            AND CAST(RTRIM(run_date) AS DATE) = CAST(GETDATE() AS DATE) --Current Date
    ) A
    WHERE 
        [RowNumber] <= @StepCount
        AND [JobStepStatus] = 'Failed'

virtualenvwrapper and Python 3

I find that running

export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3

and

export VIRTUALENVWRAPPER_VIRTUALENV=/usr/bin/virtualenv-3.4

in the command line on Ubuntu forces mkvirtualenv to use python3 and virtualenv-3.4. One still has to do

mkvirtualenv --python=/usr/bin/python3 nameOfEnvironment

to create the environment. This is assuming that you have python3 in /usr/bin/python3 and virtualenv-3.4 in /usr/local/bin/virtualenv-3.4.