Programs & Examples On #Fetching strategy

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

Possibly something has changed in recent TensorFlow builds, because for me, running

sess = tf.Session()
sess.run(tf.local_variables_initializer())

before fitting any models seems to do the trick. Most older examples and comments seem to suggest tf.global_variables_initializer().

How to implement a property in an interface

Interfaces can not contain any implementation (including default values). You need to switch to abstract class.

TypeError: '<=' not supported between instances of 'str' and 'int'

Change

vote = input('Enter the name of the player you wish to vote for')

to

vote = int(input('Enter the name of the player you wish to vote for'))

You are getting the input from the console as a string, so you must cast that input string to an int object in order to do numerical operations.

Confirmation before closing of tab/browser

Try this:

<script>
window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
};
</script>

Here is a working jsFiddle

nginx upload client_max_body_size issue

nginx "fails fast" when the client informs it that it's going to send a body larger than the client_max_body_size by sending a 413 response and closing the connection.

Most clients don't read responses until the entire request body is sent. Because nginx closes the connection, the client sends data to the closed socket, causing a TCP RST.

If your HTTP client supports it, the best way to handle this is to send an Expect: 100-Continue header. Nginx supports this correctly as of 1.2.7, and will reply with a 413 Request Entity Too Large response rather than 100 Continue if Content-Length exceeds the maximum body size.

Create a tag in a GitHub repository

It all depends what type of tag you want to create:

  • If you want to create Annotated tags, to show extra metadata, you can do it in the following way: git tag -a v1.0.0.
  • On the other hand, Lightweight tags are used to "bookmark" your commits for private use: git tag v1.0.0.

There are a few other tag functionalities such as:

  • Listing tags - git tag -l -n3. The command lists all existing tags with maximum 3 lines of their tag message. By default -n only shows the first line.
  • Tag details - git show <tag_identifier>. It shows all you need to know about a specific tag.
  • Sorting tags - git tag --sort=<type>
  • Publishing tags - git push origin v1.0. You can git push the tag individually, or you can run git push --tags which will push all tags at once.

Be sure to check this tag related article for more relevant information.

How to sort with a lambda?

Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>

struct Foo
{
    Foo() : _i(0) {};

    int _i;

    friend std::ostream& operator<<(std::ostream& os, const Foo& f)
    {
        os << f._i;
        return os;
    };
};

typedef std::vector<Foo> VectorT;

std::string toString(const VectorT& v)
{
    std::stringstream ss;
    std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
    return ss.str();
};

int main()
{

    VectorT v(10);
    std::for_each(v.begin(), v.end(),
            [](Foo& f)
            {
                f._i = rand() % 100;
            });

    std::cout << "before sort: " << toString(v) << "\n";

    sort(v.begin(), v.end(),
            [](const Foo& a, const Foo& b)
            {
                return a._i > b._i;
            });

    std::cout << "after sort:  " << toString(v) << "\n";
    return 1;
};

The output is:

before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,

Maven Modules + Building a Single Specific Module

You say you "really just want B", but this is false. You want B, but you also want an updated A if there have been any changes to it ("active development").

So, sometimes you want to work with A, B, and C. For this case you have aggregator project P. For the case where you want to work with A and B (but do not want C), you should create aggregator project Q.

Edit 2016: The above information was perhaps relevant in 2009. As of 2016, I highly recommend ignoring this in most cases, and simply using the -am or -pl command-line flags as described in the accepted answer. If you're using a version of maven from before v2.1, change that first :)

How to get base url with jquery or javascript?

This is not possible from javascript, because this is a server-side property. Javascript on the client cannot know where joomla is installed. The best option is to somehow include the value of $this->baseurl into the page javascript and then use this value (phpBaseUrl).

You can then build the url like this:

var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:

address=/example.com/127.0.0.1

A valid provisioning profile for this executable was not found... (again)

Make sure you have added your device - https://developer.apple.com/account/ios/device/create

Go into iTunes and click on the serial number and it'll change to the UDID - then right click to Copy the UDID and register it as your device.

You can then add that device to your provisioning profile.

Apply CSS Style to child elements

This code can do the trick as well, using the SCSS syntax

.parent {
  & > * {
    margin-right: 15px;
    &:last-child {
      margin-right: 0;
    }
  }
}

html div onclick event

Try this

$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
    alert('123');
});

$('#ancherComplaint').click(function (event) {
    alert($(this).attr("id"));
    event.stopPropagation()
})

DEMO

Embedding Windows Media Player for all browsers

Encoding flash video is actually very easy with ffmpeg. You can use one command to convert from just about any video format, ffmpeg is smart enough to figure the rest out, and it'll use every processor on your machine. Invoking it is easy:

ffmpeg -i input.avi output.flv

ffmpeg will guess at the bitrate you want, but if you'd like to specify one, you can use the -b option, so -b 500000 is 500kbps for example. There's a ton of options of course, but I generally get good results without much tinkering. This is a good place to start if you're looking for more options: video options.

You don't need a special web server to show flash video. I've done just fine by simply pushing .flv files up to a standard web server, and linking to them with a good swf player, like flowplayer.

WMVs are fine if you can be sure that all of your users will always use [a recent, up to date version of] Windows only, but even then, Flash is often a better fit for the web. The player is even extremely skinnable and can be controlled with javascript.

How to get start and end of previous month in VB

Try this to get the month in number form:

Month(DateAdd("m", -3, Now))

It will give you 12 for December.

So in your case you would use Month(DateAdd("m", -1, Now)) to just subract one month.

How do I change the background color with JavaScript?

Add this script element to your body element, changing the color as desired:

_x000D_
_x000D_
<body>_x000D_
  <p>Hello, World!</p>_x000D_
  <script type="text/javascript">_x000D_
     document.body.style.backgroundColor = "#ff0000";  // red_x000D_
  </script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to find a number in a string using JavaScript?

I like @jesterjunk answer, however, a number is not always just digits. Consider those valid numbers: "123.5, 123,567.789, 12233234+E12"

So I just updated the regular expression:

var regex = /[\d|,|.|e|E|\+]+/g;

var string = "you can enter maximum 5,123.6 choices";
var matches = string.match(regex);  // creates array from matches

document.write(matches); //5,123.6

Regarding Java switch statements - using return and omitting breaks in each case

Though the question is old enough it still can be referenced nowdays.

