Programs & Examples On #Mailsettings

How to configure SMTP settings in web.config

I don't have enough rep to answer ClintEastwood, and the accepted answer is correct for the Web.config file. Adding this in for code difference.

When your mailSettings are set on Web.config, you don't need to do anything other than new up your SmtpClient and .Send. It finds the connection itself without needing to be referenced. You would change your C# from this:

SmtpClient smtpClient = new SmtpClient("smtp.sender.you", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(msgMail);  

To this:

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(msgMail);

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

If you are in a test environment and do not want to set security settings you have to allow less secure apps via. this link in Gmail.

https://myaccount.google.com/lesssecureapps

Java - Reading XML file

If using another library is an option, the following may be easier:

package for_so;

import java.io.File;

import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;

public class Q7704827_SimpleRead
{
    public static void
    main(String[] args)
    {
        String fileName = args[0];

        TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
        String recipient = emailNode.nextTextFieldE("recipient");
        String sender = emailNode.nextTextFieldE("sender");
        String subject = emailNode.nextTextFieldE("subject");
        String description = emailNode.nextTextFieldE("description");
        emailNode.verifyNoMoreChildren();

        System.out.println("recipient =  " + recipient);
        System.out.println("sender =     " + sender);
        System.out.println("subject =    " + subject);
        System.out.println("desciption = " + description);
    }
}

The library and its documentation are at rasmustorkel.com

Identify duplicate values in a list in Python

You can print duplicate and Unqiue using below logic using list.

def dup(x):
    duplicate = []
    unique = []
    for i in x:
        if i in unique:
            duplicate.append(i)
        else:
            unique.append(i)
    print("Duplicate values: ",duplicate)
    print("Unique Values: ",unique)

list1 = [1, 2, 1, 3, 2, 5]
dup(list1)

Determining whether an object is a member of a collection in VBA

In your specific case (TableDefs) iterating over the collection and checking the Name is a good approach. This is OK because the key for the collection (Name) is a property of the class in the collection.

But in the general case of VBA collections, the key will not necessarily be part of the object in the collection (e.g. you could be using a Collection as a dictionary, with a key that has nothing to do with the object in the collection). In this case, you have no choice but to try accessing the item and catching the error.

How to show google.com in an iframe?

You can solve using Google CSE (Custom Searche Engine), which can be easily inserted into an iframe. You can create your own search engine, that search selected sites or also in entire Google's database.

The results can be styled as you prefer, also similar to Google style. Google CSE works with web and images search.

google.php

<script>
  (function() {
    var cx = 'xxxxxxxxxxxxxxxxxxxxxx';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
<gcse:searchresults-only></gcse:searchresults-only>

yourpage.php

<iframe src="google.php?q=<?php echo urlencode('your query'); ?>"></iframe>

XSS filtering function in PHP

htmlspecialchars() is perfectly adequate for filtering user input that is displayed in html forms.

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

If you don't want to use a separate JS library to create a custom control for that, you could use two confirm dialogs to do the checks:

if (confirm("Are you sure you want to quit?") ) {
    if (confirm("Save your work before leaving?") ) {
        // code here for save then leave (Yes)
    } else {
        //code here for no save but leave (No)
    }
} else {
    //code here for don't leave (Cancel)
}

Center a column using Twitter Bootstrap 3

Use mx-auto in your div class using Bootstrap 4.

<div class="container">
  <div class="row">
    <div class="mx-auto">
      You content here
    </div>
  </div>
</div>

React JSX: selecting "selected" on selected <select> option

I've had a problem with <select> tags not updating to the correct <option> when the state changes. My problem seemed to be that if you render twice in quick succession, the first time with no pre-selected <option> but the second time with one, then the <select> tag doesn't update on the second render, but stays on the default first .

I found a solution to this using refs. You need to get a reference to your <select> tag node (which might be nested in some component), and then manually update the value property on it, in the componentDidUpdate hook.

componentDidUpdate(){
  let selectNode = React.findDOMNode(this.refs.selectingComponent.refs.selectTag);
  selectNode.value = this.state.someValue;
}

php pdo: get the columns name of a table

My contribution ONLY for SQLite:

/**
 * Returns an array of column names for a given table.
 * Arg. $dsn should be replaced by $this->dsn in a class definition.
 *
 * @param string $dsn Database connection string, 
 * e.g.'sqlite:/home/user3/db/mydb.sq3'
 * @param string $table The name of the table
 * 
 * @return string[] An array of table names
 */
public function getTableColumns($dsn, $table) {
   $dbh = new \PDO($dsn);
   return $dbh->query('PRAGMA table_info(`'.$table.'`)')->fetchAll(\PDO::FETCH_COLUMN, 1);
}

react-router - pass props to handler component

For react router 2.x.

const WrappedComponent = (Container, propsToPass, { children }) => <Container {...propsToPass}>{children}</Container>;

and in your routes...

<Route path="/" component={WrappedComponent.bind(null, LayoutContainer, { someProp })}>
</Route>

make sure the 3rd param is an object like: { checked: false }.

How to create own dynamic type or dynamic object in C#?

ExpandoObject is what are you looking for.

dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking.
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

How do you set the document title in React?

Since React 16.8. you can build a custom hook to do so (similar to the solution of @Shortchange):

export function useTitle(title) {
  useEffect(() => {
    const prevTitle = document.title
    document.title = title
    return () => {
      document.title = prevTitle
    }
  })
}

this can be used in any react component, e.g.:

const MyComponent = () => {
  useTitle("New Title")
  return (
    <div>
     ...
    </div>
  )
}

It will update the title as soon as the component mounts and reverts it to the previous title when it unmounts.

How do I express "if value is not empty" in the VBA language?

I think the solution of this issue can be some how easier than we imagine. I have simply used the expression Not Null and it worked fine.

Browser("micclass").Page("micclass").WebElement("Test").CheckProperty "innertext", Not Null

How to store a command in a variable in a shell script?

#!/bin/bash
#Note: this script works only when u use Bash. So, don't remove the first line.

TUNECOUNT=$(ifconfig |grep -c -o tune0) #Some command with "Grep".
echo $TUNECOUNT                         #This will return 0 
                                    #if you don't have tune0 interface.
                                    #Or count of installed tune0 interfaces.

String Comparison in Java

If you check which string would come first in a lexicon, you've done a lexicographical comparison of the strings!

Some links:

Stolen from the latter link:

A string s precedes a string t in lexicographic order if

  • s is a prefix of t, or
  • if c and d are respectively the first character of s and t in which s and t differ, then c precedes d in character order.

Note: For the characters that are alphabetical letters, the character order coincides with the alphabetical order. Digits precede letters, and uppercase letters precede lowercase ones.

Example:

  • house precedes household
  • Household precedes house
  • composer precedes computer
  • H2O precedes HOTEL

Most concise way to convert a Set<T> to a List<T>

not really sure what you're doing exactly via the context of your code but...

why make the listOfTopicAuthors variable at all?

List<String> list = Arrays.asList((....).toArray( new String[0] ) );

the "...." represents however your set came into play, whether it's new or came from another location.

How to make Visual Studio copy a DLL file to the output directory?

Add builtin COPY in project.csproj file:

  <Project>
    ...
    <Target Name="AfterBuild">
      <Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Debug\bin" SkipUnchangedFiles="false" />
      <Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Release\bin" SkipUnchangedFiles="false" />
    </Target>
  </Project>

Resolve conflicts using remote changes when pulling from Git remote

If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:

# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master

I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.

If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours merge strategy:

# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

CSS change button style after click

If you're looking for a pure css option, try using the :focus pseudo class.

#style  {
    background-color: red;
}

#style:focus {     
    background-color:yellow;    
}

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id

More details here.

From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

Flask - Calling python function on button OnClick event

index.html (index.html should be in templates folder)

<!doctype html>
<html>

<head>
    <title>The jQuery Example</title>

    <h2>jQuery-AJAX in FLASK. Execute function on button click</h2>  

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
    <script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
    function(data) { }); return false; }); }); </script> 
</head>

<body>        
        <input type = "button" id = "mybutton" value = "Click Here" />
</body>    

</html>

test.py

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/SomeFunction')
def SomeFunction():
    print('In SomeFunction')
    return "Nothing"



if __name__ == '__main__':
   app.run()

COPY with docker but with exclusion

For those who can't use a .dockerignore file (e.g. if you need the file in one COPY but not another):

Yes, but you need multiple COPY instructions. Specifically, you need a COPY for each letter in the filename you wish to exclude.

COPY [^n]*    # All files that don't start with 'n'
COPY n[^o]*   # All files that start with 'n', but not 'no'
COPY no[^d]*  # All files that start with 'no', but not 'nod'

Continuing until you have the full file name, or just the prefix you're reasonably sure won't have any other files.

How to set default font family for entire Android app

I know this question is quite old, but I have found a nice solution. Basically, you pass a container layout to this function, and it will apply the font to all supported views, and recursively cicle in child layouts:

public static void setFont(ViewGroup layout)
{
    final int childcount = layout.getChildCount();
    for (int i = 0; i < childcount; i++)
    {
        // Get the view
        View v = layout.getChildAt(i);

        // Apply the font to a possible TextView
        try {
            ((TextView) v).setTypeface(MY_CUSTOM_FONT);
            continue;
        }
        catch (Exception e) { }

        // Apply the font to a possible EditText
        try {
            ((TextView) v).setTypeface(MY_CUSTOM_FONT);
            continue;
        }
        catch (Exception e) { }

        // Recursively cicle into a possible child layout
        try {
            ViewGroup vg = (ViewGroup) v;
            Utility.setFont(vg);
            continue;
        }
        catch (Exception e) { }
    }
}

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:

.unbind() deprecated

Replace all instances of .unbind with .off

.removeAttribute() is not a function

Change lines 580-581 to use jQuery's .removeAttr() instead:

Old code:

580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');

New code:

580: content.removeAttr('filter');
581: wrap.removeAttr('filter');

This combined with the other patch mentioned above solved my compatibility issues.

Create the perfect JPA entity

The JPA 2.0 Specification states that:

  • The entity class must have a no-arg constructor. It may have other constructors as well. The no-arg constructor must be public or protected.
  • The entity class must a be top-level class. An enum or interface must not be designated as an entity.
  • The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
  • If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.
  • Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.

The specification contains no requirements about the implementation of equals and hashCode methods for entities, only for primary key classes and map keys as far as I know.

if block inside echo statement?

You can always use the ( <condition> ? <value if true> : <value if false> ) syntax (it's called the ternary operator - thanks to Mark for remining me :) ).

If <condition> is true, the statement would be evaluated as <value if true>. If not, it would be evaluated as <value if false>

For instance:

$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";

This is the same as:

$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
  echo "Fourteen is more than twelve";
}else{
  echo "Fourteen is not more than twelve";
}

Failed to allocate memory: 8

In my case, changin screen resolution from WVGA720 to WSVGA works for me.

Difference Between $.getJSON() and $.ajax() in jQuery

.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc

N.B .load, .get and .post are also simple wrappers around the .ajax method.

What is the difference between "expose" and "publish" in Docker?

Short answer:

  • EXPOSE is a way of documenting
  • --publish (or -p) is a way of mapping a host port to a running container port

Notice below that:

  • EXPOSE is related to Dockerfiles ( documenting )
  • --publish is related to docker run ... ( execution / run-time )

Exposing and publishing ports

In Docker networking, there are two different mechanisms that directly involve network ports: exposing and publishing ports. This applies to the default bridge network and user-defined bridge networks.

  • You expose ports using the EXPOSE keyword in the Dockerfile or the --expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.

  • You publish ports using the --publish or --publish-all flag to docker run. This tells Docker which ports to open on the container’s network interface. When a port is published, it is mapped to an available high-order port (higher than 30000) on the host machine, unless you specify the port to map to on the host machine at runtime. You cannot specify the port to map to on the host machine when you build the image (in the Dockerfile), because there is no way to guarantee that the port will be available on the host machine where you run the image.

from: Docker container networking

Update October 2019: the above piece of text is no longer in the docs but an archived version is here: docs.docker.com/v17.09/engine/userguide/networking/#exposing-and-publishing-ports

Maybe the current documentation is the below:

Published ports

By default, when you create a container, it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host.

and can be found here: docs.docker.com/config/containers/container-networking/#published-ports

Also,

EXPOSE

...The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.

from: Dockerfile reference






Service access when EXPOSE / --publish are not defined:

At @Golo Roden's answer it is stated that::

"If you do not specify any of those, the service in the container will not be accessible from anywhere except from inside the container itself."

Maybe that was the case at the time the answer was being written, but now it seems that even if you do not use EXPOSE or --publish, the host and other containers of the same network will be able to access a service you may start inside that container.

How to test this:

I've used the following Dockerfile. Basically, I start with ubuntu and install a tiny web-server:

FROM ubuntu
RUN apt-get update && apt-get install -y mini-httpd

I build the image as "testexpose" and run a new container with:

docker run --rm -it testexpose bash

Inside the container, I launch a few instances of mini-httpd:

root@fb8f7dd1322d:/# mini_httpd -p 80
root@fb8f7dd1322d:/# mini_httpd -p 8080
root@fb8f7dd1322d:/# mini_httpd -p 8090

I am then able to use curl from the host or other containers to fetch the home page of mini-httpd.


Further reading

Very detailed articles on the subject by Ivan Pepelnjak:

Subset and ggplot2

With option 2 in @agstudy's answer now deprecated, defining data with a function can be handy.

library(plyr)
ggplot(data=dat) + 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
            data=function(x){x$ID %in% c("P1", "P3"))

This approach comes in handy if you wish to reuse a dataset in the same plot, e.g. you don't want to specify a new column in the data.frame, or you want to explicitly plot one dataset in a layer above the other.:

library(plyr)
ggplot(data=dat, aes(Value1, Value2, group=ID, colour=ID)) + 
  geom_line(data=function(x){x[!x$ID %in% c("P1", "P3"), ]}, alpha=0.5) +
  geom_line(data=function(x){x[x$ID %in% c("P1", "P3"), ]})

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

how to put focus on TextBox when the form load?

check your tab order and make sure the textbox is set to zero

How to make a variadic macro (variable number of arguments)

C99 way, also supported by VC++ compiler.

