Programs & Examples On #Data files

Changing MongoDB data store directory

The short answer is that the --dbpath parameter in MongoDB will allow you to control what directory MongoDB reads and writes it's data from.

mongod --dbpath /usr/local/mongodb-data

Would start mongodb and put the files in /usr/local/mongodb-data.

Depending on your distribution and MongoDB installation, you can also configure the mongod.conf file to do this automatically:

# Store data in /usr/local/var/mongodb instead of the default /data/db
dbpath = /usr/local/var/mongodb

The official 10gen Linux packages (Ubuntu/Debian or CentOS/Fedora) ship with a basic configuration file which is placed in /etc/mongodb.conf, and the MongoDB service reads this when it starts up. You could make your change here.

Table header to stay fixed at the top when user scrolls it out of view with jQuery

I found a simple solution without using JQuery and using CSS only.

You have to put the fixed contents inside 'th' tags and add the CSS

table th {
    position:sticky;
    top:0;
    z-index:1;
    border-top:0;
    background: #ededed;
}
   

The position, z-index and top properties are enough. But you can apply the rest to give for a better view.

Using union and count(*) together in SQL query

Is your goal...

  1. To count all the instances of "Bob Jones" in both tables (for example)
  2. To count all the instances of "Bob Jones" in Results in one row and all the instances of "Bob Jones" in Archive_Results in a separate row?

Assuming it's #1 you'd want something like...

SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name

Extract / Identify Tables from PDF python

You should definitely have a look at this answer of mine:

and also have a look at all the links included therein.

Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.

rsync: how can I configure it to create target directory on server?

I don't think you can do it with one rsync command, but you can 'pre-create' the extra directory first like this:

rsync --recursive emptydir/ destination/newdir

where 'emptydir' is a local empty directory (which you might have to create as a temporary directory first).

It's a bit of a hack, but it works for me.

cheers

Chris

Send array with Ajax to PHP script

dataString suggests the data is formatted in a string (and maybe delimted by a character).

$data = explode(",", $_POST['data']);
foreach($data as $d){
     echo $d;
}

if dataString is not a string but infact an array (what your question indicates) use JSON.

MySQL Stored procedure variables from SELECT statements

You simply need to enclose your SELECT statements in parentheses to indicate that they are subqueries:

SET cityLat = (SELECT cities.lat FROM cities WHERE cities.id = cityID);

Alternatively, you can use MySQL's SELECT ... INTO syntax. One advantage of this approach is that both cityLat and cityLng can be assigned from a single table-access:

SELECT lat, lng INTO cityLat, cityLng FROM cities WHERE id = cityID;

However, the entire procedure can be replaced with a single self-joined SELECT statement:

SELECT   b.*, HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM     cities AS a, cities AS b
WHERE    a.id = cityID
ORDER BY dist
LIMIT    10;

Replace Multiple String Elements in C#

If you are simply after a pretty solution and don't need to save a few nanoseconds, how about some LINQ sugar?

var input = "test1test2test3";
var replacements = new Dictionary<string, string> { { "1", "*" }, { "2", "_" }, { "3", "&" } };

var output = replacements.Aggregate(input, (current, replacement) => current.Replace(replacement.Key, replacement.Value));

How to close IPython Notebook properly?

Option 1

Open a different console and run

jupyter notebook stop [PORT]

The default [PORT] is 8888, so, assuming that Jupyter Notebooks is running on port 8888, just run

jupyter notebook stop

If it is on port 9000, then

jupyter notebook stop 9000

Option 2 (Source)

  1. Check runtime folder location

    jupyter --paths
    
  2. Remove all files in the runtime folder

    rm -r [RUNTIME FOLDER PATH]/*
    
  3. Use top to find any Jupyter Notebook running processes left and if so kill their PID.

    top | grep jupyter &
    kill [PID]
    

One can boilt it down to

TARGET_PORT=8888
kill -9 $(lsof -n -i4TCP:$TARGET_PORT | cut -f 2 -d " ")

Note: If one wants to launch one's Notebook on a specific IP/Port

jupyter notebook --ip=[ADD_IP] --port=[ADD_PORT] --allow-root &

Create a .csv file with values from a Python list

import csv

with open(..., 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(mylist)

Edit: this only works with python 2.x.

To make it work with python 3.x replace wb with w (see this SO answer)

with open(..., 'w', newline='') as myfile:
     wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
     wr.writerow(mylist)

Find duplicate records in a table using SQL Server

with x as (
select shoppername,count(shoppername)
              from sales
              having count(shoppername)>1
            group by shoppername)
select t.* from x,win_gp_pin1510 t
where x.shoppername=t.shoppername
order by t.shoppername

Number of elements in a javascript object

function count(){
    var c= 0;
    for(var p in this) if(this.hasOwnProperty(p))++c;
    return c;
}

var O={a: 1, b: 2, c: 3};

count.call(O);

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

I had this error for some time and found a fix. This fix is for Asp.net application, Strange it failed only in IE non compatibility mode, but works in Firefox and Crome. Giving access to the webservice service folder for all/specific users solved the issue.

Add the following code in web.config file:

 <location path="YourWebserviceFolder">
  <system.web>
   <authorization>
    <allow users="*"/>
   </authorization>
  </system.web>
 </location>

Business logic in MVC

Model = code for CRUD database operations.

Controller = responds to user actions, and passes the user requests for data retrieval or delete/update to the model, subject to the business rules specific to an organization. These business rules could be implemented in helper classes, or if they are not too complex, just directly in the controller actions. The controller finally asks the view to update itself so as to give feedback to the user in the form of a new display, or a message like 'updated, thanks', etc.,

View = UI that is generated based on a query on the model.

There are no hard and fast rules regarding where business rules should go. In some designs they go into model, whereas in others they are included with the controller. But I think it is better to keep them with the controller. Let the model worry only about database connectivity.

Configuring Git over SSH to login once

Extending Muein's thoughts for those who prefer to edit files directly over running commands in git-bash or terminal.

Go to the .git directory of your project (project root on your local machine) and open the 'config' file. Then look for [remote "origin"] and set the url config as follows:

[remote "origin"]
    #the address part will be different depending upon the service you're using github, bitbucket, unfuddle etc.
    url = [email protected]:<username>/<projectname>.git

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

In my case, I was missing the name of the Angular application in the html file. For example, I had included this file to be start of my application code. I had assumed it was being ran, but it wasn't.

app.module.js

(function () {
    'use strict';

    angular
        .module('app', [
        // Other dependencies here...
        ])
    ;

})();

However, when I declared the app in the html I had this:

index.html

<html lang="en" ng-app>

But to reference the Angular application by the name I used, I had to use:

index.html (Fixed)

<html lang="en" ng-app="app">

How to pass optional arguments to a method in C++?

Here is an example of passing mode as optional parameter

void myfunc(int blah, int mode = 0)
{
    if (mode == 0)
        do_something();
     else
        do_something_else();
}

you can call myfunc in both ways and both are valid

myfunc(10);     // Mode will be set to default 0
myfunc(10, 1);  // Mode will be set to 1

Can I have an onclick effect in CSS?

Edit: Answered before OP clarified what he wanted. The following is for an onclick similar to javascripts onclick, not the :active pseudo class.

This can only be achieved with either Javascript or the Checkbox Hack

The checkbox hack essentially gets you to click on a label, that "checks" a checkbox, allowing you to style the label as you wish.

The demo

Correct format specifier to print pointer or address?

Use %p, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u expects an unsigned int, but what if void* has a different size or alignment requirement than unsigned int?)

*) [See Jonathan's fine answer!] Alternatively to %p, you can use pointer-specific macros from <inttypes.h>, added in C99.

All object pointers are implicitly convertible to void* in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):

printf("x lives at %p.\n", (void*)&x);

Proper MIME type for OTF fonts

Since Feb 2017 RFC 8081 groups all MIME types for fonts under the top level font media type. The older MIME types from my original posting are now listed as deprecated.

Font types as listed by IANA are now:

Other non-standard font formats are left as are:


[Outdated Original Post]

As there's still a lot of confusion on the web about MIME types for web fonts, I thought I'd give a current answer, complete with effective dates, and supporting links to IANA and the W3C.

Here are the official MIME types for Web Fonts:

Note there is a movement to change all the above to MIME types of font/XXX, as backed by the W3C in its proposal for WOFF v2. This is being tracked by the Internet Engineering Task Force (IETF) under The font Top Level Type and in February 2017 was approved RFC status (see RFC 8081) so it may all change yet!

While on the topic of web servers, it's worth mentioning that HTTP responses may gzip (or otherwise compress) all the above font formats except .woff & .woff2 which are already heavily compressed.

I say more in MIME Types for Web Fonts with (Fantom) BedSheet.

How to center form in bootstrap 3

The total columns in a row has to add up to 12. So you can do col-md-4 col-md-offset-4. So your breaking up your columns into 3 groups of 4 columns each. Right now you have a 4 column form with an offset by 6 so you are only getting 2 columns to the right side of your form. You can also do col-md-8 col-md-offset-2 which would give you a 8 column form with 2 columns each of space left and right or col-md-6 col-md-offset-3 (6 column form with 3 columns space on each side), etc.

Symbol for any number of any characters in regex?

Yes, there is one, it's the asterisk: *

a* // looks for 0 or more instances of "a"

This should be covered in any Java regex tutorial or documentation that you look up.

Refresh Page C# ASP.NET

I think this should do the trick (untested):

Page.Response.Redirect(Page.Request.Url.ToString(), true);

Connect to Oracle DB using sqlplus

As David Aldridge explained, your parentheses should start right after the sqlplus command, so it should be:

sqlplus 'test/test@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname.com )(PORT=1521)))(CONNECT_DATA=(SID=mysid))'

Can I try/catch a warning?

Normaly you should never use @ unless this is the only solution. In that specific case the function dns_check_record should be use first to know if the record exists.

Use of "global" keyword in Python

It means that you should not do the following:

x = 1

def myfunc():
  global x

  # formal parameter
  def localfunction(x):
    return x+1

  # import statement
  import os.path as x

  # for loop control target
  for x in range(10):
    print x

  # class definition
  class x(object):
    def __init__(self):
      pass

  #function definition
  def x():
    print "I'm bad"

PyCharm shows unresolved references error for valid code

For me it helped: update your main directory "mark Directory as" -> "source root"

The difference between the Runnable and Callable interfaces in Java

See explanation here.

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

Should I declare Jackson's ObjectMapper as a static field?

com.fasterxml.jackson.databind.type.TypeFactory._hashMapSuperInterfaceChain(HierarchicType)

com.fasterxml.jackson.databind.type.TypeFactory._findSuperInterfaceChain(Type, Class)
  com.fasterxml.jackson.databind.type.TypeFactory._findSuperTypeChain(Class, Class)
     com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(Class, Class, TypeBindings)
        com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(JavaType, Class)
           com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(ParameterizedType, TypeBindings)
              com.fasterxml.jackson.databind.type.TypeFactory._constructType(Type, TypeBindings)
                 com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeReference)
                    com.fasterxml.jackson.databind.ObjectMapper.convertValue(Object, TypeReference)

The method _hashMapSuperInterfaceChain in class com.fasterxml.jackson.databind.type.TypeFactory is synchronized. Am seeing contention on the same at high loads.

May be another reason to avoid a static ObjectMapper

Python recursive folder read

TL;DR: This is the equivalent to find -type f to go over all files in all folders below and including the current one:

for currentpath, folders, files in os.walk('.'):
    for file in files:
        print(os.path.join(currentpath, file))

As already mentioned in other answers, os.walk() is the answer, but it could be explained better. It's quite simple! Let's walk through this tree:

docs/
+-- doc1.odt
pics/
todo.txt

With this code:

for currentpath, folders, files in os.walk('.'):
    print(currentpath)

The currentpath is the current folder it is looking at. This will output:

.
./docs
./pics

So it loops three times, because there are three folders: the current one, docs, and pics. In every loop, it fills the variables folders and files with all folders and files. Let's show them:

for currentpath, folders, files in os.walk('.'):
    print(currentpath, folders, files)

This shows us:

# currentpath  folders           files
.              ['pics', 'docs']  ['todo.txt']
./pics         []                []
./docs         []                ['doc1.odt']

So in the first line, we see that we are in folder ., that it contains two folders namely pics and docs, and that there is one file, namely todo.txt. You don't have to do anything to recurse into those folders, because as you see, it recurses automatically and just gives you the files in any subfolders. And any subfolders of that (though we don't have those in the example).

If you just want to loop through all files, the equivalent of find -type f, you can do this:

for currentpath, folders, files in os.walk('.'):
    for file in files:
        print(os.path.join(currentpath, file))

This outputs:

./todo.txt
./docs/doc1.odt

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

How does Go update third-party packages?

To specify versions, or commits:

go get -u [email protected]

go get -u otherpackage@git-sha

See https://github.com/golang/go/wiki/Modules#daily-workflow

How do you copy the contents of an array to a std::vector in C++ without looping?

Yet another answer, since the person said "I don't know how many times my function will be called", you could use the vector insert method like so to append arrays of values to the end of the vector:

vector<int> x;

void AddValues(int* values, size_t size)
{
   x.insert(x.end(), values, values+size);
}

I like this way because the implementation of the vector should be able to optimize for the best way to insert the values based on the iterator type and the type itself. You are somewhat replying on the implementation of stl.

If you need to guarantee the fastest speed and you know your type is a POD type then I would recommend the resize method in Thomas's answer:

vector<int> x;

void AddValues(int* values, size_t size)
{
   size_t old_size(x.size());
   x.resize(old_size + size, 0);
   memcpy(&x[old_size], values, size * sizeof(int));
}

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Be sure to remember to invoke json.loads() on the contents of the file, as opposed to the file path of that JSON:

json_file_path = "/path/to/example.json"

with open(json_file_path, 'r') as j:
     contents = json.loads(j.read())

I think a lot of people are guilty of doing this every once in a while (myself included):

contents = json.loads(json_file_path)

How to initialize a vector in C++

You can also do like this:

template <typename T>
class make_vector {
public:
  typedef make_vector<T> my_type;
  my_type& operator<< (const T& val) {
    data_.push_back(val);
    return *this;
  }
  operator std::vector<T>() const {
    return data_;
  }
private:
  std::vector<T> data_;
};

And use it like this:

std::vector<int> v = make_vector<int>() << 1 << 2 << 3;

How to make an Android device vibrate? with different frequency?

Vibrate without using permission

If you want to simply vibrate the device once to provide a feedback on a user action. You can use performHapticFeedback() function of a View. This doesn't need the VIBRATE permission to be declared in the manifest.

Use the following function as a top level function in some common class like Utils.kt of your project:

/**
 * Vibrates the device. Used for providing feedback when the user performs an action.
 */