Semantically that is exactly what Java 12 introduced (https://openjdk.java.net/jeps/325), thus, exactly in that simple example provided I can't see any problem or cons.

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

Including one C source file in another?

Numerous other answers have more than covered how you can do this but why you probably should not in normal circumstances. That said, I will add why I've done it in the past.

In embedded development, it's common to have silicon vendor source code as part of your compiled files. The problem is those vendors likely don't have the same style guides or standard warning/error flag settings as your organization.

So, you can create a local source file that includes the vendor source code and then compile this wrapper C file instead to suppress any issues in the included source as well as any headers included by that source. As an example:

/**
 * @file   vendor_wrap.c
 * @brief  vendor source code wrapper to prevent warnings
 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnested-externs"
#include "vendor_source_code.c"
#pragma GCC diagnostic pop

This allows you to use less complicated Make scripting with a standard set of compiler flags and settings with specific exceptions in the code rather than have custom flags for some files in the scripting.

gcc main.c vendor_wrap.c -o $(CFLAGS) main.out

CSS, Images, JS not loading in IIS

I had exact same problem, tried all of the suggestions but got nothing. Bugged me hours. Turned out my ISP blocked port 80 for some reasons.

Advice: check your traffic. Make sure port 80 works both locally (i.e. firewall) and externally.

How to convert a Scikit-learn dataset to a Pandas dataset?

There might be a better way but here is what I have done in the past and it works quite well:

items = data.items()                          #Gets all the data from this Bunch - a huge list
mydata = pd.DataFrame(items[1][1])            #Gets the Attributes
mydata[len(mydata.columns)] = items[2][1]     #Adds a column for the Target Variable
mydata.columns = items[-1][1] + [items[2][0]] #Gets the column names and updates the dataframe

Now mydata will have everything you need - attributes, target variable and columnnames

How to uninstall Ruby from /usr/local?

do this way :

sudo apt purge ruby

SQL conditional SELECT

@selectField1 AS bit
@selectField2 AS bit

SELECT
CASE 
    WHEN @selectField1 THEN Field1
    WHEN @selectField2 THEN Field2
    ELSE someDefaultField
END
FROM Table

Is this what you're looking for?

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

Get the IP address of the machine

I do not think there is a definitive right answer to your question. Instead there is a big bundle of ways how to get close to what you wish. Hence I will provide some hints how to get it done.

If a machine has more than 2 interfaces (lo counts as one) you will have problems to autodetect the right interface easily. Here are some recipes on how to do it.

The problem, for example, is if hosts are in a DMZ behind a NAT firewall which changes the public IP into some private IP and forwards the requests. Your machine may have 10 interfaces, but only one corresponds to the public one.

Even autodetection does not work in case you are on double-NAT, where your firewall even translates the source-IP into something completely different. So you cannot even be sure, that the default route leads to your interface with a public interface.

Detect it via the default route

This is my recommended way to autodetect things

Something like ip r get 1.1.1.1 usually tells you the interface which has the default route.

If you want to recreate this in your favourite scripting/programming language, use strace ip r get 1.1.1.1 and follow the yellow brick road.

Set it with /etc/hosts

This is my recommendation if you want to stay in control

You can create an entry in /etc/hosts like

80.190.1.3 publicinterfaceip

Then you can use this alias publicinterfaceip to refer to your public interface.

Sadly haproxy does not grok this trick with IPv6

Use the environment

This is a good workaround for /etc/hosts in case you are not root

Same as /etc/hosts. but use the environment for this. You can try /etc/profile or ~/.profile for this.

Hence if your program needs a variable MYPUBLICIP then you can include code like (this is C, feel free to create C++ from it):

#define MYPUBLICIPENVVAR "MYPUBLICIP"

const char *mypublicip = getenv(MYPUBLICIPENVVAR);

if (!mypublicip) { fprintf(stderr, "please set environment variable %s\n", MYPUBLICIPENVVAR); exit(3); }

So you can call your script/program /path/to/your/script like this

MYPUBLICIP=80.190.1.3 /path/to/your/script

this even works in crontab.

Enumerate all interfaces and eliminate those you do not want

The desperate way if you cannot use ip

If you do know what you do not want, you can enumerate all interfaces and ignore all the false ones.

Here already seems to be an answer https://stackoverflow.com/a/265978/490291 for this approach.

Do it like DLNA

The way of the drunken man who tries to drown himself in alcohol

You can try to enumerate all the UPnP gateways on your network and this way find out a proper route for some "external" thing. This even might be on a route where your default route does not point to.

For more on this perhaps see https://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol

This gives you a good impression which one is your real public interface, even if your default route points elsewhere.

There are even more

Where the mountain meets the prophet

IPv6 routers advertise themselves to give you the right IPv6 prefix. Looking at the prefix gives you a hint about if it has some internal IP or a global one.

You can listen for IGMP or IBGP frames to find out some suitable gateway.

There are less than 2^32 IP addresses. Hence it does not take long on a LAN to just ping them all. This gives you a statistical hint on where the majority of the Internet is located from your point of view. However you should be a bit more sensible than the famous https://de.wikipedia.org/wiki/SQL_Slammer

ICMP and even ARP are good sources for network sideband information. It might help you out as well.

You can use Ethernet Broadcast address to contact to all your network infrastructure devices which often will help out, like DHCP (even DHCPv6) and so on.

This additional list is probably endless and always incomplete, because every manufacturer of network devices is busily inventing new security holes on how to auto-detect their own devices. Which often helps a lot on how to detect some public interface where there shouln't be one.

'Nuff said. Out.

Refresh an asp.net page on button click

You can do Response.redirect("YourPage",false) that will refresh your page and also increase counter.

How to hide the title bar for an Activity in XML with existing custom theme

I'm using a support widget Toolbar v7. So, in order to be able to delete or hide the Title we need to write this.

Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);

//Remove¡ing title bar
getSupportActionBar().setDisplayShowTitleEnabled(false);

jQuery Ajax POST example with PHP

I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.

First of all, create two files, for example form.php and process.php.

We will first create a form which will be then submitted using the jQuery .ajax() method. The rest will be explained in the comments.


form.php

<form method="post" name="postForm">
    <ul>
        <li>
            <label>Name</label>
            <input type="text" name="name" id="name" placeholder="Bruce Wayne">
            <span class="throw_error"></span>
            <span id="success"></span>
       </li>
   </ul>
   <input type="submit" value="Send" />
</form>


Validate the form using jQuery client-side validation and pass the data to process.php.

$(document).ready(function() {
    $('form').submit(function(event) { //Trigger on form submit
        $('#name + .throw_error').empty(); //Clear the messages first
        $('#success').empty();

        //Validate fields if required using jQuery

        var postForm = { //Fetch form data
            'name'     : $('input[name=name]').val() //Store name fields value
        };

        $.ajax({ //Process the form using $.ajax()
            type      : 'POST', //Method type
            url       : 'process.php', //Your form processing file URL
            data      : postForm, //Forms name
            dataType  : 'json',
            success   : function(data) {
                            if (!data.success) { //If fails
                                if (data.errors.name) { //Returned if any error from process.php
                                    $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
                                }
                            }
                            else {
                                    $('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
                                }
                            }
        });
        event.preventDefault(); //Prevent the default submit
    });
});

Now we will take a look at process.php

$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`

/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
    $errors['name'] = 'Name cannot be blank';
}

if (!empty($errors)) { //If errors in validation
    $form_data['success'] = false;
    $form_data['errors']  = $errors;
}
else { //If not, process the form, and return true on success
    $form_data['success'] = true;
    $form_data['posted'] = 'Data Was Posted Successfully';
}

//Return the data back to form.php
echo json_encode($form_data);

The project files can be downloaded from http://projects.decodingweb.com/simple_ajax_form.zip.

java - path to trustStore - set property doesn't work?

Alternatively, if using javax.net.ssl.trustStore for specifying the location of your truststore does not work ( as it did in my case for two way authentication ), you can also use SSLContextBuilder as shown in the example below. This example also includes how to create a httpclient as well to show how the SSL builder would work.

SSLContextBuilder sslcontextbuilder = SSLContexts.custom();

sslcontextbuilder.loadTrustMaterial(
            new File("C:\\path to\\truststore.jks"), //path to jks file
            "password".toCharArray(), //enters in the truststore password for use
            new TrustSelfSignedStrategy() //will trust own CA and all self-signed certs
            );

SSLContext sslcontext = sslcontextbuilder.build(); //load trust store

SSLConnectionSocketFactory sslsockfac = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.getDefaultHostnameVerifier());

CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsockfac).build(); //sets up a httpclient for use with ssl socket factory 



try { 
        HttpGet httpget = new HttpGet("https://localhost:8443"); //I had a tomcat server running on localhost which required the client to have their trust cert

        System.out.println("Executing request " + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

How do I programmatically force an onchange event on an input?

if you're using jQuery you would have:

$('#elementId').change(function() { alert('Do Stuff'); });

or MS AJAX:

$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });

Or in the raw HTML of the element:

<input type="text" onchange="alert('Do Stuff');" id="myElement" />

After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:

$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
  alert('Do Stuff!');
}
function editElement(){
  var el = $get('elementId');
  el.value = 'something new';
  elementChanged();
}

Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.

Or, if you are using the Microsoft AJAX framework you can access all the event handlers via:

$get('elementId')._events

It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.

How to disable registration new users in Laravel

In Laravel 5.5

Working on a similar issue and setting the middleware argument from guest to 'auth' seemed like a more elegant solution.

Edit File: app->http->Controllers->Auth->RegisterController.php

public function __construct()
{
     //replace this
     //$this->middleware('guest');

     //with this argument.
       $this->middleware('auth');
}

I could be wrong though...but it seems more slick than editing the routing with more lines and less shity than simply redirecting the page...at least in this instance, wanting to lock down the registration for guests.

Save child objects automatically using JPA Hibernate

In short set cascade type to all , will do a job; For an example in your model. Add Code like this . @OneToMany(mappedBy = "receipt", cascade=CascadeType.ALL) private List saleSet;

Hibernate Error: a different object with the same identifier value was already associated with the session

Try to place the code of your query before. That fix my problem. e.g. change this:

query1 
query2 - get the error 
update

to this:

query2
query1
update

How to send post request to the below post method using postman rest client

The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

https://www.getpostman.com/docs/requests

Good Linux (Ubuntu) SVN client

Nobody else has mentioned it and I keep forgetting the name so I'm adding these instructions here for my future self the next time I google it...

currently pagavcs seems to be the best option.

you want one of these .deb files

sillyspamfilter://pagavcs.googlecode.com/svn/repo/pool/main/p/pagavcs/

(1.4.33 is what I have installed right now so try that one if the latest causes problems)

install then run

nautilus -q

to shutdown nautilus, then open up nautilus again and you should be good to go without having to logout/shutdown

Sadly rabbit just chokes on large repos for me so is unusable, paga doesn't slow down browsing but also doesn't seem to try and recourse into directories to see if anything has changed.

Printing all global variables/local variables?

In case you want to see the local variables of a calling function use select-frame before info locals

E.g.:

(gdb) bt
#0  0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1  0xfec36f39 in thr_kill () from /lib/libc.so.1
#2  0xfebe3603 in raise () from /lib/libc.so.1
#3  0xfebc2961 in abort () from /lib/libc.so.1
#4  0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5  0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb) 

Difference between Apache CXF and Axis

  • Axis2: More ubiquitous on the marketplace, supports more bindings, supports other languages like C/C++.
  • CXF: Much easier to use, more Spring friendly, faster got support for some WS-* extensions.

Force index use in Oracle

There is an appropriate index on column_having_index, and its use actually increase performance, but Oracle didn't use it...
You should gather statistics on your table to let optimizer see that index access can help. Using direct hint is not a good practice.

How to reference a file for variables using Bash?

The short answer

Use the source command.


An example using source

For example:

config.sh

#!/usr/bin/env bash
production="liveschool_joe"
playschool="playschool_joe"
echo $playschool

script.sh

#!/usr/bin/env bash
source config.sh
echo $production

Note that the output from sh ./script.sh in this example is:

~$ sh ./script.sh 
playschool_joe
liveschool_joe

This is because the source command actually runs the program. Everything in config.sh is executed.


Another way

You could use the built-in export command and getting and setting "environment variables" can also accomplish this.

Running export and echo $ENV should be all you need to know about accessing variables. Accessing environment variables is done the same way as a local variable.

To set them, say:

export variable=value

at the command line. All scripts will be able to access this value.

python numpy machine epsilon

It will already work, as David pointed out!

>>> def machineEpsilon(func=float):
...     machine_epsilon = func(1)
...     while func(1)+func(machine_epsilon) != func(1):
...         machine_epsilon_last = machine_epsilon
...         machine_epsilon = func(machine_epsilon) / func(2)
...     return machine_epsilon_last
... 
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07

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

I also encountered this problem in my project. It eventually worked after I inserted the my-controller.js into my karma.conf.js file, with the <script> tag.

Hope this will help. There are quite many reasons that can lead to this problem.

Undefined symbols for architecture arm64

If you faced this issue on your Flutter project while building in Release mode (or Archive) check out my this answer: https://stackoverflow.com/a/61446892/5502121 Long story short:

  • set your build system to New Build System in File > Project Settings…
  • remove ios and build_ios folders
  • run flutter create . to init new ios module
  • run pod install
  • run flutter pub get
  • check your Xcode build config (it should be Release mode and General iOS Device)

and you're good to go

How to redirect a url in NGINX

Similar to another answer here, but change the http in the rewrite to to $scheme like so:

server {
        listen 80;
        server_name test.com;
        rewrite     ^ $scheme://www.test.com$request_uri? permanent;
}

And edit your main server block server_name variable as following:

server_name  www.test.com;

I had to do this to redirect www.test.com to test.com.

Custom style to jquery ui dialogs

The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.

HTML

<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
  Nothing here
</div>

You can use CSS to style the main section of the dialog but not the title

.custom-ui-widget-header-warning {
  background: #EBCCCC;
  font-size: 1em;
}

You need some JS to style the title

$(function() {
                   $("#nonmodal1").dialog({
                     minWidth: 400,
                     minHeight: 'auto',
                     autoOpen: false,
                     dialogClass: 'custom-ui-widget-header-warning',
                     position: {
                       my: 'center',
                       at: 'left'
                     }
                   });

                   $("#dialog1").click(function() {
                     if ($("#nonmodal1").dialog("isOpen") === true) {
                       $("#nonmodal1").dialog("close");
                     } else {
                       $("#nonmodal1").dialog("open").prev().css('background','#D9534F');

                     }
                   });
    });

The example only shows simple styling (background) but you can make it as complex as you wish.

You can see it in action here:

http://codepen.io/chris-hore/pen/OVMPay

How do you pass view parameters when navigating from an action in JSF2?

Without a nicer solution, what I found to work is simply building my query string in the bean return:

public String submit() {
    // Do something
    return "/page2.xhtml?faces-redirect=true&id=" + id;
}

Not the most flexible of solutions, but seems to work how I want it to.

Also using this approach to clean up the process of building the query string: http://www.warski.org/blog/?p=185

Aborting a stash pop in Git

Try using if tracked file.

git rm <path to file>
git reset  <path to file>
git checkout <path to file>

No Network Security Config specified, using platform default - Android Log

I just had the same problem. It is not a network permission but rather thread issue. Below code helped me to solve it. Put is in main activity

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (android.os.Build.VERSION.SDK_INT > 9)
    {
        StrictMode.ThreadPolicy policy = new 
        StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

using scp in terminal

You can download in the current directory with a . :

cd # by default, goes to $HOME
scp me@host:/path/to/file .

or in you HOME directly with :

scp me@host:/path/to/file ~

Disable button in jQuery

I want to disable button on some condition, i am using 1st solution but it won't work for me. But when I use 2nd one it worked.Below are outputs from browser console.

1. $('#psl2 .btn-continue').prop("disabled", true)

<a class=?"btn btn-yellow btn-continue" href=?"#">?Next?</a>?

2. $('#psl2 .btn-continue').attr("disabled","disabled")

<a class=?"btn btn-yellow btn-continue" href=?"#" disabled=?"disabled">?Next?</a>?

Get file content from URL?

1) local simplest methods

<?php
echo readfile("http://example.com/");   //needs "Allow_url_include" enabled
//OR
echo include("http://example.com/");    //needs "Allow_url_include" enabled
//OR
echo file_get_contents("http://example.com/");
//OR
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb"  //needs "Allow_url_fopen" enabled
?> 

2) Better Way is CURL:

echo get_remote_data('http://example.com'); // GET request 
echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request

It automatically handles FOLLOWLOCATION problem + Remote urls:
src="./imageblabla.png" turned into:
src="http://example.com/path/imageblabla.png"

Code : https://github.com/tazotodua/useful-php-scripts/blob/master/get-remote-url-content-data.php

Zoom to fit: PDF Embedded in HTML

Bit of a late response but I noticed that this information can be hard to find and haven't found the answer on SO, so here it is.

Try a differnt parameter #view=FitH to force it to fit in the horzontal space and also you need to start the querystring off with a # rather than an & making it:

filename.pdf#view=FitH

What I've noticed it is that this will work if adobe reader is embedded in the browser but chrome will use it's own version of the reader and won't respond in the same way. In my own case, the chrome browser zoomed to fit width by default, so no problem , but Internet Explorer needed the above parameters to ensure the link always opened the pdf page with the correct view setting.

For a full list of available parameters see this doc

EDIT: (lazy mode on)

enter image description here enter image description here enter image description here enter image description here enter image description here

display data from SQL database into php/ html table

Look in the manual http://www.php.net/manual/en/mysqli.query.php

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

How to resolve ambiguous column names when retrieving results?

When using PDO for a database interacttion, one can use the PDO::FETCH_NAMED fetch mode that could help to resolve the issue:

$sql = "SELECT * FROM news JOIN users ON news.user = user.id";
$data = $pdo->query($sql)->fetchAll(PDO::FETCH_NAMED);
foreach ($data as $row) {
    echo $row['column-name'][0]; // from the news table
    echo $row['column-name'][1]; // from the users table
    echo $row['other-column']; // any unique column name
}

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

I think its a bug, please apply the workaround and then try again: http://support.microsoft.com/kb/281517.

Also, go into Advanced tab, and confirm if Target columns length is Varchar(max).

How can I safely create a nested directory?

If you consider the following:

os.path.isdir('/tmp/dirname')

means a directory (path) exists AND is a directory. So for me this way does what I need. So I can make sure it is folder (not a file) and exists.

Linux command to list all available commands and aliases

Add to .bashrc

function ListAllCommands
{
    echo -n $PATH | xargs -d : -I {} find {} -maxdepth 1 \
        -executable -type f -printf '%P\n' | sort -u
}

If you also want aliases, then:

function ListAllCommands
{
    COMMANDS=`echo -n $PATH | xargs -d : -I {} find {} -maxdepth 1 \
        -executable -type f -printf '%P\n'`
    ALIASES=`alias | cut -d '=' -f 1`
    echo "$COMMANDS"$'\n'"$ALIASES" | sort -u
}

Send raw ZPL to Zebra printer via USB

I spent 8 hours to do that. It is simple...

You shoud have a code like that:

private const int GENERIC_WRITE = 0x40000000;

//private const int OPEN_EXISTING = 3;
private const int OPEN_EXISTING = 1;
private const int FILE_SHARE_WRITE = 0x2;
private StreamWriter _fileWriter;
private FileStream _outFile;
private int _hPort;

Change that variable content from 3 (open file already exist) to 1 (create a new file). It'll work at Windows 7 and XP.

Delete commits from a branch in Git

use git revert https://git-scm.com/docs/git-revert .It will revert all code then you can do next commit.Then head will point to that last commit. reverted commits never delete but it will not affect on you last commit.

javax.persistence.NoResultException: No entity found for query

You mentioned getting the result list from the Query, since you don't know that there is a UniqueResult (hence the exception) you could use list and check the size?

if (query.list().size() == 1) 

Since you're not doing a get() to get your unique object a query will be executed whether you call uniqueResult or list.

PHP Get Site URL Protocol - http vs https

Use this server variable to get the protocol details:

 $scheme = $_SERVER['REQUEST_SCHEME'] . '://';
 echo $scheme; //it gives http:// or https://

Note that this server variable is unreliable. For more information take a look at: Is $_SERVER['REQUEST_SCHEME'] reliable?

Problems when trying to load a package in R due to rJava

For reading/writing excel files, you can use :

  • readxl package for reading and writexl package for writing
  • openxlsx package for reading and writing

With xlsx and XLConnect (which use rjava) you will face memory errors if you have large files

Python: get key of index in dictionary

Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.

You can only do this in a loop:

[k for (k, v) in i.iteritems() if v == 0]

Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0} is perfectly legal.

If you want ordering you either need to use a list or a OrderedDict instance instead:

items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0]         # gives 'a'

C convert floating point to int

my_var = (int)my_var;

As simple as that. Basically you don't need it if the variable is int.

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

C++ Object Instantiation

I've seen this anti-pattern from people who don't quite get the & address-of operator. If they need to call a function with a pointer, they'll always allocate on the heap so they get a pointer.

void FeedTheDog(Dog* hungryDog);

Dog* badDog = new Dog;
FeedTheDog(badDog);
delete badDog;

Dog goodDog;
FeedTheDog(&goodDog);

OpenJDK availability for Windows OS

You may find OpenJDK 6 and 7 binaries for Windows in openjdk-unofficial-builds github project.

Update: OpenJDK 8 and 11 LTS binaries for Windows x86_64 can be found in ojdkbuild github project.

Disclaimer: I've built them myself.

Update (2019): OpenJDK Updates Project Builds for 8 and 11 are available now.

How to load a xib file in a UIView

Create a XIB file :

File -> new File ->ios->cocoa touch class -> next

enter image description here

make sure check mark "also create XIB file"

I would like to perform with tableview so I choosed subclass UITableViewCell

you can choose as your requerment

enter image description here

XIB file desing as your wish (RestaurantTableViewCell.xib)

enter image description here

we need to grab the row height to set table each row hegiht

enter image description here

Now! need to huck them swift file . i am hucked the restaurantPhoto and restaurantName you can huck all of you .

enter image description here

Now adding a UITableView

enter image description here

name
The name of the nib file, which need not include the .nib extension.

owner
The object to assign as the nib’s File's Owner object.

options
A dictionary containing the options to use when opening the nib file.

first if you do not define first then grabing all view .. so you need to grab one view inside that set frist .

Bundle.main.loadNibNamed("yourUIView", owner: self, options: nil)?.first as! yourUIView

here is table view controller Full code

import UIKit

class RestaurantTableViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let restaurantTableviewCell = Bundle.main.loadNibNamed("RestaurantTableViewCell", owner: self, options: nil)?.first as! RestaurantTableViewCell

        restaurantTableviewCell.restaurantPhoto.image = UIImage(named: "image1")
        restaurantTableviewCell.restaurantName.text = "KFC Chicken"

        return restaurantTableviewCell
    }
   // set row height
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }

}

you done :)

enter image description here

Default behavior of "git push" without a branch specified

You can control the default behavior by setting push.default in your git config. From the git-config(1) documentation:

push.default

Defines the action git push should take if no refspec is given on the command line, no refspec is configured in the remote, and no refspec is implied by any of the options given on the command line. Possible values are:

  • nothing: do not push anything

  • matching: push all matching branches

    All branches having the same name in both ends are considered to be matching.

    This used to be the default, but not since Git 2.0 (simple is the new default).

  • upstream: push the current branch to its upstream branch (tracking is a deprecated synonym for upstream)

  • current: push the current branch to a branch of the same name

  • simple: (new in Git 1.7.11) like upstream, but refuses to push if the upstream branch's name is different from the local one

    This is the safest option and is well-suited for beginners.

    This mode has become the default in Git 2.0.

The simple, current and upstream modes are for those who want to push out a single branch after finishing work, even when the other branches are not yet ready to be pushed out

Command line examples:

To view the current configuration:

git config --global push.default

To set a new configuration:

git config --global push.default current

What is key=lambda

Lambda can be any function. So if you had a function

def compare_person(a):
         return a.age

You could sort a list of Person (each of which having an age attribute) like this:

sorted(personArray, key=compare_person)

This way, the list would be sorted by age in ascending order.

The parameter is called lambda because python has a nifty lambda keywords for defining such functions on the fly. Instead of defining a function compare_person and passing that to sorted, you can also write:

sorted(personArray, key=lambda a: a.age)

which does the same thing.

How to check if curl is enabled or disabled

var_dump(extension_loaded('curl'));

When to use single quotes, double quotes, and backticks in MySQL

If table cols and values are variables then there are two ways:

With double quotes "" the complete query:

$query = "INSERT INTO $table_name (id, $col1, $col2)
                 VALUES (NULL, '$val1', '$val2')";

Or

 $query = "INSERT INTO ".$table_name." (id, ".$col1.", ".$col2.")
               VALUES (NULL, '".$val1."', '".$val2."')";

With single quotes '':

$query = 'INSERT INTO '.$table_name.' (id, '.$col1.', '.$col2.')
             VALUES (NULL, '.$val1.', '.$val2.')';

Use back ticks `` when a column/value name is similar to a MySQL reserved keyword.

Note: If you are denoting a column name with a table name then use back ticks like this:

`table_name`. `column_name` <-- Note: exclude . from back ticks.

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

if...else within JSP or JSTL

In case you want to compare strings, write the following JSTL:

<c:choose>
    <c:when test="${myvar.equals('foo')}">
        ...
    </c:when>
    <c:when test="${myvar.equals('bar')}">
        ...
    </c:when>
    <c:otherwise>
        ...
    </c:otherwise>
</c:choose>

Javascript onHover event

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

Locking pattern for proper use of .NET MemoryCache

I assume this code has concurrency issues:

Actually, it's quite possibly fine, though with a possible improvement.

Now, in general the pattern where we have multiple threads setting a shared value on first use, to not lock on the value being obtained and set can be:

  1. Disastrous - other code will assume only one instance exists.
  2. Disastrous - the code that obtains the instance is not can only tolerate one (or perhaps a certain small number) concurrent operations.
  3. Disastrous - the means of storage is not thread-safe (e.g. have two threads adding to a dictionary and you can get all sorts of nasty errors).
  4. Sub-optimal - the overall performance is worse than if locking had ensured only one thread did the work of obtaining the value.
  5. Optimal - the cost of having multiple threads do redundant work is less than the cost of preventing it, especially since that can only happen during a relatively brief period.

However, considering here that MemoryCache may evict entries then:

  1. If it's disastrous to have more than one instance then MemoryCache is the wrong approach.
  2. If you must prevent simultaneous creation, you should do so at the point of creation.
  3. MemoryCache is thread-safe in terms of access to that object, so that is not a concern here.

Both of these possibilities have to be thought about of course, though the only time having two instances of the same string existing can be a problem is if you're doing very particular optimisations that don't apply here*.

So, we're left with the possibilities:

  1. It is cheaper to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().
  2. It is cheaper not to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().

And working that out can be difficult (indeed, the sort of thing where it's worth profiling rather than assuming you can work it out). It's worth considering here though that most obvious ways of locking on insert will prevent all additions to the cache, including those that are unrelated.

This means that if we had 50 threads trying to set 50 different values, then we'll have to make all 50 threads wait on each other, even though they weren't even going to do the same calculation.

As such, you're probably better off with the code you have, than with code that avoids the race-condition, and if the race-condition is a problem, you quite likely either need to handle that somewhere else, or need a different caching strategy than one that expels old entries†.

The one thing I would change is I'd replace the call to Set() with one to AddOrGetExisting(). From the above it should be clear that it probably isn't necessary, but it would allow the newly obtained item to be collected, reducing overall memory use and allowing a higher ratio of low generation to high generation collections.

So yeah, you could use double-locking to prevent concurrency, but either the concurrency isn't actually a problem, or your storing the values in the wrong way, or double-locking on the store would not be the best way to solve it.

*If you know only one each of a set of strings exists, you can optimise equality comparisons, which is about the only time having two copies of a string can be incorrect rather than just sub-optimal, but you'd want to be doing very different types of caching for that to make sense. E.g. the sort XmlReader does internally.

†Quite likely either one that stores indefinitely, or one that makes use of weak references so it will only expel entries if there are no existing uses.

android ellipsize multiline textview

This one handled my html as well,

/*
 * Copyright (C) 2013 Google Inc.
 * Licensed to The Android Open Source Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.mail.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
/**
 * A special MultiLine TextView that will apply ellipsize logic to only the last
 * line of text, such that the last line may be shorter than any previous lines.
 */
public class EllipsizedMultilineTextView extends TextView {
    public static final int ALL_AVAILABLE = -1;
    private int mMaxLines;

    public EllipsizedMultilineTextView(Context context) {
        super(context);
    }
    public EllipsizedMultilineTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }
    public EllipsizedMultilineTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private final void init(Context context, AttributeSet attrs) {
        final TypedArray a = context.obtainStyledAttributes(attrs,
            new int[] { android.R.attr.maxLines });
        setMaxLines(a.getInt(0, 2));
    }
    @Override
    public void setMaxLines(int maxlines) {
        super.setMaxLines(maxlines);
        mMaxLines = maxlines;
    }
    /**
     * Ellipsize just the last line of text in this view and set the text to the
     * new ellipsized value.
     * @param text Text to set and ellipsize
     * @param avail available width in pixels for the last line
     * @param paint Paint that has the proper properties set to measure the text
     *            for this view
     * @return the {@link CharSequence} that was set on the {@link TextView}
     */
    public CharSequence setText(final CharSequence text, int avail) {
        if (text == null || text.length() == 0) {
            return text;
        }
        setEllipsize(null);
        setText(text);
        if (avail == ALL_AVAILABLE) {
            return text;
        }
        Layout layout = getLayout();
        if (layout == null) {
            final int w = getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
            layout = new StaticLayout(text, 0, text.length(), getPaint(), w, Alignment.ALIGN_NORMAL,
                1.0f, 0f, false);
        }
        // find the last line of text and chop it according to available space
        final int lastLineStart = layout.getLineStart(mMaxLines - 1);
        final CharSequence remainder = TextUtils.ellipsize(text.subSequence(lastLineStart,
            text.length()), getPaint(), avail, TextUtils.TruncateAt.END);
        // assemble just the text portion, without spans
        final SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(text.toString(), 0, lastLineStart);
        if (!TextUtils.isEmpty(remainder)) {
            builder.append(remainder.toString());
        }
        // Now copy the original spans into the assembled string, modified for any ellipsizing.
        //
        // Merely assembling the Spanned pieces together would result in duplicate CharacterStyle
        // spans in the assembled version if a CharacterStyle spanned across the lastLineStart
        // offset.
        if (text instanceof Spanned) {
            final Spanned s = (Spanned) text;
            final Object[] spans = s.getSpans(0, s.length(), Object.class);
            final int destLen = builder.length();
            for (int i = 0; i < spans.length; i++) {
                final Object span = spans[i];
                final int start = s.getSpanStart(span);
                final int end = s.getSpanEnd(span);
                final int flags = s.getSpanFlags(span);
                if (start <= destLen) {
                    builder.setSpan(span, start, Math.min(end, destLen), flags);
                }
            }
        }
        setText(builder);
        return builder;
    }
}