#define FOO(fmt, ...) printf(fmt, ##__VA_ARGS__)

Change url query string value using jQuery

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);

Keystore type: which one to use?

There are a few more types than what's listed in the standard name list you've linked to. You can find more in the cryptographic providers documentation. The most common are certainly JKS (the default) and PKCS12 (for PKCS#12 files, often with extension .p12 or sometimes .pfx).

JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools (keytool wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).

If you already have a PKCS#12 file, it's often easier to use the PKCS12 type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.

In Java 7, PKCS12 was mainly useful as a keystore but less for a truststore (see the difference between a keystore and a truststore), because you couldn't store certificate entries without a private key. In contrast, JKS doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).

This has changed in Java 8, so you can now have certificate-only entries in PKCS12 stores too. (More details about these changes and further plans can be found in JEP 229: Create PKCS12 Keystores by Default.)

There are a few other keystore types, perhaps less frequently used (depending on the context), those include:

  • PKCS11, for PKCS#11 libraries, typically for accessing hardware cryptographic tokens, but the Sun provider implementation also supports NSS stores (from Mozilla) through this.
  • BKS, using the BouncyCastle provider (commonly used for Android).
  • Windows-MY/Windows-ROOT, if you want to access the Windows certificate store directly.
  • KeychainStore, if you want to use the OSX keychain directly.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Here is my answer to a similar question:

I think (not yet entirely sure) that this is because InvokeRequired will always return false if the control has not yet been loaded/shown. I have done a workaround which seems to work for the moment, which is to simple reference the handle of the associated control in its creator, like so:

var x = this.Handle; 

(See http://ikriv.com/en/prog/info/dotnet/MysteriousHang.html)

How to align content of a div to the bottom

You don't need absolute+relative for this. It is very much possible using relative position for both container and data. This is how you do it.

Assume height of your data is going to be x. Your container is relative and footer is also relative. All you have to do is add to your data

bottom: -webkit-calc(-100% + x);

Your data will always be at the bottom of your container. Works even if you have container with dynamic height.

HTML will be like this

<div class="container">
  <div class="data"></div>
</div>

CSS will be like this

.container{
  height:400px;
  width:600px;
  border:1px solid red;
  margin-top:50px;
  margin-left:50px;
  display:block;
}
.data{
  width:100%;
  height:40px;
  position:relative;
   float:left;
  border:1px solid blue;
  bottom: -webkit-calc(-100% + 40px);
   bottom:calc(-100% + 40px);
}

Live example here

Hope this helps.

Check if an element is a child of a parent

Vanilla 1-liner for IE8+:

parent !== child && parent.contains(child);

Here, how it works:

_x000D_
_x000D_
function contains(parent, child) {_x000D_
  return parent !== child && parent.contains(child);_x000D_
}_x000D_
_x000D_
var parentEl = document.querySelector('#parent'),_x000D_
    childEl = document.querySelector('#child')_x000D_
    _x000D_
if (contains(parentEl, childEl)) {_x000D_
  document.querySelector('#result').innerText = 'I confirm, that child is within parent el';_x000D_
}_x000D_
_x000D_
if (!contains(childEl, parentEl)) {_x000D_
  document.querySelector('#result').innerText += ' and parent is not within child';_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div>_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td><span id="child"></span></td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </div>_x000D_
</div>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How to enter command with password for git pull?

Using the credentials helper command-line option:

git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin

String date to xmlgregoriancalendar conversion

tl;dr

  • Use modern java.time classes as much as possible, rather than the terrible legacy classes.
  • Always specify your desired/expected time zone or offset-from-UTC rather than rely implicitly on JVM’s current default.

Example code (without exception-handling):

XMLGregorianCalendar xgc = 
    DatatypeFactory                           // Data-type converter.
    .newInstance()                            // Instantiate a converter object.
    .newXMLGregorianCalendar(                 // Converter going from `GregorianCalendar` to `XMLGregorianCalendar`.
        GregorianCalendar.from(               // Convert from modern `ZonedDateTime` class to legacy `GregorianCalendar` class.
            LocalDate                         // Modern class for representing a date-only, without time-of-day and without time zone.
            .parse( "2014-01-07" )            // Parsing strings in standard ISO 8601 format is handled by default, with no need for custom formatting pattern. 
            .atStartOfDay( ZoneOffset.UTC )   // Determine the first moment of the day as seen in UTC. Returns a `ZonedDateTime` object.
        )                                     // Returns a `GregorianCalendar` object.
    )                                         // Returns a `XMLGregorianCalendar` object.
;

Parsing date-only input string into an object of XMLGregorianCalendar class

Avoid the terrible legacy date-time classes whenever possible, such as XMLGregorianCalendar, GregorianCalendar, Calendar, and Date. Use only modern java.time classes.

When presented with a string such as "2014-01-07", parse as a LocalDate.

LocalDate.parse( "2014-01-07" )

To get a date with time-of-day, assuming you want the first moment of the day, specify a time zone. Let java.time determine the first moment of the day, as it is not always 00:00:00.0 in some zones on some dates.

LocalDate.parse( "2014-01-07" )
         .atStartOfDay( ZoneId.of( "America/Montreal" ) )

This returns a ZonedDateTime object.

ZonedDateTime zdt = 
        LocalDate
        .parse( "2014-01-07" )
        .atStartOfDay( ZoneId.of( "America/Montreal" ) )
;

zdt.toString() = 2014-01-07T00:00-05:00[America/Montreal]

But apparently, you want the start-of-day as seen in UTC (an offset of zero hours-minutes-seconds). So we specify ZoneOffset.UTC constant as our ZoneId argument.

ZonedDateTime zdt = 
        LocalDate
        .parse( "2014-01-07" )
        .atStartOfDay( ZoneOffset.UTC )
;

zdt.toString() = 2014-01-07T00:00Z

The Z on the end means UTC (an offset of zero), and is pronounced “Zulu”.

If you must work with legacy classes, convert to GregorianCalendar, a subclass of Calendar.

GregorianCalendar gc = GregorianCalendar.from( zdt ) ;

gc.toString() = java.util.GregorianCalendar[time=1389052800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=0,WEEK_OF_YEAR=2,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]

Apparently, you really need an object of the legacy class XMLGregorianCalendar. If the calling code cannot be updated to use java.time, convert.

XMLGregorianCalendar xgc = 
        DatatypeFactory
        .newInstance()
        .newXMLGregorianCalendar( gc ) 
;

Actually, that code requires a try-catch.

try
{
    XMLGregorianCalendar xgc =
            DatatypeFactory
                    .newInstance()
                    .newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
    e.printStackTrace();
}

xgc = 2014-01-07T00:00:00.000Z

Putting that all together, with appropriate exception-handling.

// Given an input string such as "2014-01-07", return a `XMLGregorianCalendar` object
// representing first moment of the day on that date as seen in UTC. 
static public XMLGregorianCalendar getXMLGregorianCalendar ( String input )
{
    Objects.requireNonNull( input );
    if( input.isBlank() ) { throw new IllegalArgumentException( "Received empty/blank input string for date argument. Message # 11818896-7412-49ba-8f8f-9b3053690c5d." ) ; }
    XMLGregorianCalendar xgc = null;
    ZonedDateTime zdt = null;

    try
    {
        zdt =
                LocalDate
                        .parse( input )
                        .atStartOfDay( ZoneOffset.UTC );
    }
    catch ( DateTimeParseException e )
    {
        throw new IllegalArgumentException( "Faulty input string for date does not comply with standard ISO 8601 format. Message # 568db0ef-d6bf-41c9-8228-cc3516558e68." );
    }

    GregorianCalendar gc = GregorianCalendar.from( zdt );
    try
    {
        xgc =
                DatatypeFactory
                        .newInstance()
                        .newXMLGregorianCalendar( gc );
    }
    catch ( DatatypeConfigurationException e )
    {
        e.printStackTrace();
    }

    Objects.requireNonNull( xgc );
    return xgc ;
}

Usage.

String input = "2014-01-07";
XMLGregorianCalendar xgc = App.getXMLGregorianCalendar( input );

Dump to console.

System.out.println( "xgc = " + xgc );

xgc = 2014-01-07T00:00:00.000Z

Modern date-time classes versus legacy

Table of date-time types in Java, both modern and legacy

Date-time != String

Do not conflate a date-time value with its textual representation. We parse strings to get a date-time object, and we ask the date-time object to generate a string to represent its value. The date-time object has no ‘format’, only strings have a format.

So shift your thinking into two separate modes: model and presentation. Determine the date-value you have in mind, applying appropriate time zone, as the model. When you need to display that value, generate a string in a particular format as expected by the user.

Avoid legacy date-time classes

The Question and other Answers all use old troublesome date-time classes now supplanted by the java.time classes.

ISO 8601

Your input string "2014-01-07" is in standard ISO 8601 format.

The T in the middle separates date portion from time portion.

The Z on the end is short for Zulu and means UTC.

Fortunately, the java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2014-01-07" ) ;

ld.toString(): 2014-01-07

Start of day ZonedDateTime

If you want to see the first moment of that day, specify a ZoneId time zone to get a moment on the timeline, a ZonedDateTime. The time zone is crucial because the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Never assume the day begins at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day may begin at another time-of-day such as 01:00:00. Let java.time determine the first moment.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;

zdt.toString(): 2014-01-07T00:00:00Z

For your desired format, generate a string using the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME and then replace the T in the middle with a SPACE.

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " ) ; 

2014-01-07 00:00:00


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

The remote certificate is invalid according to the validation procedure

You must check the certificate hash code.

ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain,
    errors) =>
        {
            var hashString = certificate.GetCertHashString();
            if (hashString != null)
            {
                var certHashString = hashString.ToLower();
                return certHashString == "dec2b525ddeemma8ccfaa8df174455d6e38248c5";
            }
            return false;
        };

How to make Bootstrap 4 cards the same height in card-columns?

Bootstrap 4 has all you need : USE THE .d-flex and .flex-fill class. Don't use the card-decks as they are not responsive. I used col-sm, you can use the .col class you want, or use col-lg-x the x means number of width column e.g 4 or 3 for best view if the post have many then 3 or 4 per column

Try to reduce the browser window to XS to see it in action :

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

<link href="https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,500,500i,700,700i" rel="stylesheet">
<div class="container">
  <div class="row my-4">
    <div class="col">
      <div class="jumbotron">
        <h1>Bootstrap 4 Cards all same height demo</h1>
        <p class="lead">by djibe.</p>
        <span class="text-muted">(thx to BS4)</span>
        <p>Dependencies : standard BS4</p>
        <p>
          Enjoy the magic of flexboxes and leave the useless card-decks.
        </p>
        <div class="container-fluid">
          <div class="row">
            <div class="col-sm d-flex">
              <div class="card card-body flex-fill">
                A small card content.
              </div>
            </div>
            <div class="col-sm d-flex">
              <div class="card card-body flex-fill">
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
                in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
              </div>
            </div>
            <div class="col-sm d-flex">
              <div class="card card-body flex-fill">
                Another small card content.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
_x000D_
_x000D_
_x000D_

Loaded nib but the 'view' outlet was not set

I had the same problem, I figured out and it is because of i had ticked "Static cells" in the properties of Table View under Content option. Worked when it changed to "Dynamic Prototypes". Screenshot is below. enter image description here

Escape double quotes for JSON in Python

>>> s = 'my string with \\"double quotes\\" blablabla'
>>> s
'my string with \\"double quotes\\" blablabla'
>>> print s
my string with \"double quotes\" blablabla
>>> 

When you just ask for 's' it escapes the \ for you, when you print it, you see the string a more 'raw' state. So now...

>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\\"')
my string with \"double quotes\" blablabla
>>> 

How to reset the use/password of jenkins on windows?

You can try to re-set your Jenkins security:

  1. Stop the Jenkins service
  2. Open the config.xml with a text editor (i.e notepad++), maybe be in C:\jenkins\config.xml (could backup it also).
  3. Find this <useSecurity>true</useSecurity> and change it to <useSecurity>false</useSecurity>
  4. Start Jenkins service

You might create an admin user and enable security again.

simple way to display data in a .txt file on a webpage?

I find that if I try things that others say do not work, it's how I learn the most.

<p>&nbsp;</p>
<p>README.txt</p>
<p>&nbsp;</p>
<div id="list">
  <p><iframe src="README.txt" frameborder="0" height="400"
      width="95%"></iframe></p>
</div>

This worked for me. I used the yellow background-color that I set in the stylesheet.

#list  p {
    font: arial;
    font-size: 14px;
    background-color: yellow ;
}

Convert Select Columns in Pandas Dataframe to Numpy Array

the easy way is the "values" property df.iloc[:,1:].values

a=df.iloc[:,1:]
b=df.iloc[:,1:].values

print(type(df))
print(type(a))
print(type(b))

so, you can get type

<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'numpy.ndarray'>

Normalization in DOM parsing with java - how does it work?

As an extension to @JBNizet's answer for more technical users here's what implementation of org.w3c.dom.Node interface in com.sun.org.apache.xerces.internal.dom.ParentNode looks like, gives you the idea how it actually works.

public void normalize() {
    // No need to normalize if already normalized.
    if (isNormalized()) {
        return;
    }
    if (needsSyncChildren()) {
        synchronizeChildren();
    }
    ChildNode kid;
    for (kid = firstChild; kid != null; kid = kid.nextSibling) {
         kid.normalize();
    }
    isNormalized(true);
}

It traverses all the nodes recursively and calls kid.normalize()
This mechanism is overridden in org.apache.xerces.dom.ElementImpl

public void normalize() {
     // No need to normalize if already normalized.
     if (isNormalized()) {
         return;
     }
     if (needsSyncChildren()) {
         synchronizeChildren();
     }
     ChildNode kid, next;
     for (kid = firstChild; kid != null; kid = next) {
         next = kid.nextSibling;

         // If kid is a text node, we need to check for one of two
         // conditions:
         //   1) There is an adjacent text node
         //   2) There is no adjacent text node, but kid is
         //      an empty text node.
         if ( kid.getNodeType() == Node.TEXT_NODE )
         {
             // If an adjacent text node, merge it with kid
             if ( next!=null && next.getNodeType() == Node.TEXT_NODE )
             {
                 ((Text)kid).appendData(next.getNodeValue());
                 removeChild( next );
                 next = kid; // Don't advance; there might be another.
             }
             else
             {
                 // If kid is empty, remove it
                 if ( kid.getNodeValue() == null || kid.getNodeValue().length() == 0 ) {
                     removeChild( kid );
                 }
             }
         }

         // Otherwise it might be an Element, which is handled recursively
         else if (kid.getNodeType() == Node.ELEMENT_NODE) {
             kid.normalize();
         }
     }

     // We must also normalize all of the attributes
     if ( attributes!=null )
     {
         for( int i=0; i<attributes.getLength(); ++i )
         {
             Node attr = attributes.item(i);
             attr.normalize();
         }
     }

    // changed() will have occurred when the removeChild() was done,
    // so does not have to be reissued.

     isNormalized(true);
 } 

Hope this saves you some time.

How do I view / replay a chrome network debugger har file saved with content?

Open chrome browser. right click anywhere on a page > inspect elements > go to network tab > drag and drop the .har file You should see the logs.

Validate phone number with JavaScript

This function worked for us well:

_x000D_
_x000D_
let isPhoneNumber = input => {

  try {
    let ISD_CODES = [93, 355, 213, 1684, 376, 244, 1264, 672, 1268, 54, 374, 297, 61, 43, 994, 1242, 973, 880, 1246, 375, 32, 501, 229, 1441, 975, 591, 387, 267, 55, 246, 1284, 673, 359, 226, 257, 855, 237, 1, 238, 1345, 236, 235, 56, 86, 61, 61, 57, 269, 682, 506, 385, 53, 599, 357, 420, 243, 45, 253, 1767, 1809, 1829, 1849, 670, 593, 20, 503, 240, 291, 372, 251, 500, 298, 679, 358, 33, 689, 241, 220, 995, 49, 233, 350, 30, 299, 1473, 1671, 502, 441481, 224, 245, 592, 509, 504, 852, 36, 354, 91, 62, 98, 964, 353, 441624, 972, 39, 225, 1876, 81, 441534, 962, 7, 254, 686, 383, 965, 996, 856, 371, 961, 266, 231, 218, 423, 370, 352, 853, 389, 261, 265, 60, 960, 223, 356, 692, 222, 230, 262, 52, 691, 373, 377, 976, 382, 1664, 212, 258, 95, 264, 674, 977, 31, 599, 687, 64, 505, 227, 234, 683, 850, 1670, 47, 968, 92, 680, 970, 507, 675, 595, 51, 63, 64, 48, 351, 1787, 1939, 974, 242, 262, 40, 7, 250, 590, 290, 1869, 1758, 590, 508, 1784, 685, 378, 239, 966, 221, 381, 248, 232, 65, 1721, 421, 386, 677, 252, 27, 82, 211, 34, 94, 249, 597, 47, 268, 46, 41, 963, 886, 992, 255, 66, 228, 690, 676, 1868, 216, 90, 993, 1649, 688, 1340, 256, 380, 971, 44, 1, 598, 998, 678, 379, 58, 84, 681, 212, 967, 260, 263],
      //extract numbers from string
      thenum = input.match(/[0-9]+/g).join(""),
      totalnums = thenum.length,
      last10Digits = parseInt(thenum) % 10000000000,
      ISDcode = thenum.substring(0, totalnums - 10);

    //phone numbers are generally of 8 to 16 digits
    if (totalnums >= 8 && totalnums <= 16) {
      if (ISDcode) {
        if (ISD_CODES.includes(parseInt(ISDcode))) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    }
  } catch (e) {}

  return false;
}

console.log(isPhoneNumber('91-9883208806'));
_x000D_
_x000D_
_x000D_

How can I use delay() with show() and hide() in Jquery

Why don't you try the fadeIn() instead of using a show() with delay(). I think what you are trying to do can be done with this. Here is the jQuery code for fadeIn and FadeOut() which also has inbuilt method for delaying the process.

$(document).ready(function(){
   $('element').click(function(){
      //effects take place in 3000ms
      $('element_to_hide').fadeOut(3000);
      $('element_to_show').fadeIn(3000);
   });
}

In a Git repository, how to properly rename a directory?

Simply rename the folder. git is a "content-tracker", so the SHA1 hashes are the same and git knows, that you rename it. The only thing that changes is the tree-object.

rm <directory>
git add .
git commit

iOS Launching Settings -> Restrictions URL Scheme

iOS 10

Use app-prefs:

App-prefs:root=MOBILE_DATA_SETTINGS_ID

See gist

How to remove unused C/C++ symbols with GCC and ld?

The answer is -flto. You have to pass it to both your compilation and link steps, otherwise it doesn't do anything.

It actually works very well - reduced the size of a microcontroller program I wrote to less than 50% of its previous size!

Unfortunately it did seem a bit buggy - I had instances of things not being built correctly. It may have been due to the build system I'm using (QBS; it's very new), but in any case I'd recommend you only enable it for your final build if possible, and test that build thoroughly.

printf formatting (%d versus %u)

The difference is simple: they cause different warning messages to be emitted when compiling:

1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %d\n", &a); // prints "memory add=-12"
                               ^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %u\n", &a); // prints "memory add=65456"
                               ^

If you pass your pointer as a void* and use %p as the conversion specifier, then you get no error message:

#include <stdio.h>

int main()
{
    int a = 5;
    // check the memory address
    printf("memory address = %d\n", &a); /* wrong */
    printf("memory address = %u\n", &a); /* wrong */
    printf("memory address = %p\n", (void*)&a); /* right */
}

BATCH file asks for file or folder

A seemingly undocumented trick is to put a * at the end of the destination - then xcopy will copy as a file, like so

xcopy c:\source\file.txt c:\destination\newfile.txt*

The echo f | xcopy ... trick does not work on localized versions of Windows, where the prompt is different.

How do I (or can I) SELECT DISTINCT on multiple columns?

SELECT DISTINCT a,b,c FROM t

is roughly equivalent to:

SELECT a,b,c FROM t GROUP BY a,b,c

It's a good idea to get used to the GROUP BY syntax, as it's more powerful.

For your query, I'd do it like this:

UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
    SELECT id
    FROM sales S
    INNER JOIN
    (
        SELECT saleprice, saledate
        FROM sales
        GROUP BY saleprice, saledate
        HAVING COUNT(*) = 1 
    ) T
    ON S.saleprice=T.saleprice AND s.saledate=T.saledate
 )

Get Wordpress Category from Single Post

<div class="post_category">
        <?php $category = get_the_category();
             $allcategory = get_the_category(); 
        foreach ($allcategory as $category) {
        ?>
           <a class="btn"><?php echo $category->cat_name;; ?></a>
        <?php 
        }
        ?>
 </div>

How to overplot a line on a scatter plot in python?

plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

versus

plt.plot(X_plot, X_plot*results.params[1] + results.params[0])

How to make div go behind another div?

One possible could be like this,

HTML

<div class="box-left-mini">
    <div class="front">this div is infront</div>
    <div class="behind">
        this div is behind
    </div>
</div>

CSS

.box-left-mini{
float:left;
background-image:url(website-content/hotcampaign.png);
width:292px;
height:141px;
}
.front{
    background-color:lightgreen;
}
.behind{
    background-color:grey;
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    z-index:-1;
}

http://jsfiddle.net/MgtWS/

But it really depends on the layout of your div elements i.e. if they are floating, or absolute positioned etc.

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Download proxy script and check last line for return statement Proxy IP and Port.
Add this IP and Port using these step.

   1.  Windows -->Preferences-->General -->Network Connection
   2. Select Active Provider : Manual
   3.  Proxy entries select HTTP--> Click on Edit button
   4.  Then add Host as a proxy IP and port left Required Authentication blank.
   5.  Restart eclipse
   6.  Now Eclipse Marketplace... working.

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

Leave your email.php code the same, but replace this JavaScript code:

 var name = $("#form_name").val();
        var email = $("#form_email").val();
        var text = $("#msg_text").val();
        var dataString = 'name='+ name + '&email=' + email + '&text=' + text;

        $.ajax({
            type: "POST",
            url: "email.php",
            data: dataString,
            success: function(){
            $('.success').fadeIn(1000);
            }
        });

with this:

    $.ajax({
        type: "POST",
        url: "email.php",
        data: $(form).serialize(),
        success: function(){
        $('.success').fadeIn(1000);
        }
    });

So that your form input names match up.

C# ListView Column Width Auto

Expanding a bit on Fredrik's answer, if you want to set the column's auto-resize width on the fly for example: setting the first column's auto-size width to 70:

myListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.None);
myListView.Columns[0].Width = 70;
myListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);