fun vibrate(view: View) {
    view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}

And then use it anywhere in your Fragment or Activity as following:

vibrate(requireView())

Simple as that!

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

You might check Select2 plugin:

http://ivaynberg.github.io/select2/

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

It's quite popular and very maintainable. It should cover most of your needs if not all.

Input and Output binary streams using JERSEY?

I managed to get a ZIP file or a PDF file by extending the StreamingOutput object. Here is some sample code:

@Path("PDF-file.pdf/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
    return new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                PDFGenerator generator = new PDFGenerator(getEntity());
                generator.generatePDF(output);
            } catch (Exception e) {
                throw new WebApplicationException(e);
            }
        }
    };
}

The PDFGenerator class (my own class for creating the PDF) takes the output stream from the write method and writes to that instead of a newly created output stream.

Don't know if it's the best way to do it, but it works.

What's HTML character code 8203?

If you want to search for these invisible characters in your editor and make them visible, you can use a Regular Expression searching for non-ascii characters. Try searching for [^\x00-\x7F]. Tested in IntelliJ IDEA.

How to check if an element is in an array

Just in case anybody is trying to find if an indexPath is among the selected ones (like in a UICollectionView or UITableView cellForItemAtIndexPath functions):

    var isSelectedItem = false
    if let selectedIndexPaths = collectionView.indexPathsForSelectedItems() as? [NSIndexPath]{
        if contains(selectedIndexPaths, indexPath) {
            isSelectedItem = true
        }
    }

Convert date to UTC using moment.js

This is found in the documentation. With a library like moment, I urge you to read the entirety of the documentation. It's really important.

Assuming the input text is entered in terms of the users's local time:

 var expires = moment(date).valueOf();

If the user is instructed actually enter a UTC date/time, then:

 var expires = moment.utc(date).valueOf();

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

How to detect a textbox's content has changed

Start observing 'input' event instead of 'change'.

jQuery('#some_text_box').on('input', function() {
    // do your stuff
});

...which is nice and clean, but may be extended further to:

jQuery('#some_text_box').on('input propertychange paste', function() {
    // do your stuff
});

How do I print my Java object without getting "SomeType@2f92e0f4"?

I think apache provides a better util class which provides a function to get the string

ReflectionToStringBuilder.toString(object)

How to normalize a 2-dimensional numpy array in python less verbose?

Broadcasting is really good for this:

row_sums = a.sum(axis=1)
new_matrix = a / row_sums[:, numpy.newaxis]

row_sums[:, numpy.newaxis] reshapes row_sums from being (3,) to being (3, 1). When you do a / b, a and b are broadcast against each other.

You can learn more about broadcasting here or even better here.

How to send POST request in JSON using HTTPClient in Android?

Here is an alternative solution to @Terrance's answer. You can easly outsource the conversion. The Gson library does wonderful work converting various data structures into JSON and the other way around.

public static void execute() {
    Map<String, String> comment = new HashMap<String, String>();
    comment.put("subject", "Using the GSON library");
    comment.put("message", "Using libraries is convenient.");
    String json = new GsonBuilder().create().toJson(comment, Map.class);
    makeRequest("http://192.168.0.1:3000/post/77/comments", json);
}

public static HttpResponse makeRequest(String uri, String json) {
    try {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(new StringEntity(json));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        return new DefaultHttpClient().execute(httpPost);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Similar can be done by using Jackson instead of Gson. I also recommend taking a look at Retrofit which hides a lot of this boilerplate code for you. For more experienced developers I recommend trying out RxAndroid.

jQuery multiselect drop down menu

Update (2017): The following two libraries have now become the most common drop-down libraries used with Javascript. While they are jQuery-native, they have been customized to work with everything from AngularJS 1.x to having custom CSS for Bootstrap. (Chosen JS, the original answer here, seems to have dropped to #3 in popularity.)

Obligatory screenshots below.

Select2: Select2

Selectize: Selectize


Original answer (2012): I think that the Chosen library might also be useful. Its available in jQuery, Prototype and MooTools versions.

Attached is a screenshot of how the multi-select functionality looks in Chosen.

Chosen library

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

LEFT function in Oracle

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

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

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

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

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

Notice that a negative number counts back from the end.

npm start error with create-react-app

It occurred to me but none of the above worked.

events.js:72
        throw er; // Unhandled 'error' event
              ^

npm ERR! [email protected] start: `react-scripts start`
npm ERR! spawn ENOENT

Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

This happens because you might have installed react-scripts globally.

To make this work...

  1. Go to your C:\Users\<USER>\AppData\Roaming
  2. Delete npm and npm-cache directories... (don't worry you can install npm globally later)
  3. Go back to your application directory and remove node_modules folder
  4. Now enter npm install to install the dependencies (delete package-lock.json if its already created)
  5. Now run npm install --save react react-dom react-scripts
  6. Get it started with npm start

This should get you back on track... Happy Coding

Cut off text in string after/before separator in powershell

Using regex, the result is in $matches[1]:

$str = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"
$str -match "^(.*?)\s\;"
$matches[1]
test.txt

CSS to select/style first word

Use the strong element, that is it's purpose:

<div id="content">
    <p><strong>First Word</strong> rest of paragraph.</p>
</div>

Then create a style for it in your style sheet.

#content p strong
{
    font-size: 14pt;
}

How to "z-index" to make a menu always on top of the content

you could put the style in container div menu with:

<div style="position:relative; z-index:10">
   ...
   <!--html menu-->
   ...
</div>

before enter image description here

after

enter image description here

For homebrew mysql installs, where's my.cnf?

For MacOS (High Sierra), MySQL that has been installed with home brew.

Increasing the global variables from mysql environment was not successful. So in that case creating of ~/.my.cnf is the safest option. Adding variables with [mysqld] will include the changes (Note: if you change with [mysql] , the change might not work).

<~/.my.cnf> [mysqld] connect_timeout = 43200 max_allowed_packet = 2048M net_buffer_length = 512M

Restart the mysql server. and check the variables. y

sql> SELECT @@max_allowed_packet; +----------------------+ | @@max_allowed_packet | +----------------------+ | 1073741824 | +----------------------+

1 row in set (0.00 sec)

Height equal to dynamic width (CSS fluid layout)

Extremely simple method jsfiddle

HTML

<div id="container">
    <div id="element">
        some text
    </div>
</div>

CSS

#container {
    width: 50%; /* desired width */
}

#element {
    height: 0;
    padding-bottom: 100%;
}

Get custom product attributes in Woocommerce

Try this to get an array of attribute name => attribute value(s):

global $product;

$formatted_attributes = array();

$attributes = $product->get_attributes();

foreach($attributes as $attr=>$attr_deets){

    $attribute_label = wc_attribute_label($attr);

    if ( isset( $attributes[ $attr ] ) || isset( $attributes[ 'pa_' . $attr ] ) ) {

        $attribute = isset( $attributes[ $attr ] ) ? $attributes[ $attr ] : $attributes[ 'pa_' . $attr ];

        if ( $attribute['is_taxonomy'] ) {

            $formatted_attributes[$attribute_label] = implode( ', ', wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) ) );

        } else {

            $formatted_attributes[$attribute_label] = $attribute['value'];
        }

    }
}

//print_r($formatted_attributes);

return $formatted_attributes;

It's little inefficient but does the trick.

How to edit my Excel dropdown list?

Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.

how to get all markers on google-maps-v3

If you are using JQuery Google map plug-in then below code will work for you -

var markers = $('#map_canvas').gmap('get','markers');

Cannot open include file 'afxres.h' in VC2010 Express

Had the same problem . Fixed it by installing Microsoft Foundation Classes for C++.

  1. Start
  2. Change or remove program (type)
  3. Microsoft Visual Studio
  4. Modify
  5. Select 'Microsoft Foundation Classes for C++'
  6. Update

enter image description here

PHP: Call to undefined function: simplexml_load_string()

Make sure that you have php-xml module installed and enabled in php.ini.

You can also change response format to json which is easier to handle. In that case you have to only add &format=json to url query string.

$rest_url = "http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls=".urlencode($source_url);

And then use json_decode() to retrieve data in your script:

$result = json_decode($content, true);
$fb_like_count = $result['like_count'];

How to change the button color when it is active using bootstrap?

CSS has many pseudo selector like, :active, :hover, :focus, so you can use.

Html

<div class="col-sm-12" id="my_styles">
     <button type="submit" class="btn btn-warning" id="1">Button1</button>
     <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css

.btn{
    background: #ccc;
} .btn:focus{
    background: red;
}

JsFiddle

HTML CSS Button Positioning

as I expected, yeah, it's because the whole DOM element is being pushed down. You have multiple options. You can put the buttons in separate divs, and float them so that they don't affect each other. the simpler solution is to just set the :active button to position:relative; and use top instead of margin or line-height. example fiddle: http://jsfiddle.net/5CZRP/

How to change Android usb connect mode to charge only?

Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.

How to find the duration of difference between two dates in java?

java.time.Duration

I still didn’t feel any of the answers was quite up to date and to the point. So here is the modern answer using Duration from java.time, the modern Java date and time API (the answers by MayurB and mkobit mention the same class, but none of them correctly converts to days, hours, minutes and minutes as asked).

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss");
    
    String dateStart = "11/03/14 09:29:58";
    String dateStop = "11/03/14 09:33:43";

    ZoneId zone = ZoneId.systemDefault();
    ZonedDateTime startDateTime = LocalDateTime.parse(dateStart, formatter).atZone(zone);
    ZonedDateTime endDateTime = LocalDateTime.parse(dateStop, formatter).atZone(zone);
    
    Duration diff = Duration.between(startDateTime, endDateTime);
    if (diff.isZero()) {
        System.out.println("0 minutes");
    } else {
        long days = diff.toDays();
        if (days != 0) {
            System.out.print("" + days + " days ");
            diff = diff.minusDays(days);
        }
        long hours = diff.toHours();
        if (hours != 0) {
            System.out.print("" + hours + " hours ");
            diff = diff.minusHours(hours);
        }
        long minutes = diff.toMinutes();
        if (minutes != 0) {
            System.out.print("" + minutes + " minutes ");
            diff = diff.minusMinutes(minutes);
        }
        long seconds = diff.getSeconds();
        if (seconds != 0) {
            System.out.print("" + seconds + " seconds ");
        }
        System.out.println();
    }