Orignal Source LINK

java.math.BigInteger cannot be cast to java.lang.Long

I'm lacking context, but this is working just fine:

List<BigInteger> nums = new ArrayList<BigInteger>();
Long max = Collections.max(nums).longValue(); // from BigInteger to Long...

How to capture a JFrame's close button click event?

This may work:

jdialog.addWindowListener(new WindowAdapter() {
    public void windowClosed(WindowEvent e) {
        System.out.println("jdialog window closed event received");
    }

    public void windowClosing(WindowEvent e) {
        System.out.println("jdialog window closing event received");
    }
});

Source: https://alvinalexander.com/java/jdialog-close-closing-event

jQuery Datepicker with text input that doesn't allow user input

I've found that the jQuery Calendar plugin, for me at least, in general just works better for selecting dates.

Python loop to run for certain amount of seconds

I was looking for an easier-to-read time-loop when I encountered this question here. Something like:

for sec in max_seconds(10):
      do_something()

So I created this helper:

# allow easy time-boxing: 'for sec in max_seconds(42): do_something()'
def max_seconds(max_seconds, *, interval=1):
    interval = int(interval)
    start_time = time.time()
    end_time = start_time + max_seconds
    yield 0
    while time.time() < end_time:
        if interval > 0:
            next_time = start_time
            while next_time < time.time():
                next_time += interval
            time.sleep(int(round(next_time - time.time())))
        yield int(round(time.time() - start_time))
        if int(round(time.time() + interval)) > int(round(end_time)): 
            return