How can I use Google's Roboto font on a website?

Old post, I know.

This is also possible using CSS @import url:

@import url(http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300ita??lic,400italic,500,500italic,700,700italic,900italic,900);
html, body, html * {
  font-family: 'Roboto', sans-serif;
}

Iterating through all nodes in XML file

I think the fastest and simplest way would be to use an XmlReader, this will not require any recursion and minimal memory foot print.

Here is a simple example, for compactness I just used a simple string of course you can use a stream from a file etc.

  string xml = @"
    <parent>
      <child>
        <nested />
      </child>
      <child>
        <other>
        </other>
      </child>
    </parent>
    ";

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
  {
    if (rdr.NodeType == XmlNodeType.Element)
    {
      Console.WriteLine(rdr.LocalName);
    }
  }

The result of the above will be

parent
child
nested
child
other

A list of all the elements in the XML document.

Creating Scheduled Tasks

You can use Task Scheduler Managed Wrapper:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}

Alternatively you can use native API or go for Quartz.NET. See this for details.

How to insert text into the textarea at the current cursor position?

A simple solution that work on firefox, chrome, opera, safari and edge but probably won't work on old IE browsers.

  var target = document.getElementById("mytextarea_id")

  if (target.setRangeText) {
     //if setRangeText function is supported by current browser
     target.setRangeText(data)
  } else {
    target.focus()
    document.execCommand('insertText', false /*no UI*/, data);
  }
}

setRangeText function allow you to replace current selection with the provided text or if no selection then insert the text at cursor position. It's only supported by firefox as far as I know.

For other browsers there is "insertText" command which only affect the html element currently focused and has same behavior as setRangeText

Inspired partially by this article

Plot a bar using matplotlib using a dictionary

It's a little simpler than most answers here suggest:

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(*zip(*D.items()))
plt.show()

enter image description here

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

You may also use a ResultSetExtractor instead of a RowMapper. Both are just as easy as one another, the only difference is you call ResultSet.next().

public String test() {
    String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN "
                 + " where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
    return jdbc.query(sql, new ResultSetExtractor<String>() {
        @Override
        public String extractData(ResultSet rs) throws SQLException,
                                                       DataAccessException {
            return rs.next() ? rs.getString("ID_NMB_SRZ") : null;
        }
    });
}

The ResultSetExtractor has the added benefit that you can handle all cases where there are more than one row or no rows returned.

UPDATE: Several years on and I have a few tricks to share. JdbcTemplate works superbly with java 8 lambdas which the following examples are designed for but you can quite easily use a static class to achieve the same.

While the question is about simple types, these examples serve as a guide for the common case of extracting domain objects.

First off. Let's suppose that you have an account object with two properties for simplicity Account(Long id, String name). You would likely wish to have a RowMapper for this domain object.

private static final RowMapper<Account> MAPPER_ACCOUNT =
        (rs, i) -> new Account(rs.getLong("ID"),
                               rs.getString("NAME"));

You may now use this mapper directly within a method to map Account domain objects from a query (jt is a JdbcTemplate instance).

public List<Account> getAccounts() {
    return jt.query(SELECT_ACCOUNT, MAPPER_ACCOUNT);
}

Great, but now we want our original problem and we use my original solution reusing the RowMapper to perform the mapping for us.

public Account getAccount(long id) {
    return jt.query(
            SELECT_ACCOUNT,
            rs -> rs.next() ? MAPPER_ACCOUNT.mapRow(rs, 1) : null,
            id);
}

Great, but this is a pattern you may and will wish to repeat. So you can create a generic factory method to create a new ResultSetExtractor for the task.

public static <T> ResultSetExtractor singletonExtractor(
        RowMapper<? extends T> mapper) {
    return rs -> rs.next() ? mapper.mapRow(rs, 1) : null;
}

Creating a ResultSetExtractor now becomes trivial.

private static final ResultSetExtractor<Account> EXTRACTOR_ACCOUNT =
        singletonExtractor(MAPPER_ACCOUNT);

public Account getAccount(long id) {
    return jt.query(SELECT_ACCOUNT, EXTRACTOR_ACCOUNT, id);
}

I hope this helps to show that you can now quite easily combine parts in a powerful way to make your domain simpler.

UPDATE 2: Combine with an Optional for optional values instead of null.

public static <T> ResultSetExtractor<Optional<T>> singletonOptionalExtractor(
        RowMapper<? extends T> mapper) {
    return rs -> rs.next() ? Optional.of(mapper.mapRow(rs, 1)) : Optional.empty();
}

Which now when used could have the following:

private static final ResultSetExtractor<Optional<Double>> EXTRACTOR_DISCOUNT =
        singletonOptionalExtractor(MAPPER_DISCOUNT);

public double getDiscount(long accountId) {
    return jt.query(SELECT_DISCOUNT, EXTRACTOR_DISCOUNT, accountId)
            .orElse(0.0);
}

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

What's the most useful and complete Java cheat sheet?

This Quick Reference looks pretty good if you're looking for a language reference. It's especially geared towards the user interface portion of the API.

For the complete API, however, I always use the Javadoc. I reference it constantly.

sys.stdin.readline() reads without prompt, returning 'nothing in between'

If you need just one character and you don't want to keep things in the buffer, you can simply read a whole line and drop everything that isn't needed.

Replace:

stdin.read(1)

with

stdin.readline().strip()[:1]

This will read a line, remove spaces and newlines and just keep the first character.

How to read a text file directly from Internet using Java?

Using Apache Commons IO:

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public static String readURLToString(String url) throws IOException
{
    try (InputStream inputStream = new URL(url).openStream())
    {
        return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    }
}

The imported project "C:\Microsoft.CSharp.targets" was not found

I used to have this following line in the csproj file:

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />

After deleting this file, it works fine.

Recreate the default website in IIS

Check out this answer on SuperUser:

In short: Reinstall both IIS and WAS.

In details -

Step 1

Go to "Add remove programs" "Turn windows features on or off" Remove both IIS and WAS (Windows Process Activation Service) Restart the PC Step 2

Go to "Add remove programs" "Turn windows features on or off" Turn on both IIS and WAS (Windows Process Activation Service) Note: Reinstalling IIS alone won't help. You have to reinstall both IIS and WAS

This approach fixed the problem for me.

How to sort by two fields in Java?

Arrays.sort(persons, new PersonComparator());



import java.util.Comparator;

public class PersonComparator implements Comparator<? extends Person> {

    @Override
    public int compare(Person o1, Person o2) {
        if(null == o1 || null == o2  || null == o1.getName() || null== o2.getName() ){
            throw new NullPointerException();
        }else{
            int nameComparisonResult = o1.getName().compareTo(o2.getName());
            if(0 == nameComparisonResult){
                return o1.getAge()-o2.getAge();
            }else{
                return nameComparisonResult;
            }
        }
    }
}


class Person{
    int age; String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Updated version:

public class PersonComparator implements Comparator<? extends Person> {

   @Override
   public int compare(Person o1, Person o2) {

      int nameComparisonResult = o1.getName().compareToIgnoreCase(o2.getName());
      return 0 == nameComparisonResult?o1.getAge()-o2.getAge():nameComparisonResult;

   }
 }

How many socket connections possible?

10,000? 70,000? is that all :)

FreeBSD is probably the server you want, Here's a little blog post about tuning it to handle 100,000 connections, its has had some interesting features like zero-copy sockets for some time now, along with kqueue to act as a completion port mechanism.

Solaris can handle 100,000 connections back in the last century!. They say linux would be better

The best description I've come across is this presentation/paper on writing a scalable webserver. He's not afraid to say it like it is :)

Same for software: the cretins on the application layer forced great innovations on the OS layer. Because Lotus Notes keeps one TCP connection per client open, IBM contributed major optimizations for the ”one process, 100.000 open connections” case to Linux

And the O(1) scheduler was originally created to score well on some irrelevant Java benchmark. The bottom line is that this bloat bene?ts all of us.

Android ImageButton with a selected state?

ToggleImageButton which implements Checkable interface and supports OnCheckedChangeListener and android:checked xml attribute:

public class ToggleImageButton extends ImageButton implements Checkable {
    private OnCheckedChangeListener onCheckedChangeListener;

    public ToggleImageButton(Context context) {
        super(context);
    }

    public ToggleImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        setChecked(attrs);
    }

    public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setChecked(attrs);
    }

    private void setChecked(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
        setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
        a.recycle();
    }

    @Override
    public boolean isChecked() {
        return isSelected();
    }

    @Override
    public void setChecked(boolean checked) {
        setSelected(checked);

        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(this, checked);
        }
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
    }

    @Override
    public boolean performClick() {
        toggle();
        return super.performClick();
    }

    public OnCheckedChangeListener getOnCheckedChangeListener() {
        return onCheckedChangeListener;
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    public static interface OnCheckedChangeListener {
        public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
    }
}

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ToggleImageButton">
        <attr name="android:checked" />
    </declare-styleable>
</resources>

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

Determining if a number is prime

bool check_prime(int num) {
    for (int i = num - 1; i > 1; i--) {
        if ((num % i) == 0)
            return false;
    }
    return true;
}

checks for any number if its a prime number

How do you write multiline strings in Go?

You can write:

"line 1" +
"line 2" +
"line 3"

which is the same as:

"line 1line 2line 3"

Unlike using back ticks, it will preserve escape characters. Note that the "+" must be on the 'leading' line - for instance, the following will generate an error:

"line 1"
+"line 2"

Android Studio drawable folders

In order to create the drawable directory structure for different image densities, You need to:

  1. Right-click on the \res folder
  2. Select new > android resource directory
  3. In the New Resource Directory window, under Available qualifiers resource type section, select drawable.

  4. Add density and choose the appropriate size.

SVN upgrade working copy

You can upgrade to Subversion 1.7. In order to update to Subversion 1.7 you have to launch existing project in Xcode 5 or above. This will prompt an warning ‘The working copy ProjectName should be upgraded to Subversion 1.7’ (shown in below screenshot).

Screenshot for warning

You should select ‘Upgrade’ button to upgrade to Subversion 1.7. This will take a bit of time.

If you are using terminal then you can upgrade to Subversion 1.7 by running below command in your project directory: svn upgrade

Note that once you have upgraded to Subversion 1.7 you cannot go back to Subversion 1.6.

Refer Apple docs for more details.

Current user in Magento?

I don't know this off the top of my head, but look in the file which shows the user's name, etc in the header of the page after the user has logged in. It might help if you turned on template hints (see this tutorial.

When you find the line such as "Hello <? //code for showing username?>", just copy that line and show it where you need to

Best way to do multiple constructors in PHP

As has already been shown here, there are many ways of declaring multiple constructors in PHP, but none of them are the correct way of doing so (since PHP technically doesn't allow it). But it doesn't stop us from hacking this functionality... Here's another example:

<?php

class myClass {
    public function __construct() {
        $get_arguments       = func_get_args();
        $number_of_arguments = func_num_args();

        if (method_exists($this, $method_name = '__construct'.$number_of_arguments)) {
            call_user_func_array(array($this, $method_name), $get_arguments);
        }
    }

    public function __construct1($argument1) {
        echo 'constructor with 1 parameter ' . $argument1 . "\n";
    }

    public function __construct2($argument1, $argument2) {
        echo 'constructor with 2 parameter ' . $argument1 . ' ' . $argument2 . "\n";
    }

    public function __construct3($argument1, $argument2, $argument3) {
        echo 'constructor with 3 parameter ' . $argument1 . ' ' . $argument2 . ' ' . $argument3 . "\n";
    }
}

$object1 = new myClass('BUET');
$object2 = new myClass('BUET', 'is');
$object3 = new myClass('BUET', 'is', 'Best.');

Source: The easiest way to use and understand multiple constructors:

Hope this helps. :)

Is there any way to specify a suggested filename when using data: URI?

I've looked a bit in firefox sources in netwerk/protocol/data/nsDataHandler.cpp

data handler only parses content/type and charset, and looks if there is ";base64" in the string

the rfc specifices no filename and at least firefox handles no filename for it, the code generates a random name plus ".part"

I've also checked firefox log

[b2e140]: DOCSHELL 6e5ae00 InternalLoad data:application/octet-stream;base64,SGVsbG8=
[b2e140]: Found extension '' (filename is '', handling attachment: 0)
[b2e140]: HelperAppService::DoContent: mime 'application/octet-stream', extension ''
[b2e140]: Getting mimeinfo from type 'application/octet-stream' ext ''
[b2e140]: Extension lookup on '' found: 0x0
[b2e140]: Ext. lookup for '' found 0x0
[b2e140]: OS gave back 0x43609a0 - found: 0
[b2e140]: Searched extras (by type), rv 0x80004005
[b2e140]: MIME Info Summary: Type 'application/octet-stream', Primary Ext ''
[b2e140]: Type/Ext lookup found 0x43609a0

interesting files if you want to look at mozilla sources:

data uri handler: netwerk/protocol/data/nsDataHandler.cpp
where mozilla decides the filename: uriloader/exthandler/nsExternalHelperAppService.cpp
InternalLoad string in the log: docshell/base/nsDocShell.cpp

I think you can stop searching a solution for now, because I suspect there is none :)

as noticed in this thread html5 has download attribute, it works also on firefox 20 http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download

PHP string concatenation

Just use . for concatenating. And you missed out the $personCount increment!

while ($personCount < 10) {
    $result .= $personCount . ' people';
    $personCount++;
}

echo $result;

SHA512 vs. Blowfish and Bcrypt

I agree with erickson's answer, with one caveat: for password authentication purposes, bcrypt is far better than a single iteration of SHA-512 - simply because it is far slower. If you don't get why slowness is an advantage in this particular game, read the article you linked to again (scroll down to "Speed is exactly what you don’t want in a password hash function.").

You can of course build a secure password hashing algorithm around SHA-512 by iterating it thousands of times, just like the way PHK's MD5 algorithm works. Ulrich Drepper did exactly this, for glibc's crypt(). There's no particular reason to do this, though, if you already have a tested bcrypt implementation available.

symbol(s) not found for architecture i386

Another reason this could be happening is when you UPGRADE an SDK.

If you simply delete the group, and then drag and drop the new folder to project, the "Library Search Path" would have both the SDKs. To solve, simply delete the old SDK path.

Java Array Sort descending?

First you need to sort your array using:

Collections.sort(myArray);

Then you need to reverse the order from ascending to descending using:

Collections.reverse(myArray);

Python read JSON file and modify

try this script:

with open("data.json") as f:
    data = json.load(f)
    data["id"] = 134
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "name":"mynamme",
    "id":134
}

Just the arrangement is different, You can solve the problem by converting the "data" type to a list, then arranging it as you wish, then returning it and saving the file, like that:

index_add = 0
with open("data.json") as f:
    data = json.load(f)
    data_li = [[k, v] for k, v in data.items()]
    data_li.insert(index_add, ["id", 134])
    data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "id":134,
    "name":"myname"
}

you can add if condition in order not to repeat the key, just change it, like that:

index_add = 0
n_k = "id"
n_v = 134
with open("data.json") as f:
    data = json.load(f)
    if n_k in data:
        data[n_k] = n_v
    else:
       data_li = [[k, v] for k, v in data.items()]
       data_li.insert(index_add, [n_k, n_v])
       data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

Adding a month to a date in T SQL

select * from Reference where reference_dt = DateAdd(month,1,another_date_reference)

fatal: Not a valid object name: 'master'

When I git init a folder it doesn't create a master branch

This is true, and expected behaviour. Git will not create a master branch until you commit something.

When I do git --bare init it creates the files.

A non-bare git init will also create the same files, in a hidden .git directory in the root of your project.

When I type git branch master it says "fatal: Not a valid object name: 'master'"

That is again correct behaviour. Until you commit, there is no master branch.

You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add them to prepare a commit. Then git commit to create your initial commit and master branch.

How do I fix a merge conflict due to removal of a file in a branch?

If you are using Git Gui on windows,

  1. Abort the merge
  2. Make sure you are on your target branch
  3. Delete the conflicting file from explorer
  4. Rescan for changes in Git Gui (F5)
  5. Notice that conflicting file is deleted
  6. Select Stage Changed Files To Commit (Ctrl-I) from Commit menu
  7. Enter a commit comment like "deleted conflicting file"
  8. Commit (ctrl-enter)
  9. Now if you restart the merge it will (hopefully) work.

Inner join with 3 tables in mysql

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
 INNER JOIN student
   ON student.studentId = grade.fk_studentId
 INNER JOIN exam
   ON exam.examId = grade.fk_examId
 GROUP BY grade.gradeId
 ORDER BY exam.date

Handling file renames in git

Step1: rename the file from oldfile to newfile

git mv #oldfile #newfile

Step2: git commit and add comments

git commit -m "rename oldfile to newfile"

Step3: push this change to remote sever

git push origin #localbranch:#remotebranch

jQuery - Click event on <tr> elements with in a table and getting <td> element values

$("body").on("click", "#tableid tr", function () {
    debugger
    alert($(this).text());
});

$("body").on("click", "#tableid td", function () {
    debugger
    alert($(this).text());
});

C# Pass Lambda Expression as Method Parameter

Lambda expressions have a type of Action<parameters> (in case they don't return a value) or Func<parameters,return> (in case they have a return value). In your case you have two input parameters, and you need to return a value, so you should use:

Func<FullTimeJob, Student, FullTimeJob>

How to copy Java Collections list

Why dont you just use addAll method:

    List a = new ArrayList();
         a.add("1");
         a.add("abc");

    List b = b.addAll(listA);

//b will be 1, abc

even if you have existing items in b or you want to pend some elements after it, such as:

List a = new ArrayList();
     a.add("1");
     a.add("abc");

List b = new ArrayList();
     b.add("x");
     b.addAll(listA);
     b.add("Y");

//b will be x, 1, abc, Y

Bootstrap change carousel height

From Bootstrap 4

.carousel-item{
    height: 200px;
} 
.carousel-item img{
    height: 200px;
}

Java 8 NullPointerException in Collectors.toMap

I wrote a Collector which, unlike the default java one, does not crash when you have null values:

public static <T, K, U>
        Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
                Function<? super T, ? extends U> valueMapper) {
    return Collectors.collectingAndThen(
            Collectors.toList(),
            list -> {
                Map<K, U> result = new HashMap<>();
                for (T item : list) {
                    K key = keyMapper.apply(item);
                    if (result.putIfAbsent(key, valueMapper.apply(item)) != null) {
                        throw new IllegalStateException(String.format("Duplicate key %s", key));
                    }
                }
                return result;
            });
}

Just replace your Collectors.toMap() call to a call to this function and it'll fix the problem.

What is the difference between a generative and a discriminative algorithm?

In practice, the models are used as follows.

In discriminative models, to predict the label y from the training example x, you must evaluate:

enter image description here

which merely chooses what is the most likely class y considering x. It's like we were trying to model the decision boundary between the classes. This behavior is very clear in neural networks, where the computed weights can be seen as a complexly shaped curve isolating the elements of a class in the space.

Now, using Bayes' rule, let's replace the enter image description here in the equation by enter image description here. Since you are just interested in the arg max, you can wipe out the denominator, that will be the same for every y. So, you are left with

enter image description here

which is the equation you use in generative models.

While in the first case you had the conditional probability distribution p(y|x), which modeled the boundary between classes, in the second you had the joint probability distribution p(x, y), since p(x | y) p(y) = p(x, y), which explicitly models the actual distribution of each class.

With the joint probability distribution function, given a y, you can calculate ("generate") its respective x. For this reason, they are called "generative" models.

Cleanest Way to Invoke Cross-Thread Events

I shun redundant delegate declarations.

private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    if (InvokeRequired)
    {
        Invoke(new Action<object, CoolObjectEventArgs>(mCoolObject_CoolEvent), sender, args);
        return;
    }
    // do the dirty work of my method here
}