Output from this example snippet is:

3 minutes 45 seconds

Note that Duration always counts a day as 24 hours. If you want to treat time anomalies like summer time transistions differently, solutions inlcude (1) use ChronoUnit.DAYS (2) Use Period (3) Use LocalDateTimeinstead ofZonedDateTime` (may be considered a hack).

The code above works with Java 8 and with ThreeTen Backport, that backport of java.time to Java 6 and 7. From Java 9 it may be possible to write it a bit more nicely using the methods toHoursPart, toMinutesPart and toSecondsPart added there.

I will elaborate the explanations further one of the days when I get time, maybe not until next week.

How to obtain the start time and end time of a day?

Java 8 or ThreeTenABP

ZonedDateTime

ZonedDateTime curDate = ZonedDateTime.now();

public ZonedDateTime startOfDay() {
    return curDate
    .toLocalDate()
    .atStartOfDay()
    .atZone(curDate.getZone())
    .withEarlierOffsetAtOverlap();
}

public ZonedDateTime endOfDay() {

    ZonedDateTime startOfTomorrow =
        curDate
        .toLocalDate()
        .plusDays(1)
        .atStartOfDay()
        .atZone(curDate.getZone())
        .withEarlierOffsetAtOverlap();

    return startOfTomorrow.minusSeconds(1);
}

// based on https://stackoverflow.com/a/29145886/1658268

LocalDateTime

LocalDateTime curDate = LocalDateTime.now();

public LocalDateTime startOfDay() {
    return curDate.atStartOfDay();
}

public LocalDateTime endOfDay() {
    return startOfTomorrow.atTime(LocalTime.MAX);  //23:59:59.999999999;
}

// based on https://stackoverflow.com/a/36408726/1658268

I hope that helps someone.

Playing mp3 song on python

At this point, why not mentioning python-audio-tools:

It's the best solution I found.

(I needed to install libasound2-dev, on Raspbian)

Code excerpt loosely based on:
https://github.com/tuffy/python-audio-tools/blob/master/trackplay

#!/usr/bin/python

import os
import re
import audiotools.player


START = 0
INDEX = 0

PATH = '/path/to/your/mp3/folder'

class TracklistPlayer:
    def __init__(self,
                 tr_list,
                 audio_output=audiotools.player.open_output('ALSA'),  
                 replay_gain=audiotools.player.RG_NO_REPLAYGAIN,
                 skip=False):

        if skip:
            return

        self.track_index = INDEX + START - 1
        if self.track_index < -1:
            print('--> [track index was negative]')
            self.track_index = self.track_index + len(tr_list)

        self.track_list = tr_list

        self.player = audiotools.player.Player(
                audio_output,
                replay_gain,
                self.play_track)

        self.play_track(True, False)

    def play_track(self, forward=True, not_1st_track=True):
        try:
            if forward:
                self.track_index += 1
            else:
                self.track_index -= 1

            current_track = self.track_list[self.track_index]
            audio_file = audiotools.open(current_track)
            self.player.open(audio_file)
            self.player.play()

            print('--> index:   ' + str(self.track_index))
            print('--> PLAYING: ' + audio_file.filename)

            if not_1st_track:
                pass  # here I needed to do something :)

            if forward:
                pass  # ... and also here

        except IndexError:
            print('\n--> playing finished\n')

    def toggle_play_pause(self):
        self.player.toggle_play_pause()

    def stop(self):
        self.player.stop()

    def close(self):
        self.player.stop()
        self.player.close()


def natural_key(el):
    """See http://www.codinghorror.com/blog/archives/001018.html"""
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', el)]


def natural_cmp(a, b):
    return cmp(natural_key(a), natural_key(b))


if __name__ == "__main__":

    print('--> path:    ' + PATH)

    # remove hidden files (i.e. ".thumb")
    raw_list = filter(lambda element: not element.startswith('.'), os.listdir(PATH))

    # mp3 and wav files only list
    file_list = filter(lambda element: element.endswith('.mp3') | element.endswith('.wav'), raw_list)

    # natural order sorting
    file_list.sort(key=natural_key, reverse=False)

    track_list = []
    for f in file_list:
        track_list.append(os.path.join(PATH, f))


    TracklistPlayer(track_list)

Failed to execute removeChild on Node

The direct parent of your child is markerDiv, so you should call remove from markerDiv as so:

markerDiv.removeChild(myCoolDiv);

Alternatively, you may want to remove markerNode. Since that node was appended directly to videoContainer, it can be removed with:

document.getElementById("playerContainer").removeChild(markerDiv);

Now, the easiest general way to remove a node, if you are absolutely confident that you did insert it into the DOM, is this:

markerDiv.parentNode.removeChild(markerDiv);

This works for any node (just replace markerDiv with a different node), and finds the parent of the node directly in order to call remove from it. If you are unsure if you added it, double check if the parentNode is non-null before calling removeChild.

Call a python function from jinja2

To call a python function from Jinja2, you can use custom filters which work similarly as the globals: http://jinja.pocoo.org/docs/dev/api/#writing-filters

It's quite simple and useful. In a file myTemplate.txt, I wrote:

{{ data|pythonFct }}

And in a python script:

import jinja2

def pythonFct(data):
    return "This is my data: {0}".format(data)

input="my custom filter works!"

loader = jinja2.FileSystemLoader(path or './')
env = jinja2.Environment(loader=loader)
env.filters['pythonFct'] = pythonFct
result = env.get_template("myTemplate.txt").render(data=input)
print(result)

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

The first things I would look for are color - like RED , when doing Red eye detection in an image - there is a certain color range to detect , some characteristics about it considering the surrounding area and such as distance apart from the other eye if it is indeed visible in the image.

1: First characteristic is color and Red is very dominant. After detecting the Coca Cola Red there are several items of interest 1A: How big is this red area (is it of sufficient quantity to make a determination of a true can or not - 10 pixels is probably not enough), 1B: Does it contain the color of the Label - "Coca-Cola" or wave. 1B1: Is there enough to consider a high probability that it is a label.

Item 1 is kind of a short cut - pre-process if that doe snot exist in the image - move on.

So if that is the case I can then utilize that segment of my image and start looking more zoom out of the area in question a little bit - basically look at the surrounding region / edges...

2: Given the above image area ID'd in 1 - verify the surrounding points [edges] of the item in question. A: Is there what appears to be a can top or bottom - silver? B: A bottle might appear transparent , but so might a glass table - so is there a glass table/shelf or a transparent area - if so there are multiple possible out comes. A Bottle MIGHT have a red cap, it might not, but it should have either the shape of the bottle top / thread screws, or a cap. C: Even if this fails A and B it still can be a can - partial.. This is more complex when it is partial because a partial bottle / partial can might look the same , so some more processing of measurement of the Red region edge to edge.. small bottle might be similar in size ..

3: After the above analysis that is when I would look at the lettering and the wave logo - because I can orient my search for some of the letters in the words As you might not have all of the text due to not having all of the can, the wave would align at certain points to the text (distance wise) so I could search for that probability and know which letters should exist at that point of the wave at distance x.

Twitter-Bootstrap-2 logo image on top of navbar

You should remove navbar-fixed-top class otherwise navbar stays fixed on top of page where you want logo.


If you want to place logo inside navbar:

Navbar height (set in @navbarHeight LESS variable) is 40px by default. Your logo has to fit inside or you have to make navbar higher first.

Then use brand class:

<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">
      <a href="/" class="brand"><img alt="" src="/logo.gif" /></a>
    </div>
  </div>
</div>

If your logo is higher than 20px, you have to fix stylesheets as well.

If you do that in LESS:

.navbar .brand {
  @elementHeight: 32px;
  padding: ((@navbarHeight - @elementHeight) / 2 - 2) 20px ((@navbarHeight - @elementHeight) / 2 + 2);
}

@elementHeight should be set to your image height.

Padding calculation is taken from Twitter Bootstrap LESS - https://github.com/twitter/bootstrap/blob/v2.0.4/less/navbar.less#L51-52

Alternatively you can calculate padding values yourself and use pure CSS.

This works for Twitter Bootstrap versions 2.0.x, should work in 2.1 as well, but padding calculation was changed a bit: https://github.com/twitter/bootstrap/blob/v2.1.0/less/navbar.less#L50

Identifying country by IP address

I think what you're looking for is an IP Geolocation database or service provider. There are many out there and some are free (get what you pay for).

Although I haven't used this service before, it claims to be in real-time. https://kickfire.com/kf-api

Here's another IP geo location API from Abstract API - https://www.abstractapi.com/ip-geolocation-api

But just do a google search on IP geo and you'll get more results than you need.

How to use a Java8 lambda to sort a stream in reverse order?

In simple, using Comparator and Collection you can sort like below in reversal order using JAVA 8

import java.util.Comparator;;
import java.util.stream.Collectors;

Arrays.asList(files).stream()
    .sorted(Comparator.comparing(File::getLastModified).reversed())
    .collect(Collectors.toList());

Populating a razor dropdownlist from a List<object> in MVC

@model AdventureWork.CRUD.WebApp4.Models.EmployeeViewModel
@{
    ViewBag.Title = "Detalle";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Ingresar Usuario</h2>

@using (Html.BeginForm())
{

    @Html.AntiForgeryToken()
<div class="form-horizontal">


    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.PersonType, labelText: "Tipo de Persona", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.PersonType, new List<SelectListItem>
       {
               new SelectListItem{ Text= "SC", Value = "SC" },
               new SelectListItem{ Text= "VC", Value = "VC" },
                  new SelectListItem{ Text= "IN", Value = "IN" },
               new SelectListItem{ Text= "EM", Value = "EM" },
                new SelectListItem{ Text= "SP", Value = "SP" },

       }, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.PersonType, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.EmployeeGender, labelText: "Genero", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.EmployeeGender, new List<SelectListItem>
       {
           new SelectListItem{ Text= "Masculino", Value = "M" },
           new SelectListItem{ Text= "Femenino", Value = "F" }
       }, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.EmployeeGender, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.PersonTitle, labelText: "Titulo", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.PersonTitle, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.PersonTitle, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.PersonFirstName, labelText: "Primer Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.PersonFirstName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.PersonFirstName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.PersonMiddleName, labelText: "Segundo Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.PersonMiddleName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.PersonMiddleName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.PersonLastName, labelText: "Apellido", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.PersonLastName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.PersonLastName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.PersonSuffix, labelText: "Sufijo", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.PersonSuffix, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.PersonSuffix, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.DepartmentID, labelText: "Departamento", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.DepartmentID, new SelectList(Model.ListDepartment, "DepartmentID", "DepartmentName"), htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.DepartmentID, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="form-group">
        @Html.LabelFor(model => model.Employee.EmployeeMaritalStatus, labelText: "Estado Civil", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.EmployeeMaritalStatus, new List<SelectListItem>
       {
           new SelectListItem{ Text= "Soltero", Value = "S" },
           new SelectListItem{ Text= "Casado", Value = "M" }
       }, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.EmployeeMaritalStatus, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.ShiftId, labelText: "Turno", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.ShiftId, new SelectList(Model.ListShift, "ShiftId", "ShiftName"), htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.ShiftId, "", new { @class = "text-danger" })
        </div>
    </div>



    <div class="form-group">
        @Html.LabelFor(model => model.Employee.EmployeeLoginId, labelText: "Login", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.EmployeeLoginId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.EmployeeLoginId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.EmployeeNationalIDNumber, labelText: "Identificacion Nacional", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.EmployeeNationalIDNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.EmployeeNationalIDNumber, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.EmployeeJobTitle, labelText: "Cargo", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.EmployeeJobTitle, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.EmployeeJobTitle, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.EmployeeBirthDate, labelText: "Fecha Nacimiento", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.EmployeeBirthDate, new { htmlAttributes = new { @class = "form-control datepicker" } })
            @Html.ValidationMessageFor(model => model.Employee.EmployeeBirthDate, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.EmployeeSalariedFlag, labelText: "Asalariado", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.EmployeeSalariedFlag, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.EmployeeSalariedFlag, "", new { @class = "text-danger" })
        </div>
    </div>



    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Guardar" class="btn btn-default" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10" style="color:green">
            @ViewBag.Message
        </div>
        <div class="col-md-offset-2 col-md-10" style="color:red">
            @ViewBag.ErrorMessage
        </div>
    </div>
</div>


}

Call Jquery function

To call the function on click of some html element (control).

$('#controlID').click(myFunction);

You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready

$(document).ready(function(){
    $('#controlID').click(myFunction);
});

You can use anonymous function to bind the event to the html element.

$(document).ready(function(){
    $('#controlID').click(function(){
         $.messager.show({  
            title:'My Title',  
            msg:'The message content',  
            showType:'fade',  
            style:{  
                right:'',  
                bottom:''  
            }  
        });  
    });
});

If you want to bind click with many elements you can use class selector

$('.someclass').click(myFunction);

Edit based on comments by OP, If you want to call function under some condition

You can use if for conditional execution, for example,

if(a == 3)
     myFunction();

How to create a link to a directory

you should use :

ln -s /home/jake/doc/test/2000/something xxx

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

If you want to split the data set once in two halves, you can use numpy.random.shuffle, or numpy.random.permutation if you need to keep track of the indices:

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
numpy.random.shuffle(x)
training, test = x[:80,:], x[80:,:]

or

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
indices = numpy.random.permutation(x.shape[0])
training_idx, test_idx = indices[:80], indices[80:]
training, test = x[training_idx,:], x[test_idx,:]

There are many ways to repeatedly partition the same data set for cross validation. One strategy is to resample from the dataset, with repetition:

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
training_idx = numpy.random.randint(x.shape[0], size=80)
test_idx = numpy.random.randint(x.shape[0], size=20)
training, test = x[training_idx,:], x[test_idx,:]

Finally, sklearn contains several cross validation methods (k-fold, leave-n-out, ...). It also includes more advanced "stratified sampling" methods that create a partition of the data that is balanced with respect to some features, for example to make sure that there is the same proportion of positive and negative examples in the training and test set.

Modal width (increase)

For responsive answer.

@media (min-width: 992px) {
  .modal-dialog {
    max-width: 80%;
  }
}

How to revert to origin's master branch's version of file

If you didn't commit it to the master branch yet, its easy:

  • get off the master branch (like git checkout -b oops/fluke/dang)
  • commit your changes there (like git add -u; git commit;)
  • go back the master branch (like git checkout master)

Your changes will be saved in branch oops/fluke/dang; master will be as it was.

Finding the next available id in MySQL

If this is used in conjunction for INSERTING a new record you could use something like this.

(You've stated in your comments that the id is auto incrementing and the other table needs the next ID + 1)

INSERT INTO TABLE2 (id, field1, field2, field3, etc) 
VALUES(
   SELECT (MAX(id) + 1), field1, field2, field3, etc FROM TABLE1
   WHERE condition_here_if_needed
)

This is pseudocode but you get the idea

How to `wget` a list of URLs in a text file?

If you're on OpenWrt or using some old version of wget which doesn't gives you -i option:

#!/bin/bash
input="text_file.txt"
while IFS= read -r line
do
  wget $line
done < "$input"

Furthermore, if you don't have wget, you can use curl or whatever you use for downloading individual files.

How does HTTP_USER_AGENT work?

The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

On Duplicate Key Update same as insert

There is no other way, I have to specify everything twice. First for the insert, second in the update case.

How to split data into 3 sets (train, validation and test)?

In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output). You just have to pay attention to shuffle X and y the same way before splitting.

Here, either X and y are in the same dataframe, so we shuffle them, separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.

# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]

# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]

# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])

XML string to XML document

Try this code:

var myXmlDocument = new XmlDocument();
myXmlDocument.LoadXml(theString);

./xx.py: line 1: import: command not found

Are you using a UNIX based OS such as Linux? If so, add a shebang line to the very top of your script:

#!/usr/bin/python

Underneath which you would have the rest of the code (xx.py in your case) that you already have. Then run that same command at the terminal:

$ python xx.py

This should then work fine, as it is now interpreting this as Python code. However when running from the terminal this does not matter as python tells how to interpret it here. What it does allow you to do is execute it outside the terminal, i.e. executing it from a file browser.

How to convert a string to lower or upper case in Ruby

The .swapcase method transforms the uppercase latters in a string to lowercase and the lowercase letters to uppercase.

'TESTING'.swapcase #=> testing
'testing'.swapcase #=> TESTING

PHP Error: Cannot use object of type stdClass as array (array and object issues)

$blog is an object, not an array, so you should access it like so:

$blog->id;
$blog->title;
$blog->content;

IIS w3svc error

I have had this problem after a windows update. Windows Process Activation Service is dependent service for W3SVC. First, make sure that Windows Process Activation Service is running. In my case, it was not running and when I tried to run it manually, I got below error.

Windows Process Activation Service Error 2: The system cannot find the file specified

The issue seems to be, that windows adds an incorrect parameter to the WAS service startup parameters. I fixed the issue using the following steps:

  • Start regedit (just type it into start) Navigate to

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WAS\Parameters

  • Delete the NanoSetup variable. This variable is preventing WAS from starting

  • Start the WAS service using task manager

  • Now start the W3SVC service

  • You can now start your website in IIS again

I found above WPA service solution in this stack overflow thread.

Anchor links in Angularjs?

There are a few ways to do this it seems.

Option 1: Native Angular

Angular provides an $anchorScroll service, but the documentation is severely lacking and I've not been able to get it to work.

Check out http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html for some insight into $anchorScroll.

Option 2: Custom Directive / Native JavaScript

Another way I tested out was creating a custom directive and using el.scrollIntoView(). This works pretty decently by basically doing the following in your directive link function:

var el = document.getElementById(attrs.href);
el.scrollIntoView();

However, it seems a bit overblown to do both of these when the browser natively supports this, right?

Option 3: Angular Override / Native Browser

If you take a look at http://docs.angularjs.org/guide/dev_guide.services.$location and its HTML Link Rewriting section, you'll see that links are not rewritten in the following:

Links that contain target element

Example: <a href="/ext/link?a=b" target="_self">link</a>

So, all you have to do is add the target attribute to your links, like so:

<a href="#anchorLinkID" target="_self">Go to inpage section</a>

Angular defaults to the browser and since its an anchor link and not a different base url, the browser scrolls to the correct location, as desired.

I went with option 3 because its best to rely on native browser functionality here, and saves us time and effort.

Gotta note that after a successful scroll and hash change, Angular does follow up and rewrite the hash to its custom style. However, the browser has already completed its business and you are good to go.

len() of a numpy array in python

Easy. Use .shape.

>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.

Modify a Column's Type in sqlite3

It is possible by dumping, editing and reimporting the table.

This script will do it for you (Adapt the values at the start of the script to your needs):

#!/bin/bash

DB=/tmp/synapse/homeserver.db
TABLE="public_room_list_stream"
FIELD=visibility
OLD="BOOLEAN NOT NULL"
NEW="INTEGER NOT NULL"
TMP=/tmp/sqlite_$TABLE.sql

echo "### create dump"
echo ".dump '$TABLE'" | sqlite3 "$DB" >$TMP

echo "### editing the create statement"
sed -i "s|$FIELD $OLD|$FIELD $NEW|g" $TMP

read -rsp $'Press any key to continue deleting and recreating the table $TABLE ...\n' -n1 key 

echo "### rename the original to '$TABLE"_backup"'"
sqlite3 "$DB" "PRAGMA busy_timeout=20000; ALTER TABLE '$TABLE' RENAME TO '$TABLE"_backup"'"

echo "### delete the old indexes"
for idx in $(echo "SELECT name FROM sqlite_master WHERE type == 'index' AND tbl_name LIKE '$TABLE""%';" | sqlite3 $DB); do
  echo "DROP INDEX '$idx';" | sqlite3 $DB
done

echo "### reinserting the edited table"
cat $TMP | sqlite3 $DB

How to open a new file in vim in a new window

I'm using the following, though it's hardcoded for gnome-terminal. It also changes the CWD and buffer for vim to be the same as your current buffer and it's directory.

:silent execute '!gnome-terminal -- zsh -i -c "cd ' shellescape(expand("%:h")) '; vim' shellescape(expand("%:p")) '; zsh -i"' <cr>

Why should hash functions use a prime number modulus?

http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/

Pretty clear explanation, with pictures too.

Edit: As a summary, primes are used because you have the best chance of obtaining a unique value when multiplying values by the prime number chosen and adding them all up. For example given a string, multiplying each letter value with the prime number and then adding those all up will give you its hash value.

A better question would be, why exactly the number 31?

Why can I not switch branches?

you can reset your branch with HEAD

git reset --hard branch_name

then fetch branches and delete branches which are not on remote from local,

git fetch -p 

How to post JSON to a server using C#?

WARNING! I have a very strong view on this subject.

.NET’s existing web clients are not developer friendly! WebRequest & WebClient are prime examples of "how to frustrate a developer". They are verbose & complicated to work with; when all you want to do is a simple Post request in C#. HttpClient goes some way in addressing these issues, but it still falls short. On top of that Microsoft’s documentation is bad … really bad; unless you want to sift through pages and pages of technical blurb.

Open-source to the rescue. There are three excellent open-source, free NuGet libraries as alternatives. Thank goodness! These are all well supported, documented and yes, easy - correction…super easy - to work with.

There is not much between them, but I would give ServiceStack.Text the slight edge …

  • Github stars are roughly the same.
  • Open Issues & importantly how quickly any issues closed down? ServiceStack takes the award here for the fastest issue resolution & no open issues.
  • Documentation? All have great documentation; however, ServiceStack takes it to the next level & is known for its ‘Golden standard’ for documentation.

Ok - so what does a Post Request in JSON look like within ServiceStack.Text?

var response = "http://example.org/login"
    .PostJsonToUrl(new Login { Username="admin", Password="mypassword" });

That is one line of code. Concise & easy! Compare the above to .NET’s Http libraries.

Invoking a static method using reflection

String methodName= "...";
String[] args = {};

Method[] methods = clazz.getMethods();
for (Method m : methods) {
    if (methodName.equals(m.getName())) {
        // for static methods we can use null as instance of class
        m.invoke(null, new Object[] {args});
        break;
    }
}

How to Maximize window in chrome using webDriver (python)

This works for me, with Mac OS Sierra using Python,

options = webdriver.ChromeOptions()
options.add_argument("--kiosk")
driver = webdriver.Chrome(chrome_options=options)

How to get DataGridView cell value in messagebox?

      try
        {

            for (int rows = 0; rows < dataGridView1.Rows.Count; rows++)
            {

                for (int col = 0; col < dataGridView1.Rows[rows].Cells.Count; col++)
                {
                    s1 = dataGridView1.Rows[0].Cells[0].Value.ToString();
                    label20.Text = s1;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("try again"+ex);
        }

How to refresh Gridview after pressed a button in asp.net

Before data bind change gridview databinding method, assign GridView.EditIndex to -1. It solved the same issue for me :

 gvTypes.EditIndex = -1;
 gvTypes.DataBind();

gvTypes is my GridView ID.

how to filter out a null value from spark dataframe

val df = Seq(
  ("1001", "1007"),
  ("1002", null),
  ("1003", "1005"),
  (null, "1006")
).toDF("user_id", "friend_id")

Data is:

+-------+---------+
|user_id|friend_id|
+-------+---------+
|   1001|     1007|
|   1002|     null|
|   1003|     1005|
|   null|     1006|
+-------+---------+

Drop rows containing any null or NaN values in the specified columns of the Seq:

df.na.drop(Seq("friend_id"))
  .show()

Output:

+-------+---------+
|user_id|friend_id|
+-------+---------+
|   1001|     1007|
|   1003|     1005|
|   null|     1006|
+-------+---------+

If do not specify columns, drop row as long as any column of a row contains null or NaN values:

df.na.drop()
  .show()

Output:

+-------+---------+
|user_id|friend_id|
+-------+---------+
|   1001|     1007|
|   1003|     1005|
+-------+---------+

Jquery to open Bootstrap v3 modal of remote url

e.relatedTarget.data('load-url'); won't work
use dataset.loadUrl

$('#myModal').on('show.bs.modal', function (e) {
    var loadurl = e.relatedTarget.dataset.loadUrl;
    $(this).find('.modal-body').load(loadurl);
});

Datatables: Cannot read property 'mData' of undefined

A common cause for Cannot read property 'fnSetData' of undefined is the mismatched number of columns, like in this erroneous code:

<thead>                 <!-- thead required -->
    <tr>                <!-- tr required -->
        <th>Rep</th>    <!-- td instead of th will also work -->
        <th>Titel</th>
                        <!-- th missing here -->
    </tr>
</thead>
<tbody>
    <tr>
        <td>Rep</td>
        <td>Titel</td>
        <td>Missing corresponding th</td>
    </tr>
</tbody>

While the following code with one <th> per <td> (number of columns must match) works:

<thead>
    <tr>
        <th>Rep</th>       <!-- 1st column -->
        <th>Titel</th>     <!-- 2nd column -->
        <th>Added th</th>  <!-- 3rd column; th added here -->
    </tr>
</thead>
<tbody>
    <tr>
        <td>Rep</td>             <!-- 1st column -->
        <td>Titel</td>           <!-- 2nd column -->
        <td>th now present</td>  <!-- 3rd column -->
    </tr>
</tbody>

The error also appears when using a well-formed thead with a colspan but without a second row.

For a table with 7 colums, the following does not work and we see "Cannot read property 'mData' of undefined" in the javascript console:

<thead>
    <tr>
        <th>Rep</th>
        <th>Titel</th>
        <th colspan="5">Download</th>
    </tr>
</thead>

While this works:

<thead>
    <tr>
        <th rowspan="2">Rep</th>
        <th rowspan="2">Titel</th>
        <th colspan="5">Download</th>
    </tr>
    <tr>
        <th>pdf</th>
        <th>nwc</th>
        <th>nwctxt</th>
        <th>mid</th>
        <th>xml</th>
    </tr>
</thead>

Java - Convert integer to string

Integer class has static method toString() - you can use it:

int i = 1234;
String str = Integer.toString(i);

Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.

How to loop through a plain JavaScript object with the objects as members?

Using ES8 Object.entries() should be a more compact way to achieve this.

Object.entries(validation_messages).map(([key,object]) => {

    alert(`Looping through key : ${key}`);

    Object.entries(object).map(([token, value]) => {
        alert(`${token} : ${value}`);
    });
});

How to convert a python numpy array to an RGB image with Opencv 2.4?

The images c, d, e , and f in the following show colorspace conversion they also happen to be numpy arrays <type 'numpy.ndarray'>:

import numpy, cv2
def show_pic(p):
        ''' use esc to see the results'''
        print(type(p))
        cv2.imshow('Color image', p)
        while True:
            k = cv2.waitKey(0) & 0xFF
            if k == 27: break 
        return
        cv2.destroyAllWindows()

b = numpy.zeros([200,200,3])

b[:,:,0] = numpy.ones([200,200])*255
b[:,:,1] = numpy.ones([200,200])*255
b[:,:,2] = numpy.ones([200,200])*0
cv2.imwrite('color_img.jpg', b)


c = cv2.imread('color_img.jpg', 1)
c = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)

d = cv2.imread('color_img.jpg', 1)
d = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)

e = cv2.imread('color_img.jpg', -1)
e = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)

f = cv2.imread('color_img.jpg', -1)
f = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)


pictures = [d, c, f, e]

for p in pictures:
        show_pic(p)
# show the matrix
print(c)
print(c.shape)

See here for more info: http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor

OR you could:

img = numpy.zeros([200,200,3])

img[:,:,0] = numpy.ones([200,200])*255
img[:,:,1] = numpy.ones([200,200])*255
img[:,:,2] = numpy.ones([200,200])*0

r,g,b = cv2.split(img)
img_bgr = cv2.merge([b,g,r])

What exactly is Spring Framework for?

Spring was dependency injection in the begining, then add king of wrappers for almost everything (wrapper over JPA implementations etc).

Long story ... most parts of Spring preffer XML solutions (XML scripting engine ... brrrr), so for DI I use Guice

Good library, but with growing depnedenciec, for example Spring JDBC (maybe one Java jdbc solution with real names parameters) take from maven 4-5 next.

Using Spring MVC (part of "big spring") for web development ... it is "request based" framework, there is holy war "request vs component" ... up to You

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

showDialog deprecated. What's the alternative?

From http://developer.android.com/reference/android/app/Activity.html

public final void showDialog (int id) Added in API level 1

This method was deprecated in API level 13. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

Simple version of showDialog(int, Bundle) that does not take any arguments. Simply calls showDialog(int, Bundle) with null arguments.

Why

  • A fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.
  • Here is a nice discussion Android DialogFragment vs Dialog
  • Another nice discussion DialogFragment advantages over AlertDialog

How to solve?

More

Action bar navigation modes are deprecated in Android L

It seems like they added a new Class named android.widget.Toolbar that extends ViewGroup. Also they added a new method setActionBar(Toolbar) in Activity. I haven't tested it yet, but it looks like you can wrap all kinds of TabWidgets, Spinners or custom views into a Toolbar and use it as your Actionbar.

JQuery select2 set default value from an option in list?

One more way - just add a selected = "selected" attribute to the select markup and call select2 on it. It must take your selected value. No need for extra JavaScript. Like this :

Markup

<select class="select2">
   <option id="foo">Some Text</option>
   <option id="bar" selected="selected">Other Text</option>
</select>

JavaScript

$('select').select2(); //oh yes just this!

See fiddle : http://jsfiddle.net/6hZFU/

Edit: (Thanks, Jay Haase!)

If this doesn't work, try setting the val property of select2 to null, to clear the value, like this:

$('select').select2("val", null); //a lil' bit more :)

After this, it is simple enough to set val to "Whatever You Want".

Android M Permissions: onRequestPermissionsResult() not being called

If you are calling this code from a fragment it has it’s own requestPermissions method.

So basic concept is, If you are in an Activity, then call

ActivityCompat.requestPermissions(this,
                            permissionsList,
                            permissionscode);

and if in a Fragment, just call

requestPermissions(permissionsList,
                            permissionscode);

File Upload in WebView

This solution also works for Honeycomb and Ice Cream Sandwich. Seems like Google introduced a cool new feature (accept attribute) and forgot to to implement an overload for backwards compatibility.

protected class CustomWebChromeClient extends WebChromeClient
{
    // For Android 3.0+
    public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) 
    {  
        context.mUploadMessage = uploadMsg;  
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
        i.addCategory(Intent.CATEGORY_OPENABLE);  
        i.setType("image/*");  
        context.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MainActivity.FILECHOOSER_RESULTCODE );  
    }

    // For Android < 3.0
    public void openFileChooser( ValueCallback<Uri> uploadMsg ) 
    {
        openFileChooser( uploadMsg, "" );
    }
}

Style input element to fill remaining width of its container

If you're using Bootstrap 4:

<form class="d-flex">
  <label for="myInput" class="align-items-center">Sample label</label>
  <input type="text" id="myInput" placeholder="Sample Input" class="flex-grow-1"/>
</form>

Better yet, use what's built into Bootstrap:

  <form>
    <div class="input-group">
      <div class="input-group-prepend">
        <label for="myInput" class="input-group-text">Default</label>
      </div>
      <input type="text" class="form-control" id="myInput">
    </div>
  </form>

https://jsfiddle.net/nap1ykbr/

What's the best way to loop through a set of elements in JavaScript?

I think using the first form is probably the way to go, since it's probably by far the most common loop structure in the known universe, and since I don't believe the reverse loop saves you any time in reality (still doing an increment/decrement and a comparison on each iteration).

Code that is recognizable and readable to others is definitely a good thing.

Force to open "Save As..." popup open at text link click for PDF in HTML

If you have a plugin within the browser which knows how to open a PDF file it will open directly. Like in case of images and HTML content.

So the alternative approach is not to send your MIME type in the response. In this way the browser will never know which plugin should open it. Hence it will give you a Save/Open dialog box.

Sample random rows in dataframe

Outdated answer. Please use dplyr::sample_frac() or dplyr::sample_n() instead.

In my R package there is a function sample.rows just for this purpose:

install.packages('kimisc')

library(kimisc)
example(sample.rows)

smpl..> set.seed(42)

smpl..> sample.rows(data.frame(a=c(1,2,3), b=c(4,5,6),
                               row.names=c('a', 'b', 'c')), 10, replace=TRUE)
    a b
c   3 6
c.1 3 6
a   1 4
c.2 3 6
b   2 5
b.1 2 5
c.3 3 6
a.1 1 4
b.2 2 5
c.4 3 6

Enhancing sample by making it a generic S3 function was a bad idea, according to comments by Joris Meys to a previous answer.

Add a common Legend for combined ggplots

A new, attractive solution is to use patchwork. The syntax is very simple:

library(ggplot2)
library(patchwork)

p1 <- ggplot(df1, aes(x = x, y = y, colour = group)) + 
  geom_point(position = position_jitter(w = 0.04, h = 0.02), size = 1.8)
p2 <- ggplot(df2, aes(x = x, y = y, colour = group)) + 
  geom_point(position = position_jitter(w = 0.04, h = 0.02), size = 1.8)

combined <- p1 + p2 & theme(legend.position = "bottom")
combined + plot_layout(guides = "collect")

Created on 2019-12-13 by the reprex package (v0.2.1)

Eclipse, regular expression search and replace

Using ...
search = (^.*import )(.*)(\(.*\):)
replace = $1$2

...replaces ...

from checks import checklist(_list):

...with...

from checks import checklist



Blocks in regex are delineated by parenthesis (which are not preceded by a "\")

(^.*import ) finds "from checks import " and loads it to $1 (eclipse starts counting at 1)

(.*) find the next "everything" until the next encountered "(" and loads it to $2. $2 stops at the "(" because of the next part (see next line below)

(\(.*\):) says "at the first encountered "(" after starting block $2...stop block $2 and start $3. $3 gets loaded with the "('any text'):" or, in the example, the "(_list):"

Then in the replace, just put the $1$2 to replace all three blocks with just the first two.



Screenshot

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

npm --depth 9999 update fixed the issue for me--apparently because package-lock.json was insisting on the outdated versions.

Styling the last td in a table with css

For IE, how about using a CSS expression:

<style type="text/css">
table td { 
  h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : '1px solid #000' ) );
}
</style>

Getting return value from stored procedure in C#

Suppose you need to pass Username and Password to Stored Procedure and know whether login is successful or not and check if any error has occurred in Stored Procedure.

public bool IsLoginSuccess(string userName, string password)
{
    try
    {
        SqlConnection SQLCon = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
        SqlCommand sqlcomm = new SqlCommand();
        SQLCon.Open();
        sqlcomm.CommandType = CommandType.StoredProcedure;
        sqlcomm.CommandText = "spLoginCheck"; // Stored Procedure name
        sqlcomm.Parameters.AddWithValue("@Username", userName); // Input parameters
        sqlcomm.Parameters.AddWithValue("@Password", password); // Input parameters

        // Your output parameter in Stored Procedure           
        var returnParam1 = new SqlParameter
        {
            ParameterName = "@LoginStatus",
            Direction = ParameterDirection.Output,
            Size = 1                    
        };
        sqlcomm.Parameters.Add(returnParam1);

        // Your output parameter in Stored Procedure  
        var returnParam2 = new SqlParameter
        {
            ParameterName = "@Error",
            Direction = ParameterDirection.Output,
            Size = 1000                    
        };

        sqlcomm.Parameters.Add(returnParam2);

        sqlcomm.ExecuteNonQuery(); 
        string error = (string)sqlcomm.Parameters["@Error"].Value;
        string retunvalue = (string)sqlcomm.Parameters["@LoginStatus"].Value;                    
    }
    catch (Exception ex)
    {

    }
    return false;
}

Your connection string in Web.Config

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Databasename;User id=yourusername;Password=yourpassword"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

And here is the Stored Procedure for reference

CREATE PROCEDURE spLoginCheck
    @Username Varchar(100),
    @Password Varchar(100) ,
    @LoginStatus char(1) = null output,
    @Error Varchar(1000) output 
AS
BEGIN

    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN

            SET @Error = 'None'
            SET @LoginStatus = ''

            IF EXISTS(SELECT TOP 1 * FROM EMP_MASTER WHERE EMPNAME=@Username AND EMPPASSWORD=@Password)
            BEGIN
                SET @LoginStatus='Y'
            END

            ELSE
            BEGIN
                SET @LoginStatus='N'
            END

        END
    END TRY

    BEGIN CATCH
        BEGIN           
            SET @Error = ERROR_MESSAGE()
        END
    END CATCH
END
GO

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

@mohammed, this is usually attributed to the authentication plugin that your mysql database is using.

By default and for some reason, mysql 8 default plugin is auth_socket. Applications will most times expect to log in to your database using a password.

If you have not yet already changed your mysql default authentication plugin, you can do so by:
1. Log in as root to mysql
2. Run this sql command:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
BY 'password';  

Replace 'password' with your root password. In case your application does not log in to your database with the root user, replace the 'root' user in the above command with the user that your application uses.

Digital ocean expounds some more on this here Installing Mysql

RSA encryption and decryption in Python

# coding: utf-8
from __future__ import unicode_literals
import base64
import os

import six
from Crypto import Random
from Crypto.PublicKey import RSA


class PublicKeyFileExists(Exception): pass


class RSAEncryption(object):
    PRIVATE_KEY_FILE_PATH = None
    PUBLIC_KEY_FILE_PATH = None

    def encrypt(self, message):
        public_key = self._get_public_key()
        public_key_object = RSA.importKey(public_key)
        random_phrase = 'M'
        encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
        # use base64 for save encrypted_message in database without problems with encoding
        return base64.b64encode(encrypted_message)

    def decrypt(self, encoded_encrypted_message):
        encrypted_message = base64.b64decode(encoded_encrypted_message)
        private_key = self._get_private_key()
        private_key_object = RSA.importKey(private_key)
        decrypted_message = private_key_object.decrypt(encrypted_message)
        return six.text_type(decrypted_message, encoding='utf8')

    def generate_keys(self):
        """Be careful rewrite your keys"""
        random_generator = Random.new().read
        key = RSA.generate(1024, random_generator)
        private, public = key.exportKey(), key.publickey().exportKey()

        if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
            raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
        self.create_directories()

        with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
            private_file.write(private)
        with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
            public_file.write(public)
        return private, public

    def create_directories(self, for_private_key=True):
        public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
        if not os.path.exists(public_key_path):
            os.makedirs(public_key_path)
        if for_private_key:
            private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
            if not os.path.exists(private_key_path):
                os.makedirs(private_key_path)

    def _get_public_key(self):
        """run generate_keys() before get keys """
        with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _get_private_key(self):
        """run generate_keys() before get keys """
        with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _to_format_for_encrypt(value):
        if isinstance(value, int):
            return six.binary_type(value)
        for str_type in six.string_types:
            if isinstance(value, str_type):
                return value.encode('utf8')
        if isinstance(value, six.binary_type):
            return value

And use

KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS

class TestingEncryption(RSAEncryption):
    PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
    PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'


# django/flask
from django.core.files import File

class ProductionEncryption(RSAEncryption):
    PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'

    def _get_private_key(self):
        """run generate_keys() before get keys """
        from corportal.utils import global_elements
        private_key = global_elements.request.FILES.get('private_key')
        if private_key:
            private_key_file = File(private_key)
            return private_key_file.read()

message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)

How to execute python file in linux

I suggest that you add

#!/usr/bin/env python

instead of #!/usr/bin/python at the top of the file. The reason for this is that the python installation may be in different folders in different distros or different computers. By using env you make sure that the system finds python and delegates the script's execution to it.

As said before to make the script executable, something like:

chmod u+x name_of_script.py

should do.

Custom Drawable for ProgressBar/ProgressDialog

Try setting:

android:indeterminateDrawable="@drawable/progress" 

It worked for me. Here is also the code for progress.xml:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0"
    android:toDegrees="360">

    <shape android:shape="ring" android:innerRadiusRatio="3"
        android:thicknessRatio="8" android:useLevel="false">

        <size android:width="48dip" android:height="48dip" />

        <gradient android:type="sweep" android:useLevel="false"
            android:startColor="#4c737373" android:centerColor="#4c737373"
            android:centerY="0.50" android:endColor="#ffffd300" />

    </shape>

</rotate> 

Can you center a Button in RelativeLayout?

Summarized

Adding:

android:layout_centerInParent="true"

just works on RelativeLayout, if one of the following attributes is also set for the view:

android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"

which alignes the child view to the parent view. The "center" is based on the axis of the alignement you have chosen:

left/right -> vertical

top/bottom -> horizontal

Setting the gravity of childs/content inside the view:

android:gravity="center"

is centering the child inside the parent view in any case, if there is no alignment set. Optional you can choose:

<!-- Axis to Center -->
android:gravity="center_horizontal"
android:gravity="center_vertical"

<!-- Alignment to set-->
android:gravity="top"
android:gravity="bottom"
android:gravity="left"
android:gravity="right"
android:gravity="fill"
...

Then there is:

android:layout_gravity="center"

which is centering the view itself inside it's parent

And at last you can add the following attribute to the parents view:

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

How can I concatenate strings in VBA?

& is always evaluated in a string context, while + may not concatenate if one of the operands is no string:

"1" + "2" => "12"
"1" + 2   => 3
1 + "2"   => 3
"a" + 2   => type mismatch

This is simply a subtle source of potential bugs and therefore should be avoided. & always means "string concatenation", even if its arguments are non-strings:

"1" & "2" => "12"
"1" &  2  => "12"
 1  & "2" => "12"
 1  &  2  => "12"
"a" &  2  => "a2"

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

SQL Server Insert if not exists

Different SQL, same principle. Only insert if the clause in where not exists fails

INSERT INTO FX_USDJPY
            (PriceDate, 
            PriceOpen, 
            PriceLow, 
            PriceHigh, 
            PriceClose, 
            TradingVolume, 
            TimeFrame)
    SELECT '2014-12-26 22:00',
           120.369000000000,
           118.864000000000,
           120.742000000000,
           120.494000000000,
           86513,
           'W'
    WHERE NOT EXISTS
        (SELECT 1
         FROM FX_USDJPY
         WHERE PriceDate = '2014-12-26 22:00'
           AND TimeFrame = 'W')

How do I display a decimal value to 2 decimal places?

decimalVar.ToString ("#.##"); // returns "" when decimalVar == 0

or

decimalVar.ToString ("0.##"); // returns "0"  when decimalVar == 0

How to disable javax.swing.JButton in java?

This works.

public class TestButton {

public TestButton() {
    JFrame f = new JFrame();
    f.setSize(new Dimension(200,200));
    JPanel p = new JPanel();
    p.setLayout(new FlowLayout());

    final JButton stop = new JButton("Stop");
    final JButton start = new JButton("Start");
    p.add(start);
    p.add(stop);
    f.getContentPane().add(p);
    stop.setEnabled(false);
    stop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            start.setEnabled(true);
            stop.setEnabled(false);

        }
    });

    start.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            start.setEnabled(false);
            stop.setEnabled(true);

        }
    });
    f.setVisible(true);
}

/**
 * @param args
 */
public static void main(String[] args) {
    new TestButton();

}

}

How to view the current heap size that an application is using?

You can Use the tool : Eclipse Memory Analyzer Tool http://www.eclipse.org/mat/ .

It is very useful.

How to download a file from a URL in C#?

Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.

Sample:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

For more information:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

Reversing an Array in Java

The following will reverse in place the array between indexes i and j (to reverse the whole array call reverse(a, 0, a.length - 1))

    public void reverse(int[] a, int i , int j) {
        int ii =  i;
        int jj = j;

        while (ii < jj) {
            swap(ii, jj);
            ++ii;
            --jj;
        }
    }

INSERT INTO vs SELECT INTO

  1. They do different things. Use INSERT when the table exists. Use SELECT INTO when it does not.

  2. Yes. INSERT with no table hints is normally logged. SELECT INTO is minimally logged assuming proper trace flags are set.

  3. In my experience SELECT INTO is most commonly used with intermediate data sets, like #temp tables, or to copy out an entire table like for a backup. INSERT INTO is used when you insert into an existing table with a known structure.

EDIT

To address your edit, they do different things. If you are making a table and want to define the structure use CREATE TABLE and INSERT. Example of an issue that can be created: You have a small table with a varchar field. The largest string in your table now is 12 bytes. Your real data set will need up to 200 bytes. If you do SELECT INTO from your small table to make a new one, the later INSERT will fail with a truncation error because your fields are too small.

How to escape a JSON string to have it in a URL?

Using encodeURIComponent():

var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),

Correct way to pause a Python program

Very simple:

raw_input("Press Enter to continue ...")
exit()

UITableView load more when scrolling to bottom like Facebook application

it is sample code.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:ShowComplainCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! ShowComplainCell

    let item  = self.dataArray[indexPath.row] as! ComplainListItem;

    let indexPathArray = NSArray(array: tableView.indexPathsForVisibleRows!)
    let vIndexPath = indexPathArray.lastObject as! NSIndexPath

    let lastItemReached = item.isEqual(self.dataArray.lastObject);

    if (lastItemReached && vIndexPath.row == (self.dataArray.count - 1))
       {

        self.loadData()
       }
    


    return cell
    
}

indexPathArray: is visible rows.

vIndexPath:is visible last indexpath

load data

 func loadData(){

       if(isReloadTable){
       let HUD = MBProgressHUD.showAdded(to: self.view, animated: true)
       let manager :AFHTTPSessionManager = AFHTTPSessionManager()
     
       
           var param = NSDictionary()
           param = [
               "category":cat_id,
               "smart_user_id": USERDEF.value(forKey: "user_id") as! String,
               "page":page,
               "phone":phone! as String
               
           ] as [String : Any] as NSDictionary
           print("param1 = \(param)")

           manager.get("lists.php?", parameters: param, progress: nil, success: { (task:URLSessionDataTask, responseObject: Any) in
               
     
                       let adsArray =  dic["results"] as! NSArray;
                       for item in adsArray {
                           let item  = ComplainListItem(dictionary: item as! NSDictionary )
                           self.dataArray.add(item)
                       }
                   
                       self.view.addSubview(self.cityTableView)
                       self.cityTableView.reloadData()
                   
                   if(adsArray.count==10){
                       self.cityTableView.reloadData()
                       self.isReloadTable = true
                       self.page+=1
                   }else if(adsArray.count<10){
                       self.cityTableView.reloadData()
                       self.isReloadTable = false
               }
               
               HUD.hide(animated:true)
               
           }) { (operation,error) -> Void in
               print("error = \(error)")
               HUD.hide(animated:true)
           }
       }
        
   }

check your dataArray count which is myadsarray check to equal your data limit. then if dataArray count equal next page is called if not equal which is less then 10, all data is showed or finished.

Removing nan values from an array

For me the answer by @jmetz didn't work, however using pandas isnull() did.

x = x[~pd.isnull(x)]

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

variable declares and call like this in a class

class X {
    var x: Int = 3

}
var y = X()
print("value of x is: ", y.x)

//value of x is:  3

now you want to program to make the default value of x more than or equal to 3. Now take the hypothetical case if x is less than 3, your program will fail. so, you want people to either put 3 or more than 3. Swift got it easy for you and it is important to understand this bit-advance way of dating the variable value because they will extensively use in iOS development. Now let's see how get and set will be used here.

class X {
    var _x: Int = 3
    var x: Int {
        get {
            return _x
        }
        set(newVal) {  //set always take 1 argument
            if newVal >= 3 {
             _x = newVal //updating _x with the input value by the user
            print("new value is: ", _x)
            }
            else {
                print("error must be greater than 3")
            }
        }
    }
}
let y = X()
y.x = 1
print(y.x) //error must be greater than 3
y.x = 8 // //new value is: 8

if you still have doubts, just remember, the use of get and set is to update any variable the way we want it to be updated. get and set will give you better control to rule your logic. Powerful tool hence not easily understandable.

How to use confirm using sweet alert?

_x000D_
_x000D_
document.querySelector('#from1').onsubmit = function(e){_x000D_
_x000D_
 swal({_x000D_
    title: "Are you sure?",_x000D_
    text: "You will not be able to recover this imaginary file!",_x000D_
    type: "warning",_x000D_
    showCancelButton: true,_x000D_
    confirmButtonColor: '#DD6B55',_x000D_
    confirmButtonText: 'Yes, I am sure!',_x000D_
    cancelButtonText: "No, cancel it!",_x000D_
    closeOnConfirm: false,_x000D_
    closeOnCancel: false_x000D_
 },_x000D_
 function(isConfirm){_x000D_
_x000D_
   if (isConfirm.value){_x000D_
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");_x000D_
_x000D_
    } else {_x000D_
      swal("Cancelled", "Your imaginary file is safe :)", "error");_x000D_
         e.preventDefault();_x000D_
    }_x000D_
 });_x000D_
};
_x000D_
_x000D_
_x000D_

What Java ORM do you prefer, and why?

Hibernate, because it's basically the defacto standard in Java and was one of the driving forces in the creation of the JPA. It's got excellent support in Spring, and almost every Java framework supports it. Finally, GORM is a really cool wrapper around it doing dynamic finders and so on using Groovy.

It's even been ported to .NET (NHibernate) so you can use it there too.

Is it possible to have SSL certificate for IP address, not domain name?

Yep. Cloudflare uses it for its DNS instructions homepage: https://1.1.1.1

How to dock "Tool Options" to "Toolbox"?

In the detached 'Tool Options' window, click on the red 'X' in the upper right corner to get rid of the window. Then on the main Gimp screen, click on 'Windows,' then 'Dockable Dialogs.' The first entry on its list will be 'Tool Options,' so click on that. Then, Tool Options will appear as a tab in the window on the right side of the screen, along with layers and undo history. Click and drag that tab over to the toolbox window on hte left and drop it inside. The tool options will again be docked in the toolbox.

What is the most efficient way to check if a value exists in a NumPy array?

The most obvious to me would be:

np.any(my_array[:, 0] == value)

How to use BigInteger?

Biginteger is an immutable class. You need to explicitly assign value of your output to sum like this:

sum = sum.add(BigInteger.valueof(i));    

Adding files to java classpath at runtime

You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;

public class ClassPathHacker {

  private static final Class[] parameters = new Class[]{URL.class};

  public static void addFile(String s) throws IOException {
    File f = new File(s);
    addFile(f);
  }//end method

  public static void addFile(File f) throws IOException {
    addURL(f.toURL());
  }//end method


  public static void addURL(URL u) throws IOException {

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class sysclass = URLClassLoader.class;

    try {
      Method method = sysclass.getDeclaredMethod("addURL", parameters);
      method.setAccessible(true);
      method.invoke(sysloader, new Object[]{u});
    } catch (Throwable t) {
      t.printStackTrace();
      throw new IOException("Error, could not add URL to system classloader");
    }//end try catch

   }//end method

}//end class

The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.

How to create an array from a CSV file using PHP and the fgetcsv function

I came up with this pretty basic code. I think it could be useful to anyone.

$link = "link to the CSV here"
$fp = fopen($link, 'r');

while(($line = fgetcsv($fp)) !== FALSE) {
    foreach($line as $key => $value) {
        echo $key . " - " . $value . "<br>";
    }
}


fclose($fp);

This action could not be completed. Try Again (-22421)

The problem can not be solved with xCode Upload Process. I was facing same issues few days ago when submitting few of my apps and all apps showing same error. After many tries, I used Application Loader to upload app and it worked.

First go to xcode -> product menu -> archive Select Export for Appstore Save IPA file Now Open Application loader by going to xCode -> xCode Menu -> Open Developer Tool -> Application Loader Login with the credentials of account, and select the IPA file. Submit it! It works!

Javascript Src Path

If you have

<base href="/" />

It's will not load file right. Just delete it.

Regex to check with starts with http://, https:// or ftp://

You need a whole input match here.

System.out.println(test.matches("^(http|https|ftp)://.*$")); 

Edit:(Based on @davidchambers's comment)

System.out.println(test.matches("^(https?|ftp)://.*$")); 

Capturing browser logs with Selenium WebDriver using Java

Adding LoggingPreferences to "goog:loggingPrefs" properties with the Chrome Driver options can help to fetch the Browser console logs for all Log levels.

ChromeOptions options = new ChromeOptions();    
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
options.setCapability("goog:loggingPrefs", logPrefs);
WebDriver driver = new ChromeDriver(options);

Expand a div to fill the remaining width

Have a look at the available CSS layout frameworks. I would recommend Simpl or, the slightly more complex, Blueprint framework.

If you are using Simpl (which involves importing just one simpl.css file), you can do this:

<div class="Colum­nOne­Half">Tree</div>
<div class="Colum­nOne­Half">View</div>

, for a 50-50 layout, or :

<div class="Colum­nOne­Quarter">Tree</div>
<div class="Colum­nThreeQuarters">View</div>

, for a 25-75 one.

It's that simple.

Is Safari on iOS 6 caching $.ajax results?

A quick work-around for GWT-RPC services is to add this to all the remote methods:

getThreadLocalResponse().setHeader("Cache-Control", "no-cache");

Vertically aligning text next to a radio button

This will give dead on alignment

input[type="radio"] {
  margin-top: 1px;
  vertical-align: top;
}

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

As @hanmari mentioned in his comment. when inserting into a postgres tables, the on conflict (..) do nothing is the best code to use for not inserting duplicate data.:

query = "INSERT INTO db_table_name(column_name)
         VALUES(%s) ON CONFLICT (column_name) DO NOTHING;"

The ON CONFLICT line of code will allow the insert statement to still insert rows of data. The query and values code is an example of inserted date from a Excel into a postgres db table. I have constraints added to a postgres table I use to make sure the ID field is unique. Instead of running a delete on rows of data that is the same, I add a line of sql code that renumbers the ID column starting at 1. Example:

q = 'ALTER id_column serial RESTART WITH 1'

If my data has an ID field, I do not use this as the primary ID/serial ID, I create a ID column and I set it to serial. I hope this information is helpful to everyone. *I have no college degree in software development/coding. Everything I know in coding, I study on my own.

How to clear mysql screen console in windows?

EDIT:
I don't think Any of the commands will work. In linux Ctrl-L will do the job. in windows there is no equivalent. You can only Exit MySql, Type CLS and then re-enter MySql.

Where are static variables stored in C and C++?

static variable stored in data segment or code segment as mentioned before.
You can be sure that it will not be allocated on stack or heap.
There is no risk for collision since static keyword define the scope of the variable to be a file or function, in case of collision there is a compiler/linker to warn you about.
A nice example

How do relative file paths work in Eclipse?

You need "src/Hankees.txt"

Your file is in the source folder which is not counted as the working directory.\

Or you can move the file up to the root directory of your project and just use "Hankees.txt"

Link to Flask static files with url_for

You have by default the static endpoint for static files. Also Flask application has the following arguments:

static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.

static_folder: the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

It means that the filename argument will take a relative path to your file in static_folder and convert it to a relative path combined with static_url_default:

url_for('static', filename='path/to/file')

will convert the file path from static_folder/path/to/file to the url path static_url_default/path/to/file.

So if you want to get files from the static/bootstrap folder you use this code:

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">

Which will be converted to (using default settings):

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">

Also look at url_for documentation.

How can I run MongoDB as a Windows service?

  1. check windows services

    if you have service for mongo remove it by run bellow command
    mongod --remove

  2. create mongo.cfg file with bellow content

    systemLog:
    destination: file
    path: c:\data\log\mongod.log
    storage:
    dbPath: c:\data\db

    path: where you want to store log datas
    dbPath: your database directory

  3. then run bellow command

    sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe\" --service --config=\"C:\Program Files\MongoDB\Server\3.2\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"

    binPath : mongodb installation directory
    config: .cfg file address
    DisplayName:Your Service Name

  4. start service

    net start MongoDB

now every things are done . enjoy that

Finding the number of days between two dates

Used this :)

$days = (strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24);
print $days;

Now it works

Remove lines that contain certain string

Use python-textops package :

from textops import *

'oldfile.txt' | cat() | grepv('bad') | tofile('newfile.txt')

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

In addition to what the other answers have said, note that the '/' character in "dd/MM/yyyy" is not a literal character: it represents the date separator of the current user's culture. Therefore, if the current culture uses yyyy-MM-dd dates, then when you call toString it will give you a date such as "31-12-2016" (using dashes instead of slashes). To force it to use slashes, you need to escape that character:

DateTime.Now.ToString("dd/MM/yyyy")     --> "19-12-2016" for a Japanese user
DateTime.Now.ToString("dd/MM/yyyy")     --> "19/12/2016" for a UK user
DateTime.Now.ToString("dd\\/MM\\/yyyy") --> "19/12/2016" independent of region

Find duplicate records in MongoDB

db.getCollection('orders').aggregate([  
    {$group: { 
            _id: {name: "$name"},
            uniqueIds: {$addToSet: "$_id"},
            count: {$sum: 1}
        } 
    },
    {$match: { 
        count: {"$gt": 1}
        }
    }
])

First Group Query the group according to the fields.

Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.

Confused about stdin, stdout and stderr?

Here is a lengthy article on stdin, stdout and stderr:

To summarize:

Streams Are Handled Like Files

Streams in Linux—like almost everything else—are treated as though they were files. You can read text from a file, and you can write text into a file. Both of these actions involve a stream of data. So the concept of handling a stream of data as a file isn’t that much of a stretch.

Each file associated with a process is allocated a unique number to identify it. This is known as the file descriptor. Whenever an action is required to be performed on a file, the file descriptor is used to identify the file.

These values are always used for stdin, stdout, and stderr:

0: stdin
1: stdout
2: stderr

Ironically I found this question on stack overflow and the article above because I was searching for information on abnormal / non-standard streams. So my search continues.

What are the best PHP input sanitizing functions?

This is 1 of the way I am currently practicing,

  1. Implant csrf, and salt tempt token along with the request to be made by user, and validate them all together from the request. Refer Here
  2. ensure not too much relying on the client side cookies and make sure to practice using server side sessions
  3. when any parsing data, ensure to accept only the data type and transfer method (such as POST and GET)
  4. Make sure to use SSL for ur webApp/App
  5. Make sure to also generate time base session request to restrict spam request intentionally.
  6. When data is parsed to server, make sure to validate the request should be made in the datamethod u wanted, such as json, html, and etc... and then proceed
  7. escape all illegal attributes from the input using escape type... such as realescapestring.
  8. after that verify onlyclean format of data type u want from user.
    Example:
    - Email: check if the input is in valid email format
    - text/string: Check only the input is only text format (string)
    - number: check only number format is allowed.
    - etc. Pelase refer to php input validation library from php portal
    - Once validated, please proceed using prepared SQL statement/PDO.
    - Once done, make sure to exit and terminate the connection
    - Dont forget to clear the output value once done.

Thats all I believe is sufficient enough for basic sec. It should prevent all major attack from hacker.

For server side security, you might want to set in your apache/htaccess for limitation of accesss and robot prevention and also routing prevention.. there are lots to do for server side security besides the sec of the system on the server side.

You can learn and get a copy of the sec from the htaccess apache sec level (common rpactices)

How to Correctly handle Weak Self in Swift Blocks with Arguments

If you are crashing than you probably need [weak self]

My guess is that the block you are creating is somehow still wired up.

Create a prepareForReuse and try clearing the onTextViewEditClosure block inside that.

func prepareForResuse() {
   onTextViewEditClosure = nil
   textView.delegate = nil
}

See if that prevents the crash. (It's just a guess).

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

Additionally, how do I retrieve the number of days of a given month?

Aside from calculating it yourself (and consequently having to get leap years right), you can use a Date calculation to do it:

var y= 2010, m= 11;            // December 2010 - trap: months are 0-based in JS

var next= Date.UTC(y, m+1);    // timestamp of beginning of following month
var end= new Date(next-1);     // date for last second of this month
var lastday= end.getUTCDate(); // 31

In general for timestamp/date calculations I'd recommend using the UTC-based methods of Date, like getUTCSeconds instead of getSeconds(), and Date.UTC to get a timestamp from a UTC date, rather than new Date(y, m), so you don't have to worry about the possibility of weird time discontinuities where timezone rules change.

PHP Function Comments

You must check this: Docblock Comment standards

http://pear.php.net/manual/en/standards.sample.php

How do I install the babel-polyfill library?

First off, the obvious answer that no one has provided, you need to install Babel into your application:

npm install babel --save

(or babel-core if you instead want to require('babel-core/polyfill')).

Aside from that, I have a grunt task to transpile my es6 and jsx as a build step (i.e. I don't want to use babel/register, which is why I am trying to use babel/polyfill directly in the first place), so I'd like to put more emphasis on this part of @ssube's answer:

Make sure you require it at the entry-point to your application, before anything else is called

I ran into some weird issue where I was trying to require babel/polyfill from some shared environment startup file and I got the error the user referenced - I think it might have had something to do with how babel orders imports versus requires but I'm unable to reproduce now. Anyway, moving import 'babel/polyfill' as the first line in both my client and server startup scripts fixed the problem.

Note that if you instead want to use require('babel/polyfill') I would make sure all your other module loader statements are also requires and not use imports - avoid mixing the two. In other words, if you have any import statements in your startup script, make import babel/polyfill the first line in your script rather than require('babel/polyfill').

Remove file extension from a file name string

There's a method in the framework for this purpose, which will keep the full path except for the extension.

System.IO.Path.ChangeExtension(path, null);

If only file name is needed, use

System.IO.Path.GetFileNameWithoutExtension(path);

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In you app config file change the url to localhost/example/public

Then when you want to link to something

<a href="{{ url('page') }}">Some Text</a>

without blade

<a href="<?php echo url('page') ?>">Some Text</a>

Remove Top Line of Text File with PowerShell

Inspired by AASoft's answer, I went out to improve it a bit more:

  1. Avoid the loop variable $i and the comparison with 0 in every loop
  2. Wrap the execution into a try..finally block to always close the files in use
  3. Make the solution work for an arbitrary number of lines to remove from the beginning of the file
  4. Use a variable $p to reference the current directory

These changes lead to the following code:

$p = (Get-Location).Path

(Measure-Command {
    # Number of lines to skip
    $skip = 1
    $ins = New-Object System.IO.StreamReader ($p + "\test.log")
    $outs = New-Object System.IO.StreamWriter ($p + "\test-1.log")
    try {
        # Skip the first N lines, but allow for fewer than N, as well
        for( $s = 1; $s -le $skip -and !$ins.EndOfStream; $s++ ) {
            $ins.ReadLine()
        }
        while( !$ins.EndOfStream ) {
            $outs.WriteLine( $ins.ReadLine() )
        }
    }
    finally {
        $outs.Close()
        $ins.Close()
    }
}).TotalSeconds

The first change brought the processing time for my 60 MB file down from 5.3s to 4s. The rest of the changes is more cosmetic.

SQL Developer with JDK (64 bit) cannot find JVM

This looks like you might not have enough memory allocated to your Windows VM. If the JVM is configured to use more (maximum) memory than is available then you'll get this sort of error message.

You can read more about SQL Developer's memory at (that) Jeff Smith's blog.

The default settings still seem to be -Xms128m -Xmx800m. I can generate a similar error by setting -Xmx to be large than the physical RAM in my (physical) PC. So with the default settings, you will have problems if you don't have 800m of memory allocated to Windows. That doesn't seem like much, but it seems to be in the recommended window based on this knowledgebase article.

While you could attempt to reduce the JVM requirements in your product.conf file that will likely lead to other issues later, if it works at all. So increase your Windows VM memory allocation, reboot, and try to launch SQL Developer again.

While variable is not defined - wait

I have upvoted @dnuttle's answer, but ended up using the following strategy:

// On doc ready for modern browsers
document.addEventListener('DOMContentLoaded', (e) => {
  // Scope all logic related to what you want to achieve by using a function
  const waitForMyFunction = () => {
    // Use a timeout id to identify your process and purge it when it's no longer needed
    let timeoutID;
    // Check if your function is defined, in this case by checking its type
    if (typeof myFunction === 'function') {
      // We no longer need to wait, purge the timeout id
      window.clearTimeout(timeoutID);
      // 'myFunction' is defined, invoke it with parameters, if any
      myFunction('param1', 'param2');
    } else {
      // 'myFunction' is undefined, try again in 0.25 secs
      timeoutID = window.setTimeout(waitForMyFunction, 250);
    }
  };
  // Initialize
  waitForMyFunction();
});

It is tested and working! ;)

Gist: https://gist.github.com/dreamyguy/f319f0b2bffb1f812cf8b7cae4abb47c

How to select a specific node with LINQ-to-XML

I'd use something like:

dim customer = (from c in xmldoc...<Customer> 
                where c.<ID>.Value=22 
                select c).SingleOrDefault 

Edit:

missed the c# tag, sorry......the example is in VB.NET

Bootstrap 4 Center Vertical and Horizontal Alignment

Use This Code In CSS :

.container {
    width: 600px;
    height: 350px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: inline-flex;
}

extract digits in a simple way from a python string

Without using regex, you can just do:

def get_num(x):
    return int(''.join(ele for ele in x if ele.isdigit()))

Result:

>>> get_num(x)
120
>>> get_num(y)
90
>>> get_num(banana)
200
>>> get_num(orange)
300

EDIT :

Answering the follow up question.

If we know that the only period in a given string is the decimal point, extracting a float is quite easy:

def get_num(x):
    return float(''.join(ele for ele in x if ele.isdigit() or ele == '.'))

Result:

>>> get_num('dfgd 45.678fjfjf')
45.678

.toLowerCase not working, replacement function?

.toLowerCase function only exists on strings. You can call toString() on anything in javascript to get a string representation. Putting this all together:

var ans = 334;
var temp = ans.toString().toLowerCase();
alert(temp);

Defining a variable with or without export

export makes the variable available to sub-processes.

That is,

export name=value

means that the variable name is available to any process you run from that shell process. If you want a process to make use of this variable, use export, and run the process from that shell.

name=value

means the variable scope is restricted to the shell, and is not available to any other process. You would use this for (say) loop variables, temporary variables etc.

It's important to note that exporting a variable doesn't make it available to parent processes. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.

MVC4 StyleBundle not resolving images

Better yet (IMHO) implement a custom Bundle that fixes the image paths. I wrote one for my app.

using System;
using System.Collections.Generic;
using IO = System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Optimization;

...

public class StyleImagePathBundle : Bundle
{
    public StyleImagePathBundle(string virtualPath)
        : base(virtualPath, new IBundleTransform[1]
      {
        (IBundleTransform) new CssMinify()
      })
    {
    }

    public StyleImagePathBundle(string virtualPath, string cdnPath)
        : base(virtualPath, cdnPath, new IBundleTransform[1]
      {
        (IBundleTransform) new CssMinify()
      })
    {
    }

    public new Bundle Include(params string[] virtualPaths)
    {
        if (HttpContext.Current.IsDebuggingEnabled)
        {
            // Debugging. Bundling will not occur so act normal and no one gets hurt.
            base.Include(virtualPaths.ToArray());
            return this;
        }

        // In production mode so CSS will be bundled. Correct image paths.
        var bundlePaths = new List<string>();
        var svr = HttpContext.Current.Server;
        foreach (var path in virtualPaths)
        {
            var pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
            var contents = IO.File.ReadAllText(svr.MapPath(path));
            if(!pattern.IsMatch(contents))
            {
                bundlePaths.Add(path);
                continue;
            }


            var bundlePath = (IO.Path.GetDirectoryName(path) ?? string.Empty).Replace(@"\", "/") + "/";
            var bundleUrlPath = VirtualPathUtility.ToAbsolute(bundlePath);
            var bundleFilePath = String.Format("{0}{1}.bundle{2}",
                                               bundlePath,
                                               IO.Path.GetFileNameWithoutExtension(path),
                                               IO.Path.GetExtension(path));
            contents = pattern.Replace(contents, "url($1" + bundleUrlPath + "$2$1)");
            IO.File.WriteAllText(svr.MapPath(bundleFilePath), contents);
            bundlePaths.Add(bundleFilePath);
        }
        base.Include(bundlePaths.ToArray());
        return this;
    }

}

To use it, do:

bundles.Add(new StyleImagePathBundle("~/bundles/css").Include(
  "~/This/Is/Some/Folder/Path/layout.css"));

...instead of...

bundles.Add(new StyleBundle("~/bundles/css").Include(
  "~/This/Is/Some/Folder/Path/layout.css"));

What it does is (when not in debug mode) looks for url(<something>) and replaces it with url(<absolute\path\to\something>). I wrote the thing about 10 seconds ago so it might need a little tweaking. I've taken into account fully-qualified URLs and base64 DataURIs by making sure there's no colons (:) in the URL path. In our environment, images normally reside in the same folder as their css files, but I've tested it with both parent folders (url(../someFile.png)) and child folders (url(someFolder/someFile.png).

how do I get eclipse to use a different compiler version for Java?

First off, are you setting your desired JRE or your desired JDK?

Even if your Eclipse is set up properly, there might be a wacky project-specific setting somewhere. You can open up a context menu on a given Java project in the Project Explorer and select Properties > Java Compiler to check on that.

If none of that helps, leave a comment and I'll take another look.

PHP how to get local IP of system

In windows

$exec = 'ipconfig | findstr /R /C:"IPv4.*"';
exec($exec, $output);
preg_match('/\d+\.\d+\.\d+\.\d+/', $output[0], $matches);
print_r($matches[0]);

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

Plot mean and standard deviation

You may find an answer with this example : errorbar_demo_features.py

"""
Demo of errorbar function with different ways of specifying error bars.

Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.

N x 1:
    Error varies for each point, but the error values are symmetric (i.e. the
    lower and upper values are equal).

2 x N:
    Error varies for each point, and the lower and upper limits (in that order)
    are different (asymmetric case)

In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt

# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]

fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')

ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()

Which plots this:

enter image description here

Best approach to converting Boolean object to string in java

Depends on what you mean by "efficient". Performance-wise both versions are the same as its the same bytecode.

$ ./javap.exe -c java.lang.String | grep -A 10 "valueOf(boolean)"
  public static java.lang.String valueOf(boolean);
    Code:
       0: iload_0
       1: ifeq          9
       4: ldc           #14                 // String true
       6: goto          11
       9: ldc           #10                 // String false
      11: areturn


$ ./javap.exe -c java.lang.Boolean | grep -A 10 "toString(boolean)"
  public static java.lang.String toString(boolean);
    Code:
       0: iload_0
       1: ifeq          9
       4: ldc           #3                  // String true
       6: goto          11
       9: ldc           #2                  // String false
      11: areturn

Multiple conditions in ngClass - Angular 4

I had this similar issue. I wanted to set a class after looking at multiple expressions. ngClass can evaluate a method inside the component code and tell you what to do.

So inside an *ngFor:

<div [ngClass]="{'shrink': shouldShrink(a.category1, a.category2), 'showAll': section == 'allwork' }">{{a.listing}}</div>

And inside the component:

section = 'allwork';

shouldShrink(cat1, cat2) {
    return this.section === cat1 || this.section === cat2 ? false : true;
}

Here I need to calculate if i should shrink a div based on if a 2 different categories have matched what the selected category is. And it works. So from there you can computer a true/false for the [ngClass] based on what your method returns given the inputs.

VBA: Conditional - Is Nothing

Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.

Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.

Sub test()

Dim dict As Object
Set dict = CreateObject("scripting.dictionary")

If Not dict Is Nothing Then
    MsgBox "Dict is something!"  '<--- This shows
Else
    MsgBox "Dict is nothing!"
End If

End Sub

However if you declare an object but never create it, it's nothing.

Sub test()

Dim temp As Object

If Not temp Is Nothing Then
    MsgBox "Temp is something!"
Else
    MsgBox "Temp is nothing!" '<---- This shows
End If

End Sub

Easiest way to rotate by 90 degrees an image using OpenCV?

Well I was looking for some details and didn't find any example. So I am posting a transposeImage function which, I hope, will help others who are looking for a direct way to rotate 90° without losing data:

IplImage* transposeImage(IplImage* image) {

    IplImage *rotated = cvCreateImage(cvSize(image->height,image->width),   
        IPL_DEPTH_8U,image->nChannels);
    CvPoint2D32f center;
    float center_val = (float)((image->width)-1) / 2;
    center.x = center_val;
    center.y = center_val;
    CvMat *mapMatrix = cvCreateMat( 2, 3, CV_32FC1 );        
    cv2DRotationMatrix(center, 90, 1.0, mapMatrix);
    cvWarpAffine(image, rotated, mapMatrix, 
        CV_INTER_LINEAR + CV_WARP_FILL_OUTLIERS, 
        cvScalarAll(0));      
    cvReleaseMat(&mapMatrix);

    return rotated;
}

Question : Why this?

float center_val = (float)((image->width)-1) / 2; 

Answer : Because it works :) The only center I found that doesn't translate image. Though if somebody has an explanation I would be interested.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

If use Json.NET to generate the json string, it doesn't need to set MaxJsonLength value.

return new ContentResult()
{
    Content = Newtonsoft.Json.JsonConvert.SerializeObject(data),
    ContentType = "application/json",
};

How can I scan barcodes on iOS?

For a native iOS 7 bar code scanner take a look at my project on GitHub:

https://github.com/werner77/WECodeScanner