It only works with full seconds which was OK for my use-case.

Examples:

for sec in max_seconds(10) # -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
for sec in max_seconds(10, interval=3) # -> 0, 3, 6, 9
for sec in max_seconds(7): sleep(1.5) # -> 0, 2, 4, 6
for sec in max_seconds(8): sleep(1.5) # -> 0, 2, 4, 6, 8

Be aware that interval isn't that accurate, as I only wait full seconds (sleep never was any good for me with times < 1 sec). So if your job takes 500 ms and you ask for an interval of 1 sec, you'll get called at: 0, 500ms, 2000ms, 2500ms, 4000ms and so on. One could fix this by measuring time in a loop rather than sleep() ...

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

All the above not working for me.. Because I am using Facebook Ad dependency..

Incase If anybody using this dependency compile 'com.facebook.android:audience-network-sdk:4.16.0'

Try this code instead of above

compile ('com.facebook.android:audience-network-sdk:4.16.0'){
exclude group: 'com.google.android.gms'
}

Java - escape string to prevent SQL injection

From:Source

public String MysqlRealScapeString(String str){
  String data = null;
  if (str != null && str.length() > 0) {
    str = str.replace("\\", "\\\\");
    str = str.replace("'", "\\'");
    str = str.replace("\0", "\\0");
    str = str.replace("\n", "\\n");
    str = str.replace("\r", "\\r");
    str = str.replace("\"", "\\\"");
    str = str.replace("\\x1a", "\\Z");
    data = str;
  }
  return data;
}

Tab Escape Character?

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

\t     Horizontal tab (ASCII code value: 9)

\n     Line feed (ASCII code value: 10)

\r     Carriage return (ASCII code value: 13)

\'     Single quotation mark

\"     Double quotation mark

\\     Backslash

\?     Literal question mark

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

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

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

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

How to join a slice of strings into a single string?

Use a slice, not an arrray. Just create it using

reg := []string {"a","b","c"}

An alternative would have been to convert your array to a slice when joining :

fmt.Println(strings.Join(reg[:],","))

Read the Go blog about the differences between slices and arrays.

What is the proper declaration of main in C++?

From Standard docs., 3.6.1.2 Main Function,

It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

int main() { / ... / } and int main(int argc, char* argv[]) { / ... / }

In the latter form argc shall be the number of arguments passed to the program from the environment in which the program is run.If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings.....

Hope that helps..

Create SQL script that create database and tables

An excellent explanation can be found here: Generate script in SQL Server Management Studio

Courtesy Ali Issa Here's what you have to do:

  1. Right click the database (not the table) and select tasks --> generate scripts
  2. Next --> select the requested table/tables (from select specific database objects)
  3. Next --> click advanced --> types of data to script = schema and data

If you want to create a script that just generates the tables (no data) you can skip the advanced part of the instructions!

Passing argument to alias in bash

In csh (as opposed to bash) you can do exactly what you want.

alias print 'lpr \!^ -Pps5'
print memo.txt

The notation \!^ causes the argument to be inserted in the command at this point.

The ! character is preceeded by a \ to prevent it being interpreted as a history command.

You can also pass multiple arguments:

alias print 'lpr \!* -Pps5'
print part1.ps glossary.ps figure.ps

(Examples taken from http://unixhelp.ed.ac.uk/shell/alias_csh2.1.html .)

How to add days to the current date?

In SQL Server 2008 and above just do this:

SELECT DATEADD(day, 1, Getdate()) AS DateAdd;

Setting up connection string in ASP.NET to SQL SERVER

You can use following format:

  <connectionStrings>
    <add name="ConStringBDName" connectionString="Data Source=serverpath;Initial Catalog=YourDataBaseName;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Most probably you will fing connectionstring tag in web.config after <appSettings>

Try out this.

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Although a bit late, I've come across this question while searching the solution for the same problem, so I hope it can be of any help...

Found myself in the same darkness than you. Just found this article, which explains some new hints introduced in NetBeans 7.4, including this one:

https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new

The reason why it has been added is because superglobals usually are filled with user input, which shouldn't ever be blindly trusted. Instead, some kind of filtering should be done, and that's what the hint suggests. Filter the superglobal value in case it has some poisoned content.

For instance, where I had:

$_SERVER['SERVER_NAME']

I've put instead:

filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_STRING)

You have the filter_input and filters doc here:

http://www.php.net/manual/en/function.filter-input.php

http://www.php.net/manual/en/filter.filters.php

Can I change the checkbox size using CSS?

I just came out with this:

_x000D_
_x000D_
input[type="checkbox"] {display:none;}_x000D_
input[type="checkbox"] + label:before {content:"?";}_x000D_
input:checked + label:before {content:"?";}_x000D_
label:hover {color:blue;}
_x000D_
<input id="check" type="checkbox" /><label for="check">Checkbox</label>
_x000D_
_x000D_
_x000D_

Of course, thanks to this, you can change the value of content to your needs and use an image if you wish or use another font...

The main interest here is that:

  1. The checkbox size stays proportional to the text size

  2. You can control the aspect, the color, the size of the checkbox

  3. No extra HTML needed !

  4. Only 3 lines of CSS needed (the last one is just to give you ideas)

Edit: As pointed out in the comment, the checkbox won't be accessible by key navigation. You should probably add tabindex=0 as a property for your label to make it focusable.

How do I finish the merge after resolving my merge conflicts?

A merge conflict occurs when two branches you're trying to merge both changed the same part of the same file. You can generate a list of conflicts with git status.

When the conflicted line is encountered, Git will edit the content of the affected files with visual indicators that mark both sides of the conflicting content.

<<<<<<< HEAD
conflicted text from HEAD
=======
conflicted text from merging_branch
>>>>>>> merging_branch

When you fix your conflicted files and you are ready to merge, all you have to do is run git add and git commit to generate the merge commit. Once the commit was made ,git push the changes to the branch.

Reference article: Git merge.

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

What is the difference between Document style and RPC style communication?

In WSDL definition, bindings contain operations, here comes style for each operation.

Document : In WSDL file, it specifies types details either having inline Or imports XSD document, which describes the structure(i.e. schema) of the complex data types being exchanged by those service methods which makes loosely coupled. Document style is default.

  • Advantage:
    • Using this Document style, we can validate SOAP messages against predefined schema. It supports xml datatypes and patterns.
    • loosely coupled.
  • Disadvantage: It is a little bit hard to get understand.

In WSDL types element looks as follows:

<types>
 <xsd:schema>
  <xsd:import schemaLocation="http://localhost:9999/ws/hello?xsd=1" namespace="http://ws.peter.com/"/>
 </xsd:schema>
</types>

The schema is importing from external reference.

RPC :In WSDL file, it does not creates types schema, within message elements it defines name and type attributes which makes tightly coupled.

<types/>  
<message name="getHelloWorldAsString">  
<part name="arg0" type="xsd:string"/>  
</message>  
<message name="getHelloWorldAsStringResponse">  
<part name="return" type="xsd:string"/>  
</message>  
  • Advantage: Easy to understand.
  • Disadvantage:
    • we can not validate SOAP messages.
    • tightly coupled

RPC : No types in WSDL
Document: Types section would be available in WSDL

How can I set a custom baud rate on Linux?

You can just use the normal termios header and normal termios structure (it's the same as the termios2 when using header asm/termios).

So, you open the device using open() and get a file descriptor, then use it in tcgetattr() to fill your termios structure.

Then clear CBAUD and set CBAUDEX on c_cflag. CBAUDEX has the same value as BOTHER.

After setting this, you can set a custom baud rate using normal functions, like cfsetspeed(), specifying the desired baud rate as an integer.

Replace a character at a specific index in a string?

I agree with Petar Ivanov but it is best if we implement in following way:

public String replace(String str, int index, char replace){     
    if(str==null){
        return str;
    }else if(index<0 || index>=str.length()){
        return str;
    }
    char[] chars = str.toCharArray();
    chars[index] = replace;
    return String.valueOf(chars);       
}

Transform only one axis to log10 scale with ggplot2

The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:

m + geom_boxplot() + scale_y_continuous(trans='log10')

EDIT: Or if you don't like that, then either of these appears to give different but useful results:

m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot() 
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()

EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):

fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) + 
  geom_boxplot() + 
  scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)

alt text

Note added mid 2017 in comment about package syntax change:

scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

What is a practical, real world example of the Linked List?

Real life example for:

**1) Singly linked list **

  1. Human brain of a child(In order to remember something eg . poem he has to link it , if you will ask him the last line he will have to read from the first line)
  2. message delivery on network (message is broken into packets and each packet has a key of the next one so that at the receiver's end , it will be easy to club them)

2) Doubly linked list

  1. DNA molecules
  2. Browser cache which allows to use BACK button.
  3. Train coaches are connected with the next and the previous ones.
  4. Roller chain of bicycle(doubly circular linked list)

3) Circular linked list

  1. Escalator
  2. Time sharing problem used by the scheduler during the scheduling of the processes in the Operating system.
  3. Multiple Player board game

Concatenating strings doesn't work as expected

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:

std::string c = "hello" + "world";

This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:

std::string c = std::string("hello") + "world";

Convert hex to binary

Another way:

import math

def hextobinary(hex_string):
    s = int(hex_string, 16) 
    num_digits = int(math.ceil(math.log(s) / math.log(2)))
    digit_lst = ['0'] * num_digits
    idx = num_digits
    while s > 0:
        idx -= 1
        if s % 2 == 1: digit_lst[idx] = '1'
        s = s / 2
    return ''.join(digit_lst)

print hextobinary('abc123efff')

Which is the fastest algorithm to find prime numbers?

It depends on your application. There are some considerations:

  • Do you need just the information whether a few numbers are prime, do you need all prime numbers up to a certain limit, or do you need (potentially) all prime numbers?
  • How big are the numbers you have to deal with?

The Miller-Rabin and analogue tests are only faster than a sieve for numbers over a certain size (somewhere around a few million, I believe). Below that, using a trial division (if you just have a few numbers) or a sieve is faster.

PHP 7: Missing VCRUNTIME140.dll

If you've followed Adam's instructions and you're still getting this error make sure you've installed the right variants (x86 or x64).

I had VC14x64 with PHP7x86 and I still got this error. Changing PHP7 to x64 fixed it. It's easy to miss you accidentally installed the wrong version.

Asp.net Hyperlink control equivalent to <a href="#"></a>

hyperlink1.NavigateUrl = "#"; or
hyperlink1.attributes["href"] = "#"; or
<asp:HyperLink NavigateUrl="#" runat="server" />

Plotting a 2D heatmap with Matplotlib

The imshow() function with parameters interpolation='nearest' and cmap='hot' should do what you want.

import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()

enter image description here

How can I make PHP display the error instead of giving me 500 Internal Server Error

Be careful to check if

display_errors

or

error_reporting

is active (not a comment) somewhere else in the ini file.

My development server refused to display errors after upgrade to Kubuntu 16.04 - I had checked php.ini numerous times ... turned out that there was a diplay_errors = off; about 100 lines below my

display_errors = on;

So remember the last one counts!

XMLHttpRequest cannot load an URL with jQuery

In new jQuery 1.5 you can use:

$.ajax({
    type: "GET",
    url: "http://localhost:99000/Services.svc/ReturnPersons",
    dataType: "jsonp",
    success: readData(data),
    error: function (xhr, ajaxOptions, thrownError) {
      alert(xhr.status);
      alert(thrownError);
    }
})

How can I start PostgreSQL on Windows?

Remove Postmaster file in "C:\Program Files\PostgreSQL\9.6\data"

and restart the PostgreSQL services

Failed to load resource: the server responded with a status of 404 (Not Found)

For me the error was the files under js folder not included in the project this solve my issue :

1- In the solution explorer toolbar click Show All Files.

2- open js folder and select all files under the folder

3- right click then select include In Project

4- Save and build your application then its working correct and load .css and .js files

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

Java Calendar, getting current month value, clarification needed

Calendar.get takes as argument one of the standard Calendar fields, like YEAR or MONTH not a month name.

Calendar.JANUARY is 0, which is also the value of Calendar.ERA, so Calendar.getInstance().get(0) will return the era, in this case Calendar.AD, which is 1.

For the first part of your question, note that, as is wildly documented, months start at 0, so 10 is actually November.

Converting a String array into an int Array in java

public static int[] strArrayToIntArray(String[] a){
    int[] b = new int[a.length];
    for (int i = 0; i < a.length; i++) {
        b[i] = Integer.parseInt(a[i]);
    }

    return b;
}

This is a simple function, that should help you. You can use him like this:

int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);

How to implode array with key and value without foreach in PHP

For debugging purposes. Recursive write an array of nested arrays to a string. Used foreach. Function stores National Language characters.

function q($input)
{
    $glue = ', ';
    $function = function ($v, $k) use (&$function, $glue) {
        if (is_array($v)) {
            $arr = [];
            foreach ($v as $key => $value) {
                $arr[] = $function($value, $key);
            }
            $result = "{" . implode($glue, $arr) . "}";
        } else {
            $result = sprintf("%s=\"%s\"", $k, var_export($v, true));
        }
        return $result;
    };
    return implode($glue, array_map($function, $input, array_keys($input))) . "\n";
}

javascript: detect scroll end

OK Here is a Good And Proper Solution

You have a Div call with an id="myDiv"

so the function goes.

function GetScrollerEndPoint()
{
   var scrollHeight = $("#myDiv").prop('scrollHeight');
   var divHeight = $("#myDiv").height();
   var scrollerEndPoint = scrollHeight - divHeight;

   var divScrollerTop =  $("#myDiv").scrollTop();
   if(divScrollerTop === scrollerEndPoint)
   {
       //Your Code 
       //The Div scroller has reached the bottom
   }
}

How do you make strings "XML safe"?

Since PHP 5.4 you can use:

htmlspecialchars($string, ENT_XML1);

You should specify the encoding, such as:

htmlspecialchars($string, ENT_XML1, 'UTF-8');

Update

Note that the above will only convert:

  • & to &amp;
  • < to &lt;
  • > to &gt;

If you want to escape text for use in an attribute enclosed in double quotes:

htmlspecialchars($string, ENT_XML1 | ENT_COMPAT, 'UTF-8');

will convert " to &quot; in addition to &, < and >.


And if your attributes are enclosed in single quotes:

htmlspecialchars($string, ENT_XML1 | ENT_QUOTES, 'UTF-8');

will convert ' to &apos; in addition to &, <, > and ".

(Of course you can use this even outside of attributes).


See the manual entry for htmlspecialchars.

Synchronizing a local Git repository with a remote one

If you are talking about syncing a forked repo then you can follow these steps.

How to sync a fork repository from git

  1. check your current git branch

    git branch

  2. checkout to master if you are not on master

    git checkout master

  3. Fetch the upstream repository if you have correct access rights

    git fetch upstream

  4. If you are getting below error then run

    git remote add upstream [email protected]:upstream_clone_repo_url/xyz.git

    fatal: 'upstream/master' does not appear to be a git repository  
    fatal: Could not read from remote repository.
    Please make sure you have the correct access rights and the repository exists.
    
  5. Now run the below command.

    git fetch upstream

  6. Now if you are on master then merge the upstream/master into master branch

    git merge upstream/master

    That's it!!

    Crosscheck via git remote command, more specific git remote -v

    If I also have commit rights to the upstream repo, I can create a local upstream branch and do work that will go upstream there.

Media Queries - In between two widths

@Jonathan Sampson i think your solution is wrong if you use multiple @media.

You should use (min-width first):

@media screen and (min-width:400px) and (max-width:900px){
   ...
}

Filter dataframe rows if value in column is in a set list of values

you can also use ranges by using:

b = df[(df['a'] > 1) & (df['a'] < 5)]

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

Since the count is the intended final value, in your query pass

$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record); 
$query = $this->db->get()->result_array();
return count($query);

The count the retuned value

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

The location of jfxrt.jar in Oracle Java 7 is:

<JRE_HOME>/lib/jfxrt.jar

The location of jfxrt.jar in Oracle Java 8 is:

<JRE_HOME>/lib/ext/jfxrt.jar

The <JRE_HOME> will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.

jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).


An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.


Use Oracle Java 8.

With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.

OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.

My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6

Yes, but only the Oracle JDK.

The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).

In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.

CSS Margin: 0 is not setting to 0

Try

html, body{
  margin:0 !important;
  padding:0 !important;
}

Getting the name / key of a JToken with JSON.net

JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

How do I programmatically change file permissions?

If you want to set 777 permission to your created file than you can use the following method:

public void setPermission(File file) throws IOException{
    Set<PosixFilePermission> perms = new HashSet<>();
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);

    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_WRITE);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);

    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);

    Files.setPosixFilePermissions(file.toPath(), perms);
}

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

For those who had trouble with the apt-get, or with the long instruction. I solved it in a relatively painless way.

  1. Download the installer from here, or direct download link
  2. $ sudo dpkg -i oracle-java8-installer_8u51+8u51arm-1-webupd8-0_all.deb

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

This worked perfectly for me.

mysql> use mysql; mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'my-password-here';

Groovy / grails how to determine a data type?

To determine the class of an object simply call:

someObject.getClass()

You can abbreviate this to someObject.class in most cases. However, if you use this on a Map it will try to retrieve the value with key 'class'. Because of this, I always use getClass() even though it's a little longer.

If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:

(somObject instanceof Date)

or to check if the class of an object is exactly a particular class (not a subclass of it), use:

(somObject.getClass() == Date)

Twitter bootstrap scrollable modal

I´ve done a tiny solution using only jQuery.

First, you need to put an additional class to your <div class="modal-body"> I called "ativa-scroll", so it becomes something like this:

<div class="modal-body ativa-scroll">

So now just put this piece of code on your page, near your JS loading:

<script type="text/javascript">
  $(document).ready(ajustamodal);
  $(window).resize(ajustamodal);
  function ajustamodal() {
    var altura = $(window).height() - 155; //value corresponding to the modal heading + footer
    $(".ativa-scroll").css({"height":altura,"overflow-y":"auto"});
  }
</script>

I works perfectly for me, also in a responsive way! :)

How to modify a specified commit?

Run:

$ git rebase --interactive commit_hash^

each ^ indicates how many commits back you want to edit, if it's only one (the commit hash that you specified), then you just add one ^.

Using Vim you change the words pick to reword for the commits you want to change, save and quit(:wq). Then git will prompt you with each commit that you marked as reword so you can change the commit message.

Each commit message you have to save and quit(:wq) to go to the next commit message

If you want to exit without applying the changes, press :q!

EDIT: to navigate in vim you use j to go up, k to go down, h to go left, and l to go right( all this in NORMAL mode, press ESC to go to NORMAL mode ). To edit a text, press i so that you enter the INSERT mode, where you insert text. Press ESC to go back to NORMAL mode :)

UPDATE: Here's a great link from github listing How to undo (almost) anything with git

How to iterate over the file in python

This is probably because an empty line at the end of your input file.

Try this:

for x in f:
    try:
        print int(x.strip(),16)
    except ValueError:
        print "Invalid input:", x

How to create a Java cron job

First I would recommend you always refer docs before you start a new thing.

We have SchedulerFactory which schedules Job based on the Cron Expression given to it.

    //Create instance of factory
    SchedulerFactory schedulerFactory=new StdSchedulerFactory();

    //Get schedular
    Scheduler scheduler= schedulerFactory.getScheduler();

    //Create JobDetail object specifying which Job you want to execute
    JobDetail jobDetail=new JobDetail("myJobClass","myJob1",MyJob.class);

    //Associate Trigger to the Job
    CronTrigger trigger=new CronTrigger("cronTrigger","myJob1","0 0/1 * * * ?");

    //Pass JobDetail and trigger dependencies to schedular
    scheduler.scheduleJob(jobDetail,trigger);

    //Start schedular
    scheduler.start();