For non-events, you can use the System.Windows.Forms.MethodInvoker delegate or System.Action.

EDIT: Additionally, every event has a corresponding EventHandler delegate so there's no need at all to redeclare one.

Inverse of matrix in R

You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package

Installing pip packages to $HOME folder

You can specify the -t option (--target) to specify the destination directory. See pip install --help for detailed information. This is the command you need:

pip install -t path_to_your_home package-name

for example, for installing say mxnet, in my $HOME directory, I type:

pip install -t /home/foivos/ mxnet

Remove part of a string

You can use a built-in for this, strsplit:

> s = "TGAS_1121"
> s1 = unlist(strsplit(s, split='_', fixed=TRUE))[2]
> s1    
 [1] "1121"

strsplit returns both pieces of the string parsed on the split parameter as a list. That's probably not what you want, so wrap the call in unlist, then index that array so that only the second of the two elements in the vector are returned.

Finally, the fixed parameter should be set to TRUE to indicate that the split parameter is not a regular expression, but a literal matching character.

How do I share variables between different .c files?

Those other variables would have to be declared public (use extern, public is for C++), and you would have to include that .c file. However, I recommend creating appropriate .h files to define all of your variables.

For example, for hello.c, you would have a hello.h, and hello.h would store your variable definitions. Then another .c file, such as world.c would have this piece of code at the top:

#include "hello.h"

That will allow world.c to use variables that are defined in hello.h

It's slightly more complicated than that though. You may use < > to include library files found on your OS's path. As a beginner I would stick all of your files in the same folder and use the " " syntax.

jQuery checkbox change and click event

Try this

$('#checkbox1').click(function() {
        if (!this.checked) {
            var sure = confirm("Are you sure?");
            this.checked = sure;
            $('#textbox1').val(sure.toString());
        }
    });

How can I get the baseurl of site?

The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:

uri.GetComponents(
    UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);

Read data from a text file using Java

The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0

Adb over wireless without usb cable at all for not rooted phones

Had same issue, however I'm using Macbook Pro (2016) which has USB-c only and I forgot my adapter at home.

Since unable to run adb at all on my development machine, I found a different approach.

Connecting phone with USB cable to another computer (in same WiFi) and enable run adb tcpip from there.

Master-machine : computer where development goes on, with only USB-C connectors

Slave-machine: another computer with USB and in same WiFi

Steps:

  1. Connect the phone to a different computer (slave-machine)
  2. Run adb usb && adb tcpip 5555 from there
  3. On master machine

    deko$: adb devices
    List of devices attached
    
    deko$: adb connect 10.0.20.153:5555
    connected to 10.0.20.153:5555
    
  4. Now Android Studio or Xamarin can install and run app on the phone


Sidenote:

I also tested Bluetooth tethering from the Phone to Master-machine and successfully connected to phone. Both Android Studio and Xamarin worked well, however the upload process, from Xamarin was taking long time. But it works.

How to get all groups that a user is a member of?

The below works well:

get-aduser $username -Properties memberof | select -expand memberof

If you have a list of users:

$list = 'administrator','testuser1','testuser2'
$list | `
    %{  
        $user = $_; 
        get-aduser $user -Properties memberof | `
        select -expand memberof | `
        %{new-object PSObject -property @{User=$user;Group=$_;}} `
    }

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

How does HTTP file upload work?

Send file as binary content (upload without form or FormData)

In the given answers/examples the file is (most likely) uploaded with a HTML form or using the FormData API. The file is only a part of the data sent in the request, hence the multipart/form-data Content-Type header.

If you want to send the file as the only content then you can directly add it as the request body and you set the Content-Type header to the MIME type of the file you are sending. The file name can be added in the Content-Disposition header. You can upload like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

If you don't (want to) use forms and you are only interested in uploading one single file this is the easiest way to include your file in the request.

How does a hash table work?

Here's an explanation in layman's terms.

Let's assume you want to fill up a library with books and not just stuff them in there, but you want to be able to easily find them again when you need them.

So, you decide that if the person that wants to read a book knows the title of the book and the exact title to boot, then that's all it should take. With the title, the person, with the aid of the librarian, should be able to find the book easily and quickly.

So, how can you do that? Well, obviously you can keep some kind of list of where you put each book, but then you have the same problem as searching the library, you need to search the list. Granted, the list would be smaller and easier to search, but still you don't want to search sequentially from one end of the library (or list) to the other.

You want something that, with the title of the book, can give you the right spot at once, so all you have to do is just stroll over to the right shelf, and pick up the book.

But how can that be done? Well, with a bit of forethought when you fill up the library and a lot of work when you fill up the library.

Instead of just starting to fill up the library from one end to the other, you devise a clever little method. You take the title of the book, run it through a small computer program, which spits out a shelf number and a slot number on that shelf. This is where you place the book.

The beauty of this program is that later on, when a person comes back in to read the book, you feed the title through the program once more, and get back the same shelf number and slot number that you were originally given, and this is where the book is located.

The program, as others have already mentioned, is called a hash algorithm or hash computation and usually works by taking the data fed into it (the title of the book in this case) and calculates a number from it.

For simplicity, let's say that it just converts each letter and symbol into a number and sums them all up. In reality, it's a lot more complicated than that, but let's leave it at that for now.

The beauty of such an algorithm is that if you feed the same input into it again and again, it will keep spitting out the same number each time.

Ok, so that's basically how a hash table works.

Technical stuff follows.

First, there's the size of the number. Usually, the output of such a hash algorithm is inside a range of some large number, typically much larger than the space you have in your table. For instance, let's say that we have room for exactly one million books in the library. The output of the hash calculation could be in the range of 0 to one billion which is a lot higher.

So, what do we do? We use something called modulus calculation, which basically says that if you counted to the number you wanted (i.e. the one billion number) but wanted to stay inside a much smaller range, each time you hit the limit of that smaller range you started back at 0, but you have to keep track of how far in the big sequence you've come.

Say that the output of the hash algorithm is in the range of 0 to 20 and you get the value 17 from a particular title. If the size of the library is only 7 books, you count 1, 2, 3, 4, 5, 6, and when you get to 7, you start back at 0. Since we need to count 17 times, we have 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, and the final number is 3.

Of course modulus calculation isn't done like that, it's done with division and a remainder. The remainder of dividing 17 by 7 is 3 (7 goes 2 times into 17 at 14 and the difference between 17 and 14 is 3).

Thus, you put the book in slot number 3.

This leads to the next problem. Collisions. Since the algorithm has no way to space out the books so that they fill the library exactly (or the hash table if you will), it will invariably end up calculating a number that has been used before. In the library sense, when you get to the shelf and the slot number you wish to put a book in, there's already a book there.

Various collision handling methods exist, including running the data into yet another calculation to get another spot in the table (double hashing), or simply to find a space close to the one you were given (i.e. right next to the previous book assuming the slot was available also known as linear probing). This would mean that you have some digging to do when you try to find the book later, but it's still better than simply starting at one end of the library.

Finally, at some point, you might want to put more books into the library than the library allows. In other words, you need to build a bigger library. Since the exact spot in the library was calculated using the exact and current size of the library, it goes to follow that if you resize the library you might end up having to find new spots for all the books since the calculation done to find their spots has changed.

I hope this explanation was a bit more down to earth than buckets and functions :)

TypeError: 'dict_keys' object does not support indexing

Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:

next(iter(keys))

Or, if you want to iterate over all items, you can use:

items = iter(keys)
while True:
    try:
        item = next(items)
    except StopIteration as e:
        pass # finish

Combining CSS Pseudo-elements, ":after" the ":last-child"

Just To mention, in CSS 3

:after

should be used like this

::after

From https://developer.mozilla.org/de/docs/Web/CSS/::after :

The ::after notation was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :after introduced in CSS 2.

So it should be:

li { display: inline; list-style-type: none; }
li::after { content: ", "; }
li:last-child::before { content: "and "; }
li:last-child::after { content: "."; }

Finishing current activity from a fragment

Well actually...

I wouldn't have the Fragment try to finish the Activity. That places too much authority on the Fragment in my opinion. Instead, I would use the guide here: http://developer.android.com/training/basics/fragments/communicating.html

Have the Fragment define an interface which the Activity must implement. Make a call up to the Activity, then let the Activity decide what to do with the information. If the activity wishes to finish itself, then it can.

How do I change the hover over color for a hover over table in Bootstrap?

For me @pvskisteak5 answer has caused a "flicker-effect". To fix this, add the following:

            .table-hover tbody tr:hover,
            .table-hover tbody tr:hover td,
            .table-hover tbody tr:hover th{
                background:#22313F !important;
                color:#fff !important;
            }

Most efficient way to map function over numpy array

As mentioned in this post, just use generator expressions like so:

numpy.fromiter((<some_func>(x) for x in <something>),<dtype>,<size of something>)

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

Doctrine and LIKE query

This is not possible with the magic methods, however you can achieve this using DQL (Doctrine Query Language). In your example, assuming you have entity named Orders with Product property, just go ahead and do the following:

$dql_query = $em->createQuery("
    SELECT o FROM AcmeCodeBundle:Orders o
    WHERE 
      o.OrderEmail = '[email protected]' AND
      o.Product LIKE 'My Products%'
");
$orders = $dql_query->getResult();

Should do exactly what you need.

Row numbers in query result using Microsoft Access

I needed the best x results of points per team.

Ranking does not solves this problem when there are results with equal points. So I need a recordnumber

I made a VBA function in Access to create a recordnumber that resets on ID change.

You have to query this query with where recordnumber <= x to get the points per team.

NB Access changes the record-number

  1. when you query the query filtered on record number
  2. when you filter out some results
  3. when you change the sort order

That is not what I thought that would happen.

Solved this by using a temporary table and saving the recordnumbers and keys or an extra field in the table.

SELECT ID, Points, RecordNumberOffId([ID}) AS Recordnumber
FROM Team ORDER BY ID ASC, Points DESC;

It uses 3 module level variables to remember between calls

Dim PreviousID As Long
Dim PreviousRecordNumber As Long
Dim TimeLastID As Date

Public Function RecordNumberOffID(ID As Long) As Long 
'ID is sortgroup identity
'Reset if last call longer dan nn seconds in the past
If Time() - TimeLastID > 0.0003 Then '0,000277778 = 1 second
    PreviousID = 0
    PreviousRecordNumber = 0
End If
If ID <> PreviousID Then
    PreviousRecordNumber = 0
    PreviousID = ID
End If
PreviousRecordNumber = PreviousRecordNumber + 1
RecordNumberOffID = PreviousRecordNumber
TimeLastID = Time()
End Function

How to add fonts to create-react-app based projects?

There are two options:

Using Imports

This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.

As described in “Adding Images, Fonts, and Files”, you need to have a CSS file imported from JS. For example, by default src/index.js imports src/index.css:

import './index.css';

A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in src/fonts/MyFont.woff, your index.css might include this:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(./fonts/MyFont.woff) format('woff');
}

Notice how we’re using a relative path starting with ./. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.

Normally this should be enough.

Using public Folder

If for some reason you prefer not to use the build pipeline, and instead do it the “classic way”, you can use the public folder and put your fonts there.

The downside of this approach is that the files don’t get hashes when you compile for production so you’ll have to update their names every time you change them, or browsers will cache the old versions.

If you want to do it this way, put the fonts somewhere into the public folder, for example, into public/fonts/MyFont.woff. If you follow this approach, you should put CSS files into public folder as well and not import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you’d have a file like public/index.css. You would have to manually add <link> to this stylesheet from public/index.html:

<link rel="stylesheet" href="%PUBLIC_URL%/index.css">

And inside of it, you would use the regular CSS notation:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(fonts/MyFont.woff) format('woff');
}

