Programs & Examples On #Criteriaquery

0

In JPA 2, using a CriteriaQuery, how to count results

With Spring Data Jpa, we can use this method:

    /*
     * (non-Javadoc)
     * @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#count(org.springframework.data.jpa.domain.Specification)
     */
    @Override
    public long count(@Nullable Specification<T> spec) {
        return executeCountQuery(getCountQuery(spec, getDomainClass()));
    }

JPA Query selecting only specific columns without using Criteria Query?

Yes, it is possible. All you have to do is change your query to something like SELECT i.foo, i.bar FROM ObjectName i WHERE i.id = 10. The result of the query will be a List of array of Object. The first element in each array is the value of i.foo and the second element is the value i.bar. See the relevant section of JPQL reference.

Call fragment from fragment

I would use a listener. Fragment1 calling the listener (main activity)

Convert a list of objects to an array of one of the object's properties

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

Yes, LINQ can do this. It's simply:

MyList.Select(x => x.Name).ToArray();

Most likely the issue is that you either don't have a reference to System.Core, or you are missing an using directive for System.Linq.

MySql : Grant read only options?

Various permissions that you can grant to a user are

ALL PRIVILEGES- This would allow a MySQL user all access to a designated database (or if no database is selected, across the system)
CREATE- allows them to create new tables or databases
DROP- allows them to them to delete tables or databases
DELETE- allows them to delete rows from tables
INSERT- allows them to insert rows into tables
SELECT- allows them to use the Select command to read through databases
UPDATE- allow them to update table rows
GRANT OPTION- allows them to grant or remove other users' privileges

To provide a specific user with a permission, you can use this framework:

GRANT [type of permission] ON [database name].[table name] TO ‘[username]’@'localhost’;

I found this article very helpful

Swing JLabel text change on the running application

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);

Convert alphabet letters to number in Python

This is a function I used to use for this purpose. Works for both uppercase and lowercase.

def convert_char(old):
    if len(old) != 1:
        return 0
    new = ord(old)
    if 65 <= new <= 90:
        # Upper case letter
        return new - 64
    elif 97 <= new <= 122:
        # Lower case letter
        return new - 96
    # Unrecognized character
    return 0

Flask ImportError: No Module Named Flask

This is what worked for me when I got a similar error in Windows; 1. Install virtualenv

pip install virtualenve
  1. Create a virtualenv

    virtualenv flask

  2. Navigate to Scripts and activate the virtualenv

    activate

  3. Install Flask

    python -m pip install flask

  4. Check if flask is installed

    python -m pip list

How to insert an item into a key/value pair object?

Hashtables are not inherently sorted, your best bet is to use another structure such as a SortedList or an ArrayList

Getting 400 bad request error in Jquery Ajax POST

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

Checkout multiple git repos into same Jenkins workspace

We are using git-repo to manage our multiple GIT repositories. There is also a Jenkins Repo plugin that allows to checkout all or part of the repositories managed by git-repo to the same Jenkins job workspace.

How to use MD5 in javascript to transmit a password

In response to jt. You are correct, the HTML with just the password is susceptible to the Man in the middle attack. However, you can seed it with a GUID from the server ...

$.post(
  'includes/login.php', 
  { user: username, pass: $.md5(password + GUID) },
   onLogin, 
  'json' );

This would defeat the Man-In-The middle ... in that the server would generate a new GUID for each attempt.

Java: how do I initialize an array size if it's unknown?

You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.

If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.

What is this weird colon-member (" : ") syntax in the constructor?

there is another 'benefit'

if the member variable type does not support null initialization or if its a reference (which cannot be null initialized) then you have no choice but to supply an initialization list

How to determine whether a year is a leap year?

The logic in the "one-liner" works fine. From personal experience, what has helped me is to assign the statements to variables (in their "True" form) and then use logical operators for the result:

A = year % 4 == 0
B = year % 100 == 0
C = year % 400 == 0

I used '==' in the B statement instead of "!=" and applied 'not' logical operator in the calculation:

leap = A and (not B or C)

This comes in handy with a larger set of conditions, and to simplify the boolean operation where applicable before writing a whole bunch of if statements.

Get the time difference between two datetimes

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') //[days, years, months, seconds, ...]
//Result 1 

Worked for me

See more in http://momentjs.com/docs/#/displaying/difference/

Redirecting to URL in Flask

You can use like this:

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
     # Redirect from here, replace your custom site url "www.google.com"
    return redirect("https://www.google.com", code=200)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

Here is the referenced link to this code.

Android Studio - local path doesn't exist

In my case the problem was only that a folder in the project path contains non-English (Arabic) characters

What does %>% function mean in R?

%...% operators

%>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

"%,%" <- function(x, y) paste0(x, ", ", y)

# test run

"Hello" %,% "World"
## [1] "Hello, World"

The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See http://cran.r-project.org/web/packages/operators/operators.pdf

igraph This package defines %--% , %->% and %<-% to select edges.

lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .

Pipes

magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html

magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%, %<>% and %$% and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.

dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/

The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf

postlogic The postlogic package defined %if% and %unless% operators.

wrapr The R package, wrapr, defines a dot pipe %.>% that is an explicit version of %>% in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%. See https://winvector.github.io/wrapr/articles/dot_pipe.html

Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:

1:8 %>% sum %>% sqrt
## [1] 6

one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.) . We follow that with a semicolon.

1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6

Update Added info on expm package and simplified example at top. Added postlogic package.

How to check if field is null or empty in MySQL?

Try using nullif:

SELECT ifnull(nullif(field1,''),'empty') AS field1
  FROM tablename;

Finding repeated words on a string and counting the repetitions

Hope this helps :

public static int countOfStringInAText(String stringToBeSearched, String masterString){

    int count = 0;
    while (masterString.indexOf(stringToBeSearched)>=0){
      count = count + 1;
      masterString = masterString.substring(masterString.indexOf(stringToBeSearched)+1);
    }
    return count;
}

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

How can I count the number of elements with same class?

document.getElementsByClassName("classstringhere").length

The document.getElementsByClassName("classstringhere") method returns an array of all the elements with that class name, so .length gives you the amount of them.

CSS3 scrollbar styling on a div

The problem with the css3 scroll bars is that, interaction can only be performed on the content. we can't interact with the scroll bar on touch devices.

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

I am trying to connect my db docker container on Ubuntu 18.04, same problem.

First check your device by run nmcli dev to check if device docker0 is connected.

If it is not connected, try to restart docker service:

sudo service docker restart

Retrieve list of tasks in a queue in Celery

This worked for me in my application:

def get_celery_queue_active_jobs(queue_name):
    connection = <CELERY_APP_INSTANCE>.connection()

    try:
        channel = connection.channel()
        name, jobs, consumers = channel.queue_declare(queue=queue_name, passive=True)
        active_jobs = []

        def dump_message(message):
            active_jobs.append(message.properties['application_headers']['task'])

        channel.basic_consume(queue=queue_name, callback=dump_message)

        for job in range(jobs):
            connection.drain_events()

        return active_jobs
    finally:
        connection.close()

active_jobs will be a list of strings that correspond to tasks in the queue.

Don't forget to swap out CELERY_APP_INSTANCE with your own.

Thanks to @ashish for pointing me in the right direction with his answer here: https://stackoverflow.com/a/19465670/9843399

How to convert from java.sql.Timestamp to java.util.Date?

The fancy new Java 8 way is Date.from(timestamp.toInstant()). See my similar answer elsewhere.

How to make UIButton's text alignment center? Using IB

Use the line:

myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

This should center the content (horizontally).

And if you want to set the text inside the label to the center as well, use:

[labelOne setTextAlignment:UITextAlignmentCenter];

If you want to use IB, I've got a small example here which is linked in XCode 4 but should provide enough detail (also mind, on top of that properties screen it shows the property tab. You can find the same tabs in XCode 3.x): enter image description here

How to pip or easy_install tkinter on Windows

If you are using virtualenv, it is fine to install tkinter using sudo apt-get install python-tk(python2), sudo apt-get install python3-tk(python3), and and it will work fine in the virtual environment

Writing to an Excel spreadsheet

OpenPyxl is quite a nice library, built to read/write Excel 2010 xlsx/xlsm files:

https://openpyxl.readthedocs.io/en/stable

The other answer, referring to it is using the deperciated function (get_sheet_by_name). This is how to do it without it:

import openpyxl

wbkName = 'New.xlsx'        #The file should be created before running the code.
wbk = openpyxl.load_workbook(wbkName)
wks = wbk['test1']
someValue = 1337
wks.cell(row=10, column=1).value = someValue
wbk.save(wbkName)
wbk.close

Passing a string with spaces as a function argument in bash

Simple solution that worked for me -- quoted $@

Test(){
   set -x
   grep "$@" /etc/hosts
   set +x
}
Test -i "3 rb"
+ grep -i '3 rb' /etc/hosts

I could verify the actual grep command (thanks to set -x).

Android add placeholder text to EditText

If you mean the location where you will add it in the layout. You can define a container like a FrameLayout and add this EditText to it when it is created.

<LinearLayout xmlns=".."/>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/container" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

FrameLayout layout = (FrameLayout) findViewById(R.id.container);
layout.addView(name);

How to change Elasticsearch max memory size

If you installed ES using the RPM/DEB packages as provided (as you seem to have), you can adjust this by editing the init script (/etc/init.d/elasticsearch on RHEL/CentOS). If you have a look in the file you'll see a block with the following:

export ES_HEAP_SIZE
export ES_HEAP_NEWSIZE
export ES_DIRECT_SIZE
export ES_JAVA_OPTS
export JAVA_HOME

To adjust the size, simply change the ES_HEAP_SIZE line to the following:

export ES_HEAP_SIZE=xM/xG

(where x is the number of MB/GB of RAM that you would like to allocate)

Example:

export ES_HEAP_SIZE=1G

Would allocate 1GB.

Once you have edited the script, save and exit, then restart the service. You can check if it has been correctly set by running the following:

ps aux | grep elasticsearch

And checking for the -Xms and -Xmx flags in the java process that returns:

/usr/bin/java -Xms1G -Xmx1G

Hope this helps :)

Cannot connect to the Docker daemon on macOS

Docker for Mac is deprecated. And you don't need Homebrew to run Docker on Mac. Instead you'll likely want to install Docker Desktop or, if already installed, make sure it's up-to-date and running, then attempt to connect to the socket again.

enter image description here

ES6 modules implementation, how to load a json file

First of all you need to install json-loader:

npm i json-loader --save-dev

Then, there are two ways how you can use it:

  1. In order to avoid adding json-loader in each import you can add to webpack.config this line:

    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      // other loaders 
    ]
    

    Then import json files like this

    import suburbs from '../suburbs.json';
    
  2. Use json-loader directly in your import, as in your example:

    import suburbs from 'json!../suburbs.json';
    

Note: In webpack 2.* instead of keyword loaders need to use rules.,

also webpack 2.* uses json-loader by default

*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.

v2.1.0-beta.28

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

Printing 1 to 1000 without loop or conditionals

Obviously requires Windows/Visual Studio... But it works.

#include <stdio.h>
#include <Windows.h>

void print(int x)
{
    int y;

    printf("%d\n", x);
    __try
    {
        y = 1 / (x - 1000);
        print(x + 1);
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        return;
    }
}

void main()
{
    print(1);
}

What is &amp used for

That's a great example. When &current is parsed into a text node it is converted to ¤t. When parsed into an attribute value, it is parsed as &current.

If you want &current in a text node, you should write &amp;current in your markup.

The gory details are in the HTML5 parsing spec - Named Character Reference State

How do I view an older version of an SVN file?

Update to a specific revision:

svn up -r1234 file

How to use pagination on HTML tables?

Use tr to <tr class="paginate">

//Pagination

<div id="page-nav"></div>

//Script

 <script>
        jQuery(function($) {
            // Grab whatever we need to paginate
            var pageParts = $(".paginate");
    
            // How many parts do we have?
            var numPages = 100;
            // How many parts do we want per page?
            var perPage = 10;
    
            // When the document loads we're on page 1
            // So to start with... hide everything else
            pageParts.slice(perPage).hide();
            // Apply simplePagination to our placeholder
            $("#page-nav").pagination({
                items: numPages,
                itemsOnPage: perPage,
                cssStyle: "light-theme",
                // We implement the actual pagination
                //   in this next function. It runs on
                //   the event that a user changes page
                onPageClick: function(pageNum) {
                    // Which page parts do we show?
                    var start = perPage * (pageNum - 1);
                    var end = start + perPage;
    
                    // First hide all page parts
                    // Then show those just for our page
                    pageParts.hide()
                        .slice(start, end).show();
                }
            });
        });
    </script>

Unable to start MySQL server

Try manually start the service from Windows services, Start -> cmd.exe -> services.msc. Also try to configure the MySQL server to run on another port and try starting it again. Change the my.ini file to change the port number.

Export table data from one SQL Server to another

There is script table option in Tasks/Generate scripts! I also missed it at beginning! But you can generate insert scripts there (very nice feature, but in very un-intuitive place).

When you get to step "Set Scripting Options" go to "Advanced" tab.

Steps described here (pictures can understand, but i do write in latvian there).

Execute php file from another php

Sounds like you're trying to execute the PHP code directly in your shell. Your shell doesn't speak PHP, so it interprets your PHP code as though it's in your shell's native language, as though you had literally run <?php at the command line.

Shell scripts usually start with a "shebang" line that tells the shell what program to use to interpret the file. Begin your file like this:

#!/usr/bin/env php
<?php
//Connection
function connection () {

Besides that, the string you're passing to exec doesn't make any sense. It starts with a slash all by itself, it uses too many periods in the path, and it has a stray right parenthesis.

Copy the contents of the command string and paste them at your command line. If it doesn't run there, then exec probably won't be able to run it, either.

Another option is to change the command you execute. Instead of running the script directly, run php and pass your script as an argument. Then you shouldn't need the shebang line.

exec('php name.php');

nano error: Error opening terminal: xterm-256color

After upgrading to OSX Lion, I started getting this error on certain (Debian/Ubuntu) servers. The fix is simply to install the “ncurses-term” package which provides the file /usr/share/terminfo/x/xterm-256color.

This worked for me on a Ubuntu server, via Erik Osterman.

What's the environment variable for the path to the desktop?

EDIT: Use the accepted answer, this will not work if the default location isn't being used, for example: The user moved the desktop to another drive like D:\Desktop


At least on Windows XP, Vista and 7 you can use the "%UserProfile%\Desktop" safely.

Windows XP en-US it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows XP pt-BR it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows 7 en-US it will expand to "C:\Users\YourName\Desktop"
Windows 7 pt-BR it will expand to "C:\Usuarios\YourName\Desktop"

On XP you can't use this to others folders exept for Desktop My documents turning to Meus Documentos and Local Settings to Configuracoes locais Personaly I thinks this is a bad thing when projecting a OS.

Node package ( Grunt ) installed but not available

The command line tools are not included with the latest version of Grunt (0.4 at time of writing) instead you need to install them separately.

This is a good idea because it means you can have different versions of Grunt running on different projects but still use the nice concise grunt command to run them.

So first install the grunt cli tools globally:

npm install -g grunt-cli

(or possibly sudo npm install -g grunt-cli ).

You can establish that's working by typing grunt --version

Now you can install the current version of Grunt local to your project. So from your project's location...

npm install grunt --save-dev

The save-dev switch isn't strictly necessary but is a good idea because it will mark grunt in its package.json devDependencies section as a development only module.

jQuery Set Selected Option Using Next

Update:

As of jQuery 1.6+ you should use prop() instead of attr() in this case.

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);


Original Answer:

If you want to select by the value of the option, REGARDLESS of its position (this example assumes you have an ID for your select):

var theValue = "whatever";
$("#selectID").val( theValue ).attr('selected',true);

You do not need to "unselect". That happens automatically when you select another.

Load and execution sequence of a web page?

If you're asking this because you want to speed up your web site, check out Yahoo's page on Best Practices for Speeding Up Your Web Site. It has a lot of best practices for speeding up your web site.

DROP IF EXISTS VS DROP?

If no table with such name exists, DROP fails with error while DROP IF EXISTS just does nothing.

This is useful if you create/modifi your database with a script; this way you do not have to ensure manually that previous versions of the table are deleted. You just do a DROP IF EXISTS and forget about it.

Of course, your current DB engine may not support this option, it is hard to tell more about the error with the information you provide.

Sort columns of a dataframe by column name

So to have a specific column come first, then the rest alphabetically, I'd propose this solution:

test[, c("myFirstColumn", sort(setdiff(names(test), "myFirstColumn")))]

How to change package name in android studio?

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

or Look into this post

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

enable/disable zoom in Android WebView

hey there for anyone who might be looking for solution like this.. i had issue with scaling inside WebView so best way to do is in your java.class where you set all for webView put this two line of code: (webViewSearch is name of my webView -->webViewSearch = (WebView) findViewById(R.id.id_webview_search);)

// force WebView to show content not zoomed---------------------------------------------------------
    webViewSearch.getSettings().setLoadWithOverviewMode(true);
    webViewSearch.getSettings().setUseWideViewPort(true);

Update a dataframe in pandas while iterating row by row

A method you can use is itertuples(), it iterates over DataFrame rows as namedtuples, with index value as first element of the tuple. And it is much much faster compared with iterrows(). For itertuples(), each row contains its Index in the DataFrame, and you can use loc to set the value.

for row in df.itertuples():
    if <something>:
        df.at[row.Index, 'ifor'] = x
    else:
        df.at[row.Index, 'ifor'] = x

    df.loc[row.Index, 'ifor'] = x

Under most cases, itertuples() is faster than iat or at.

Thanks @SantiStSupery, using .at is much faster than loc.

Maven skip tests

I had some inter-dependency with the tests in order to build the package.

The following command manage to override the need for the test artifact in order to complete the goal:

mvn -DskipTests=true  package

Invalid character in identifier

A little bit late but I got the same error and I realized that it was because I copied some code from a PDF. Check the difference between these two: - - The first one is from hitting the minus sign on keyboard and the second is from a latex generated PDF.

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

32bit windows has a 2GB process memory limit. The /3GB boot option others have mentioned will make this 3GB with just 1gb remaining for OS kernel use. Realistically if you want to use more than 2GB without hassle then a 64bit OS is required. This also overcomes the problem whereby although you may have 4GB of physical RAM, the address space requried for the video card can make a sizeable chuck of that memory unusable - usually around 500MB.

AngularJS - pass function to directive

In your 'test' directive Html tag, the attribute name of the function should not be camelCased, but dash-based.

so - instead of :

<test color1="color1" updateFn="updateFn()"></test>

write:

<test color1="color1" update-fn="updateFn()"></test>

This is angular's way to tell the difference between directive attributes (such as update-fn function) and functions.

How to set Python's default version to 3.x on OS X?

$ sudo ln -s -f $(which python3) $(which python)

done.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Convert double/float to string

The only exact solution is to perform arbitrary-precision decimal arithmetic for the base conversion, since the exact value can be very long - for 80-bit long double, up to about 10000 decimal places. Fortunately it's "only" up to about 700 places or so for IEEE double.

Rather than working with individual decimal digits, it's helpful to instead work base-1-billion (the highest power of 10 that fits in a 32-bit integer) and then convert these "base-1-billion digits" to 9 decimal digits each at the end of your computation.

I have a very dense (rather hard to read) but efficient implementation here, under LGPL MIT license:

http://git.musl-libc.org/cgit/musl/blob/src/stdio/vfprintf.c?h=v1.1.6

If you strip out all the hex float support, infinity/nan support, %g/%f/%e variation support, rounding (which will never be needed if you only want exact answers), and other things you might not need, the remaining code is rather simple.

How to get HTTP Response Code using Selenium WebDriver

I was also having same issue and stuck for some days, but after some research i figured out that we can actually use chrome's "--remote-debugging-port" to intercept requests in conjunction with selenium web driver. Use following Pseudocode as a reference:-

create instance of chrome driver with remote debugging

int freePort = findFreePort();

chromeOptions.addArguments("--remote-debugging-port=" + freePort);