MyJob.class

public class MyJob implements Job{

      @Override
      public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                 System.out.println("My Logic");
        }

    }

Proxy with urllib2

In addition set the proxy for the command line session Open a command line where you might want to run your script

netsh winhttp set proxy YourProxySERVER:yourProxyPORT

run your script in that terminal.

Set "Homepage" in Asp.Net MVC

I tried the answer but it didn't worked for me. This is what i ended up doing:

Create a new controller DefaultController. In index action, i wrote one line redirect:

return Redirect("~/Default.aspx")

In RouteConfig.cs, change controller="Default" for the route.

 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
        );

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

Its complete installation nightmare, but I'll give one more hope you can avoid building opencv from source:

pip install opencv-contrib-python

C# DataRow Empty-check

I created an extension method (gosh I wish Java had these) called IsEmpty as follows:

public static bool IsEmpty(this DataRow row)
{
    return row == null || row.ItemArray.All(i => i is DBNull);
}

The other answers here are correct. I just felt mine lent brevity in its succinct use of Linq to Objects. BTW, this is really useful in conjunction with Excel parsing since users may tack on a row down the page (thousands of lines) with no regard to how that affects parsing the data.

In the same class, I put any other helpers I found useful, like parsers so that if the field contains text that you know should be a number, you can parse it fluently. Minor pro tip for anyone new to the idea. (Anyone at SO, really? Nah!)

With that in mind, here is an enhanced version:

public static bool IsEmpty(this DataRow row)
{
    return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
}

public static bool IsNullEquivalent(this object value)
{
    return value == null
           || value is DBNull
           || string.IsNullOrWhiteSpace(value.ToString());
}

Now you have another useful helper, IsNullEquivalent which can be used in this context and any other, too. You could extend this to include things like "n/a" or "TBD" if you know that your data has placeholders like that.

How to store arrays in MySQL?

Use database field type BLOB to store arrays.

Ref: http://us.php.net/manual/en/function.serialize.php

Return Values

Returns a string containing a byte-stream representation of value that can be stored anywhere.

Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.

Regular Expression for matching parentheses

For any special characters you should use '\'. So, for matching parentheses - /\(/

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

I have researched a lot for cleaning Backstack, and finally see Transaction BackStack and its management. Here is the solution that worked best for me.

 // CLEAR BACK STACK.
    private void clearBackStack() {
        final FragmentManager fragmentManager = getSupportFragmentManager();
        while (fragmentManager.getBackStackEntryCount() != 0) {
            fragmentManager.popBackStackImmediate();
        }
    }

The above method loops over all the transactions in the backstack and removes them immediately one at a time.

Note: above code sometime not work and i face ANR because of this code,so please do not try this.

Update below method remove all fregment of that "name" from backstack.

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack("name",FragmentManager.POP_BACK_STACK_INCLUSIVE);
  • name If non-null, this is the name of a previous back state to look for; if found, all states up to that state will be popped. The
  • POP_BACK_STACK_INCLUSIVE flag can be used to control whether the named state itself is popped. If null, only the top state is popped.

MySQL Insert query doesn't work with WHERE clause

It depends on the situation INSERT can actually have a where clause.

For example if you are matching values from a form.

Consider INSERT INTO Users(name,email,weight, desiredWeight) VALUES (fred,[email protected],160,145) WHERE name != fred AND email != [email protected]

Makes sense doesn't it?

Setting top and left CSS attributes

We can create a new CSS class for div.

 .div {
      position: absolute;
      left: 150px;
      width: 200px;
      height: 120px;
    }

Hive: how to show all partitions of a table?

Okay, I'm writing this answer by extending wmky's answer above & also, assuming that you've configured mysql for your metastore instead of derby.

select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='<table_name>');

The above query gives you all possible values of the partition columns.

Example:

hive> desc clicks_fact;
OK
time                    timestamp                                   
..                              
day                     date                                        
file_date               varchar(8)                                  

# Partition Information      
# col_name              data_type               comment             

day                     date                                        
file_date               varchar(8)                                  
Time taken: 1.075 seconds, Fetched: 28 row(s)

I'm going to fetch the values of partition columns.

mysql> select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='clicks_fact');
+-----------------------------------+
| PART_NAME                         |
+-----------------------------------+
| day=2016-08-16/file_date=20160816 |
| day=2016-08-17/file_date=20160816 |
....
....
| day=2017-09-09/file_date=20170909 |
| day=2017-09-08/file_date=20170909 |
| day=2017-09-09/file_date=20170910 |
| day=2017-09-10/file_date=20170910 |
+-----------------------------------+

1216 rows in set (0.00 sec)

Returns all partition columns.

Note: JOIN table DBS ON DB_ID when there is a DB involved (i.e, when, multiple DB's have same table_name)

How to install an apk on the emulator in Android Studio?

Just download the apk from talkback website

Drag the downloaded apk to the started emulator, Go to settings on emulator > Search for talkback, you will now find it there

Staging Deleted files

for those using git 2.x+ in powershell:

foreach ($filePath in (git ls-files --deleted)) { git add "$filePath" }

Open web in new tab Selenium + Python

This is a common code adapted from another examples:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.google.com/")

#open tab
# ... take the code from the options below

# Load a page 
driver.get('http://bings.com')
# Make the tests...

# close the tab
driver.quit()

the possible ways were:

  1. Sending <CTRL> + <T> to one element

    #open tab
    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
    
  2. Sending <CTRL> + <T> via Action chains

    ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
    
  3. Execute a javascript snippet

    driver.execute_script('''window.open("http://bings.com","_blank");''')
    

    In order to achieve this you need to ensure that the preferences browser.link.open_newwindow and browser.link.open_newwindow.restriction are properly set. The default values in the last versions are ok, otherwise you supposedly need:

    fp = webdriver.FirefoxProfile()
    fp.set_preference("browser.link.open_newwindow", 3)
    fp.set_preference("browser.link.open_newwindow.restriction", 2)
    
    driver = webdriver.Firefox(browser_profile=fp)
    

    the problem is that those preferences preset to other values and are frozen at least selenium 3.4.0. When you use the profile to set them with the java binding there comes an exception and with the python binding the new values are ignored.

    In Java there is a way to set those preferences without specifying a profile object when talking to geckodriver, but it seem to be not implemented yet in the python binding:

    FirefoxOptions options = new FirefoxOptions().setProfile(fp);
    options.addPreference("browser.link.open_newwindow", 3);
    options.addPreference("browser.link.open_newwindow.restriction", 2);
    FirefoxDriver driver = new FirefoxDriver(options);
    

The third option did stop working for python in selenium 3.4.0.

The first two options also did seem to stop working in selenium 3.4.0. They do depend on sending CTRL key event to an element. At first glance it seem that is a problem of the CTRL key, but it is failing because of the new multiprocess feature of Firefox. It might be that this new architecture impose new ways of doing that, or maybe is a temporary implementation problem. Anyway we can disable it via:

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.tabs.remote.autostart", False)
fp.set_preference("browser.tabs.remote.autostart.1", False)
fp.set_preference("browser.tabs.remote.autostart.2", False)

driver = webdriver.Firefox(browser_profile=fp)

... and then you can use successfully the first way.

Is the LIKE operator case-sensitive with MSSQL Server?

You have an option to define collation order at the time of defining your table. If you define a case-sensitive order, your LIKE operator will behave in a case-sensitive way; if you define a case-insensitive collation order, the LIKE operator will ignore character case as well:

CREATE TABLE Test (
    CI_Str VARCHAR(15) COLLATE Latin1_General_CI_AS -- Case-insensitive
,   CS_Str VARCHAR(15) COLLATE Latin1_General_CS_AS -- Case-sensitive
);

Here is a quick demo on sqlfiddle showing the results of collation order on searches with LIKE.

Does a "Find in project..." feature exist in Eclipse IDE?

CTRL + H is actually the right answer, but the scope in which it was pressed is actually pretty important. When you have last clicked on file you're working on, you'll get a different search window - Java Search: enter image description here

Whereas when you select directory on Package Explorer and then press Ctrl + H (or choose Search -> File.. from main menu), you get the desired window - File Search: enter image description here

How to check if a URL exists or returns 404 with Java?

There is nothing wrong with your code. It's the NBC.com doing tricks on you. When NBC.com decides that your browser is not capable of displaying PDF, it simply sends back a webpage regardless what you are requesting, even if it doesn't exist.

You need to trick it back by telling it your browser is capable, something like,

conn.setRequestProperty("User-Agent",
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13");

How do I instantiate a Queue object in java?

enter image description here

The Queue interface extends java.util.Collection with additional insertion, extraction, and inspection operations like:

+offer(element: E): boolean // Inserting an element

+poll(): E // Retrieves the element and returns NULL if queue is empty

+remove(): E // Retrieves and removes the element and throws an Exception if queue is empty

+peek(): E // Retrieves,but does not remove, the head of this queue, returning null if this queue is empty.

+element(): E // Retrieves, but does not remove, the head of this queue, throws an exception if te queue is empty.

Example Code for implementing Queue:

java.util.Queue<String> queue = new LinkedList<>();
queue.offer("Hello");
queue.offer("StackOverFlow");
queue.offer("User");

System.out.println(queue.peek());

while (queue.size() > 0){
    System.out.println(queue.remove() + " ");
}
//Since Queue is empty now so this will return NULL
System.out.println(queue.peek());

Output Of the code :

Hello
Hello 
StackOverFlow 
User 
null

ADB - Android - Getting the name of the current activity

I prefer parsing results of dumpsys window windows over dumpsys activity

adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'

Keyguard or Recent tasks list used to not show up as Activities but you were able to see them with mCurrentFocus. I have explained why in this answer.

Convert a float64 to an int in Go

Simply casting to an int truncates the float, which if your system internally represent 2.0 as 1.9999999999, you will not get what you expect. The various printf conversions deal with this and properly round the number when converting. So to get a more accurate value, the conversion is even more complicated than you might first expect:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    floats := []float64{1.9999, 2.0001, 2.0}
    for _, f := range floats {
        t := int(f)
        s := fmt.Sprintf("%.0f", f)
        if i, err := strconv.Atoi(s); err == nil {
            fmt.Println(f, t, i)
        } else {
            fmt.Println(f, t, err)
        }
    }
}

Code on Go Playground

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

Because Stage is required, all one-to-many relationships where Stage is involved will have cascading delete enabled by default. It means, if you delete a Stage entity

  • the delete will cascade directly to Side
  • the delete will cascade directly to Card and because Card and Side have a required one-to-many relationship with cascading delete enabled by default again it will then cascade from Card to Side

So, you have two cascading delete paths from Stage to Side - which causes the exception.

You must either make the Stage optional in at least one of the entities (i.e. remove the [Required] attribute from the Stage properties) or disable cascading delete with Fluent API (not possible with data annotations):

modelBuilder.Entity<Card>()
    .HasRequired(c => c.Stage)
    .WithMany()
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Side>()
    .HasRequired(s => s.Stage)
    .WithMany()
    .WillCascadeOnDelete(false);

Disable browser 'Save Password' functionality

Use real two-factor authentication to avoid the sole dependency on passwords which might be stored in many more places than the user's browser cache.

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {
...
});

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

How to pass a vector to a function?

You're using the argument as a reference but actually it's a pointer. Change vector<int>* to vector<int>&. And you should really set search4 to something before using it.

Remove Item from ArrayList

If you use "=", a replica is created for the original arraylist in the second one, but the reference is same so if you change in one list , the other one will also get modified. Use this instead of "="

        List_Of_Array1.addAll(List_Of_Array);

ASP.NET Core 1.0 on IIS error 502.5

Sharing that in my case this error was because i forgot to update project.json with:

"buildOptions": {
    "emitEntryPoint": true
  }

How to make a transparent HTML button?

Setting its background image to none also works:

button {
    background-image: none;
}

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

how to stop a running script in Matlab