Notice how I’m using fonts/MyFont.woff as the path. This is because index.css is in the public folder so it will be served from the public path (usually it’s the server root, but if you deploy to GitHub Pages and set your homepage field to http://myuser.github.io/myproject, it will be served from /myproject). However fonts are also in the public folder, so they will be served from fonts relatively (either http://mywebsite.com/fonts or http://myuser.github.io/myproject/fonts). Therefore we use the relative path.

Note that since we’re avoiding the build pipeline in this example, it doesn’t verify that the file actually exists. This is why I don’t recommend this approach. Another problem is that our index.css file doesn’t get minified and doesn’t get a hash. So it’s going to be slower for the end users, and you risk the browsers caching old versions of the file.

 Which Way to Use?

Go with the first method (“Using Imports”). I only described the second one since that’s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you’re working around some issue.

What does "connection reset by peer" mean?

It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.

Hibernate Criteria Query to get specific columns

You can use JPQL as well as JPA Criteria API for any kind of DTO projection(Mapping only selected columns to a DTO class) . Look at below code snippets showing how to selectively select various columns instead of selecting all columns . These example also show how to select various columns from joining multiple columns . I hope this helps .

JPQL code :

String dtoProjection = "new com.katariasoft.technologies.jpaHibernate.college.data.dto.InstructorDto"
                + "(i.id, i.name, i.fatherName, i.address, id.proofNo, "
                + " v.vehicleNumber, v.vechicleType, s.name, s.fatherName, "
                + " si.name, sv.vehicleNumber , svd.name) ";

        List<InstructorDto> instructors = queryExecutor.fetchListForJpqlQuery(
                "select " + dtoProjection + " from Instructor i " + " join i.idProof id " + " join i.vehicles v "
                        + " join i.students s " + " join s.instructors si " + " join s.vehicles sv "
                        + " join sv.documents svd " + " where i.id > :id and svd.name in (:names) "
                        + " order by i.id , id.proofNo , v.vehicleNumber , si.name , sv.vehicleNumber , svd.name ",
                CollectionUtils.mapOf("id", 2, "names", Arrays.asList("1", "2")), InstructorDto.class);

        if (Objects.nonNull(instructors))
            instructors.forEach(i -> i.setName("Latest Update"));

        DataPrinters.listDataPrinter.accept(instructors);

JPA Criteria API code :

@Test
    public void fetchFullDataWithCriteria() {
        CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
        CriteriaQuery<InstructorDto> cq = cb.createQuery(InstructorDto.class);

        // prepare from expressions
        Root<Instructor> root = cq.from(Instructor.class);
        Join<Instructor, IdProof> insIdProofJoin = root.join(Instructor_.idProof);
        Join<Instructor, Vehicle> insVehicleJoin = root.join(Instructor_.vehicles);
        Join<Instructor, Student> insStudentJoin = root.join(Instructor_.students);
        Join<Student, Instructor> studentInsJoin = insStudentJoin.join(Student_.instructors);
        Join<Student, Vehicle> studentVehicleJoin = insStudentJoin.join(Student_.vehicles);
        Join<Vehicle, Document> vehicleDocumentJoin = studentVehicleJoin.join(Vehicle_.documents);

        // prepare select expressions.
        CompoundSelection<InstructorDto> selection = cb.construct(InstructorDto.class, root.get(Instructor_.id),
                root.get(Instructor_.name), root.get(Instructor_.fatherName), root.get(Instructor_.address),
                insIdProofJoin.get(IdProof_.proofNo), insVehicleJoin.get(Vehicle_.vehicleNumber),
                insVehicleJoin.get(Vehicle_.vechicleType), insStudentJoin.get(Student_.name),
                insStudentJoin.get(Student_.fatherName), studentInsJoin.get(Instructor_.name),
                studentVehicleJoin.get(Vehicle_.vehicleNumber), vehicleDocumentJoin.get(Document_.name));

        // prepare where expressions.
        Predicate instructorIdGreaterThan = cb.greaterThan(root.get(Instructor_.id), 2);
        Predicate documentNameIn = cb.in(vehicleDocumentJoin.get(Document_.name)).value("1").value("2");
        Predicate where = cb.and(instructorIdGreaterThan, documentNameIn);

        // prepare orderBy expressions.
        List<Order> orderBy = Arrays.asList(cb.asc(root.get(Instructor_.id)),
                cb.asc(insIdProofJoin.get(IdProof_.proofNo)), cb.asc(insVehicleJoin.get(Vehicle_.vehicleNumber)),
                cb.asc(studentInsJoin.get(Instructor_.name)), cb.asc(studentVehicleJoin.get(Vehicle_.vehicleNumber)),
                cb.asc(vehicleDocumentJoin.get(Document_.name)));

        // prepare query
        cq.select(selection).where(where).orderBy(orderBy);
        DataPrinters.listDataPrinter.accept(queryExecutor.fetchListForCriteriaQuery(cq));

    }

How to deal with page breaks when printing a large HTML table

Well Guys... Most of the Solutions up here didn't worked for. So this is how things worked for me..

HTML

<table>
  <thead>
   <tr>
     <th style="border:none;height:26px;"></th>
     <th style="border:none;height:26px;"></th>
     .
     .
   </tr>
   <tr>
     <th style="border:1px solid black">ABC</th>
     <th style="border:1px solid black">ABC</th>
     .
     .
   <tr>
  </thead>
<tbody>

    //YOUR CODE

</tbody>
</table>

The first set of head is used as a dummy one so that there won't be a missing top border in 2nd head(i.e. original head) while page break.

.append(), prepend(), .after() and .before()

There is a basic difference between .append() and .after() and .prepend() and .before().

.append() adds the parameter element inside the selector element's tag at the very end whereas the .after() adds the parameter element after the element's tag.

The vice-versa is for .prepend() and .before().

Fiddle

How do I update a Python package?

In Juptyer notebook, a very simple way is

!pip install <package_name> --upgrade

So, you just need to replace with the actual package name.

Pass entire form as data in jQuery Ajax function

The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.

My solution:

<form id="form_1" action="result.php" method="post"
 onsubmit="sendForm(this.id);return false">
    <input type="hidden" name="something" value="1">
</form>

js:

function sendForm(form_id){
    var form = $('#'+form_id);
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: $(form).serialize(),
        success: function(result) {
            console.log(result)
        }
    });
}

How to remove all ListBox items?

Write the following code in the .cs file:

ListBox.Items.Clear();

PHP "php://input" vs $_POST

php://input can give you the raw bytes of the data. This is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request.

Here's a function to do just that:

  /**
   * Returns the JSON encoded POST data, if any, as an object.
   * 
   * @return Object|null
   */
  private function retrieveJsonPostData()
  {
    // get the raw POST data
    $rawData = file_get_contents("php://input");

    // this returns null if not valid json
    return json_decode($rawData);
  }

The $_POST array is more useful when you're handling key-value data from a form, submitted by a traditional POST. This only works if the POSTed data is in a recognised format, usually application/x-www-form-urlencoded (see http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 for details).

pthread function from a class

My guess would be this is b/c its getting mangled up a bit by C++ b/c your sending it a C++ pointer, not a C function pointer. There is a difference apparently. Try doing a

(void)(*p)(void) = ((void) *(void)) &c[0].print; //(check my syntax on that cast)

and then sending p.

I've done what your doing with a member function also, but i did it in the class that was using it, and with a static function - which i think made the difference.

Cron and virtualenv

This is a solution that has worked well for me.

source /root/miniconda3/etc/profile.d/conda.sh && \
conda activate <your_env> && \
python <your_application> &

I am using miniconda with Conda version 4.7.12 on a Ubuntu 18.04.3 LTS.

I am able to place the above inside a script and run it via crontab as well without any trouble.

How to set up a PostgreSQL database in Django

Also make sure you have the PostgreSQL development package installed. On Ubuntu you need to do something like this:

$ sudo apt-get install libpq-dev

Passing variables to the next middleware using next() in Express.js

The trick is pretty simple... The request cycle is still pretty much alive. You can just add a new variable that will create a temporary, calling

app.get('some/url/endpoint', middleware1, middleware2);

Since you can handle your request in the first middleware

(req, res, next) => {
    var yourvalue = anyvalue
}

In middleware 1 you handle your logic and store your value like below:

req.anyvariable = yourvalue

In middleware 2 you can catch this value from middleware 1 doing the following:

(req, res, next) => {
    var storedvalue = req.yourvalue
}

How does @synchronized lock/unlock in Objective-C?

In Objective-C, a @synchronized block handles locking and unlocking (as well as possible exceptions) automatically for you. The runtime dynamically essentially generates an NSRecursiveLock that is associated with the object you're synchronizing on. This Apple documentation explains it in more detail. This is why you're not seeing the log messages from your NSLock subclass — the object you synchronize on can be anything, not just an NSLock.

Basically, @synchronized (...) is a convenience construct that streamlines your code. Like most simplifying abstractions, it has associated overhead (think of it as a hidden cost), and it's good to be aware of that, but raw performance is probably not the supreme goal when using such constructs anyway.

What integer hash function are good that accepts an integer hash key?

Knuth's multiplicative method:

hash(i)=i*2654435761 mod 2^32

In general, you should pick a multiplier that is in the order of your hash size (2^32 in the example) and has no common factors with it. This way the hash function covers all your hash space uniformly.

Edit: The biggest disadvantage of this hash function is that it preserves divisibility, so if your integers are all divisible by 2 or by 4 (which is not uncommon), their hashes will be too. This is a problem in hash tables - you can end up with only 1/2 or 1/4 of the buckets being used.

SameSite warning Chrome 77

Fixed by adding crossorigin to the script tag.

From: https://code.jquery.com/

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org

How to preventDefault on anchor tags?

This is what I always do. Works like a charm!

<a href ng-click="do()">Click</a>

Cannot install node modules that require compilation on Windows 7 x64/VS2012

To do it without VS2010 installation, and only 2012, set the msvs_version flag:

node-gyp rebuild --msvs_version=2012

npm install <module> --msvs_version=2012

as per @Jacob comment

npm install --msvs_version=2013 if you have the 2013 version

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

Incorrect integer value: '' for column 'id' at row 1

That probably means that your id is an AUTO_INCREMENT integer and you're trying to send a string. You should specify a column list and omit it from your INSERT.

INSERT INTO workorders (column1, column2) VALUES ($column1, $column2)

How to set text size of textview dynamically for different screens

EDIT: And As I Search on StackOverflow now I found This Question is Duplicate of : This and This

You need to use another function setTextSize(unit, size) with unit SP like this,

tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f);

Please read more for TypedValue constants.

Set android shape color programmatically

Expanding on Vikram's answer, if you are coloring dynamic views, like recycler view items, etc.... Then you probably want to call mutate() before you set the color. If you don't do this, any views that have a common drawable (i.e a background) will also have their drawable changed/colored.

public static void setBackgroundColorAndRetainShape(final int color, final Drawable background) {

    if (background instanceof ShapeDrawable) {
        ((ShapeDrawable) background.mutate()).getPaint().setColor(color);
    } else if (background instanceof GradientDrawable) {
        ((GradientDrawable) background.mutate()).setColor(color);
    } else if (background instanceof ColorDrawable) {
        ((ColorDrawable) background.mutate()).setColor(color);
    }else{
        Log.w(TAG,"Not a valid background type");
    }

}

Static method in a generic class?

I ran into this same problem. I found my answer by downloading the source code for Collections.sort in the java framework. The answer I used was to put the <T> generic in the method, not in the class definition.

So this worked:

public class QuickSortArray  {
    public static <T extends Comparable> void quickSort(T[] array, int bottom, int top){
//do it
}

}

Of course, after reading the answers above I realized that this would be an acceptable alternative without using a generic class:

public static void quickSort(Comparable[] array, int bottom, int top){
//do it
}

click or change event on radio using jquery

Try

$(document).ready(

instead of

$('document').ready(

or you can use a shorthand form

$(function(){
});

How to run a script file remotely using SSH

I don't know if it's possible to run it just like that.

I usually first copy it with scp and then log in to run it.

scp foo.sh user@host:~
ssh user@host
./foo.sh

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Swift 2.0 & iOS 7+ / iOS 8+ / iOS 9+

public class Helper {
    public class var isIpad:Bool {
        if #available(iOS 8.0, *) {
            return UIScreen.mainScreen().traitCollection.userInterfaceIdiom == .Pad
        } else {
            return UIDevice.currentDevice().userInterfaceIdiom == .Pad
        }
    }
    public class var isIphone:Bool {
        if #available(iOS 8.0, *) {
            return UIScreen.mainScreen().traitCollection.userInterfaceIdiom == .Phone
        } else {
            return UIDevice.currentDevice().userInterfaceIdiom == .Phone
        }
    }
}

Use :

if Helper.isIpad {

}

OR

guard Helper.isIpad else {
    return
} 

Thanks @user3378170

Make the current commit the only (initial) commit in a Git repository?

This deletes the history on the master branch (you might want to make a backup before running the commands):

git branch tmp_branch $(echo "commit message" | git commit-tree HEAD^{tree})
git checkout tmp_branch
git branch -D master
git branch -m master
git push -f --set-upstream origin master

This is based on the answer from @dan_waterworth.

On select change, get data attribute value

You can use context syntax with this or $(this). This is the same effect as find().