ChromeDriver driver = new ChromeDriver(chromeOptions);`

make a get call to http://127.0.0.1:freePort

String response = makeGetCall( "http://127.0.0.1" + freePort  + "/json" );

Extract chrome's webSocket Url to listen, you can see response and figure out how to extract

String webSocketUrl = response.substring(response.indexOf("ws://127.0.0.1"), response.length() - 4);

Connect to this socket, u can use asyncHttp

socket = maketSocketConnection( webSocketUrl );

Enable network capture

socket.send( { "id" : 1, "method" : "Network.enable" } );

Now chrome will send all network related events and captures them as follows

socket.onMessageReceived( String message ){

    Json responseJson = toJson(message);
    if( responseJson.method == "Network.responseReceived" ){
       //extract status code
    }
}

driver.get("http://stackoverflow.com");

you can do everything mentioned in dev tools site. see https://chromedevtools.github.io/devtools-protocol/ Note:- use chromedriver 2.39 or above.

I hope it helps someone.

reference : Using Google Chrome remote debugging protocol

Maximum filename length in NTFS (Windows XP and Windows Vista)?

According to MSDN, it's 260 characters. It includes "<NUL>" -the invisible terminating null character, so the actual length is 259.

But read the article, it's a bit more complicated.

jQuery check/uncheck radio button onclick

$(document).ready(function(){ $("input:radio:checked").data("chk",true);

$("input:radio").click(function(){
    $("input[name='"+$(this).attr("name")+"']:radio").not(this).removeData("chk");

    $(this).data("chk",!$(this).data("chk"));

    $(this).prop("checked",$(this).data("chk"));
});

});

Send POST request using NSURLSession

If you are using Swift, the Just library does this for you. Example from it's readme file:

//  talk to registration end point
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
    if (r.ok) { /* success! */ }
}

Position an element relative to its container

You are right that CSS positioning is the way to go. Here's a quick run down:

position: relative will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).

However, you're most likely interested in position: absolute which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative or position: absolute set on it, then it will act as the parent for positioning coordinates for its children.

To demonstrate:

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  border: 1px solid red;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  left: 20px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="box">absolute</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In that example, the top left corner of #box would be 100px down and 50px left of the top left corner of #container. If #container did not have position: relative set, the coordinates of #box would be relative to the top left corner of the browser view port.

Git copy file preserving history

In my case, I made the change on my hard drive (cut/pasted about 200 folders/files from one path in my working copy to another path in my working copy), and used SourceTree (2.0.20.1) to stage both the detected changes (one add, one remove), and as long as I staged both the add and remove together, it automatically combined into a single change with a pink R icon (rename I assume).

I did notice that because I had such a large number of changes at once, SourceTree was a little slow detecting all the changes, so some of my staged files look like just adds (green plus) or just deletes (red minus), but I kept refreshing the file status and kept staging new changes as they eventually popped up, and after a few minutes, the whole list was perfect and ready for commit.

I verified that the history is present, as long as when I look for history, I check the "Follow renamed files" option.

Save text file UTF-8 encoded with VBA

I looked into the answer from Máta whose name hints at encoding qualifications and experience. The VBA docs say CreateTextFile(filename, [overwrite [, unicode]]) creates a file "as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it's created as an ASCII file. If omitted, an ASCII file is assumed." It's fine that a file stores unicode characters, but in what encoding? Unencoded unicode can't be represented in a file.

The VBA doc page for OpenTextFile(filename[, iomode[, create[, format]]]) offers a third option for the format:

  • TriStateDefault 2 "opens the file using the system default."
  • TriStateTrue 1 "opens the file as Unicode."
  • TriStateFalse 0 "opens the file as ASCII."

Máta passes -1 for this argument.

Judging from VB.NET documentation (not VBA but I think reflects realities about how underlying Windows OS represents unicode strings and echoes up into MS Office, I don't know) the system default is an encoding using 1 byte/unicode character using an ANSI code page for the locale. UnicodeEncoding is UTF-16. The docs also describe UTF-8 is also a "Unicode encoding," which makes sense to me. But I don't yet know how to specify UTF-8 for VBA output nor be confident that the data I write to disk with the OpenTextFile(,,,1) is UTF-16 encoded. Tamalek's post is helpful.

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

For Sublime Text 3:

defaults write com.apple.LaunchServices LSHandlers -array-add '{LSHandlerContentType=public.plain-text;LSHandlerRoleAll=com.sublimetext.3;}'

See Set TextMate as the default text editor on Mac OS X for details.

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

For date:

#!/usr/bin/ruby -w

date = Time.new
#set 'date' equal to the current date/time. 

date = date.day.to_s + "/" + date.month.to_s + "/" + date.year.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display DD/MM/YYYY

puts date
#output the date

The above will display, for example, 10/01/15

And for time

time = Time.new
#set 'time' equal to the current time. 

time = time.hour.to_s + ":" + time.min.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display hour and           minute

puts time
#output the time

The above will display, for example, 11:33

Then to put it together, add to the end:

puts date + " " + time

Trim a string in C

#include "stdafx.h"
#include <string.h>
#include <ctype.h>

char* trim(char* input);


int _tmain(int argc, _TCHAR* argv[])
{
    char sz1[]="  MQRFH  ";
    char sz2[]=" MQRFH";
    char sz3[]="  MQR FH";
    char sz4[]="MQRFH  ";
    char sz5[]="MQRFH";
    char sz6[]="M";
    char sz7[]="M ";
    char sz8[]=" M";
    char sz9[]="";
    char sz10[]="        ";

    printf("sz1:[%s] %d\n",trim(sz1), strlen(sz1));
    printf("sz2:[%s] %d\n",trim(sz2), strlen(sz2));
    printf("sz3:[%s] %d\n",trim(sz3), strlen(sz3));
    printf("sz4:[%s] %d\n",trim(sz4), strlen(sz4));
    printf("sz5:[%s] %d\n",trim(sz5), strlen(sz5));
    printf("sz6:[%s] %d\n",trim(sz6), strlen(sz6));
    printf("sz7:[%s] %d\n",trim(sz7), strlen(sz7));
    printf("sz8:[%s] %d\n",trim(sz8), strlen(sz8));
    printf("sz9:[%s] %d\n",trim(sz9), strlen(sz9));
    printf("sz10:[%s] %d\n",trim(sz10), strlen(sz10));

    return 0;
}

char *ltrim(char *s) 
{     
    while(isspace(*s)) s++;     
    return s; 
}  

char *rtrim(char *s) 
{     
    char* back;
    int len = strlen(s);

    if(len == 0)
        return(s); 

    back = s + len;     
    while(isspace(*--back));     
    *(back+1) = '\0';     
    return s; 
}  

char *trim(char *s) 
{     
    return rtrim(ltrim(s));  
} 

Output:

sz1:[MQRFH] 9
sz2:[MQRFH] 6
sz3:[MQR FH] 8
sz4:[MQRFH] 7
sz5:[MQRFH] 5
sz6:[M] 1
sz7:[M] 2
sz8:[M] 2
sz9:[] 0
sz10:[] 8

Centering brand logo in Bootstrap Navbar

The simplest way is css transform:

.navbar-brand {
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
}

DEMO: http://codepen.io/candid/pen/dGPZvR

centered background logo bootstrap 3


This way also works with dynamically sized background images for the logo and allows us to utilize the text-hide class:

CSS:

.navbar-brand {
  background: url(http://disputebills.com/site/uploads/2015/10/dispute.png) center / contain no-repeat;
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
  width: 200px; /* no height needed ... image will resize automagically */
}

HTML:

<a class="navbar-brand text-hide" href="http://disputebills.com">Brand Text
        </a>

We can also use flexbox though. However, using this method we'd have to move navbar-brand outside of navbar-header. This way is great though because we can now have image and text side by side:

bootstrap 3 logo centered

.brand-centered {
  display: flex;
  justify-content: center;
  position: absolute;
  width: 100%;
  left: 0;
  top: 0;
}
.navbar-brand {
  display: flex;
  align-items: center;
}

Demo: http://codepen.io/candid/pen/yeLZax

To only achieve these results on mobile simply wrap the above css inside a media query:

@media (max-width: 768px) {

}

Android Color Picker

After some searches in the android references, the newcomer QuadFlask Color Picker seems to be a technically and aesthetically good choice. Also it has Transparency slider and supports HEX coded colors.

Take a look:
QuadFlask Color Picker

How to increase the timeout period of web service in asp.net?

In app.config file (or .exe.config) you can add or change the "receiveTimeout" property in binding. like this

<binding name="WebServiceName" receiveTimeout="00:00:59" />

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

How to parse freeform street/postal address out of text, and into components

UPDATE: Geocode.xyz now works worldwide. For examples see https://geocode.xyz

For USA, Mexico and Canada, see geocoder.ca.

For example:

Input: something going on near the intersection of main and arthur kill rd new york

Output:

<geodata>
  <latt>40.5123510000</latt>
  <longt>-74.2500500000</longt>
  <AreaCode>347,718</AreaCode>
  <TimeZone>America/New_York</TimeZone>
  <standard>
    <street1>main</street1>
    <street2>arthur kill</street2>
    <stnumber/>
    <staddress/>
    <city>STATEN ISLAND</city>
    <prov>NY</prov>
    <postal>11385</postal>
    <confidence>0.9</confidence>
  </standard>
</geodata>

You may also check the results in the web interface or get output as Json or Jsonp. eg. I'm looking for restaurants around 123 Main Street, New York

Twig ternary operator, Shorthand if-then-else

Support for the extended ternary operator was added in Twig 1.12.0.

  1. If foo echo yes else echo no:

    {{ foo ? 'yes' : 'no' }}
    
  2. If foo echo it, else echo no:

    {{ foo ?: 'no' }}
    

    or

    {{ foo ? foo : 'no' }}
    
  3. If foo echo yes else echo nothing:

    {{ foo ? 'yes' }}
    

    or

    {{ foo ? 'yes' : '' }}
    
  4. Returns the value of foo if it is defined and not null, no otherwise:

    {{ foo ?? 'no' }}
    
  5. Returns the value of foo if it is defined (empty values also count), no otherwise:

    {{ foo|default('no') }}
    

Jump to function definition in vim

1- install exuberant ctags. If you're using osx, this article shows a little trick: http://www.runtime-era.com/2012/05/exuberant-ctags-in-osx-107.html

2- If you only wish to include the ctags for the files in your directory only, run this command in your directory:

ctags -R

This will create a "tags" file for you.

3- If you're using Ruby and wish to include the ctags for your gems (this has been really helpful for me with RubyMotion and local gems that I have developed), do the following:

ctags --exclude=.git --exclude='*.log' -R * `bundle show --paths`

credit: https://coderwall.com/p/lv1qww (Note that I omitted the -e option which generates tags for emacs instead of vim)

4- Add the following line to your ~/.vimrc

set autochdir 
set tags+=./tags;

(Why the semi colon: http://vim.wikia.com/wiki/Single_tags_file_for_a_source_tree )

5- Go to the word you'd like to follow and hit ctrl + ] ; if you'd like to go back, use ctrl+o (source: https://stackoverflow.com/a/53929/226255)

Node.js client for a socket.io server

Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.

How to check if directory exist using C++ and winAPI

Here is a simple function which does exactly this :

#include <windows.h>
#include <string>

bool dirExists(const std::string& dirName_in)
{
  DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
  if (ftyp == INVALID_FILE_ATTRIBUTES)
    return false;  //something is wrong with your path!

  if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return true;   // this is a directory!

  return false;    // this is not a directory!
}

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

Convert this string to datetime

Use DateTime::createFromFormat

$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();

Mockito: InvalidUseOfMatchersException

It might help some one in the future: Mockito doesn't support mocking of 'final' methods (right now). It gave me the same InvalidUseOfMatchersException.

The solution for me was to put the part of the method that didn't have to be 'final' in a separate, accessible and overridable method.

Review the Mockito API for your use case.

Remove NaN from pandas series

A small usage of np.nan ! = np.nan

s[s==s]
Out[953]: 
0    1.0
1    2.0
2    3.0
3    4.0
5    5.0
dtype: float64

More Info

np.nan == np.nan
Out[954]: False

How get value from URL

You can also get a query string value as:

$uri =  $_SERVER["REQUEST_URI"]; //it will print full url
$uriArray = explode('/', $uri); //convert string into array with explode
$id = $uriArray[1]; //Print first array value

java.lang.RuntimeException: Unable to start activity ComponentInfo

It was my own stupidity:

java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());

Putting this inside onCreate() method fixed my problem.

The ResourceConfig instance does not contain any root resource classes

I ran across this problem with JBOSS EAP 6.1. I was able to deploy my code through eclipse to the JBOSS server but once I attempted to deploy the file as a WAR file to JBOSS I started getting this error.

The solution was configuring the web.xml to work properly with JBOSS by allowing the two to work together.

The following two lines were commented out in web.xml to allow JBOSS to do it's own configurations

<!--  
    <init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>com.your.package</param-value>
</init-param> -->

And then add the following context params after

<context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>resteasy.scan.resources</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>resteasy.scan.providers</param-name>
    <param-value>false</param-value>
</context-param>

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Java current machine name and logged in user?

Using user.name is not secure as environment variables can be faked. Method you were using is good, there are similar methods for unix based OS as well

ASP.NET Core Web API exception handling

If you want set custom exception handling behavior for a specific controller, you can do so by overriding the controllers OnActionExecuted method.

Remember to set the ExceptionHandled property to true to disable default exception handling behavior.

Here is a sample from an api I'm writing, where I want to catch specific types of exceptions and return a json formatted result:

    private static readonly Type[] API_CATCH_EXCEPTIONS = new Type[]
    {
        typeof(InvalidOperationException),
        typeof(ValidationException)           
    };

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        base.OnActionExecuted(context);

        if (context.Exception != null)
        {
            var exType = context.Exception.GetType();
            if (API_CATCH_EXCEPTIONS.Any(type => exType == type || exType.IsSubclassOf(type)))
            {
                context.Result = Problem(detail: context.Exception.Message);
                context.ExceptionHandled = true;
            }
        }  
    }

How to extract the first two characters of a string in shell scripting?

if mystring = USCAGoleta9311734.5021-120.1287855805

print substr(mystring,0,2)

would print US

where 0 is the start position and 2 is how meny chars to read

Oracle pl-sql escape character (for a " ' ")

To escape it, double the quotes:

INSERT INTO TABLE_A VALUES ( 'Alex''s Tea Factory' );

ERROR Error: No value accessor for form control with unspecified name attribute on switch

Have you tried moving your [(ngModel)] to the div instead of the switch in your HTML? I had the same error appear in my code and it was because I bound the model to a <mat-option> instead of a <mat-select>. Though I am not using form control.

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

You can skip the var declaration and the stringify. Otherwise, that will work just fine.

$.ajax({
    url: '/home/check',
    type: 'POST',
    data: {
        Address1: "423 Judy Road",
        Address2: "1001",
        City: "New York",
        State: "NY",
        ZipCode: "10301",
        Country: "USA"
    },
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert(data.success);
    },
    error: function () {
        alert("error");
    }
});

Installing Python packages from local file system folder to virtualenv with pip

Having requirements in requirements.txt and egg_dir as a directory

you can build your local cache:

$ pip download -r requirements.txt -d eggs_dir

then, using that "cache" is simple like:

$ pip install -r requirements.txt --find-links=eggs_dir

Choice between vector::resize() and vector::reserve()

From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.

Take note that resize initialize the newly allocated vector where reserve just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'

You can refer to the documentation regarding the difference of resize and reserve

Hashmap with Streams in Java 8 Streams to collect value of Map

Maybe the sample is oversimplified, but you don't need the Java stream API here. Just use the Map directly.

 List<String> list1 = id1.get(1); // this will return the list from your map

get an element's id

In events handler you can get id as follows

_x000D_
_x000D_
function show(btn) {_x000D_
  console.log('Button id:',btn.id);_x000D_
}
_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>
_x000D_
_x000D_
_x000D_

Common xlabel/ylabel for matplotlib subplots

Update:

This feature is now part of the proplot matplotlib package that I recently released on pypi. By default, when you make figures, the labels are "shared" between axes.


Original answer:

I discovered a more robust method:

If you know the bottom and top kwargs that went into a GridSpec initialization, or you otherwise know the edges positions of your axes in Figure coordinates, you can also specify the ylabel position in Figure coordinates with some fancy "transform" magic. For example:

import matplotlib.transforms as mtransforms
bottom, top = .1, .9
f, a = plt.subplots(nrows=2, ncols=1, bottom=bottom, top=top)
avepos = (bottom+top)/2
a[0].yaxis.label.set_transform(mtransforms.blended_transform_factory(
       mtransforms.IdentityTransform(), f.transFigure # specify x, y transform
       )) # changed from default blend (IdentityTransform(), a[0].transAxes)
a[0].yaxis.label.set_position((0, avepos))
a[0].set_ylabel('Hello, world!')

...and you should see that the label still appropriately adjusts left-right to keep from overlapping with ticklabels, just like normal -- but now it will adjust to be always exactly between the desired subplots.

Furthermore, if you don't even use set_position, the ylabel will show up by default exactly halfway up the figure. I'm guessing this is because when the label is finally drawn, matplotlib uses 0.5 for the y-coordinate without checking whether the underlying coordinate transform has changed.

Android appcompat v7:23

Ran into a similar issue using React Native

> Could not find com.android.support:appcompat-v7:23.0.1.

the Support Libraries are Local Maven repository for Support Libraries

enter image description here

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

Test if a vector contains a given element

Also to find the position of the element "which" can be used as

pop <- c(3,4,5,7,13)

which(pop==13)

and to find the elements which are not contained in the target vector, one may do this:

pop <- c(1,2,4,6,10)

Tset <- c(2,10,7)   # Target set

pop[which(!(pop%in%Tset))]

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

"No suitable driver" usually means that the JDBC URL you've supplied to connect has incorrect syntax or when the driver isn't loaded at all.

When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.(using Class.forName())

For Example

import oracle.jdbc.driver.OracleDriver;

Class.forName("oracle.jdbc.driver.­OracleDriver");

Also check that you have ojdbc6.jar in your classpath. I would suggest to place .jar at physical location to JBoss "$JBOSS_HOME/server/default/lib/" directory of your project.

EDIT:

You have mentioned hibernate lately.

Check that your hibernate.cfg.xml file has connection properties something like this:

<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> 
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>

Import numpy on pycharm

I have encountered problem installing numpy package to pycharm and finally figured out. I hope it would be helpful for someone having the same problem in installing numpy and other packages on pycharm.

Pycharm Setting : Pycharm Setting

Go to File => Setting => Project => Project Interpreter. On this window select the appropriate project interpreter. After this, a list of packages under the selected project interpreter will be shown. From the list select pip and check if the version column and the latest version column are the same. If different upgrade the version to the latest version by selecting the pip and using the upward triangle sign on the right side of the lists. Once the upgrading completed successfully, you can now add new packages from the plus sign.

enter image description here

I hope this would be clear and useful for someone.

How to get ERD diagram for an existing database?

The PGADMIN4, version 30, can plot the ERD. Just click on the database with the mouse right-button and then select ERD(beta).

how can I login anonymously with ftp (/usr/bin/ftp)?

As others point out, the user name is usually anonymous, and the password is usually your e-mail address, but this is not universally true, and has been found not to work for certain anonymous FTP sites. For example, at least some cPanel sites seem to deviate from the norm, and if given the traditional user name without domain, one of various errors may result:

If the server uses Pure-FTP as the FTP server:

421 Can't change directory to /var/ftp/ error message.

If the server uses ProFTP as the FTP server:

530 Login Authentication Failed error message.

When one of the aforementioned errors occurs when attempting anonymous access, try including a domain with the username. For example, where example.com is the domain used in your e-mail address:

User name: [email protected]

In the specific case of a cPanel site, the password value is unimportant, and may be left blank, but there is no harm in providing a "traditional" anonymous password formatted as an e-mail address.

For reference, this answer is based on content found on a documentation.cpanel.net Anonymous FTP page. At the time of this writing, it stated:

When users log in to FTP anonymously, they must format usernames as [email protected], where example.com represents the user's domain name. This requirement directs your server to the correct public_ftp directory.

RAW POST using cURL in PHP

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

How do I get the color from a hexadecimal color code using .NET?

You could use the following code:

Color color = System.Drawing.ColorTranslator.FromHtml("#FFDFD991");

Color Tint UIButton Image

Not sure exactly what you want but this category method will mask a UIImage with a specified color so you can have a single image and change its color to whatever you want.

ImageUtils.h

- (UIImage *) maskWithColor:(UIColor *)color;

ImageUtils.m

-(UIImage *) maskWithColor:(UIColor *)color 
{
    CGImageRef maskImage = self.CGImage;
    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    CGRect bounds = CGRectMake(0,0,width,height);

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextClipToMask(bitmapContext, bounds, maskImage);
    CGContextSetFillColorWithColor(bitmapContext, color.CGColor);    
    CGContextFillRect(bitmapContext, bounds);

    CGImageRef cImage = CGBitmapContextCreateImage(bitmapContext);
    UIImage *coloredImage = [UIImage imageWithCGImage:cImage];

    CGContextRelease(bitmapContext);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(cImage);

    return coloredImage;    
}

Import the ImageUtils category and do something like this...

#import "ImageUtils.h"

...

UIImage *icon = [UIImage imageNamed:ICON_IMAGE];

UIImage *redIcon = [icon maskWithColor:UIColor.redColor];
UIImage *blueIcon = [icon maskWithColor:UIColor.blueColor];

Program does not contain a static 'Main' method suitable for an entry point

Project Properties \ Output file -> Select Class Library :)

How to display items side-by-side without using tables?

You should float them inside a container that is cleared.

Example:

https://jsfiddle.net/W74Z8/504/

enter image description here

A clean implementation is the "clearfix hack". This is Nicolas Gallagher's version:

/**
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    contenteditable attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that are clearfixed.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */
.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/**
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */
.clearfix {
    *zoom: 1;
}
?

Function to Calculate a CRC16 Checksum

crcany will generate efficient C code for any CRC, and includes a library of over one hundred known CRC definitions.

Efficient CRC code uses tables instead of bit-wise calculations. crcany generates both byte-wise routines and word-wise routines, the latter tuned to the architecture they are generated on. Word-wise is the fastest. Byte-wise is still much faster than bit-wise, but the implementation is more easily portable over architectures.

You do not seem to have a protocol definition with a specific CRC definition that you need to match. In this case, you can pick any 16-bit CRC in the catalog, and you will get good performance.

If you have a relatively low bit error rate, e.g. single digit number of errors per packet, and you want to maximize your error detection performance, you would need to look at the packet size you are applying the CRC to, assuming that that is constant or bounded, and look at the performance of the best polynomials in Philip Koopman's extensive research. The classic CRCs, such as the CCITT/Kermit 16-bit CRC or the X.25 16-bit CRC are not the best performers.

One of the good 16-bit performers in Koopman's tables that is also in the catalog of CRCs used in practice is CRC-16/DNP. It has very good performance detecting up to 6-bit errors in a packet. Following is the code generated by crcany for that CRC definition. This code assumes a little-endian architecture for the word-wise calculation, e.g. Intel x86 and x86-64, and it assumes that uintmax_t is 64 bits. crcany can be used to generate alternative code for big-endian and other word sizes.

crc16dnp.h:

// The _bit, _byte, and _word routines return the CRC of the len bytes at mem,
// applied to the previous CRC value, crc. If mem is NULL, then the other
// arguments are ignored, and the initial CRC, i.e. the CRC of zero bytes, is
// returned. Those routines will all return the same result, differing only in
// speed and code complexity. The _rem routine returns the CRC of the remaining
// bits in the last byte, for when the number of bits in the message is not a
// multiple of eight. The low bits bits of the low byte of val are applied to
// crc. bits must be in 0..8.

#include <stddef.h>

// Compute the CRC a bit at a time.
unsigned crc16dnp_bit(unsigned crc, void const *mem, size_t len);

// Compute the CRC of the low bits bits in val.
unsigned crc16dnp_rem(unsigned crc, unsigned val, unsigned bits);

// Compute the CRC a byte at a time.
unsigned crc16dnp_byte(unsigned crc, void const *mem, size_t len);

// Compute the CRC a word at a time.
unsigned crc16dnp_word(unsigned crc, void const *mem, size_t len);

crc16dnp.c:

#include <stdint.h>
#include "crc16dnp.h"

// This code assumes that unsigned is 4 bytes.

unsigned crc16dnp_bit(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc = ~crc;
    crc &= 0xffff;
    while (len--) {
        crc ^= *data++;
        for (unsigned k = 0; k < 8; k++)
            crc = crc & 1 ? (crc >> 1) ^ 0xa6bc : crc >> 1;
    }
    crc ^= 0xffff;
    return crc;
}

unsigned crc16dnp_rem(unsigned crc, unsigned val, unsigned bits) {
    crc = ~crc;
    crc &= 0xffff;
    val &= (1U << bits) - 1;
    crc ^= val;
    while (bits--)
        crc = crc & 1 ? (crc >> 1) ^ 0xa6bc : crc >> 1;
    crc ^= 0xffff;
    return crc;
}

#define table_byte table_word[0]

static unsigned short const table_word[][256] = {
   {0xed35, 0xdb6b, 0x8189, 0xb7d7, 0x344d, 0x0213, 0x58f1, 0x6eaf, 0x12bc, 0x24e2,
    0x7e00, 0x485e, 0xcbc4, 0xfd9a, 0xa778, 0x9126, 0x5f5e, 0x6900, 0x33e2, 0x05bc,
    0x8626, 0xb078, 0xea9a, 0xdcc4, 0xa0d7, 0x9689, 0xcc6b, 0xfa35, 0x79af, 0x4ff1,
    0x1513, 0x234d, 0xc49a, 0xf2c4, 0xa826, 0x9e78, 0x1de2, 0x2bbc, 0x715e, 0x4700,
    0x3b13, 0x0d4d, 0x57af, 0x61f1, 0xe26b, 0xd435, 0x8ed7, 0xb889, 0x76f1, 0x40af,
    0x1a4d, 0x2c13, 0xaf89, 0x99d7, 0xc335, 0xf56b, 0x8978, 0xbf26, 0xe5c4, 0xd39a,
    0x5000, 0x665e, 0x3cbc, 0x0ae2, 0xbe6b, 0x8835, 0xd2d7, 0xe489, 0x6713, 0x514d,
    0x0baf, 0x3df1, 0x41e2, 0x77bc, 0x2d5e, 0x1b00, 0x989a, 0xaec4, 0xf426, 0xc278,
    0x0c00, 0x3a5e, 0x60bc, 0x56e2, 0xd578, 0xe326, 0xb9c4, 0x8f9a, 0xf389, 0xc5d7,
    0x9f35, 0xa96b, 0x2af1, 0x1caf, 0x464d, 0x7013, 0x97c4, 0xa19a, 0xfb78, 0xcd26,
    0x4ebc, 0x78e2, 0x2200, 0x145e, 0x684d, 0x5e13, 0x04f1, 0x32af, 0xb135, 0x876b,
    0xdd89, 0xebd7, 0x25af, 0x13f1, 0x4913, 0x7f4d, 0xfcd7, 0xca89, 0x906b, 0xa635,
    0xda26, 0xec78, 0xb69a, 0x80c4, 0x035e, 0x3500, 0x6fe2, 0x59bc, 0x4b89, 0x7dd7,
    0x2735, 0x116b, 0x92f1, 0xa4af, 0xfe4d, 0xc813, 0xb400, 0x825e, 0xd8bc, 0xeee2,
    0x6d78, 0x5b26, 0x01c4, 0x379a, 0xf9e2, 0xcfbc, 0x955e, 0xa300, 0x209a, 0x16c4,
    0x4c26, 0x7a78, 0x066b, 0x3035, 0x6ad7, 0x5c89, 0xdf13, 0xe94d, 0xb3af, 0x85f1,
    0x6226, 0x5478, 0x0e9a, 0x38c4, 0xbb5e, 0x8d00, 0xd7e2, 0xe1bc, 0x9daf, 0xabf1,
    0xf113, 0xc74d, 0x44d7, 0x7289, 0x286b, 0x1e35, 0xd04d, 0xe613, 0xbcf1, 0x8aaf,
    0x0935, 0x3f6b, 0x6589, 0x53d7, 0x2fc4, 0x199a, 0x4378, 0x7526, 0xf6bc, 0xc0e2,
    0x9a00, 0xac5e, 0x18d7, 0x2e89, 0x746b, 0x4235, 0xc1af, 0xf7f1, 0xad13, 0x9b4d,
    0xe75e, 0xd100, 0x8be2, 0xbdbc, 0x3e26, 0x0878, 0x529a, 0x64c4, 0xaabc, 0x9ce2,
    0xc600, 0xf05e, 0x73c4, 0x459a, 0x1f78, 0x2926, 0x5535, 0x636b, 0x3989, 0x0fd7,
    0x8c4d, 0xba13, 0xe0f1, 0xd6af, 0x3178, 0x0726, 0x5dc4, 0x6b9a, 0xe800, 0xde5e,
    0x84bc, 0xb2e2, 0xcef1, 0xf8af, 0xa24d, 0x9413, 0x1789, 0x21d7, 0x7b35, 0x4d6b,
    0x8313, 0xb54d, 0xefaf, 0xd9f1, 0x5a6b, 0x6c35, 0x36d7, 0x0089, 0x7c9a, 0x4ac4,
    0x1026, 0x2678, 0xa5e2, 0x93bc, 0xc95e, 0xff00},
   {0x740f, 0xdf41, 0x6fea, 0xc4a4, 0x43c5, 0xe88b, 0x5820, 0xf36e, 0x1b9b, 0xb0d5,
    0x007e, 0xab30, 0x2c51, 0x871f, 0x37b4, 0x9cfa, 0xab27, 0x0069, 0xb0c2, 0x1b8c,
    0x9ced, 0x37a3, 0x8708, 0x2c46, 0xc4b3, 0x6ffd, 0xdf56, 0x7418, 0xf379, 0x5837,
    0xe89c, 0x43d2, 0x8726, 0x2c68, 0x9cc3, 0x378d, 0xb0ec, 0x1ba2, 0xab09, 0x0047,
    0xe8b2, 0x43fc, 0xf357, 0x5819, 0xdf78, 0x7436, 0xc49d, 0x6fd3, 0x580e, 0xf340,
    0x43eb, 0xe8a5, 0x6fc4, 0xc48a, 0x7421, 0xdf6f, 0x379a, 0x9cd4, 0x2c7f, 0x8731,
    0x0050, 0xab1e, 0x1bb5, 0xb0fb, 0xdf24, 0x746a, 0xc4c1, 0x6f8f, 0xe8ee, 0x43a0,
    0xf30b, 0x5845, 0xb0b0, 0x1bfe, 0xab55, 0x001b, 0x877a, 0x2c34, 0x9c9f, 0x37d1,
    0x000c, 0xab42, 0x1be9, 0xb0a7, 0x37c6, 0x9c88, 0x2c23, 0x876d, 0x6f98, 0xc4d6,
    0x747d, 0xdf33, 0x5852, 0xf31c, 0x43b7, 0xe8f9, 0x2c0d, 0x8743, 0x37e8, 0x9ca6,
    0x1bc7, 0xb089, 0x0022, 0xab6c, 0x4399, 0xe8d7, 0x587c, 0xf332, 0x7453, 0xdf1d,
    0x6fb6, 0xc4f8, 0xf325, 0x586b, 0xe8c0, 0x438e, 0xc4ef, 0x6fa1, 0xdf0a, 0x7444,
    0x9cb1, 0x37ff, 0x8754, 0x2c1a, 0xab7b, 0x0035, 0xb09e, 0x1bd0, 0x6f20, 0xc46e,
    0x74c5, 0xdf8b, 0x58ea, 0xf3a4, 0x430f, 0xe841, 0x00b4, 0xabfa, 0x1b51, 0xb01f,
    0x377e, 0x9c30, 0x2c9b, 0x87d5, 0xb008, 0x1b46, 0xabed, 0x00a3, 0x87c2, 0x2c8c,
    0x9c27, 0x3769, 0xdf9c, 0x74d2, 0xc479, 0x6f37, 0xe856, 0x4318, 0xf3b3, 0x58fd,
    0x9c09, 0x3747, 0x87ec, 0x2ca2, 0xabc3, 0x008d, 0xb026, 0x1b68, 0xf39d, 0x58d3,
    0xe878, 0x4336, 0xc457, 0x6f19, 0xdfb2, 0x74fc, 0x4321, 0xe86f, 0x58c4, 0xf38a,
    0x74eb, 0xdfa5, 0x6f0e, 0xc440, 0x2cb5, 0x87fb, 0x3750, 0x9c1e, 0x1b7f, 0xb031,
    0x009a, 0xabd4, 0xc40b, 0x6f45, 0xdfee, 0x74a0, 0xf3c1, 0x588f, 0xe824, 0x436a,
    0xab9f, 0x00d1, 0xb07a, 0x1b34, 0x9c55, 0x371b, 0x87b0, 0x2cfe, 0x1b23, 0xb06d,
    0x00c6, 0xab88, 0x2ce9, 0x87a7, 0x370c, 0x9c42, 0x74b7, 0xdff9, 0x6f52, 0xc41c,
    0x437d, 0xe833, 0x5898, 0xf3d6, 0x3722, 0x9c6c, 0x2cc7, 0x8789, 0x00e8, 0xaba6,
    0x1b0d, 0xb043, 0x58b6, 0xf3f8, 0x4353, 0xe81d, 0x6f7c, 0xc432, 0x7499, 0xdfd7,
    0xe80a, 0x4344, 0xf3ef, 0x58a1, 0xdfc0, 0x748e, 0xc425, 0x6f6b, 0x879e, 0x2cd0,
    0x9c7b, 0x3735, 0xb054, 0x1b1a, 0xabb1, 0x00ff},
   {0x7c67, 0x65df, 0x4f17, 0x56af, 0x1a87, 0x033f, 0x29f7, 0x304f, 0xb1a7, 0xa81f,
    0x82d7, 0x9b6f, 0xd747, 0xceff, 0xe437, 0xfd8f, 0xaa9e, 0xb326, 0x99ee, 0x8056,
    0xcc7e, 0xd5c6, 0xff0e, 0xe6b6, 0x675e, 0x7ee6, 0x542e, 0x4d96, 0x01be, 0x1806,
    0x32ce, 0x2b76, 0x9cec, 0x8554, 0xaf9c, 0xb624, 0xfa0c, 0xe3b4, 0xc97c, 0xd0c4,
    0x512c, 0x4894, 0x625c, 0x7be4, 0x37cc, 0x2e74, 0x04bc, 0x1d04, 0x4a15, 0x53ad,
    0x7965, 0x60dd, 0x2cf5, 0x354d, 0x1f85, 0x063d, 0x87d5, 0x9e6d, 0xb4a5, 0xad1d,
    0xe135, 0xf88d, 0xd245, 0xcbfd, 0xf008, 0xe9b0, 0xc378, 0xdac0, 0x96e8, 0x8f50,
    0xa598, 0xbc20, 0x3dc8, 0x2470, 0x0eb8, 0x1700, 0x5b28, 0x4290, 0x6858, 0x71e0,
    0x26f1, 0x3f49, 0x1581, 0x0c39, 0x4011, 0x59a9, 0x7361, 0x6ad9, 0xeb31, 0xf289,
    0xd841, 0xc1f9, 0x8dd1, 0x9469, 0xbea1, 0xa719, 0x1083, 0x093b, 0x23f3, 0x3a4b,
    0x7663, 0x6fdb, 0x4513, 0x5cab, 0xdd43, 0xc4fb, 0xee33, 0xf78b, 0xbba3, 0xa21b,
    0x88d3, 0x916b, 0xc67a, 0xdfc2, 0xf50a, 0xecb2, 0xa09a, 0xb922, 0x93ea, 0x8a52,
    0x0bba, 0x1202, 0x38ca, 0x2172, 0x6d5a, 0x74e2, 0x5e2a, 0x4792, 0x29c0, 0x3078,
    0x1ab0, 0x0308, 0x4f20, 0x5698, 0x7c50, 0x65e8, 0xe400, 0xfdb8, 0xd770, 0xcec8,
    0x82e0, 0x9b58, 0xb190, 0xa828, 0xff39, 0xe681, 0xcc49, 0xd5f1, 0x99d9, 0x8061,
    0xaaa9, 0xb311, 0x32f9, 0x2b41, 0x0189, 0x1831, 0x5419, 0x4da1, 0x6769, 0x7ed1,
    0xc94b, 0xd0f3, 0xfa3b, 0xe383, 0xafab, 0xb613, 0x9cdb, 0x8563, 0x048b, 0x1d33,
    0x37fb, 0x2e43, 0x626b, 0x7bd3, 0x511b, 0x48a3, 0x1fb2, 0x060a, 0x2cc2, 0x357a,
    0x7952, 0x60ea, 0x4a22, 0x539a, 0xd272, 0xcbca, 0xe102, 0xf8ba, 0xb492, 0xad2a,
    0x87e2, 0x9e5a, 0xa5af, 0xbc17, 0x96df, 0x8f67, 0xc34f, 0xdaf7, 0xf03f, 0xe987,
    0x686f, 0x71d7, 0x5b1f, 0x42a7, 0x0e8f, 0x1737, 0x3dff, 0x2447, 0x7356, 0x6aee,
    0x4026, 0x599e, 0x15b6, 0x0c0e, 0x26c6, 0x3f7e, 0xbe96, 0xa72e, 0x8de6, 0x945e,
    0xd876, 0xc1ce, 0xeb06, 0xf2be, 0x4524, 0x5c9c, 0x7654, 0x6fec, 0x23c4, 0x3a7c,
    0x10b4, 0x090c, 0x88e4, 0x915c, 0xbb94, 0xa22c, 0xee04, 0xf7bc, 0xdd74, 0xc4cc,
    0x93dd, 0x8a65, 0xa0ad, 0xb915, 0xf53d, 0xec85, 0xc64d, 0xdff5, 0x5e1d, 0x47a5,
    0x6d6d, 0x74d5, 0x38fd, 0x2145, 0x0b8d, 0x1235},
   {0xf917, 0x3bff, 0x31be, 0xf356, 0x253c, 0xe7d4, 0xed95, 0x2f7d, 0x0c38, 0xced0,
    0xc491, 0x0679, 0xd013, 0x12fb, 0x18ba, 0xda52, 0x5e30, 0x9cd8, 0x9699, 0x5471,
    0x821b, 0x40f3, 0x4ab2, 0x885a, 0xab1f, 0x69f7, 0x63b6, 0xa15e, 0x7734, 0xb5dc,
    0xbf9d, 0x7d75, 0xfa20, 0x38c8, 0x3289, 0xf061, 0x260b, 0xe4e3, 0xeea2, 0x2c4a,
    0x0f0f, 0xcde7, 0xc7a6, 0x054e, 0xd324, 0x11cc, 0x1b8d, 0xd965, 0x5d07, 0x9fef,
    0x95ae, 0x5746, 0x812c, 0x43c4, 0x4985, 0x8b6d, 0xa828, 0x6ac0, 0x6081, 0xa269,
    0x7403, 0xb6eb, 0xbcaa, 0x7e42, 0xff79, 0x3d91, 0x37d0, 0xf538, 0x2352, 0xe1ba,
    0xebfb, 0x2913, 0x0a56, 0xc8be, 0xc2ff, 0x0017, 0xd67d, 0x1495, 0x1ed4, 0xdc3c,
    0x585e, 0x9ab6, 0x90f7, 0x521f, 0x8475, 0x469d, 0x4cdc, 0x8e34, 0xad71, 0x6f99,
    0x65d8, 0xa730, 0x715a, 0xb3b2, 0xb9f3, 0x7b1b, 0xfc4e, 0x3ea6, 0x34e7, 0xf60f,
    0x2065, 0xe28d, 0xe8cc, 0x2a24, 0x0961, 0xcb89, 0xc1c8, 0x0320, 0xd54a, 0x17a2,
    0x1de3, 0xdf0b, 0x5b69, 0x9981, 0x93c0, 0x5128, 0x8742, 0x45aa, 0x4feb, 0x8d03,
    0xae46, 0x6cae, 0x66ef, 0xa407, 0x726d, 0xb085, 0xbac4, 0x782c, 0xf5cb, 0x3723,
    0x3d62, 0xff8a, 0x29e0, 0xeb08, 0xe149, 0x23a1, 0x00e4, 0xc20c, 0xc84d, 0x0aa5,
    0xdccf, 0x1e27, 0x1466, 0xd68e, 0x52ec, 0x9004, 0x9a45, 0x58ad, 0x8ec7, 0x4c2f,
    0x466e, 0x8486, 0xa7c3, 0x652b, 0x6f6a, 0xad82, 0x7be8, 0xb900, 0xb341, 0x71a9,
    0xf6fc, 0x3414, 0x3e55, 0xfcbd, 0x2ad7, 0xe83f, 0xe27e, 0x2096, 0x03d3, 0xc13b,
    0xcb7a, 0x0992, 0xdff8, 0x1d10, 0x1751, 0xd5b9, 0x51db, 0x9333, 0x9972, 0x5b9a,
    0x8df0, 0x4f18, 0x4559, 0x87b1, 0xa4f4, 0x661c, 0x6c5d, 0xaeb5, 0x78df, 0xba37,
    0xb076, 0x729e, 0xf3a5, 0x314d, 0x3b0c, 0xf9e4, 0x2f8e, 0xed66, 0xe727, 0x25cf,
    0x068a, 0xc462, 0xce23, 0x0ccb, 0xdaa1, 0x1849, 0x1208, 0xd0e0, 0x5482, 0x966a,
    0x9c2b, 0x5ec3, 0x88a9, 0x4a41, 0x4000, 0x82e8, 0xa1ad, 0x6345, 0x6904, 0xabec,
    0x7d86, 0xbf6e, 0xb52f, 0x77c7, 0xf092, 0x327a, 0x383b, 0xfad3, 0x2cb9, 0xee51,
    0xe410, 0x26f8, 0x05bd, 0xc755, 0xcd14, 0x0ffc, 0xd996, 0x1b7e, 0x113f, 0xd3d7,
    0x57b5, 0x955d, 0x9f1c, 0x5df4, 0x8b9e, 0x4976, 0x4337, 0x81df, 0xa29a, 0x6072,
    0x6a33, 0xa8db, 0x7eb1, 0xbc59, 0xb618, 0x74f0},
   {0x3108, 0x120e, 0x7704, 0x5402, 0xbd10, 0x9e16, 0xfb1c, 0xd81a, 0x6441, 0x4747,
    0x224d, 0x014b, 0xe859, 0xcb5f, 0xae55, 0x8d53, 0x9b9a, 0xb89c, 0xdd96, 0xfe90,
    0x1782, 0x3484, 0x518e, 0x7288, 0xced3, 0xedd5, 0x88df, 0xabd9, 0x42cb, 0x61cd,
    0x04c7, 0x27c1, 0x2955, 0x0a53, 0x6f59, 0x4c5f, 0xa54d, 0x864b, 0xe341, 0xc047,
    0x7c1c, 0x5f1a, 0x3a10, 0x1916, 0xf004, 0xd302, 0xb608, 0x950e, 0x83c7, 0xa0c1,
    0xc5cb, 0xe6cd, 0x0fdf, 0x2cd9, 0x49d3, 0x6ad5, 0xd68e, 0xf588, 0x9082, 0xb384,
    0x5a96, 0x7990, 0x1c9a, 0x3f9c, 0x01b2, 0x22b4, 0x47be, 0x64b8, 0x8daa, 0xaeac,
    0xcba6, 0xe8a0, 0x54fb, 0x77fd, 0x12f7, 0x31f1, 0xd8e3, 0xfbe5, 0x9eef, 0xbde9,
    0xab20, 0x8826, 0xed2c, 0xce2a, 0x2738, 0x043e, 0x6134, 0x4232, 0xfe69, 0xdd6f,
    0xb865, 0x9b63, 0x7271, 0x5177, 0x347d, 0x177b, 0x19ef, 0x3ae9, 0x5fe3, 0x7ce5,
    0x95f7, 0xb6f1, 0xd3fb, 0xf0fd, 0x4ca6, 0x6fa0, 0x0aaa, 0x29ac, 0xc0be, 0xe3b8,
    0x86b2, 0xa5b4, 0xb37d, 0x907b, 0xf571, 0xd677, 0x3f65, 0x1c63, 0x7969, 0x5a6f,
    0xe634, 0xc532, 0xa038, 0x833e, 0x6a2c, 0x492a, 0x2c20, 0x0f26, 0x507c, 0x737a,
    0x1670, 0x3576, 0xdc64, 0xff62, 0x9a68, 0xb96e, 0x0535, 0x2633, 0x4339, 0x603f,
    0x892d, 0xaa2b, 0xcf21, 0xec27, 0xfaee, 0xd9e8, 0xbce2, 0x9fe4, 0x76f6, 0x55f0,
    0x30fa, 0x13fc, 0xafa7, 0x8ca1, 0xe9ab, 0xcaad, 0x23bf, 0x00b9, 0x65b3, 0x46b5,
    0x4821, 0x6b27, 0x0e2d, 0x2d2b, 0xc439, 0xe73f, 0x8235, 0xa133, 0x1d68, 0x3e6e,
    0x5b64, 0x7862, 0x9170, 0xb276, 0xd77c, 0xf47a, 0xe2b3, 0xc1b5, 0xa4bf, 0x87b9,
    0x6eab, 0x4dad, 0x28a7, 0x0ba1, 0xb7fa, 0x94fc, 0xf1f6, 0xd2f0, 0x3be2, 0x18e4,
    0x7dee, 0x5ee8, 0x60c6, 0x43c0, 0x26ca, 0x05cc, 0xecde, 0xcfd8, 0xaad2, 0x89d4,
    0x358f, 0x1689, 0x7383, 0x5085, 0xb997, 0x9a91, 0xff9b, 0xdc9d, 0xca54, 0xe952,
    0x8c58, 0xaf5e, 0x464c, 0x654a, 0x0040, 0x2346, 0x9f1d, 0xbc1b, 0xd911, 0xfa17,
    0x1305, 0x3003, 0x5509, 0x760f, 0x789b, 0x5b9d, 0x3e97, 0x1d91, 0xf483, 0xd785,
    0xb28f, 0x9189, 0x2dd2, 0x0ed4, 0x6bde, 0x48d8, 0xa1ca, 0x82cc, 0xe7c6, 0xc4c0,
    0xd209, 0xf10f, 0x9405, 0xb703, 0x5e11, 0x7d17, 0x181d, 0x3b1b, 0x8740, 0xa446,
    0xc14c, 0xe24a, 0x0b58, 0x285e, 0x4d54, 0x6e52},
   {0xffb8, 0x4a5f, 0xd90f, 0x6ce8, 0xb2d6, 0x0731, 0x9461, 0x2186, 0x6564, 0xd083,
    0x43d3, 0xf634, 0x280a, 0x9ded, 0x0ebd, 0xbb5a, 0x8779, 0x329e, 0xa1ce, 0x1429,
    0xca17, 0x7ff0, 0xeca0, 0x5947, 0x1da5, 0xa842, 0x3b12, 0x8ef5, 0x50cb, 0xe52c,
    0x767c, 0xc39b, 0x0e3a, 0xbbdd, 0x288d, 0x9d6a, 0x4354, 0xf6b3, 0x65e3, 0xd004,
    0x94e6, 0x2101, 0xb251, 0x07b6, 0xd988, 0x6c6f, 0xff3f, 0x4ad8, 0x76fb, 0xc31c,
    0x504c, 0xe5ab, 0x3b95, 0x8e72, 0x1d22, 0xa8c5, 0xec27, 0x59c0, 0xca90, 0x7f77,
    0xa149, 0x14ae, 0x87fe, 0x3219, 0x51c5, 0xe422, 0x7772, 0xc295, 0x1cab, 0xa94c,
    0x3a1c, 0x8ffb, 0xcb19, 0x7efe, 0xedae, 0x5849, 0x8677, 0x3390, 0xa0c0, 0x1527,
    0x2904, 0x9ce3, 0x0fb3, 0xba54, 0x646a, 0xd18d, 0x42dd, 0xf73a, 0xb3d8, 0x063f,
    0x956f, 0x2088, 0xfeb6, 0x4b51, 0xd801, 0x6de6, 0xa047, 0x15a0, 0x86f0, 0x3317,
    0xed29, 0x58ce, 0xcb9e, 0x7e79, 0x3a9b, 0x8f7c, 0x1c2c, 0xa9cb, 0x77f5, 0xc212,
    0x5142, 0xe4a5, 0xd886, 0x6d61, 0xfe31, 0x4bd6, 0x95e8, 0x200f, 0xb35f, 0x06b8,
    0x425a, 0xf7bd, 0x64ed, 0xd10a, 0x0f34, 0xbad3, 0x2983, 0x9c64, 0xee3b, 0x5bdc,
    0xc88c, 0x7d6b, 0xa355, 0x16b2, 0x85e2, 0x3005, 0x74e7, 0xc100, 0x5250, 0xe7b7,
    0x3989, 0x8c6e, 0x1f3e, 0xaad9, 0x96fa, 0x231d, 0xb04d, 0x05aa, 0xdb94, 0x6e73,
    0xfd23, 0x48c4, 0x0c26, 0xb9c1, 0x2a91, 0x9f76, 0x4148, 0xf4af, 0x67ff, 0xd218,
    0x1fb9, 0xaa5e, 0x390e, 0x8ce9, 0x52d7, 0xe730, 0x7460, 0xc187, 0x8565, 0x3082,
    0xa3d2, 0x1635, 0xc80b, 0x7dec, 0xeebc, 0x5b5b, 0x6778, 0xd29f, 0x41cf, 0xf428,
    0x2a16, 0x9ff1, 0x0ca1, 0xb946, 0xfda4, 0x4843, 0xdb13, 0x6ef4, 0xb0ca, 0x052d,
    0x967d, 0x239a, 0x4046, 0xf5a1, 0x66f1, 0xd316, 0x0d28, 0xb8cf, 0x2b9f, 0x9e78,
    0xda9a, 0x6f7d, 0xfc2d, 0x49ca, 0x97f4, 0x2213, 0xb143, 0x04a4, 0x3887, 0x8d60,
    0x1e30, 0xabd7, 0x75e9, 0xc00e, 0x535e, 0xe6b9, 0xa25b, 0x17bc, 0x84ec, 0x310b,
    0xef35, 0x5ad2, 0xc982, 0x7c65, 0xb1c4, 0x0423, 0x9773, 0x2294, 0xfcaa, 0x494d,
    0xda1d, 0x6ffa, 0x2b18, 0x9eff, 0x0daf, 0xb848, 0x6676, 0xd391, 0x40c1, 0xf526,
    0xc905, 0x7ce2, 0xefb2, 0x5a55, 0x846b, 0x318c, 0xa2dc, 0x173b, 0x53d9, 0xe63e,
    0x756e, 0xc089, 0x1eb7, 0xab50, 0x3800, 0x8de7},
   {0xc20e, 0x9d6c, 0x7cca, 0x23a8, 0xf2ff, 0xad9d, 0x4c3b, 0x1359, 0xa3ec, 0xfc8e,
    0x1d28, 0x424a, 0x931d, 0xcc7f, 0x2dd9, 0x72bb, 0x01ca, 0x5ea8, 0xbf0e, 0xe06c,
    0x313b, 0x6e59, 0x8fff, 0xd09d, 0x6028, 0x3f4a, 0xdeec, 0x818e, 0x50d9, 0x0fbb,
    0xee1d, 0xb17f, 0x08ff, 0x579d, 0xb63b, 0xe959, 0x380e, 0x676c, 0x86ca, 0xd9a8,
    0x691d, 0x367f, 0xd7d9, 0x88bb, 0x59ec, 0x068e, 0xe728, 0xb84a, 0xcb3b, 0x9459,
    0x75ff, 0x2a9d, 0xfbca, 0xa4a8, 0x450e, 0x1a6c, 0xaad9, 0xf5bb, 0x141d, 0x4b7f,
    0x9a28, 0xc54a, 0x24ec, 0x7b8e, 0x1a95, 0x45f7, 0xa451, 0xfb33, 0x2a64, 0x7506,
    0x94a0, 0xcbc2, 0x7b77, 0x2415, 0xc5b3, 0x9ad1, 0x4b86, 0x14e4, 0xf542, 0xaa20,
    0xd951, 0x8633, 0x6795, 0x38f7, 0xe9a0, 0xb6c2, 0x5764, 0x0806, 0xb8b3, 0xe7d1,
    0x0677, 0x5915, 0x8842, 0xd720, 0x3686, 0x69e4, 0xd064, 0x8f06, 0x6ea0, 0x31c2,
    0xe095, 0xbff7, 0x5e51, 0x0133, 0xb186, 0xeee4, 0x0f42, 0x5020, 0x8177, 0xde15,
    0x3fb3, 0x60d1, 0x13a0, 0x4cc2, 0xad64, 0xf206, 0x2351, 0x7c33, 0x9d95, 0xc2f7,
    0x7242, 0x2d20, 0xcc86, 0x93e4, 0x42b3, 0x1dd1, 0xfc77, 0xa315, 0x3e41, 0x6123,
    0x8085, 0xdfe7, 0x0eb0, 0x51d2, 0xb074, 0xef16, 0x5fa3, 0x00c1, 0xe167, 0xbe05,
    0x6f52, 0x3030, 0xd196, 0x8ef4, 0xfd85, 0xa2e7, 0x4341, 0x1c23, 0xcd74, 0x9216,
    0x73b0, 0x2cd2, 0x9c67, 0xc305, 0x22a3, 0x7dc1, 0xac96, 0xf3f4, 0x1252, 0x4d30,
    0xf4b0, 0xabd2, 0x4a74, 0x1516, 0xc441, 0x9b23, 0x7a85, 0x25e7, 0x9552, 0xca30,
    0x2b96, 0x74f4, 0xa5a3, 0xfac1, 0x1b67, 0x4405, 0x3774, 0x6816, 0x89b0, 0xd6d2,
    0x0785, 0x58e7, 0xb941, 0xe623, 0x5696, 0x09f4, 0xe852, 0xb730, 0x6667, 0x3905,
    0xd8a3, 0x87c1, 0xe6da, 0xb9b8, 0x581e, 0x077c, 0xd62b, 0x8949, 0x68ef, 0x378d,
    0x8738, 0xd85a, 0x39fc, 0x669e, 0xb7c9, 0xe8ab, 0x090d, 0x566f, 0x251e, 0x7a7c,
    0x9bda, 0xc4b8, 0x15ef, 0x4a8d, 0xab2b, 0xf449, 0x44fc, 0x1b9e, 0xfa38, 0xa55a,
    0x740d, 0x2b6f, 0xcac9, 0x95ab, 0x2c2b, 0x7349, 0x92ef, 0xcd8d, 0x1cda, 0x43b8,
    0xa21e, 0xfd7c, 0x4dc9, 0x12ab, 0xf30d, 0xac6f, 0x7d38, 0x225a, 0xc3fc, 0x9c9e,
    0xefef, 0xb08d, 0x512b, 0x0e49, 0xdf1e, 0x807c, 0x61da, 0x3eb8, 0x8e0d, 0xd16f,
    0x30c9, 0x6fab, 0xbefc, 0xe19e, 0x0038, 0x5f5a},
   {0x4a8f, 0x5c9d, 0x66ab, 0x70b9, 0x12c7, 0x04d5, 0x3ee3, 0x28f1, 0xfa1f, 0xec0d,
    0xd63b, 0xc029, 0xa257, 0xb445, 0x8e73, 0x9861, 0x66d6, 0x70c4, 0x4af2, 0x5ce0,
    0x3e9e, 0x288c, 0x12ba, 0x04a8, 0xd646, 0xc054, 0xfa62, 0xec70, 0x8e0e, 0x981c,
    0xa22a, 0xb438, 0x123d, 0x042f, 0x3e19, 0x280b, 0x4a75, 0x5c67, 0x6651, 0x7043,
    0xa2ad, 0xb4bf, 0x8e89, 0x989b, 0xfae5, 0xecf7, 0xd6c1, 0xc0d3, 0x3e64, 0x2876,
    0x1240, 0x0452, 0x662c, 0x703e, 0x4a08, 0x5c1a, 0x8ef4, 0x98e6, 0xa2d0, 0xb4c2,
    0xd6bc, 0xc0ae, 0xfa98, 0xec8a, 0xfbeb, 0xedf9, 0xd7cf, 0xc1dd, 0xa3a3, 0xb5b1,
    0x8f87, 0x9995, 0x4b7b, 0x5d69, 0x675f, 0x714d, 0x1333, 0x0521, 0x3f17, 0x2905,
    0xd7b2, 0xc1a0, 0xfb96, 0xed84, 0x8ffa, 0x99e8, 0xa3de, 0xb5cc, 0x6722, 0x7130,
    0x4b06, 0x5d14, 0x3f6a, 0x2978, 0x134e, 0x055c, 0xa359, 0xb54b, 0x8f7d, 0x996f,
    0xfb11, 0xed03, 0xd735, 0xc127, 0x13c9, 0x05db, 0x3fed, 0x29ff, 0x4b81, 0x5d93,
    0x67a5, 0x71b7, 0x8f00, 0x9912, 0xa324, 0xb536, 0xd748, 0xc15a, 0xfb6c, 0xed7e,
    0x3f90, 0x2982, 0x13b4, 0x05a6, 0x67d8, 0x71ca, 0x4bfc, 0x5dee, 0x653e, 0x732c,
    0x491a, 0x5f08, 0x3d76, 0x2b64, 0x1152, 0x0740, 0xd5ae, 0xc3bc, 0xf98a, 0xef98,
    0x8de6, 0x9bf4, 0xa1c2, 0xb7d0, 0x4967, 0x5f75, 0x6543, 0x7351, 0x112f, 0x073d,
    0x3d0b, 0x2b19, 0xf9f7, 0xefe5, 0xd5d3, 0xc3c1, 0xa1bf, 0xb7ad, 0x8d9b, 0x9b89,
    0x3d8c, 0x2b9e, 0x11a8, 0x07ba, 0x65c4, 0x73d6, 0x49e0, 0x5ff2, 0x8d1c, 0x9b0e,
    0xa138, 0xb72a, 0xd554, 0xc346, 0xf970, 0xef62, 0x11d5, 0x07c7, 0x3df1, 0x2be3,
    0x499d, 0x5f8f, 0x65b9, 0x73ab, 0xa145, 0xb757, 0x8d61, 0x9b73, 0xf90d, 0xef1f,
    0xd529, 0xc33b, 0xd45a, 0xc248, 0xf87e, 0xee6c, 0x8c12, 0x9a00, 0xa036, 0xb624,
    0x64ca, 0x72d8, 0x48ee, 0x5efc, 0x3c82, 0x2a90, 0x10a6, 0x06b4, 0xf803, 0xee11,
    0xd427, 0xc235, 0xa04b, 0xb659, 0x8c6f, 0x9a7d, 0x4893, 0x5e81, 0x64b7, 0x72a5,
    0x10db, 0x06c9, 0x3cff, 0x2aed, 0x8ce8, 0x9afa, 0xa0cc, 0xb6de, 0xd4a0, 0xc2b2,
    0xf884, 0xee96, 0x3c78, 0x2a6a, 0x105c, 0x064e, 0x6430, 0x7222, 0x4814, 0x5e06,
    0xa0b1, 0xb6a3, 0x8c95, 0x9a87, 0xf8f9, 0xeeeb, 0xd4dd, 0xc2cf, 0x1021, 0x0633,
    0x3c05, 0x2a17, 0x4869, 0x5e7b, 0x644d, 0x725f}
};

unsigned crc16dnp_byte(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc &= 0xffff;
    while (len--)
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
    return crc;
}

// This code assumes that integers are stored little-endian.

unsigned crc16dnp_word(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc &= 0xffff;
    while (len && ((ptrdiff_t)data & 0x7)) {
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
        len--;
    }
    if (len >= 8) {
        do {
            uintmax_t word = crc ^ *(uintmax_t const *)data;
            crc = table_word[7][word & 0xff] ^
                  table_word[6][(word >> 8) & 0xff] ^
                  table_word[5][(word >> 16) & 0xff] ^
                  table_word[4][(word >> 24) & 0xff] ^
                  table_word[3][(word >> 32) & 0xff] ^
                  table_word[2][(word >> 40) & 0xff] ^
                  table_word[1][(word >> 48) & 0xff] ^
                  table_word[0][word >> 56];
            data += 8;
            len -= 8;
        } while (len >= 8);
    }
    while (len--)
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
    return crc;
}

Matplotlib: ValueError: x and y must have same first dimension

Changing your lists to numpy arrays will do the job!!

import matplotlib.pyplot as plt
from scipy import stats
import numpy as np 

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15

plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()

enter image description here

How to print like printf in Python3?

Simple Example:

print("foo %d, bar %d" % (1,2))

using batch echo with special characters

Here's one more approach by using SET and FOR /F

@echo off

set "var=<?xml version="1.0" encoding="utf-8" ?>"

for /f "tokens=1* delims==" %%a in ('set var') do echo %%b

and you can beautify it like:

@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "print{[=for /f "tokens=1* delims==" %%a in ('set " & set "]}=') do echo %%b"
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


set "xml_line.1=<?xml version="1.0" encoding="utf-8" ?>"
set "xml_line.2=<root>"
set "xml_line.3=</root>"

%print{[% xml_line %]}%

"No such file or directory" but it exists

I got this error “No such file or directory” but it exists because my file was created in Windows and I tried to run it on Ubuntu and the file contained invalid 15\r where ever a new line was there. I just created a new file truncating unwanted stuff

sleep: invalid time interval ‘15\r’
Try 'sleep --help' for more information.
script.sh: 5: script.sh: /opt/ag/cont: not found
script.sh: 6: script.sh: /opt/ag/cont: not found
root@Ubuntu14:/home/abc12/Desktop# vi script.sh 
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  \r  \n   w   g   e   t       h   t   t   p   :   /

0000400   :   4   1   2   0   /  \r  \n
0000410
root@Ubuntu14:/home/abc12/Desktop# tr -d \\015 < script.sh > script.sh.fixed
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh.fixed 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  \n   w   g   e   t       h   t   t   p   :   /   /

0000400   /  \n
0000402
root@Ubuntu14:/home/abc12/Desktop# sh -x script.sh.fixed 

Webdriver findElements By xpath

Instead of

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)

2D arrays in Python

In Python one would usually use lists for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. Have a look at the examples I linked to.

batch file to copy files to another location?

robocopy yourfolder yourdestination /MON:0

should do it, although you may need some more options. The switch at the end will re-run robocopy if more than 0 changes are seen.

How to reset a timer in C#?

For a Timer (System.Windows.Forms.Timer).

The .Stop, then .Start methods worked as a reset.

Text File Parsing in Java

While calling/invoking your programme you can use this command : java [-options] className [args...]
in place of [-options] provide more memory e.g -Xmx1024m or more. but this is just a workaround, u have to change ur parsing mechanism.

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

ContextLoaderListener has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml

You can customize this by using

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>

on web.xml, or remove this listener if you don't need one.

Get the list of stored procedures created and / or modified on a particular date?

SELECT name
FROM sys.objects
WHERE type = 'P'
AND (DATEDIFF(D,modify_date, GETDATE()) < 7
     OR DATEDIFF(D,create_date, GETDATE()) < 7)

Serialize an object to string

Code Safety Note

Regarding the accepted answer, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes.

Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject<T>() that is defined in the derived type's base class: http://ideone.com/1Z5J1. Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

For the sake of completeness I post the full code sample here for future reference, just in case Ideone (where I posted the code) becomes unavailable in the future:

using System;
using System.Xml.Serialization;
using System.IO;

public class Test
{
    public static void Main()
    {
        Sub subInstance = new Sub();
        Console.WriteLine(subInstance.TestMethod());
    }

    public class Super
    {
        public string TestMethod() {
            return this.SerializeObject();
        }
    }

    public class Sub : Super
    {
    }
}

public static class TestExt {
    public static string SerializeObject<T>(this T toSerialize)
    {
        Console.WriteLine(typeof(T).Name);             // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
        Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter textWriter = new StringWriter();

        // And now...this will throw and Exception!
        // Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType()); 
        // solves the problem
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

merge into x as target using y as Source on target.ID = Source.ID
when not matched by target then insert
when matched then update
when not matched by source and target.ID is not null then
update whatevercolumn = 'isdeleted' ;

How to set opacity to the background color of a div?

I would say that the easiest way is to use transparent background image.

http://jsfiddle.net/m48nH/

background: url("http://musescore.org/sites/musescore.org/files/blue-translucent.png") repeat top left;

What's the C# equivalent to the With statement in VB?

The closest thing in C# 3.0, is that you can use a constructor to initialize properties:

Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}

Javascript variable access in HTML

Try this :

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
  $(document).ready(function () {
            var simpleText = "hello_world";
            var finalSplitText = simpleText.split("_");
            var splitText = finalSplitText[0];
            $("#target").text(splitText);
        });
</script>

<body>
<a id="target" href = test.html></a>
</body>
</html>

Hide separator line on one UITableViewCell

If you don't want to draw the separator yourself, use this:

  // Hide the cell separator by moving it to the far right
  cell.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);

This API is only available starting from iOS 7 though.

.htaccess mod_rewrite - how to exclude directory from rewrite rule

Try this rule before your other rules:

RewriteRule ^(admin|user)($|/) - [L]

This will end the rewriting process.

How to convert milliseconds into a readable date?

You can use datejs and convert in different formate. I have tested some formate and working fine.

var d = new Date(1469433907836);

d.toLocaleString()     // 7/25/2016, 1:35:07 PM
d.toLocaleDateString() // 7/25/2016
d.toDateString()       // Mon Jul 25 2016
d.toTimeString()       // 13:35:07 GMT+0530 (India Standard Time)
d.toLocaleTimeString() // 1:35:07 PM
d.toISOString();       // 2016-07-25T08:05:07.836Z
d.toJSON();            // 2016-07-25T08:05:07.836Z
d.toString();          // Mon Jul 25 2016 13:35:07 GMT+0530 (India Standard Time)
d.toUTCString();       // Mon, 25 Jul 2016 08:05:07 GMT

How to convert a string to utf-8 in Python

If I understand you correctly, you have a utf-8 encoded byte-string in your code.

Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding).

You do that by using the unicode function or the decode method. Either:

unicodestr = unicode(bytestr, encoding)
unicodestr = unicode(bytestr, "utf-8")

Or:

unicodestr = bytestr.decode(encoding)
unicodestr = bytestr.decode("utf-8")

Python pandas: how to specify data types when reading an Excel file?

You just specify converters. I created an excel spreadsheet of the following structure:

names   ages
bob     05
tom     4
suzy    3

Where the "ages" column is formatted as strings. To load:

import pandas as pd

df = pd.read_excel('Book1.xlsx',sheetname='Sheet1',header=0,converters={'names':str,'ages':str})
>>> df
       names ages
   0   bob   05
   1   tom   4
   2   suzy  3

How to change string into QString?

std::string s = "Sambuca";
QString q = s.c_str();

Warning: This won't work if the std::string contains \0s.

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

PL/SQL, how to escape single quote in a string?

EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'; worked for me. closing the varchar/string with two pairs of single quotes did the trick. Other option could be to use using keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'; Remember using keyword will not work, if you are using EXECUTE IMMEDIATE to execute DDL's with parameters, however, using quotes will work for DDL's.

How can I check if a program exists from a Bash script?

I use this, because it's very easy:

if [ `LANG=C type example 2>/dev/null|wc -l` = 1 ];then echo exists;else echo "not exists";fi

or

if [ `LANG=C type example 2>/dev/null|wc -l` = 1 ];then
echo exists
else echo "not exists"
fi

It uses shell builtins and programs' echo status to standard output and nothing to standard error. On the other hand, if a command is not found, it echos status only to standard error.

How to add \newpage in Rmarkdown in a smart way?

You can make the pagebreak conditional on knitting to PDF. This worked for me.

```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```

Get the string value from List<String> through loop for display

pst = con.createStatement(); ResultSet resultSet= pst.executeQuery(query);

     String str1 = "<table>";
     int i = 1;
    while(resultSet.next()) {
             str1+= "</tr><td>"+i+"</td>"+
             "<td>"+resultSet.getString("first_name")+"</td>"+
             "<td>"+resultSet.getString("last_name")+"</td>"+
             "<td>"+resultSet.getString("email_id")+"</td>"+
             "<td>"+resultSet.getString("dob") +"</td>"+

             "</tr>";
        i++;

    }
        str1 =str1+"<table>";

    model.addAttribute("list",str1);

    return "userlist";  //Sending to views .jsp 

Eclipse reported "Failed to load JNI shared library"

Yep, in Windows 7 64 bit you have C:\Program Files and C:\Program Files (x86). You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin to environment variable PATH.

Reading an Excel file in python using pandas

I think this should satisfy your need:

import pandas as pd

# Read the excel sheet to pandas dataframe
df = pd.read_excel("PATH\FileName.xlsx", sheetname=0)

How to view the contents of an Android APK file?

Depending on your reason for wanting to extract the APK, APK Analyzer might be sufficient. It shows you directories, and file sizes. It also shows method counts grouped by package that you can drill down into.

APK Analyzer is built into Android Studio. You can access it from the top menu, Build -> Analyze APK.

Build query string for System.Net.HttpClient get

Darin offered an interesting and clever solution, and here is something that may be another option:

public class ParameterCollection
{
    private Dictionary<string, string> _parms = new Dictionary<string, string>();

    public void Add(string key, string val)
    {
        if (_parms.ContainsKey(key))
        {
            throw new InvalidOperationException(string.Format("The key {0} already exists.", key));
        }
        _parms.Add(key, val);
    }

    public override string ToString()
    {
        var server = HttpContext.Current.Server;
        var sb = new StringBuilder();
        foreach (var kvp in _parms)
        {
            if (sb.Length > 0) { sb.Append("&"); }
            sb.AppendFormat("{0}={1}",
                server.UrlEncode(kvp.Key),
                server.UrlEncode(kvp.Value));
        }
        return sb.ToString();
    }
}

and so when using it, you might do this:

var parms = new ParameterCollection();
parms.Add("key", "value");

var url = ...
url += "?" + parms;

@selector() in Swift?

For Swift 3

//Sample code to create timer

Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)

WHERE
timeInterval:- Interval in which timer should fire like 1s, 10s, 100s etc. [Its value is in secs]
target:- function which pointed to class. So here I am pointing to current class.
selector:- function that will execute when timer fires.

func updateTimer(){
    //Implemetation 
} 

repeats:- true/false specifies that timer should call again n again.

Loop structure inside gnuplot?

Here is the alternative command:

gnuplot -p -e 'plot for [file in system("find . -name \\*.txt -depth 1")] file using 1:2 title file with lines'

How to get current foreground activity context in android?

A rather simple solution is to create a singleton manager class, in which you can store a reference to one or more Activities, or anything else you want access to throughout the app.

Call UberManager.getInstance().setMainActivity( activity ); in the main activity's onCreate.

Call UberManager.getInstance().getMainActivity(); anywhere in your app to retrieve it. (I am using this to be able to use Toast from a non UI thread.)

Make sure you add a call to UberManager.getInstance().cleanup(); when your app is being destroyed.

import android.app.Activity;

public class UberManager
{
    private static UberManager instance = new UberManager();

    private Activity mainActivity = null;

    private UberManager()
    {

    }

    public static UberManager getInstance()
    {
        return instance;
    }

    public void setMainActivity( Activity mainActivity )
    {
        this.mainActivity = mainActivity;
    }

    public Activity getMainActivity()
    {
        return mainActivity;
    }

    public void cleanup()
    {
        mainActivity = null;
    }
}

How to use global variables in React Native?

The global scope in React Native is variable global. Such as global.foo = foo, then you can use global.foo anywhere.

But do not abuse it! In my opinion, global scope may used to store the global config or something like that. Share variables between different views, as your description, you can choose many other solutions(use redux,flux or store them in a higher component), global scope is not a good choice.

A good practice to define global variable is to use a js file. For example global.js

global.foo = foo;
global.bar = bar;

Then, to make sure it is executed when project initialized. For example, import the file in index.js:

import './global.js'
// other code

Now, you can use the global variable anywhere, and don't need to import global.js in each file. Try not to modify them!

How do I convert an existing callback API to promises?

With plain old vanilla javaScript, here's a solution to promisify an api callback.

function get(url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url);
        xhr.addEventListener('readystatechange', function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    console.log('successful ... should call callback ... ');
                    callback(null, JSON.parse(xhr.responseText));
                } else {
                    console.log('error ... callback with error data ... ');
                    callback(xhr, null);
                }
            }
        });
        xhr.send();
    }

/**
     * @function promisify: convert api based callbacks to promises
     * @description takes in a factory function and promisifies it
     * @params {function} input function to promisify
     * @params {array} an array of inputs to the function to be promisified
     * @return {function} promisified function
     * */
    function promisify(fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            return new Promise(function(resolve, reject) {
                fn.apply(null, args.concat(function (err, result) {
                    if (err) reject(err);
                    else resolve(result);
                }));
            });
        }
    }

var get_promisified = promisify(get);
var promise = get_promisified('some_url');
promise.then(function (data) {
        // corresponds to the resolve function
        console.log('successful operation: ', data);
}, function (error) {
        console.log(error);
});

How do you search an amazon s3 bucket?

Here's a short and ugly way to do search file names using the AWS CLI:

aws s3 ls s3://your-bucket --recursive | grep your-search | cut -c 32-

How could others, on a local network, access my NodeJS app while it's running on my machine?

The port is probably blocked by your local firewall or router. Hard to tell without details.

But there is a simple solution for which you don't have to mess with firewall rules, run node as a privileded process to serve on port 80, etc...

Check out Localtunnel. Its a great Ruby script/service, which allows you to make any local port available on the internet within seconds. It's certainly not useful for a production setup, but to try out a game with colleagues, it should work just fine!

How to add elements of a string array to a string array list?

public class duplicateArrayList {


    ArrayList al = new ArrayList();
    public duplicateArrayList(Object[] obj) {

        for (int i = 0; i < obj.length; i++) {

            al.add(obj[i]);
        }

        Iterator iter = al.iterator();
        while(iter.hasNext()){

            System.out.print(" "+iter.next());
        }
    }

    public static void main(String[] args) {


    String[] str = {"A","B","C","D"};

    duplicateArrayList dd = new duplicateArrayList(str);

    }

}

In a bootstrap responsive page how to center a div

Try this, For the example, I used a fixed height. I think it is doesn't affect the responsive scenario.

_x000D_
_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
</head>_x000D_
<body>_x000D_
    <div class="d-flex justify-content-center align-items-center bg-secondary w-100" style="height: 300px;">_x000D_
        <div class="bg-primary" style="width: 200px; height: 50px;"></div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I get specific properties with Get-AdUser

using select-object for example:

Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv" 

How can I programmatically get the MAC address of an iphone

Starting from iOS 7, the system always returns the value 02:00:00:00:00:00 when you ask for the MAC address on any device.

In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)"

Reference: releasenotes

Create intermediate folders if one doesn't exist

You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.

You can use File#mkdirs() method to create the directory: -

theFile.mkdirs();

Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.

How to convert array values to lowercase in PHP?

use array_map():

$yourArray = array_map('strtolower', $yourArray);

In case you need to lowercase nested array (by Yahya Uddin):

$yourArray = array_map('nestedLowercase', $yourArray);

function nestedLowercase($value) {
    if (is_array($value)) {
        return array_map('nestedLowercase', $value);
    }
    return strtolower($value);
}

Centering Bootstrap input fields

For bootstrap 4 use offset-4, see below.

<div class="mx-auto">        
        <form class="mx-auto" action="/campgrounds" method="POST">
            <div class="form-group row">                
                <div class="col-sm-4 offset-4">
                    <input class="form-control" type="text" name="name" placeholder="name">
                </div>
            </div>
            <div class="form-group row">               
                <div class="col-sm-4 offset-4">
                    <input class="form-control" type="text" name="picture" placeholder="image url">
                </div>
            </div>
            <div class="form-group row">
                    <div class="col-sm-4 offset-4">
                        <input class="form-control" type="text" name="description" placeholder="description">
                    </div>
                </div>
            <button class="btn btn-primary" type="submit">Submit!</button>
            <a class="btn btn-secondary"  href="/campgrounds">Go Back</a>
        </form>      
    </div>

How to rebase local branch onto remote master

git pull --rebase origin master

Best way to create a temp table with same columns and type as a permanent table

Sortest one...

select top 0 * into #temptable from mytable

Note : This creates an empty copy of temp, But it doesn't create a primary key

Cygwin Make bash command not found

when selecting packages at installation or update search for 'make' in searchbox and select the boxes showing 'make' and also 'gcc' mostly found in devel package.

How to resolve ORA 00936 Missing Expression Error?

Remove the coma at the end of your SELECT statement (VALUE,), and also remove the one at the end of your FROM statement (rrf b,)

What is difference between functional and imperative programming languages?

Functional programming is "programming with functions," where a function has some expected mathematical properties, including referential transparency. From these properties, further properties flow, in particular familiar reasoning steps enabled by substitutability that lead to mathematical proofs (i.e. justifying confidence in a result).

It follows that a functional program is merely an expression.

You can easily see the contrast between the two styles by noting the places in an imperative program where an expression is no longer referentially transparent (and therefore is not built with functions and values, and cannot itself be part of a function). The two most obvious places are: mutation (e.g. variables) other side-effects non-local control flow (e.g. exceptions)

On this framework of programs-as-expressions which are composed of functions and values, is built an entire practical paradigm of languages, concepts, "functional patterns", combinators, and various type systems and evaluation algorithms.

By the most extreme definition, almost any language—even C or Java—can be called functional, but usually people reserve the term for languages with specifically relevant abstractions (such as closures, immutable values, and syntactic aids like pattern matching). As far as use of functional programming is concerned it involves use of functins and builds code without any side effects . used to write proofs

Axios having CORS issue

I have encountered with same issue. When I changed content type it has solved. I'm not sure this solution will help you but maybe it is. If you don't mind about content-type, it worked for me.

axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';

CSS display:inline property with list-style-image: property on <li> tags

Try using float: left (or right) instead of display: inline. Inline display replaces list-item display, which is what adds the bullet points.

What exactly does += do in python?

I'm seeing a lot of answers that don't bring up using += with multiple integers.

One example:

x -= 1 + 3

This would be similar to:

x = x - (1 + 3)

and not:

x = (x - 1) + 3

log4j:WARN No appenders could be found for logger in web.xml

You'll see this warning if log4j can't find a file "log4j.properties" or "log4j.xml" anywhere.

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

A lot has changed in the Spring world since this question was answered. Spring has simplified getting the current user in a controller. For other beans, Spring has adopted the suggestions of the author and simplified the injection of 'SecurityContextHolder'. More details are in the comments.


This is the solution I've ended up going with. Instead of using SecurityContextHolder in my controller, I want to inject something which uses SecurityContextHolder under the hood but abstracts away that singleton-like class from my code. I've found no way to do this other than rolling my own interface, like so:

public interface SecurityContextFacade {

  SecurityContext getContext();

  void setContext(SecurityContext securityContext);

}

Now, my controller (or whatever POJO) would look like this:

public class FooController {

  private final SecurityContextFacade securityContextFacade;

  public FooController(SecurityContextFacade securityContextFacade) {
    this.securityContextFacade = securityContextFacade;
  }

  public void doSomething(){
    SecurityContext context = securityContextFacade.getContext();
    // do something w/ context
  }

}

And, because of the interface being a point of decoupling, unit testing is straightforward. In this example I use Mockito:

public class FooControllerTest {

  private FooController controller;
  private SecurityContextFacade mockSecurityContextFacade;
  private SecurityContext mockSecurityContext;

  @Before
  public void setUp() throws Exception {
    mockSecurityContextFacade = mock(SecurityContextFacade.class);
    mockSecurityContext = mock(SecurityContext.class);
    stub(mockSecurityContextFacade.getContext()).toReturn(mockSecurityContext);
    controller = new FooController(mockSecurityContextFacade);
  }

  @Test
  public void testDoSomething() {
    controller.doSomething();
    verify(mockSecurityContextFacade).getContext();
  }

}

The default implementation of the interface looks like this:

public class SecurityContextHolderFacade implements SecurityContextFacade {

  public SecurityContext getContext() {
    return SecurityContextHolder.getContext();
  }

  public void setContext(SecurityContext securityContext) {
    SecurityContextHolder.setContext(securityContext);
  }

}

And, finally, the production Spring config looks like this:

<bean id="myController" class="com.foo.FooController">
     ...
  <constructor-arg index="1">
    <bean class="com.foo.SecurityContextHolderFacade">
  </constructor-arg>
</bean>

It seems more than a little silly that Spring, a dependency injection container of all things, has not supplied a way to inject something similar. I understand SecurityContextHolder was inherited from acegi, but still. The thing is, they're so close - if only SecurityContextHolder had a getter to get the underlying SecurityContextHolderStrategy instance (which is an interface), you could inject that. In fact, I even opened a Jira issue to that effect.

One last thing - I've just substantially changed the answer I had here before. Check the history if you're curious but, as a coworker pointed out to me, my previous answer would not work in a multi-threaded environment. The underlying SecurityContextHolderStrategy used by SecurityContextHolder is, by default, an instance of ThreadLocalSecurityContextHolderStrategy, which stores SecurityContexts in a ThreadLocal. Therefore, it is not necessarily a good idea to inject the SecurityContext directly into a bean at initialization time - it may need to be retrieved from the ThreadLocal each time, in a multi-threaded environment, so the correct one is retrieved.

Find duplicate values in R

A terser way, either with rev :

x[!(!duplicated(x) & rev(!duplicated(rev(x))))]

... rather than fromLast:

x[!(!duplicated(x) & !duplicated(x, fromLast = TRUE))]

... and as a helper function to provide either logical vector or elements from original vector :

duplicates <- function(x, as.bool = FALSE) {
    is.dup <- !(!duplicated(x) & rev(!duplicated(rev(x))))
    if (as.bool) { is.dup } else { x[is.dup] }
}

Treating vectors as data frames to pass to table is handy but can get difficult to read, and the data.table solution is fine but I'd prefer base R solutions for dealing with simple vectors like IDs.

#1071 - Specified key was too long; max key length is 767 bytes

If you have changed innodb_log_file_size recently, try to restore the previous value which worked.

"for" vs "each" in Ruby

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


  a = 9 if i==3

  puts a 


}
#nil
#nil
#9
#nil

for i in 1..4

  a = 9 if i==3

  puts a

end
#nil
#nil
#9
#9

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

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

If you want to run angular app ported from another machine without ng command then edit package.json as follows

"scripts": {
    "ng": "ng",
    "start": "node node_modules/.bin/ng serve",
    "build": "node node_modules/.bin/ng build",
    "test": "node node_modules/.bin/ng test",
    "lint": "node node_modules/.bin/ng lint",
    "e2e": "node node_modules/.bin/ng e2e"
  }

Finally run usual npm start command to start build server.

How do I set the path to a DLL file in Visual Studio?

  1. Go to project properties (Alt+F7)
  2. Under Debugging, look to the right
  3. There's an Environment field.
  4. Add your relative path there (relative to vcproj folder) i.e. ..\some-framework\lib by appending PATH=%PATH%;$(ProjectDir)\some-framework\lib or prepending to the path PATH=C:\some-framework\lib;%PATH%
  5. Hit F5 (debug) again and it should work.

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Well, this is a terribly late answer but I think I'll still put my two cents in... I could have posted this as a comment because this answer doesn't essentially add any new solution but it does add value to the post as yet another alternative. But in a comment I wouldn't be able to give all the details because of character limit.

NOTE: This needs an edit to bootstrap CSS file - move style definitions for .badge above .label-default. Couldn't find any practical side effects due to the change in my limited testing.

While broc.seib's solution is probably the best way to achieve the requirement of OP with minimal addition to CSS, it is possible to achieve the same effect without any extra CSS at all just like Jens A. Koch's solution or by using .label-xxx contextual classes because they are easy to remember compared to progress-bar-xxx classes. I don't think that .alert-xxx classes give the same effect.

All you have to do is just use .badge and .label-xxx classes together (but in this order). Don't forget to make the changes mentioned in NOTE above.

<a href="#">Inbox <span class="badge label-warning">42</span></a> looks like this:

Badge with warning bg

IMPORTANT: This solution may break your styles if you decide to upgrade and forget to make the changes in your new local CSS file. My solution for this challenge was to copy all .label-xxx styles in my custom CSS file and load it after all other CSS files. This approach also helps when I use a CDN for loading BS3.

**P.S: ** Both the top rated answers have their pros and cons. It's just the way you prefer to do your CSS because there is no "only correct way" to do it.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

This one works:

cd /usr/local/bin/
ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm

Description: It list all the links, removes @ character and then removes them.

Stash just a single file

The best option is to stage everything but this file, and tell stash to keep the index with git stash save --keep-index, thus stashing your unstaged file:

$ git add .
$ git reset thefiletostash
$ git stash save --keep-index

As Dan points out, thefiletostash is the only one to be reset by the stash, but it also stashes the other files, so it's not exactly what you want.

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

Bootstrap onClick button event

There is no show event in js - you need to bind your button either to the click event:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.

PHP, MySQL error: Column count doesn't match value count at row 1

You have 9 fields listed, but only 8 values. Try adding the method.

How do I use a custom Serializer with Jackson?

As mentioned, @JsonValue is a good way. But if you don't mind a custom serializer, there's no need to write one for Item but rather one for User -- if so, it'd be as simple as:

public void serialize(Item value, JsonGenerator jgen,
    SerializerProvider provider) throws IOException,
    JsonProcessingException {
  jgen.writeNumber(id);
}

Yet another possibility is to implement JsonSerializable, in which case no registration is needed.

As to error; that is weird -- you probably want to upgrade to a later version. But it is also safer to extend org.codehaus.jackson.map.ser.SerializerBase as it will have standard implementations of non-essential methods (i.e. everything but actual serialization call).

START_STICKY and START_NOT_STICKY

The documentation for START_STICKY and START_NOT_STICKY is quite straightforward.

START_STICKY:

If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Example: Local Service Sample

START_NOT_STICKY:

If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will not be re-started if there are no pending Intents to deliver.

This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service. When its onStartCommand(Intent, int, int) is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.

Example: ServiceStartArguments.java

rails simple_form - hidden field - create?

try this

= f.input :title, :as => :hidden, :input_html => { :value => "some value" }

Android Studio doesn't start, fails saying components not installed

In OS X run as admin the first time by opening a new Terminal and run the commands:

cd /Applications/Android\ Studio.app/Contents/MacOS/

sudo ./studio

Global and local variables in R

A bit more along the same lines

attrs <- {}

attrs.a <- 1

f <- function(d) {
    attrs.a <- d
}

f(20)
print(attrs.a)

will print "1"

attrs <- {}

attrs.a <- 1

f <- function(d) {
   attrs.a <<- d
}

f(20)
print(attrs.a)

Will print "20"

Set max-height on inner div so scroll bars appear, but not on parent div

It might be easier to use JavaScript or jquery for this. Assuming that the height of the header and the footer is 200 then the code will be:

function SetHeight(){
    var h = $(window).height();
    $("#inner-right").height(h-200);    
}

$(document).ready(SetHeight);
$(window).resize(SetHeight);

Available text color classes in Bootstrap

You can use text classes:

.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white

use text classes in any tag where needed.

<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>

You can add your own classes or modify above classes as your requirement.

Find the closest ancestor element that has a specific class

This solution should work for IE9 and up.

It's like jQuery's parents() method when you need to get a parent container which might be up a few levels from the given element, like finding the containing <form> of a clicked <button>. Looks through the parents until the matching selector is found, or until it reaches the <body>. Returns either the matching element or the <body>.

function parents(el, selector){
    var parent_container = el;
    do {
        parent_container = parent_container.parentNode;
    }
    while( !parent_container.matches(selector) && parent_container !== document.body );

    return parent_container;
}

Get the decimal part from a double

Why not use int y = value.Split('.')[1];?

The Split() function splits the value into separate content and the 1 is outputting the 2nd value after the .

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

How to clear an EditText on click?

For me the easiest way... Create an public EditText, for Example "myEditText1"

public EditText myEditText1;

Then, connect it with the EditText which should get cleared

myEditText1 = (EditText) findViewById(R.id.numberfield);

After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example

@OnClick(R.id.numberfield)
        void textGone(){
            if (myEditText1.isFocused()){
                myEditText1.setText("");

        }
    }

Hope i could help you, Have a nice Day everyone

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

addEventListener vs onclick

element.onclick = function() { /* do stuff */ }

element.addEventListener('click', function(){ /* do stuff */ },false);

They apparently do the same thing: listen for the click event and execute a callback function. Nevertheless, they’re not equivalent. If you ever need to choose between the two, this could help you to figure out which one is the best for you.

The main difference is that onclick is just a property, and like all object properties, if you write on more than once, it will be overwritten. With addEventListener() instead, we can simply bind an event handler to the element, and we can call it each time we need it without being worried of any overwritten properties. Example is shown here,

Try it: https://jsfiddle.net/fjets5z4/5/

In first place I was tempted to keep using onclick, because it’s shorter and looks simpler… and in fact it is. But I don’t recommend using it anymore. It’s just like using inline JavaScript. Using something like – that’s inline JavaScript – is highly discouraged nowadays (inline CSS is discouraged too, but that’s another topic).

However, the addEventListener() function, despite it’s the standard, just doesn’t work in old browsers (Internet Explorer below version 9), and this is another big difference. If you need to support these ancient browsers, you should follow the onclick way. But you could also use jQuery (or one of its alternatives): it basically simplifies your work and reduces the differences between browsers, therefore can save you a lot of time.

var clickEvent = document.getElementByID("onclick-eg");
var EventListener = document.getElementByID("addEventListener-eg");

clickEvent.onclick = function(){
    window.alert("1 is not called")
}
clickEvent.onclick = function(){
    window.alert("1 is not called, 2 is called")
}

EventListener.addEventListener("click",function(){
    window.alert("1 is called")
})
EventListener.addEventListener("click",function(){
    window.alert("2 is also called")
})

How to sort findAll Doctrine's method?

Look at the Doctrine API source-code :

class EntityRepository{
  ...
  public function findAll(){
    return $this->findBy(array());
  }
  ...
}

How to Auto-start an Android Application?

If by autostart you mean auto start on phone bootup then you should register a BroadcastReceiver for the BOOT_COMPLETED Intent. Android systems broadcasts that intent once boot is completed.

Once you receive that intent you can launch a Service that can do whatever you want to do.

Keep note though that having a Service running all the time on the phone is generally a bad idea as it eats up system resources even when it is idle. You should launch your Service / application only when needed and then stop it when not required.

pull/push from multiple remote locations

Adding the all remote gets a bit tedious as you have to setup on each machine that you use.

Also, the bash and git aliases provided all assume that you have will push to all remotes. (Ex: I have a fork of sshag that I maintain on GitHub and GitLab. I have the upstream remote added, but I don't have permission to push to it.)

Here is a git alias that only pushes to remotes with a push URL that includes @.

psall    = "!f() { \
    for R in $(git remote -v | awk '/@.*push/ { print $1 }'); do \
    git push $R $1; \
    done \
    }; f"

Password Protect a SQLite DB. Is it possible?

Use SQLCipher, it's an opensource extension for SQLite that provides transparent 256-bit AES encryption of database files. http://sqlcipher.net