If ctrl+c doesn't respond right away because your script is too long/complex, hold it.

The break command doesn't run when matlab is executing some of its deeper scripts, and either it won't log a ctrl sequence in the buffer, or it clears the buffer just before or just after it completes those pieces of code. In either case, when matlab returns to execute more of your script, it will recognize that you are holding ctrl+c and terminate.

For longer running programs, I usually try to find a good place to provide a status update and I always accompany that with some measure of time using tic and toc. Depending on what I am doing, I might use run time, segment time, some kind of average, etc...

For really long running programs, I found this to be exceptionally useful http://www.mathworks.com/matlabcentral/fileexchange/16649-send-text-message-to-cell-phone/content/send_text_message.m

but it looks like they have some newer functions for this too.

Performance of Arrays vs. Lists

Do not attempt to add capacity by increasing the number of elements.

Performance

List For Add: 1ms
Array For Add: 2397ms

    Stopwatch watch;
        #region --> List For Add <--

        List<int> intList = new List<int>();
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 60000; rpt++)
        {
            intList.Add(rand.Next());
        }
        watch.Stop();
        Console.WriteLine("List For Add: {0}ms", watch.ElapsedMilliseconds);
        #endregion

        #region --> Array For Add <--

        int[] intArray = new int[0];
        watch = Stopwatch.StartNew();
        int sira = 0;
        for (int rpt = 0; rpt < 60000; rpt++)
        {
            sira += 1;
            Array.Resize(ref intArray, intArray.Length + 1);
            intArray[rpt] = rand.Next();

        }
        watch.Stop();
        Console.WriteLine("Array For Add: {0}ms", watch.ElapsedMilliseconds);

        #endregion

Valid characters in a Java class name

I'd like to add to bosnic's answer that any valid currency character is legal for an identifier in Java. th€is is a legal identifier, as is €this, and € as well. However, I can't figure out how to edit his or her answer, so I am forced to post this trivial addition.

Regex expressions in Java, \\s vs. \\s+

The first regex will match one whitespace character. The second regex will reluctantly match one or more whitespace characters. For most purposes, these two regexes are very similar, except in the second case, the regex can match more of the string, if it prevents the regex match from failing.  from http://www.coderanch.com/t/570917/java/java/regex-difference

How can I get the key value in a JSON object?

When you parse the JSON representation, it'll become a JavaScript array of objects.

Because of this, you can use the .length property of the JavaScript array to see how many elements are contained, and use a for loop to enumerate it.

How to recover corrupted Eclipse workspace?

If the workspace is not that big you could backup to say dropbox as a private locked folder.

async await return Task

In order to get proper responses back from async methods, you need to put await while calling those task methods. That will wait for converting it back to the returned value type rather task type.

E.g var content = await StringAsyncTask (

where public async Task<String> StringAsyncTask ())

Polygon Drawing and Getting Coordinates with Google Map API v3

It's cleaner/safer to use the getters provided by google instead of accessing the properties like some did

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
    var coordinatesArray = polygon.overlay.getPath().getArray();
});

IE11 prevents ActiveX from running

There is no solution to this problem. As of IE11 on Windows 8, Microsoft no longer allows ActiveX plugins to run in its browser space. There is absolutely nothing that a third party developer can do about it.

A similar thing has recently happened with the Chrome browser which no longer supports NPAPI plugins. Instead Chrome only supports PPAPI plugins which are useless for system level tasks once performed by NPAPI plugins.

So developers needing browser support for system interactive plugins can only recommend either the Firefox browser or the ASPS web browser.

How to specify jackson to only use fields - preferably globally

How about this: I used it with a mixin

non-compliant object

@Entity
@Getter
@NoArgsConstructor
public class Telemetry {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long pk;
    private String id;
    private String organizationId;
    private String baseType;
    private String name;
    private Double lat;
    private Double lon;
    private Instant updateTimestamp;
}

Mixin:

@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE)
public static class TelemetryMixin {}

Usage:

    ObjectMapper om = objectMapper.addMixIn(Telemetry.class, TelemetryMixin.class);
    Telemetry[] telemetries = om.readValue(someJson, Telemetry[].class);

There is nothing that says you couldn't foreach any number of classes and apply the same mixin.

If you're not familiar with mixins, they are conceptually simply: The structure of the mixin is super imposed on the target class (according to jackson, not as far as the JVM is concerned).

Unable to convert MySQL date/time value to System.DateTime

I also faced the same problem, and get the columns name and its types. Then cast(col_Name as Char) from table name. From this way i get the problem as '0000-00-00 00:00:00' then I Update as valid date and time the error gets away for my case.

List<Map<String, String>> vs List<? extends Map<String, String>>

What I'm missing in the other answers is a reference to how this relates to co- and contravariance and sub- and supertypes (that is, polymorphism) in general and to Java in particular. This may be well understood by the OP, but just in case, here it goes:

Covariance

If you have a class Automobile, then Car and Truck are their subtypes. Any Car can be assigned to a variable of type Automobile, this is well-known in OO and is called polymorphism. Covariance refers to using this same principle in scenarios with generics or delegates. Java doesn't have delegates (yet), so the term applies only to generics.

I tend to think of covariance as standard polymorphism what you would expect to work without thinking, because:

List<Car> cars;
List<Automobile> automobiles = cars;
// You'd expect this to work because Car is-a Automobile, but
// throws inconvertible types compile error.

The reason of the error is, however, correct: List<Car> does not inherit from List<Automobile> and thus cannot be assigned to each other. Only the generic type parameters have an inherit relationship. One might think that the Java compiler simply isn't smart enough to properly understand your scenario there. However, you can help the compiler by giving him a hint:

List<Car> cars;
List<? extends Automobile> automobiles = cars;   // no error

Contravariance

The reverse of co-variance is contravariance. Where in covariance the parameter types must have a subtype relationship, in contravariance they must have a supertype relationship. This can be considered as an inheritance upper-bound: any supertype is allowed up and including the specified type:

class AutoColorComparer implements Comparator<Automobile>
    public int compare(Automobile a, Automobile b) {
        // Return comparison of colors
    }

This can be used with Collections.sort:

public static <T> void sort(List<T> list, Comparator<? super T> c)

// Which you can call like this, without errors:
List<Car> cars = getListFromSomewhere();
Collections.sort(cars, new AutoColorComparer());

You could even call it with a comparer that compares objects and use it with any type.

When to use contra or co-variance?

A bit OT perhaps, you didn't ask, but it helps understanding answering your question. In general, when you get something, use covariance and when you put something, use contravariance. This is best explained in an answer to Stack Overflow question How would contravariance be used in Java generics?.

So what is it then with List<? extends Map<String, String>>

You use extends, so the rules for covariance applies. Here you have a list of maps and each item you store in the list must be a Map<string, string> or derive from it. The statement List<Map<String, String>> cannot derive from Map, but must be a Map.

Hence, the following will work, because TreeMap inherits from Map:

List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
mapList.add(new TreeMap<String, String>());

but this will not:

List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new TreeMap<String, String>());

and this will not work either, because it does not satisfy the covariance constraint:

List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new ArrayList<String>());   // This is NOT allowed, List does not implement Map

What else?

This is probably obvious, but you may have already noted that using the extends keyword only applies to that parameter and not to the rest. I.e., the following will not compile:

List<? extends Map<String, String>> mapList = new List<? extends Map<String, String>>();
mapList.add(new TreeMap<String, Element>())  // This is NOT allowed

Suppose you want to allow any type in the map, with a key as string, you can use extend on each type parameter. I.e., suppose you process XML and you want to store AttrNode, Element etc in a map, you can do something like:

List<? extends Map<String, ? extends Node>> listOfMapsOfNodes = new...;

// Now you can do:
listOfMapsOfNodes.add(new TreeMap<Sting, Element>());
listOfMapsOfNodes.add(new TreeMap<Sting, CDATASection>());

ARM compilation error, VFP registers used by executable, not object file

Your target triplet indicates that your compiler is configured for the hard-float ABI. This means that the libgcc library will also be hardfp. The error message indicates that at least part of your system is using soft-float ABI.

If the compiler has multilib enabled (you can tell with -print-multi-lib) then you can use -mfloat-abi=softfp, but if not then that option won't help you much: gcc will happily generate softfp code, but then there'll be no compatible libgcc to link against.

Basically, hardfp and softfp are just not compatible. You need to get your whole system configured one way or the other.

EDIT: some distros are, or will be, "multiarch". If you have one of those then it's possible to install both ABIs at once, but that's done by doubling everything up -- the compatibility issues still exist.

How to post data using HttpClient?

Use UploadStringAsync method:

WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
    if (e.Error != null)
    {
        //handle your error here
    }
    else
    {
        //post was successful, so do what you need to do here
    }
};

webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);     

Entity Framework 6 Code first Default value

In .NET Core 3.1 you can do the following in the model class:

    public bool? Active { get; set; } 

In the DbContext OnModelCreating you add the default value.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foundation>()
            .Property(b => b.Active)
            .HasDefaultValueSql("1");

        base.OnModelCreating(modelBuilder);
    }

Resulting in the following in the database

enter image description here

Note: If you don't have nullable (bool?) for you property you will get the following warning

The 'bool' property 'Active' on entity type 'Foundation' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead so that the default will only be used for inserts when the property value is 'null'.

Reliable and fast FFT in Java

I wrote a function for the FFT in Java: http://www.wikijava.org/wiki/The_Fast_Fourier_Transform_in_Java_%28part_1%29

It's in the Public Domain so you can use those functions everywhere (personal or business projects too). Just cite me in the credits and send me just a link of your work, and you're ok.

It is completely reliable. I've checked its output against the Mathematica's FFT and they were always correct until the 15th decimal digit. I think it's a very good FFT implementation for Java. I wrote it on the J2SE 1.6 version, and tested it on the J2SE 1.5-1.6 version.