_x000D_
_x000D_
$('select').change(function() {_x000D_
    console.log('Clicked option value => ' + $(this).val());_x000D_
    <!-- undefined console.log('$(this) without explicit :select => ' + $(this).data('id')); -->_x000D_
    <!-- error console.log('this without explicit :select => ' + this.data('id')); -->_x000D_
    console.log(':select & $(this) =>    ' + $(':selected', $(this)).data('id'));_x000D_
    console.log(':select & this =>       ' + $(':selected', this).data('id'));_x000D_
    console.log('option:select & this => ' + $('option:selected', this).data('id'));_x000D_
    console.log('$(this) & find =>       ' + $(this).find(':selected').data('id'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
    <option data-id="1">one</option>_x000D_
    <option data-id="2">two</option>_x000D_
    <option data-id="3">three</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

As a matter of microoptimization, you might opt for find(). If you are more of a code golfer, the context syntax is more brief. It comes down to coding style basically.

Here is a relevant performance comparison.

How to generate .env file for laravel?

If the .env a file is missing, then there is another way to generate a .env file

You can download env.example, rename it to .env and edit it. Just set up correct DB credentials etc.

Don't forget to When you use the php artisan key:generate it will generate the new key to your .env file

Python Pandas replicate rows in dataframe

Appending and concatenating is usually slow in Pandas so I recommend just making a new list of the rows and turning that into a dataframe (unless appending a single row or concatenating a few dataframes).

import pandas as pd

df = pd.DataFrame([
[1,1,'2010-02-05',24924.5,False],
[1,1,'2010-02-12',46039.49,True],
[1,1,'2010-02-19',41595.55,False],
[1,1,'2010-02-26',19403.54,False],
[1,1,'2010-03-05',21827.9,False],
[1,1,'2010-03-12',21043.39,False],
[1,1,'2010-03-19',22136.64,False],
[1,1,'2010-03-26',26229.21,False],
[1,1,'2010-04-02',57258.43,False]
], columns=['Store','Dept','Date','Weekly_Sales','IsHoliday'])

temp_df = []
for row in df.itertuples(index=False):
    if row.IsHoliday:
        temp_df.extend([list(row)]*5)
    else:
        temp_df.append(list(row))

df = pd.DataFrame(temp_df, columns=df.columns)

Handler vs AsyncTask vs Thread

Thread:

You can use the new Thread for long-running background tasks without impacting UI Thread. From java Thread, you can't update UI Thread.

Since normal Thread is not much useful for Android architecture, helper classes for threading have been introduced.

You can find answers to your queries in Threading performance documentation page.

Handler:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.

There are two main uses for a Handler:

  1. To schedule messages and runnables to be executed as some point in the future;

  2. To enqueue an action to be performed on a different thread than your own.

AsyncTask:

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Drawbacks:

  1. By default, an app pushes all of the AsyncTask objects it creates into a single thread. Therefore, they execute in serial fashion, and—as with the main thread—an especially long work packet can block the queue. Due to this reason, use AsyncTask to handle work items shorter than 5ms in duration.

  2. AsyncTask objects are also the most common offenders for implicit-reference issues. AsyncTask objects present risks related to explicit references, as well.

HandlerThread:

You may need a more traditional approach to executing a block of work on a long-running thread (unlike AsyncTask, which should be used for 5ms workload), and some ability to manage that workflow manually. A handler thread is effectively a long-running thread that grabs work from a queue and operates on it.

ThreadPoolExecutor:

This class manages the creation of a group of threads, sets their priorities, and manages how work is distributed among those threads. As workload increases or decreases, the class spins up or destroys more threads to adjust to the workload.

If the workload is more and single HandlerThread is not suffice, you can go for ThreadPoolExecutor

However I would like to have a socket connection run in service. Should this be run in a handler or a thread, or even an AsyncTask? UI interaction is not necessary at all. Does it make a difference in terms of performance which I use?

Since UI interaction is not required, you may not go for AsyncTask. Normal threads are not much useful and hence HandlerThread is the best option. Since you have to maintain socket connection, Handler on the main thread is not useful at all. Create a HandlerThread and get a Handler from the looper of HandlerThread.

 HandlerThread handlerThread = new HandlerThread("SocketOperation");
 handlerThread.start();
 Handler requestHandler = new Handler(handlerThread.getLooper());
 requestHandler.post(myRunnable); // where myRunnable is your Runnable object. 

If you want to communicate back to UI thread, you can use one more Handler to process response.

final Handler responseHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            //txtView.setText((String) msg.obj);
            Toast.makeText(MainActivity.this,
                    "Foreground task is completed:"+(String)msg.obj,
                    Toast.LENGTH_LONG)
                    .show();
        }
    };

in your Runnable, you can add

responseHandler.sendMessage(msg);

More details about implementation can be found here:

Android: Toast in a thread

SSIS Convert Between Unicode and Non-Unicode Error

I have been having the same issue and tried everything written here but it was still giving me the same error. Turned out to be NULL value in the column which I was trying to convert.

Removing the NULL value solved my issue.

Cheers, Ahmed

How to kill a running SELECT statement

There is no need to kill entire session. In Oracle 18c you could use ALTER SYSTEM CANCEL:

Cancelling a SQL Statement in a Session

You can cancel a SQL statement in a session using the ALTER SYSTEM CANCEL SQL statement.

Instead of terminating a session, you can cancel a high-load SQL statement in a session. When you cancel a DML statement, the statement is rolled back.

ALTER SYSTEM CANCEL SQL 'SID, SERIAL[, @INST_ID][, SQL_ID]';

If @INST_ID is not specified, the instance ID of the current session is used.

If SQL_ID is not specified, the currently running SQL statement in the specified session is terminated.

How to determine the current language of a wordpress page when using polylang?

Simple:

if(pll_current_language() == 'en'){
   //do your work here
}

How do I create a file AND any folders, if the folders don't exist?

Use Directory.CreateDirectory before you create the file. It creates the folder recursively for you.

Lodash remove duplicates from array

For a simple array, you have the union approach, but you can also use :

_.uniq([2, 1, 2]);

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

There are two main differences.

Accessing the association sides

The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.

So, for a unidirectional @ManyToOne association, it means you can only access the relationship from the child side where the foreign key resides.

If you have a unidirectional @OneToMany association, it means you can only access the relationship from the parent side which manages the foreign key.

For the bidirectional @OneToMany association, you can navigate the association in both ways, either from the parent or from the child side.

You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.

Performance

The second aspect is related to performance.

  1. For @OneToMany, unidirectional associations don't perform as well as bidirectional ones.
  2. For @OneToOne, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.
  3. For @ManyToMany, the collection type makes quite a difference as Sets perform better than Lists.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

ClusterIP: Services are reachable by pods/services in the Cluster
If I make a service called myservice in the default namespace of type: ClusterIP then the following predictable static DNS address for the service will be created:

myservice.default.svc.cluster.local (or just myservice.default, or by pods in the default namespace just "myservice" will work)

And that DNS name can only be resolved by pods and services inside the cluster.

NodePort: Services are reachable by clients on the same LAN/clients who can ping the K8s Host Nodes (and pods/services in the cluster) (Note for security your k8s host nodes should be on a private subnet, thus clients on the internet won't be able to reach this service)
If I make a service called mynodeportservice in the mynamespace namespace of type: NodePort on a 3 Node Kubernetes Cluster. Then a Service of type: ClusterIP will be created and it'll be reachable by clients inside the cluster at the following predictable static DNS address:

mynodeportservice.mynamespace.svc.cluster.local (or just mynodeportservice.mynamespace)

For each port that mynodeportservice listens on a nodeport in the range of 30000 - 32767 will be randomly chosen. So that External clients that are outside the cluster can hit that ClusterIP service that exists inside the cluster. Lets say that our 3 K8s host nodes have IPs 10.10.10.1, 10.10.10.2, 10.10.10.3, the Kubernetes service is listening on port 80, and the Nodeport picked at random was 31852.

A client that exists outside of the cluster could visit 10.10.10.1:31852, 10.10.10.2:31852, or 10.10.10.3:31852 (as NodePort is listened for by every Kubernetes Host Node) Kubeproxy will forward the request to mynodeportservice's port 80.

LoadBalancer: Services are reachable by everyone connected to the internet* (Common architecture is L4 LB is publicly accessible on the internet by putting it in a DMZ or giving it both a private and public IP and k8s host nodes are on a private subnet)
(Note: This is the only service type that doesn't work in 100% of Kubernetes implementations, like bare metal Kubernetes, it works when Kubernetes has cloud provider integrations.)

If you make mylbservice, then a L4 LB VM will be spawned (a cluster IP service, and a NodePort Service will be implicitly spawned as well). This time our NodePort is 30222. the idea is that the L4 LB will have a public IP of 1.2.3.4 and it will load balance and forward traffic to the 3 K8s host nodes that have private IP addresses. (10.10.10.1:30222, 10.10.10.2:30222, 10.10.10.3:30222) and then Kube Proxy will forward it to the service of type ClusterIP that exists inside the cluster.


You also asked: Does the NodePort service type still use the ClusterIP? Yes*
Or is the NodeIP actually the IP found when you run kubectl get nodes? Also Yes*

Lets draw a parrallel between Fundamentals:
A container is inside a pod. a pod is inside a replicaset. a replicaset is inside a deployment.
Well similarly:
A ClusterIP Service is part of a NodePort Service. A NodePort Service is Part of a Load Balancer Service.


In that diagram you showed, the Client would be a pod inside the cluster.

What to put in a python module docstring?

Think about somebody doing help(yourmodule) at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in x.py:

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

then:

>>> import x; help(x)

shows:

Help on module x:

NAME
    x - This module does blah blah.

FILE
    /tmp/x.py

CLASSES
    __builtin__.object
        Blah

    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  
     |  Data and other attributes defined here:
     |  
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).

I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.

Common elements comparison between 2 lists

There are solutions here that do it in O(l1+l2) that don't count repeating items, and slow solutions (at least O(l1*l2), but probably more expensive) that do consider repeating items.

So I figured I should add an O(l1log(l1)+l2(log(l2)) solution. This is particularly useful if the lists are already sorted.

def common_elems_with_repeats(first_list, second_list):
    first_list = sorted(first_list)
    second_list = sorted(second_list)
    marker_first = 0
    marker_second = 0
    common = []
    while marker_first < len(first_list) and marker_second < len(second_list):
        if(first_list[marker_first] == second_list[marker_second]):
            common.append(first_list[marker_first])
            marker_first +=1
            marker_second +=1
        elif first_list[marker_first] > second_list[marker_second]:
            marker_second += 1
        else:
            marker_first += 1
    return common

Another faster solution would include making a item->count map from list1, and iterating through list2, while updating the map and counting dups. Wouldn't require sorting. Would require extra a bit extra memory but it's technically O(l1+l2).

How to model type-safe enum types?

A slightly less verbose way of declaring named enumerations:

object WeekDay extends Enumeration("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") {
  type WeekDay = Value
  val Sun, Mon, Tue, Wed, Thu, Fri, Sat = Value
}

WeekDay.valueOf("Wed") // returns Some(Wed)
WeekDay.Fri.toString   // returns Fri

Of course the problem here is that you will need to keep the ordering of the names and vals in sync which is easier to do if name and val are declared on the same line.

Transparent background on winforms?

Here was my solution:

In the constructors add these two lines:

this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;

In your form, add this method:

protected override void OnPaintBackground(PaintEventArgs e)
{
    e.Graphics.FillRectangle(Brushes.LimeGreen, e.ClipRectangle);
}

Be warned, not only is this form fully transparent inside the frame, but you can also click through it. However, it might be cool to draw an image onto it and make the form able to be dragged everywhere to create a custom shaped form.

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Python Extension. From the Python Docs:

The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).

Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python

https://docs.python.org/3/howto/regex.html

Using BETWEEN in CASE SQL statement

You do not specify why you think it is wrong but I can se two dangers:

BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.

Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.

Specifying trust store information in spring boot application.properties

java properties "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword" do not correspond to "server.ssl.trust-store" and "server.ssl.trust-store-password" from Spring boot "application.properties" ("application.yml")

so you can not set "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword" simply by setting "server.ssl.trust-store" and "server.ssl.trust-store-password" in "application.properties" ("application.yml")

an alternative of setting "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword" is by Spring boot Externalized Configuration

below are excerpts of my implementation :

Params class holds the external settings

@Component
@ConfigurationProperties("params")
public class Params{

    //default values, can be override by external settings
    public static String trustStorePath = "config/client-truststore.jks";
    public static String trustStorePassword = "wso2carbon";
    public static String keyStorePath = "config/wso2carbon.jks";
    public static String keyStorePassword = "wso2carbon";
    public static String defaultType = "JKS";
    
    public void setTrustStorePath(String trustStorePath){
        Params.trustStorePath = trustStorePath;
    }
           
    public void settrustStorePassword(String trustStorePassword){
        Params.trustStorePassword=trustStorePassword;
    }

    public void setKeyStorePath(String keyStorePath){
        Params.keyStorePath = keyStorePath;
    }
         
    public void setkeyStorePassword(String keyStorePassword){
        Params.keyStorePassword = keyStorePassword;
    }
    
    public void setDefaultType(String defaultType){
        Params.defaultType = defaultType;
    }

KeyStoreUtil class undertakes the settings of "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword"

public class KeyStoreUtil {
    
    public static void setTrustStoreParams() {
        File filePath = new File( Params.trustStorePath);
        String tsp = filePath.getAbsolutePath();
        System.setProperty("javax.net.ssl.trustStore", tsp);
        System.setProperty("javax.net.ssl.trustStorePassword", Params.trustStorePassword);
        System.setProperty("javax.net.ssl.keyStoreType", Params.defaultType);

    }

    public static void setKeyStoreParams() {
        File filePath = new File(Params.keyStorePath);
        String ksp = filePath.getAbsolutePath();
        System.setProperty("Security.KeyStore.Location", ksp);
        System.setProperty("Security.KeyStore.Password", Params.keyStorePassword);

    }     
}

you get the setters executed within the startup function

@SpringBootApplication
@ComponentScan("com.myapp.profiles")
public class ProfilesApplication {

    public static void main(String[] args) {
        KeyStoreUtil.setKeyStoreParams();
        KeyStoreUtil.setTrustStoreParams();
        SpringApplication.run(ProfilesApplication.class, args);
    }
}

Edited on 2018-10-03

you may also want to adopt the annotation "PostConstruct" as as an alternative to execute the setters

import javax.annotation.PostConstruct;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages={"com.xxx"})
public class GateApplication {

    public static void main(String[] args) {
        SpringApplication.run(GateApplication.class, args);
    }
    
    @PostConstruct
    void postConstruct(){
        setTrustStoreParams();
        setKeyStoreParams();
    }
    
    
    private static void setTrustStoreParams() {
        File filePath = new File( Params.trustStorePath);
        String tsp = filePath.getAbsolutePath();
        System.setProperty("javax.net.ssl.trustStore", tsp);
        System.setProperty("javax.net.ssl.trustStorePassword", Params.trustStorePassword);
        System.setProperty("javax.net.ssl.keyStoreType", Params.defaultType);

    }

    private static void setKeyStoreParams() {
        File filePath = new File(Params.keyStorePath);
        String ksp = filePath.getAbsolutePath();
        System.setProperty("Security.KeyStore.Location", ksp);
        System.setProperty("Security.KeyStore.Password", Params.keyStorePassword);

    }
}

the application.yml

---
 params: 
   trustStorePath: config/client-truststore.jks
   trustStorePassword: wso2carbon
   keyStorePath: config/wso2carbon.jks
   keyStorePassword: wso2carbon
   defaultType: JKS
---

finally, within the running environment(deployment server), you create a folder named "config" under the same folder where the jar archive is stored .

within the "config" folder, you store "application.yml", "client-truststore.jks", and "wso2carbon.jks". done!

Update on 2018-11-27 about Spring boot 2.x.x

starting from spring boot 2.x.x, static properties are no longer supported, please see here. I personally do not think it a good move, because complex changes have to be made along the reference chain...

anyway, an implementation excerpt might look like this

the 'Params' class

    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    import lombok.Data;
    
    /**
     * Params class represent all config parameters that can 
     * be external set by spring xml file
     */
    
    @Component
    @ConfigurationProperties("params")
    @Data
    public class Params{
    
        //default values, can be override by external settings
        public String trustStorePath = "config/client-truststore.jks";
        public String trustStorePassword = "wso2carbon";
        public String keyStorePath = "config/wso2carbon.jks";
        public String keyStorePassword = "wso2carbon";
        public String defaultType = "JKS";  
}

the 'Springboot application class' (with 'PostConstruct')

import java.io.File;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages={"com.xx.xx"})
public class BillingApplication {
    
    @Autowired
    Params params;
    
    public static void main(String[] args) {
        SpringApplication.run(BillingApplication.class, args);
    }
    
    @PostConstruct
    void postConstruct() {
        
        // set TrustStoreParams
        File trustStoreFilePath = new File(params.trustStorePath);
        String tsp = trustStoreFilePath.getAbsolutePath();
        System.setProperty("javax.net.ssl.trustStore", tsp);
        System.setProperty("javax.net.ssl.trustStorePassword", params.trustStorePassword);
        System.setProperty("javax.net.ssl.keyStoreType", params.defaultType);
        // set KeyStoreParams
        File keyStoreFilePath = new File(params.keyStorePath);
        String ksp = keyStoreFilePath.getAbsolutePath();
        System.setProperty("Security.KeyStore.Location", ksp);
        System.setProperty("Security.KeyStore.Password", params.keyStorePassword);
    }
    
}

When should I use a List vs a LinkedList

The primary advantage of linked lists over arrays is that the links provide us with the capability to rearrange the items efficiently. Sedgewick, p. 91

How to get the onclick calling object?

http://docs.jquery.com/Events/jQuery.Event

Try with event.target

Contains the DOM element that issued the event. This can be the element that registered for the event or a child of it.

Run a PostgreSQL .sql file using command line arguments

Of course, you will get a fatal error for authenticating, because you do not include a user name...

Try this one, it is OK for me :)

psql -U username -d myDataBase -a -f myInsertFile

If the database is remote, use the same command with host

psql -h host -U username -d myDataBase -a -f myInsertFile

How to restart Activity in Android

This is the way I do it.

        val i = Intent(context!!, MainActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        startActivity(i)

Fastest way to check if a string matches a regexp in ruby?

This is the benchmark I have run after finding some articles around the net.

With 2.4.0 the winner is re.match?(str) (as suggested by @wiktor-stribizew), on previous versions, re =~ str seems to be fastest, although str =~ re is almost as fast.

#!/usr/bin/env ruby
require 'benchmark'

str = "aacaabc"
re = Regexp.new('a+b').freeze

N = 4_000_000

Benchmark.bm do |b|
    b.report("str.match re\t") { N.times { str.match re } }
    b.report("str =~ re\t")    { N.times { str =~ re } }
    b.report("str[re]  \t")    { N.times { str[re] } }
    b.report("re =~ str\t")    { N.times { re =~ str } }
    b.report("re.match str\t") { N.times { re.match str } }
    if re.respond_to?(:match?)
        b.report("re.match? str\t") { N.times { re.match? str } }
    end
end

Results MRI 1.9.3-o551:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         2.390000   0.000000   2.390000 (  2.397331)
str =~ re         2.450000   0.000000   2.450000 (  2.446893)
str[re]           2.940000   0.010000   2.950000 (  2.941666)
re.match str      3.620000   0.000000   3.620000 (  3.619922)
str.match re      4.180000   0.000000   4.180000 (  4.180083)

Results MRI 2.1.5:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         1.150000   0.000000   1.150000 (  1.144880)
str =~ re         1.160000   0.000000   1.160000 (  1.150691)
str[re]           1.330000   0.000000   1.330000 (  1.337064)
re.match str      2.250000   0.000000   2.250000 (  2.255142)
str.match re      2.270000   0.000000   2.270000 (  2.270948)

Results MRI 2.3.3 (there is a regression in regex matching, it seems):

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         3.540000   0.000000   3.540000 (  3.535881)
str =~ re         3.560000   0.000000   3.560000 (  3.560657)
str[re]           4.300000   0.000000   4.300000 (  4.299403)
re.match str      5.210000   0.010000   5.220000 (  5.213041)
str.match re      6.000000   0.000000   6.000000 (  6.000465)

Results MRI 2.4.0:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re.match? str     0.690000   0.010000   0.700000 (  0.682934)
re =~ str         1.040000   0.000000   1.040000 (  1.035863)
str =~ re         1.040000   0.000000   1.040000 (  1.042963)
str[re]           1.340000   0.000000   1.340000 (  1.339704)
re.match str      2.040000   0.000000   2.040000 (  2.046464)
str.match re      2.180000   0.000000   2.180000 (  2.174691)

Global variables in c#.net

You can create a variable with an application scope

Generating a random hex color code with PHP

As of PHP 5.3, you can use openssl_random_pseudo_bytes():

$hex_string = bin2hex(openssl_random_pseudo_bytes(3));

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

I'll take a stab at it:

/^[a-z](?:_?[a-z0-9]+)*$/i

Explained:

/
 ^           # match beginning of string
 [a-z]       # match a letter for the first char
 (?:         # start non-capture group
   _?          # match 0 or 1 '_'
   [a-z0-9]+   # match a letter or number, 1 or more times
 )*          # end non-capture group, match whole group 0 or more times
 $           # match end of string
/i           # case insensitive flag

The non-capture group takes care of a) not allowing two _'s (it forces at least one letter or number per group) and b) only allowing the last char to be a letter or number.

Some test strings:

"a": match
"_": fail
"zz": match
"a0": match
"A_": fail
"a0_b": match
"a__b": fail
"a_1_c": match

How to make a smooth image rotation in Android?

Pruning the <set>-Element that wrapped the <rotate>-Element solves the problem!

Thanks to Shalafi!

So your Rotation_ccw.xml should loook like this:

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

<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="-360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="2000"
    android:fillAfter="false"
    android:startOffset="0"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/linear_interpolator"
    />

How to Call a Function inside a Render in React/Jsx

_x000D_
_x000D_
class App extends React.Component {_x000D_
  _x000D_
  buttonClick(){_x000D_
    console.log("came here")_x000D_
    _x000D_
  }_x000D_
  _x000D_
  subComponent() {_x000D_
    return (<div>Hello World</div>);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return ( _x000D_
      <div className="patient-container">_x000D_
          <button onClick={this.buttonClick.bind(this)}>Click me</button>_x000D_
          {this.subComponent()}_x000D_
       </div>_x000D_
     )_x000D_
  }_x000D_
  _x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

it depends on your need, u can use either this.renderIcon() or bind this.renderIcon.bind(this)

UPDATE

This is how you call a method outside the render.

buttonClick(){
    console.log("came here")
}

render() {
   return (
       <div className="patient-container">
          <button onClick={this.buttonClick.bind(this)}>Click me</button>
       </div>
   );
}

The recommended way is to write a separate component and import it.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

I had the same issue and I believe this occurred because of checksum between linux and windows (also mac). you can use repair() command in flyway.

flyway.repair();

Be careful , if you are in production environment , make sure that you did not change the migration SQL file; because when you run the flyway.repair(); it means you saying to flyway that your are sure about the migration version and their checksum and then the flyway repair them !

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Matt's answer is fine, but just to avoid this to propagate to other elements inside the navbar (like when you also have a dropdown), use

.navbar-nav > li > a {
   line-height: 50px;
}

How to create a folder with name as current date in batch (.bat) files

Thanks for the info all, very helpful. I needed something that could create "backup" folder as often as every minute in the same directory, as well as call on it later in the script. Here's what I came up with:

@ echo off

CD %userprofile%\desktop

SET Datefolder="%DATE:~4,2%-%DATE:~7,2%-%DATE:~12,2%_%time:~1,1%%time:~3,2%"

MD "%Datefolder%"

This gives me a folder on the currently logged on user's desktop named: mm-dd-yy_hmm (hour minute minute) ie: 07-28-15_719

Setting a backgroundImage With React Inline Styles

If you are using ES5 -

backgroundImage: "url(" + Background + ")"

If you are using ES6 -

backgroundImage: `url(${Background})`

Basically removing unnecessary curly braces while adding value to backgroundImage property works will work.

Convert Unicode to ASCII without errors in Python

I think the answer is there but only in bits and pieces, which makes it difficult to quickly fix the problem such as

UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 2818: ordinal not in range(128)

Let's take an example, Suppose I have file which has some data in the following form ( containing ascii and non-ascii chars )

1/10/17, 21:36 - Land : Welcome ��

and we want to ignore and preserve only ascii characters.

This code will do:

import unicodedata
fp  = open(<FILENAME>)
for line in fp:
    rline = line.strip()
    rline = unicode(rline, "utf-8")
    rline = unicodedata.normalize('NFKD', rline).encode('ascii','ignore')
    if len(rline) != 0:
        print rline

and type(rline) will give you

>type(rline) 
<type 'str'>

Parse usable Street Address, City, State, Zip from a string

I've been working in the address processing domain for about 5 years now, and there really is no silver bullet. The correct solution is going to depend on the value of the data. If it's not very valuable, throw it through a parser as the other answers suggest. If it's even somewhat valuable you'll definitely need to have a human evaluate/correct all the results of the parser. If you're looking for a fully automated, repeatable solution, you probably want to talk to a address correction vendor like Group1 or Trillium.

This compilation unit is not on the build path of a Java project

If it is a Maven project then sometimes re-importing of it helps:

  1. Right-click the project in the Project Explorer and choose Delete.
  2. File > Import... > Maven > Existing Maven Projects > Next > Root Directory > Browse your project from Disk.

Hope it will resolve the issue.

How to set variable from a SQL query?

I prefer just setting it from the declare statement

DECLARE @ModelID uniqueidentifer = (SELECT modelid 
                                    FROM models
                                    WHERE areaid = 'South Coast')

sql server #region

BEGIN...END works, you just have to add a commented section. The easiest way to do this is to add a section name! Another route is to add a comment block. See below:

BEGIN  -- Section Name
/* 
Comment block some stuff  --end comment should be on next line
*/

 --Very long query
SELECT * FROM FOO
SELECT * FROM BAR
END

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

It's supposed to be as simple as this:

<select id='multipleSelect' multiple='multiple'>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<script type='text/javascript'>
    $('#multipleSelect').val(['1', '2']);
</script>

Check my Fiddle: https://jsfiddle.net/luthrayatin/jaLygLzo/

Need to remove href values when printing in Chrome

If you use the following CSS

<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css"    />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />

just change it into the following style by adding media="screen"

<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />

I think it will work.

the former answers like

    @media print {
  a[href]:after {
    content: none !important;
  }
}

were not worked well in the chrome browse.

What is the => assignment in C# in a property signature

For the following statement shared by Alex Booker in their answer

When the compiler encounters an expression-bodied property member, it essentially converts it to a getter like this:

Please see the following screenshot, it shows how this statement (using SharpLab link)

public string APIBasePath => Configuration.ToolsAPIBasePath;

converts to

public string APIBasePath
{
    get
    {
        return Configuration.ToolsAPIBasePath;
    }
}

Screenshot: enter image description here

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I have got the solution for my query:

i have done something like this:

cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"

function setDefaultImage(source){
        var badImg = new Image();
        badImg.src = "video.png";
        var cpyImg = new Image();
        cpyImg.src = source.src;

        if(!cpyImg.width)
        {
            source.src = badImg.src;
        }

    }


    function onImgError(source){
        source.src = "video.png";
        source.onerror = ""; 
        return true; 
    } 

This way it's working in all browsers.

Using DateTime in a SqlParameter for Stored Procedure, format error

How are you setting up the SqlParameter? You should set the SqlDbType property to SqlDbType.DateTime and then pass the DateTime directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).

You should be able to get the value into the DB. If not, here is a very simple example of how to do it:

static void Main(string[] args)
{
    // Create the connection.
    using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
    {
        // Open the connection.
        connection.Open();

        // Create the command.
        using (SqlCommand command = new SqlCommand("xsp_Test", connection))
        {
            // Set the command type.
            command.CommandType = System.Data.CommandType.StoredProcedure;

            // Add the parameter.
            SqlParameter parameter = command.Parameters.Add("@dt",
                System.Data.SqlDbType.DateTime);

            // Set the value.
            parameter.Value = DateTime.Now;

            // Make the call.
            command.ExecuteNonQuery();
        }
    }
}

I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.

If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime struct will easily do).

All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime method, not by converting to a string) to the stored procedure.

And when you get the value back, call the ToLocalTime method to get the time in the local time zone.

How to fix 'sudo: no tty present and no askpass program specified' error?

sudo by default will read the password from the attached terminal. Your problem is that there is no terminal attached when it is run from the netbeans console. So you have to use an alternative way to enter the password: that is called the askpass program.

The askpass program is not a particular program, but any program that can ask for a password. For example in my system x11-ssh-askpass works fine.

In order to do that you have to specify what program to use, either with the environment variable SUDO_ASKPASS or in the sudo.conf file (see man sudo for details).

You can force sudo to use the askpass program by using the option -A. By default it will use it only if there is not an attached terminal.

Code line wrapping - how to handle long lines

In general, I break lines before operators, and indent the subsequent lines:

Map<long parameterization> longMap
    = new HashMap<ditto>();

String longString = "some long text"
                  + " some more long text";

To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.

CSV in Python adding an extra carriage return, on Windows

Note that if you use DictWriter, you will have a new line from the open function and a new line from the writerow function. You can use newline='' within the open function to remove the extra newline.

How to copy a folder via cmd?

xcopy  "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i

Probably the problem is the space.Try with quotes.

How to check Network port access and display useful message?

Great answer by mshutov & Salselvaprabu. I needed something a little bit more robust, and that checked all IPAddresses that was provided instead of checking only the first one.

I also wanted to replicate some of the parameter names and functionality than the Test-Connection function.

This new function allows you to set a Count for the number of retries, and the Delay between each try. Enjoy!

function Test-Port {

    [CmdletBinding()]
    Param (
        [string] $ComputerName,
        [int] $Port,
        [int] $Delay = 1,
        [int] $Count = 3
    )

    function Test-TcpClient ($IPAddress, $Port) {

        $TcpClient = New-Object Net.Sockets.TcpClient
        Try { $TcpClient.Connect($IPAddress, $Port) } Catch {}

        If ($TcpClient.Connected) { $TcpClient.Close(); Return $True }
        Return $False

    }

    function Invoke-Test ($ComputerName, $Port) {

        Try   { [array]$IPAddress = [System.Net.Dns]::GetHostAddresses($ComputerName) | Select-Object -Expand IPAddressToString } 
        Catch { Return $False }

        [array]$Results = $IPAddress | % { Test-TcpClient -IPAddress $_ -Port $Port }
        If ($Results -contains $True) { Return $True } Else { Return $False }

    }

    for ($i = 1; ((Invoke-Test -ComputerName $ComputerName -Port $Port) -ne $True); $i++)
    {
        if ($i -ge $Count) {
            Write-Warning "Timed out while waiting for port $Port to be open on $ComputerName!"
            Return $false
        }

        Write-Warning "Port $Port not open, retrying..."
        Sleep $Delay
    }

    Return $true

}

Switch statement equivalent in Windows batch file

I searched switch / case in batch files today and stumbled upon this. I used this solution and extended it with a goto exit.

IF "%1"=="red" echo "one selected" & goto exit
IF "%1"=="two" echo "two selected" & goto exit
...

echo "Options: [one | two | ...]

:exit 

Which brings in the default state (echo line) and no extra if's when the choice is found.