If you count the number of instruction (it's a lot much simpler than a perfect computational complexity function estimation) you can clearly see that this version is great even if it's not optimized at all. I'm planning to publish the optimized version if there are enough requests.

Let me know if it was useful, and tell me any comment you like.

I share the same code right here:

/**
* @author Orlando Selenu
*
*/
public class FFTbase {
/**
 * The Fast Fourier Transform (generic version, with NO optimizations).
 *
 * @param inputReal
 *            an array of length n, the real part
 * @param inputImag
 *            an array of length n, the imaginary part
 * @param DIRECT
 *            TRUE = direct transform, FALSE = inverse transform
 * @return a new array of length 2n
 */
public static double[] fft(final double[] inputReal, double[] inputImag,
                           boolean DIRECT) {
    // - n is the dimension of the problem
    // - nu is its logarithm in base e
    int n = inputReal.length;

    // If n is a power of 2, then ld is an integer (_without_ decimals)
    double ld = Math.log(n) / Math.log(2.0);

    // Here I check if n is a power of 2. If exist decimals in ld, I quit
    // from the function returning null.
    if (((int) ld) - ld != 0) {
        System.out.println("The number of elements is not a power of 2.");
        return null;
    }

    // Declaration and initialization of the variables
    // ld should be an integer, actually, so I don't lose any information in
    // the cast
    int nu = (int) ld;
    int n2 = n / 2;
    int nu1 = nu - 1;
    double[] xReal = new double[n];
    double[] xImag = new double[n];
    double tReal, tImag, p, arg, c, s;

    // Here I check if I'm going to do the direct transform or the inverse
    // transform.
    double constant;
    if (DIRECT)
        constant = -2 * Math.PI;
    else
        constant = 2 * Math.PI;

    // I don't want to overwrite the input arrays, so here I copy them. This
    // choice adds \Theta(2n) to the complexity.
    for (int i = 0; i < n; i++) {
        xReal[i] = inputReal[i];
        xImag[i] = inputImag[i];
    }

    // First phase - calculation
    int k = 0;
    for (int l = 1; l <= nu; l++) {
        while (k < n) {
            for (int i = 1; i <= n2; i++) {
                p = bitreverseReference(k >> nu1, nu);
                // direct FFT or inverse FFT
                arg = constant * p / n;
                c = Math.cos(arg);
                s = Math.sin(arg);
                tReal = xReal[k + n2] * c + xImag[k + n2] * s;
                tImag = xImag[k + n2] * c - xReal[k + n2] * s;
                xReal[k + n2] = xReal[k] - tReal;
                xImag[k + n2] = xImag[k] - tImag;
                xReal[k] += tReal;
                xImag[k] += tImag;
                k++;
            }
            k += n2;
        }
        k = 0;
        nu1--;
        n2 /= 2;
    }

    // Second phase - recombination
    k = 0;
    int r;
    while (k < n) {
        r = bitreverseReference(k, nu);
        if (r > k) {
            tReal = xReal[k];
            tImag = xImag[k];
            xReal[k] = xReal[r];
            xImag[k] = xImag[r];
            xReal[r] = tReal;
            xImag[r] = tImag;
        }
        k++;
    }

    // Here I have to mix xReal and xImag to have an array (yes, it should
    // be possible to do this stuff in the earlier parts of the code, but
    // it's here to readibility).
    double[] newArray = new double[xReal.length * 2];
    double radice = 1 / Math.sqrt(n);
    for (int i = 0; i < newArray.length; i += 2) {
        int i2 = i / 2;
        // I used Stephen Wolfram's Mathematica as a reference so I'm going
        // to normalize the output while I'm copying the elements.
        newArray[i] = xReal[i2] * radice;
        newArray[i + 1] = xImag[i2] * radice;
    }
    return newArray;
}

/**
 * The reference bitreverse function.
 */
private static int bitreverseReference(int j, int nu) {
    int j2;
    int j1 = j;
    int k = 0;
    for (int i = 1; i <= nu; i++) {
        j2 = j1 / 2;
        k = 2 * k + j1 - 2 * j2;
        j1 = j2;
    }
    return k;
  }
}

How to see if an object is an array without using reflection?

You can use Class.isArray()

public static boolean isArray(Object obj)
{
    return obj!=null && obj.getClass().isArray();
}

This works for both object and primitive type arrays.

For toString take a look at Arrays.toString. You'll have to check the array type and call the appropriate toString method.

How to set $_GET variable

You can create a link , having get variable in href.

<a href="www.site.com/hello?getVar=value" >...</a>

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You could do it with JavaScript with something like this:

<input onblur="checkLength(this)" id="groupidtext" type="text" style="width: 100px;" maxlength="6" />
<!-- Or use event onkeyup instead if you want to check every character strike -->

function checkLength(el) {
  if (el.value.length != 6) {
    alert("length must be exactly 6 characters")
  }
}

Note this would work in older browsers which don't support HTML 5, but it relies on the user having JavaScript switched on.

Python error message io.UnsupportedOperation: not readable

This will let you read, write and create the file if it don't exist:

f = open('filename.txt','a+')
f = open('filename.txt','r+')

Often used commands:

f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file

Download file and automatically save it to folder

Take a look at http://www.csharp-examples.net/download-files/ and msdn docs on webclient http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx

My suggestion is try the synchronous download as its more straightforward. you might get ideas on whether webclient parameters are wrong or the file is in incorrect format while trying this.

Here is a code sample..

private void btnDownload_Click(object sender, EventArgs e)
{
  string filepath = textBox1.Text;
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), filepath);
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
  progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  MessageBox.Show("Download completed!");
}

Python SQL query string formatting

Cleanest way I have come across is inspired by the sql style guide.

sql = """
    SELECT field1, field2, field3, field4
      FROM table
     WHERE condition1 = 1
       AND condition2 = 2;
"""

Essentially, the keywords that begin a clause should be right-aligned and the field names etc, should be left aligned. This looks very neat and is easier to debug as well.

Change IPython/Jupyter notebook working directory

This question keeps coming up when I search for ipython change pwd even though I am not interested in a notebook, but a terminal or qtconsole. Not finding a relevant config entry I tried:

# lines of code to run at IPython startup.
c.InteractiveShellApp.exec_lines = ['%cd /home/paul/mypy']

This is the base level shell class; there are Terminal and Console (and probably notebook) entries that could further customize the action.

From the docs it looks like import statements are most common in the entry, but it appears that many magic commands work as well.

Automatically running a batch file as an administrator

If you're trying to invoke a Windows UAC prompt (the one that puts the whole screen black and asks if you're granting administrator privileges to the following task), RUNAS is not the smoothest way to do it, since:

  1. You're not going to get prompted for UAC authorization, even if logged in as the administrator and
  2. RUNAS expects that you have the administrator password, even if your user is setup as a local administrator, in which case the former password is not a sound security practice, specially in work environments.

Instead, try to copy & paste the following code to ensure that your batch file runs with administrator privileges:

@echo off

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

if '%errorlevel%' NEQ '0' (
    echo Requesting Admin access...
    goto goUAC )
    else goto goADMIN

:goUAC
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:goADMIN
    pushd "%CD%"
    CD /D "%~dp0"

rem --- FROM HERE PASTE YOUR ADMIN-ENABLED BATCH SCRIPT ---
echo Stopping some Microsoft Service...
net stop sqlserveragent
rem --- END OF BATCH ----

This solution works 100% under Windows 7, 8.1 and 10 setups with UAC enabled.

Edit a text file on the console using Powershell

Bit of a resurrect but for anyone else coming to this question, take a look at the Micro editor. It's a small standalone EXE with no dependencies and with native Windows 32\64 versions. Works well in both PowerShell and CMD.EXE.

enter image description here

How does a PreparedStatement avoid or prevent SQL injection?

PreparedStatement:

1) Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.

2) Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the value.

Android - set TextView TextStyle programmatically?

Kotlin Version

To retain current font in addition to text style:

textView.apply {
    setTypeface(typeface, Typeface.NORMAL)
    // or
    setTypeface(typeface, Typeface.BOLD)
    // or
    setTypeface(typeface, Typeface.ITALIC)
    // or
    setTypeface(typeface, Typeface.BOLD_ITALIC)
}

Do conditional INSERT with SQL?

You can do that with a single statement and a subquery in nearly all relational databases.

INSERT INTO targetTable(field1) 
SELECT field1
FROM myTable
WHERE NOT(field1 IN (SELECT field1 FROM targetTable))

Certain relational databases have improved syntax for the above, since what you describe is a fairly common task. SQL Server has a MERGE syntax with all kinds of options, and MySQL has optional INSERT OR IGNORE syntax.

Edit: SmallSQL's documentation is fairly sparse as to which parts of the SQL standard it implements. It may not implement subqueries, and as such you may be unable to follow the advice above, or anywhere else, if you need to stick with SmallSQL.

View content of H2 or HSQLDB in-memory database

You can run H2 web server within your application that will access the same in-memory database. You can also access the H2 running in server mode using any generic JDBC client like SquirrelSQL.

UPDATE:

Server webServer = Server.createWebServer("-web,-webAllowOthers,true,-webPort,8082").start();
Server server = Server.createTcpServer("-tcp,-tcpAllowOthers,true,-tcpPort,9092").start();

Now you can connect to your database via jdbc:h2:mem:foo_db URL within the same process or browse the foo_db database using localhost:8082. Remember to close both servers. See also: H2 database in memory mode cannot be accessed by Console.

You can also use Spring:

<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg value="-tcp,-tcpAllowOthers,true,-tcpPort,9092"/>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg value="-web,-webAllowOthers,true,-webPort,8082"/>
</bean>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" depends-on="h2Server">
    <property name="driverClass" value="org.h2.Driver"/>
    <property name="jdbcUrl" value="jdbc:h2:mem:foo_db"/>
</bean>

BTW you should only depend on assertions and not on manual peeking the database contents. Use this only for troubleshooting.

N.B. if you use Spring test framework you won't see changes made by a running transaction and this transaction will be rolled back immediately after the test.

WCF named pipe minimal example

I created this simple example from different search results on the internet.

public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
  //Create base address
  string baseAddress = "net.pipe://localhost/MyService";

  ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));

  //Net named pipe
  NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
  serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);

  //MEX - Meta data exchange
  ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
  serviceHost.Description.Behaviors.Add(behavior);
  serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");

  return serviceHost;
}

Using the above URI I can add a reference in my client to the web service.

Add my custom http header to Spring RestTemplate request / extend RestTemplate

You can pass custom http headers with RestTemplate exchange method as below.

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);

RestTemplate template = new RestTemplate();

ResponseEntity<RestResponse> respEntity = template
    .exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);

EDIT : Below is the updated code. This link has several ways of calling rest service with examples

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);

Mall[] resp = respEntity.getBody();

Is Laravel really this slow?

Laravel is not actually that slow. 500-1000ms is absurd; I got it down to 20ms in debug mode.

The problem was Vagrant/VirtualBox + shared folders. I didn't realize they incurred such a performance hit. I guess because Laravel has so many dependencies (loads ~280 files) and each of those file reads is slow, it adds up really quick.

kreeves pointed me in the right direction, this blog post describes a new feature in Vagrant 1.5 that lets you rsync your files into the VM rather than using a shared folder.

There's no native rsync client on Windows, so you'll have to use cygwin. Install it, and make sure to check off Net/rsync. Add C:\cygwin64\bin to your paths. [Or you can install it on Win10/Bash]

Vagrant introduces the new feature. I'm using Puphet, so my Vagrantfile looks a bit funny. I had to tweak it to look like this:

  data['vm']['synced_folder'].each do |i, folder|
    if folder['source'] != '' && folder['target'] != '' && folder['id'] != ''
      config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", 
        id: "#{folder['id']}", 
        type: "rsync",
        rsync__auto: "true",
        rsync__exclude: ".hg/"
    end
  end

Once you're all set up, try vagrant up. If everything goes smoothly your machine should boot up and it should copy all the files over. You'll need to run vagrant rsync-auto in a terminal to keep the files up to date. You'll pay a little bit in latency, but for 30x faster page loads, it's worth it!


If you're using PhpStorm, it's auto-upload feature works even better than rsync. PhpStorm creates a lot of temporary files which can trip up file watchers, but if you let it handle the uploads itself, it works nicely.


One more option is to use lsyncd. I've had great success using this on Ubuntu host -> FreeBSD guest. I haven't tried it on a Windows host yet.

Is there a way to split a widescreen monitor in to two or more virtual monitors?

The next version of Windows (Windows 7) will be able to snap windows to the left or right half of the screen. Doesn't help right now, but it's something to look forward to.

http://arstechnica.com/news.ars/post/20081028-first-look-at-windows-7.html

Getting the name of a variable as a string

>> my_var = 5
>> my_var_name = [ k for k,v in locals().items() if v == my_var][0]
>> my_var_name 
'my_var'

In case you get an error if myvar points to another variable, try this (suggested by @mherzog)-

 >> my_var = 5
>> my_var_name = [ k for k,v in locals().items() if v is my_var][0]
>> my_var_name 
'my_var'

locals() - Return a dictionary containing the current scope's local variables. by iterating through this dictionary we can check the key which has a value equal to the defined variable, just extracting the key will give us the text of variable in string format.

from (after a bit changes) https://www.tutorialspoint.com/How-to-get-a-variable-name-as-a-string-in-Python

bitwise XOR of hex numbers in python

If the strings are the same length, then I would go for '%x' % () of the built-in xor (^).

Examples -

>>>a = '290b6e3a'
>>>b = 'd6f491c5'
>>>'%x' % (int(a,16)^int(b,16))
'ffffffff'
>>>c = 'abcd'
>>>d = '12ef'
>>>'%x' % (int(a,16)^int(b,16))
'b922'

If the strings are not the same length, truncate the longer string to the length of the shorter using a slice longer = longer[:len(shorter)]